three.js 821 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809
  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: '66dev' };
  7. self.console = self.console || {
  8. info: function () {},
  9. log: function () {},
  10. debug: function () {},
  11. warn: function () {},
  12. error: function () {}
  13. };
  14. // based on https://github.com/documentcloud/underscore/blob/bf657be243a075b5e72acc8a83e6f12a564d8f55/underscore.js#L767
  15. THREE.extend = function ( obj, source ) {
  16. // ECMAScript5 compatibility based on: http://www.nczonline.net/blog/2012/12/11/are-your-mixins-ecmascript-5-compatible/
  17. if ( Object.keys ) {
  18. var keys = Object.keys( source );
  19. for (var i = 0, il = keys.length; i < il; i++) {
  20. var prop = keys[i];
  21. Object.defineProperty( obj, prop, Object.getOwnPropertyDescriptor( source, prop ) );
  22. }
  23. } else {
  24. var safeHasOwnProperty = {}.hasOwnProperty;
  25. for ( var prop in source ) {
  26. if ( safeHasOwnProperty.call( source, prop ) ) {
  27. obj[prop] = source[prop];
  28. }
  29. }
  30. }
  31. return obj;
  32. };
  33. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  34. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  35. // requestAnimationFrame polyfill by Erik Möller
  36. // fixes from Paul Irish and Tino Zijdel
  37. // using 'self' instead of 'window' for compatibility with both NodeJS and IE10.
  38. ( function () {
  39. var lastTime = 0;
  40. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  41. for ( var x = 0; x < vendors.length && !self.requestAnimationFrame; ++ x ) {
  42. self.requestAnimationFrame = self[ vendors[ x ] + 'RequestAnimationFrame' ];
  43. self.cancelAnimationFrame = self[ vendors[ x ] + 'CancelAnimationFrame' ] || self[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  44. }
  45. if ( self.requestAnimationFrame === undefined && self['setTimeout'] !== undefined ) {
  46. self.requestAnimationFrame = function ( callback ) {
  47. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  48. var id = self.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  49. lastTime = currTime + timeToCall;
  50. return id;
  51. };
  52. }
  53. if( self.cancelAnimationFrame === undefined && self['clearTimeout'] !== undefined ) {
  54. self.cancelAnimationFrame = function ( id ) { self.clearTimeout( id ) };
  55. }
  56. }() );
  57. // GL STATE CONSTANTS
  58. THREE.CullFaceNone = 0;
  59. THREE.CullFaceBack = 1;
  60. THREE.CullFaceFront = 2;
  61. THREE.CullFaceFrontBack = 3;
  62. THREE.FrontFaceDirectionCW = 0;
  63. THREE.FrontFaceDirectionCCW = 1;
  64. // SHADOWING TYPES
  65. THREE.BasicShadowMap = 0;
  66. THREE.PCFShadowMap = 1;
  67. THREE.PCFSoftShadowMap = 2;
  68. // MATERIAL CONSTANTS
  69. // side
  70. THREE.FrontSide = 0;
  71. THREE.BackSide = 1;
  72. THREE.DoubleSide = 2;
  73. // shading
  74. THREE.NoShading = 0;
  75. THREE.FlatShading = 1;
  76. THREE.SmoothShading = 2;
  77. // colors
  78. THREE.NoColors = 0;
  79. THREE.FaceColors = 1;
  80. THREE.VertexColors = 2;
  81. // blending modes
  82. THREE.NoBlending = 0;
  83. THREE.NormalBlending = 1;
  84. THREE.AdditiveBlending = 2;
  85. THREE.SubtractiveBlending = 3;
  86. THREE.MultiplyBlending = 4;
  87. THREE.CustomBlending = 5;
  88. // custom blending equations
  89. // (numbers start from 100 not to clash with other
  90. // mappings to OpenGL constants defined in Texture.js)
  91. THREE.AddEquation = 100;
  92. THREE.SubtractEquation = 101;
  93. THREE.ReverseSubtractEquation = 102;
  94. // custom blending destination factors
  95. THREE.ZeroFactor = 200;
  96. THREE.OneFactor = 201;
  97. THREE.SrcColorFactor = 202;
  98. THREE.OneMinusSrcColorFactor = 203;
  99. THREE.SrcAlphaFactor = 204;
  100. THREE.OneMinusSrcAlphaFactor = 205;
  101. THREE.DstAlphaFactor = 206;
  102. THREE.OneMinusDstAlphaFactor = 207;
  103. // custom blending source factors
  104. //THREE.ZeroFactor = 200;
  105. //THREE.OneFactor = 201;
  106. //THREE.SrcAlphaFactor = 204;
  107. //THREE.OneMinusSrcAlphaFactor = 205;
  108. //THREE.DstAlphaFactor = 206;
  109. //THREE.OneMinusDstAlphaFactor = 207;
  110. THREE.DstColorFactor = 208;
  111. THREE.OneMinusDstColorFactor = 209;
  112. THREE.SrcAlphaSaturateFactor = 210;
  113. // TEXTURE CONSTANTS
  114. THREE.MultiplyOperation = 0;
  115. THREE.MixOperation = 1;
  116. THREE.AddOperation = 2;
  117. // Mapping modes
  118. THREE.UVMapping = function () {};
  119. THREE.CubeReflectionMapping = function () {};
  120. THREE.CubeRefractionMapping = function () {};
  121. THREE.SphericalReflectionMapping = function () {};
  122. THREE.SphericalRefractionMapping = function () {};
  123. // Wrapping modes
  124. THREE.RepeatWrapping = 1000;
  125. THREE.ClampToEdgeWrapping = 1001;
  126. THREE.MirroredRepeatWrapping = 1002;
  127. // Filters
  128. THREE.NearestFilter = 1003;
  129. THREE.NearestMipMapNearestFilter = 1004;
  130. THREE.NearestMipMapLinearFilter = 1005;
  131. THREE.LinearFilter = 1006;
  132. THREE.LinearMipMapNearestFilter = 1007;
  133. THREE.LinearMipMapLinearFilter = 1008;
  134. // Data types
  135. THREE.UnsignedByteType = 1009;
  136. THREE.ByteType = 1010;
  137. THREE.ShortType = 1011;
  138. THREE.UnsignedShortType = 1012;
  139. THREE.IntType = 1013;
  140. THREE.UnsignedIntType = 1014;
  141. THREE.FloatType = 1015;
  142. // Pixel types
  143. //THREE.UnsignedByteType = 1009;
  144. THREE.UnsignedShort4444Type = 1016;
  145. THREE.UnsignedShort5551Type = 1017;
  146. THREE.UnsignedShort565Type = 1018;
  147. // Pixel formats
  148. THREE.AlphaFormat = 1019;
  149. THREE.RGBFormat = 1020;
  150. THREE.RGBAFormat = 1021;
  151. THREE.LuminanceFormat = 1022;
  152. THREE.LuminanceAlphaFormat = 1023;
  153. // Compressed texture formats
  154. THREE.RGB_S3TC_DXT1_Format = 2001;
  155. THREE.RGBA_S3TC_DXT1_Format = 2002;
  156. THREE.RGBA_S3TC_DXT3_Format = 2003;
  157. THREE.RGBA_S3TC_DXT5_Format = 2004;
  158. /*
  159. // Potential future PVRTC compressed texture formats
  160. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  161. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  162. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  163. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  164. */
  165. /**
  166. * @author mrdoob / http://mrdoob.com/
  167. */
  168. THREE.Color = function ( color ) {
  169. if ( arguments.length === 3 ) {
  170. return this.setRGB( arguments[ 0 ], arguments[ 1 ], arguments[ 2 ] );
  171. }
  172. return this.set( color )
  173. };
  174. THREE.Color.prototype = {
  175. constructor: THREE.Color,
  176. r: 1, g: 1, b: 1,
  177. set: function ( value ) {
  178. if ( value instanceof THREE.Color ) {
  179. this.copy( value );
  180. } else if ( typeof value === 'number' ) {
  181. this.setHex( value );
  182. } else if ( typeof value === 'string' ) {
  183. this.setStyle( value );
  184. }
  185. return this;
  186. },
  187. setHex: function ( hex ) {
  188. hex = Math.floor( hex );
  189. this.r = ( hex >> 16 & 255 ) / 255;
  190. this.g = ( hex >> 8 & 255 ) / 255;
  191. this.b = ( hex & 255 ) / 255;
  192. return this;
  193. },
  194. setRGB: function ( r, g, b ) {
  195. this.r = r;
  196. this.g = g;
  197. this.b = b;
  198. return this;
  199. },
  200. setHSL: function ( h, s, l ) {
  201. // h,s,l ranges are in 0.0 - 1.0
  202. if ( s === 0 ) {
  203. this.r = this.g = this.b = l;
  204. } else {
  205. var hue2rgb = function ( p, q, t ) {
  206. if ( t < 0 ) t += 1;
  207. if ( t > 1 ) t -= 1;
  208. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  209. if ( t < 1 / 2 ) return q;
  210. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  211. return p;
  212. };
  213. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  214. var q = ( 2 * l ) - p;
  215. this.r = hue2rgb( q, p, h + 1 / 3 );
  216. this.g = hue2rgb( q, p, h );
  217. this.b = hue2rgb( q, p, h - 1 / 3 );
  218. }
  219. return this;
  220. },
  221. setStyle: function ( style ) {
  222. // rgb(255,0,0)
  223. if ( /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.test( style ) ) {
  224. var color = /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.exec( style );
  225. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  226. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  227. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  228. return this;
  229. }
  230. // rgb(100%,0%,0%)
  231. if ( /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.test( style ) ) {
  232. var color = /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.exec( style );
  233. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  234. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  235. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  236. return this;
  237. }
  238. // #ff0000
  239. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  240. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  241. this.setHex( parseInt( color[ 1 ], 16 ) );
  242. return this;
  243. }
  244. // #f00
  245. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  246. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  247. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  248. return this;
  249. }
  250. // red
  251. if ( /^(\w+)$/i.test( style ) ) {
  252. this.setHex( THREE.ColorKeywords[ style ] );
  253. return this;
  254. }
  255. },
  256. copy: function ( color ) {
  257. this.r = color.r;
  258. this.g = color.g;
  259. this.b = color.b;
  260. return this;
  261. },
  262. copyGammaToLinear: function ( color ) {
  263. this.r = color.r * color.r;
  264. this.g = color.g * color.g;
  265. this.b = color.b * color.b;
  266. return this;
  267. },
  268. copyLinearToGamma: function ( color ) {
  269. this.r = Math.sqrt( color.r );
  270. this.g = Math.sqrt( color.g );
  271. this.b = Math.sqrt( color.b );
  272. return this;
  273. },
  274. convertGammaToLinear: function () {
  275. var r = this.r, g = this.g, b = this.b;
  276. this.r = r * r;
  277. this.g = g * g;
  278. this.b = b * b;
  279. return this;
  280. },
  281. convertLinearToGamma: function () {
  282. this.r = Math.sqrt( this.r );
  283. this.g = Math.sqrt( this.g );
  284. this.b = Math.sqrt( this.b );
  285. return this;
  286. },
  287. getHex: function () {
  288. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  289. },
  290. getHexString: function () {
  291. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  292. },
  293. getHSL: function ( optionalTarget ) {
  294. // h,s,l ranges are in 0.0 - 1.0
  295. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  296. var r = this.r, g = this.g, b = this.b;
  297. var max = Math.max( r, g, b );
  298. var min = Math.min( r, g, b );
  299. var hue, saturation;
  300. var lightness = ( min + max ) / 2.0;
  301. if ( min === max ) {
  302. hue = 0;
  303. saturation = 0;
  304. } else {
  305. var delta = max - min;
  306. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  307. switch ( max ) {
  308. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  309. case g: hue = ( b - r ) / delta + 2; break;
  310. case b: hue = ( r - g ) / delta + 4; break;
  311. }
  312. hue /= 6;
  313. }
  314. hsl.h = hue;
  315. hsl.s = saturation;
  316. hsl.l = lightness;
  317. return hsl;
  318. },
  319. getStyle: function () {
  320. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  321. },
  322. offsetHSL: function ( h, s, l ) {
  323. var hsl = this.getHSL();
  324. hsl.h += h; hsl.s += s; hsl.l += l;
  325. this.setHSL( hsl.h, hsl.s, hsl.l );
  326. return this;
  327. },
  328. add: function ( color ) {
  329. this.r += color.r;
  330. this.g += color.g;
  331. this.b += color.b;
  332. return this;
  333. },
  334. addColors: function ( color1, color2 ) {
  335. this.r = color1.r + color2.r;
  336. this.g = color1.g + color2.g;
  337. this.b = color1.b + color2.b;
  338. return this;
  339. },
  340. addScalar: function ( s ) {
  341. this.r += s;
  342. this.g += s;
  343. this.b += s;
  344. return this;
  345. },
  346. multiply: function ( color ) {
  347. this.r *= color.r;
  348. this.g *= color.g;
  349. this.b *= color.b;
  350. return this;
  351. },
  352. multiplyScalar: function ( s ) {
  353. this.r *= s;
  354. this.g *= s;
  355. this.b *= s;
  356. return this;
  357. },
  358. lerp: function ( color, alpha ) {
  359. this.r += ( color.r - this.r ) * alpha;
  360. this.g += ( color.g - this.g ) * alpha;
  361. this.b += ( color.b - this.b ) * alpha;
  362. return this;
  363. },
  364. equals: function ( c ) {
  365. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  366. },
  367. fromArray: function ( array ) {
  368. this.r = array[ 0 ];
  369. this.g = array[ 1 ];
  370. this.b = array[ 2 ];
  371. return this;
  372. },
  373. toArray: function () {
  374. return [ this.r, this.g, this.b ];
  375. },
  376. clone: function () {
  377. return new THREE.Color().setRGB( this.r, this.g, this.b );
  378. }
  379. };
  380. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  381. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  382. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  383. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  384. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  385. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  386. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  387. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  388. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  389. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  390. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  391. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  392. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  393. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  394. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  395. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  396. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  397. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  398. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  399. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  400. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  401. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  402. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  403. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  404. /**
  405. * @author mikael emtinger / http://gomo.se/
  406. * @author alteredq / http://alteredqualia.com/
  407. * @author WestLangley / http://github.com/WestLangley
  408. * @author bhouston / http://exocortex.com
  409. */
  410. THREE.Quaternion = function ( x, y, z, w ) {
  411. this._x = x || 0;
  412. this._y = y || 0;
  413. this._z = z || 0;
  414. this._w = ( w !== undefined ) ? w : 1;
  415. };
  416. THREE.Quaternion.prototype = {
  417. constructor: THREE.Quaternion,
  418. _x: 0,_y: 0, _z: 0, _w: 0,
  419. _euler: undefined,
  420. _updateEuler: function ( callback ) {
  421. if ( this._euler !== undefined ) {
  422. this._euler.setFromQuaternion( this, undefined, false );
  423. }
  424. },
  425. get x () {
  426. return this._x;
  427. },
  428. set x ( value ) {
  429. this._x = value;
  430. this._updateEuler();
  431. },
  432. get y () {
  433. return this._y;
  434. },
  435. set y ( value ) {
  436. this._y = value;
  437. this._updateEuler();
  438. },
  439. get z () {
  440. return this._z;
  441. },
  442. set z ( value ) {
  443. this._z = value;
  444. this._updateEuler();
  445. },
  446. get w () {
  447. return this._w;
  448. },
  449. set w ( value ) {
  450. this._w = value;
  451. this._updateEuler();
  452. },
  453. set: function ( x, y, z, w ) {
  454. this._x = x;
  455. this._y = y;
  456. this._z = z;
  457. this._w = w;
  458. this._updateEuler();
  459. return this;
  460. },
  461. copy: function ( quaternion ) {
  462. this._x = quaternion._x;
  463. this._y = quaternion._y;
  464. this._z = quaternion._z;
  465. this._w = quaternion._w;
  466. this._updateEuler();
  467. return this;
  468. },
  469. setFromEuler: function ( euler, update ) {
  470. if ( euler instanceof THREE.Euler === false ) {
  471. throw new Error( 'ERROR: Quaternion\'s .setFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  472. }
  473. // http://www.mathworks.com/matlabcentral/fileexchange/
  474. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  475. // content/SpinCalc.m
  476. var c1 = Math.cos( euler._x / 2 );
  477. var c2 = Math.cos( euler._y / 2 );
  478. var c3 = Math.cos( euler._z / 2 );
  479. var s1 = Math.sin( euler._x / 2 );
  480. var s2 = Math.sin( euler._y / 2 );
  481. var s3 = Math.sin( euler._z / 2 );
  482. if ( euler.order === 'XYZ' ) {
  483. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  484. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  485. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  486. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  487. } else if ( euler.order === 'YXZ' ) {
  488. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  489. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  490. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  491. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  492. } else if ( euler.order === 'ZXY' ) {
  493. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  494. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  495. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  496. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  497. } else if ( euler.order === 'ZYX' ) {
  498. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  499. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  500. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  501. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  502. } else if ( euler.order === 'YZX' ) {
  503. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  504. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  505. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  506. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  507. } else if ( euler.order === 'XZY' ) {
  508. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  509. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  510. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  511. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  512. }
  513. if ( update !== false ) this._updateEuler();
  514. return this;
  515. },
  516. setFromAxisAngle: function ( axis, angle ) {
  517. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  518. // axis have to be normalized
  519. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  520. this._x = axis.x * s;
  521. this._y = axis.y * s;
  522. this._z = axis.z * s;
  523. this._w = Math.cos( halfAngle );
  524. this._updateEuler();
  525. return this;
  526. },
  527. setFromRotationMatrix: function ( m ) {
  528. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  529. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  530. var te = m.elements,
  531. m11 = te[0], m12 = te[4], m13 = te[8],
  532. m21 = te[1], m22 = te[5], m23 = te[9],
  533. m31 = te[2], m32 = te[6], m33 = te[10],
  534. trace = m11 + m22 + m33,
  535. s;
  536. if ( trace > 0 ) {
  537. s = 0.5 / Math.sqrt( trace + 1.0 );
  538. this._w = 0.25 / s;
  539. this._x = ( m32 - m23 ) * s;
  540. this._y = ( m13 - m31 ) * s;
  541. this._z = ( m21 - m12 ) * s;
  542. } else if ( m11 > m22 && m11 > m33 ) {
  543. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  544. this._w = (m32 - m23 ) / s;
  545. this._x = 0.25 * s;
  546. this._y = (m12 + m21 ) / s;
  547. this._z = (m13 + m31 ) / s;
  548. } else if ( m22 > m33 ) {
  549. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  550. this._w = (m13 - m31 ) / s;
  551. this._x = (m12 + m21 ) / s;
  552. this._y = 0.25 * s;
  553. this._z = (m23 + m32 ) / s;
  554. } else {
  555. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  556. this._w = ( m21 - m12 ) / s;
  557. this._x = ( m13 + m31 ) / s;
  558. this._y = ( m23 + m32 ) / s;
  559. this._z = 0.25 * s;
  560. }
  561. this._updateEuler();
  562. return this;
  563. },
  564. inverse: function () {
  565. this.conjugate().normalize();
  566. return this;
  567. },
  568. conjugate: function () {
  569. this._x *= -1;
  570. this._y *= -1;
  571. this._z *= -1;
  572. this._updateEuler();
  573. return this;
  574. },
  575. lengthSq: function () {
  576. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  577. },
  578. length: function () {
  579. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  580. },
  581. normalize: function () {
  582. var l = this.length();
  583. if ( l === 0 ) {
  584. this._x = 0;
  585. this._y = 0;
  586. this._z = 0;
  587. this._w = 1;
  588. } else {
  589. l = 1 / l;
  590. this._x = this._x * l;
  591. this._y = this._y * l;
  592. this._z = this._z * l;
  593. this._w = this._w * l;
  594. }
  595. return this;
  596. },
  597. multiply: function ( q, p ) {
  598. if ( p !== undefined ) {
  599. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  600. return this.multiplyQuaternions( q, p );
  601. }
  602. return this.multiplyQuaternions( this, q );
  603. },
  604. multiplyQuaternions: function ( a, b ) {
  605. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  606. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  607. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  608. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  609. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  610. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  611. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  612. this._updateEuler();
  613. return this;
  614. },
  615. multiplyVector3: function ( vector ) {
  616. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  617. return vector.applyQuaternion( this );
  618. },
  619. slerp: function ( qb, t ) {
  620. var x = this._x, y = this._y, z = this._z, w = this._w;
  621. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  622. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  623. if ( cosHalfTheta < 0 ) {
  624. this._w = -qb._w;
  625. this._x = -qb._x;
  626. this._y = -qb._y;
  627. this._z = -qb._z;
  628. cosHalfTheta = -cosHalfTheta;
  629. } else {
  630. this.copy( qb );
  631. }
  632. if ( cosHalfTheta >= 1.0 ) {
  633. this._w = w;
  634. this._x = x;
  635. this._y = y;
  636. this._z = z;
  637. return this;
  638. }
  639. var halfTheta = Math.acos( cosHalfTheta );
  640. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  641. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  642. this._w = 0.5 * ( w + this._w );
  643. this._x = 0.5 * ( x + this._x );
  644. this._y = 0.5 * ( y + this._y );
  645. this._z = 0.5 * ( z + this._z );
  646. return this;
  647. }
  648. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  649. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  650. this._w = ( w * ratioA + this._w * ratioB );
  651. this._x = ( x * ratioA + this._x * ratioB );
  652. this._y = ( y * ratioA + this._y * ratioB );
  653. this._z = ( z * ratioA + this._z * ratioB );
  654. this._updateEuler();
  655. return this;
  656. },
  657. equals: function ( quaternion ) {
  658. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  659. },
  660. fromArray: function ( array ) {
  661. this._x = array[ 0 ];
  662. this._y = array[ 1 ];
  663. this._z = array[ 2 ];
  664. this._w = array[ 3 ];
  665. this._updateEuler();
  666. return this;
  667. },
  668. toArray: function () {
  669. return [ this._x, this._y, this._z, this._w ];
  670. },
  671. clone: function () {
  672. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  673. }
  674. };
  675. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  676. return qm.copy( qa ).slerp( qb, t );
  677. }
  678. /**
  679. * @author mrdoob / http://mrdoob.com/
  680. * @author philogb / http://blog.thejit.org/
  681. * @author egraether / http://egraether.com/
  682. * @author zz85 / http://www.lab4games.net/zz85/blog
  683. */
  684. THREE.Vector2 = function ( x, y ) {
  685. this.x = x || 0;
  686. this.y = y || 0;
  687. };
  688. THREE.Vector2.prototype = {
  689. constructor: THREE.Vector2,
  690. set: function ( x, y ) {
  691. this.x = x;
  692. this.y = y;
  693. return this;
  694. },
  695. setX: function ( x ) {
  696. this.x = x;
  697. return this;
  698. },
  699. setY: function ( y ) {
  700. this.y = y;
  701. return this;
  702. },
  703. setComponent: function ( index, value ) {
  704. switch ( index ) {
  705. case 0: this.x = value; break;
  706. case 1: this.y = value; break;
  707. default: throw new Error( "index is out of range: " + index );
  708. }
  709. },
  710. getComponent: function ( index ) {
  711. switch ( index ) {
  712. case 0: return this.x;
  713. case 1: return this.y;
  714. default: throw new Error( "index is out of range: " + index );
  715. }
  716. },
  717. copy: function ( v ) {
  718. this.x = v.x;
  719. this.y = v.y;
  720. return this;
  721. },
  722. add: function ( v, w ) {
  723. if ( w !== undefined ) {
  724. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  725. return this.addVectors( v, w );
  726. }
  727. this.x += v.x;
  728. this.y += v.y;
  729. return this;
  730. },
  731. addVectors: function ( a, b ) {
  732. this.x = a.x + b.x;
  733. this.y = a.y + b.y;
  734. return this;
  735. },
  736. addScalar: function ( s ) {
  737. this.x += s;
  738. this.y += s;
  739. return this;
  740. },
  741. sub: function ( v, w ) {
  742. if ( w !== undefined ) {
  743. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  744. return this.subVectors( v, w );
  745. }
  746. this.x -= v.x;
  747. this.y -= v.y;
  748. return this;
  749. },
  750. subVectors: function ( a, b ) {
  751. this.x = a.x - b.x;
  752. this.y = a.y - b.y;
  753. return this;
  754. },
  755. multiplyScalar: function ( s ) {
  756. this.x *= s;
  757. this.y *= s;
  758. return this;
  759. },
  760. divideScalar: function ( scalar ) {
  761. if ( scalar !== 0 ) {
  762. var invScalar = 1 / scalar;
  763. this.x *= invScalar;
  764. this.y *= invScalar;
  765. } else {
  766. this.x = 0;
  767. this.y = 0;
  768. }
  769. return this;
  770. },
  771. min: function ( v ) {
  772. if ( this.x > v.x ) {
  773. this.x = v.x;
  774. }
  775. if ( this.y > v.y ) {
  776. this.y = v.y;
  777. }
  778. return this;
  779. },
  780. max: function ( v ) {
  781. if ( this.x < v.x ) {
  782. this.x = v.x;
  783. }
  784. if ( this.y < v.y ) {
  785. this.y = v.y;
  786. }
  787. return this;
  788. },
  789. clamp: function ( min, max ) {
  790. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  791. if ( this.x < min.x ) {
  792. this.x = min.x;
  793. } else if ( this.x > max.x ) {
  794. this.x = max.x;
  795. }
  796. if ( this.y < min.y ) {
  797. this.y = min.y;
  798. } else if ( this.y > max.y ) {
  799. this.y = max.y;
  800. }
  801. return this;
  802. },
  803. negate: function() {
  804. return this.multiplyScalar( - 1 );
  805. },
  806. dot: function ( v ) {
  807. return this.x * v.x + this.y * v.y;
  808. },
  809. lengthSq: function () {
  810. return this.x * this.x + this.y * this.y;
  811. },
  812. length: function () {
  813. return Math.sqrt( this.x * this.x + this.y * this.y );
  814. },
  815. normalize: function () {
  816. return this.divideScalar( this.length() );
  817. },
  818. distanceTo: function ( v ) {
  819. return Math.sqrt( this.distanceToSquared( v ) );
  820. },
  821. distanceToSquared: function ( v ) {
  822. var dx = this.x - v.x, dy = this.y - v.y;
  823. return dx * dx + dy * dy;
  824. },
  825. setLength: function ( l ) {
  826. var oldLength = this.length();
  827. if ( oldLength !== 0 && l !== oldLength ) {
  828. this.multiplyScalar( l / oldLength );
  829. }
  830. return this;
  831. },
  832. lerp: function ( v, alpha ) {
  833. this.x += ( v.x - this.x ) * alpha;
  834. this.y += ( v.y - this.y ) * alpha;
  835. return this;
  836. },
  837. equals: function( v ) {
  838. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  839. },
  840. fromArray: function ( array ) {
  841. this.x = array[ 0 ];
  842. this.y = array[ 1 ];
  843. return this;
  844. },
  845. toArray: function () {
  846. return [ this.x, this.y ];
  847. },
  848. clone: function () {
  849. return new THREE.Vector2( this.x, this.y );
  850. }
  851. };
  852. /**
  853. * @author mrdoob / http://mrdoob.com/
  854. * @author *kile / http://kile.stravaganza.org/
  855. * @author philogb / http://blog.thejit.org/
  856. * @author mikael emtinger / http://gomo.se/
  857. * @author egraether / http://egraether.com/
  858. * @author WestLangley / http://github.com/WestLangley
  859. */
  860. THREE.Vector3 = function ( x, y, z ) {
  861. this.x = x || 0;
  862. this.y = y || 0;
  863. this.z = z || 0;
  864. };
  865. THREE.Vector3.prototype = {
  866. constructor: THREE.Vector3,
  867. set: function ( x, y, z ) {
  868. this.x = x;
  869. this.y = y;
  870. this.z = z;
  871. return this;
  872. },
  873. setX: function ( x ) {
  874. this.x = x;
  875. return this;
  876. },
  877. setY: function ( y ) {
  878. this.y = y;
  879. return this;
  880. },
  881. setZ: function ( z ) {
  882. this.z = z;
  883. return this;
  884. },
  885. setComponent: function ( index, value ) {
  886. switch ( index ) {
  887. case 0: this.x = value; break;
  888. case 1: this.y = value; break;
  889. case 2: this.z = value; break;
  890. default: throw new Error( "index is out of range: " + index );
  891. }
  892. },
  893. getComponent: function ( index ) {
  894. switch ( index ) {
  895. case 0: return this.x;
  896. case 1: return this.y;
  897. case 2: return this.z;
  898. default: throw new Error( "index is out of range: " + index );
  899. }
  900. },
  901. copy: function ( v ) {
  902. this.x = v.x;
  903. this.y = v.y;
  904. this.z = v.z;
  905. return this;
  906. },
  907. add: function ( v, w ) {
  908. if ( w !== undefined ) {
  909. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  910. return this.addVectors( v, w );
  911. }
  912. this.x += v.x;
  913. this.y += v.y;
  914. this.z += v.z;
  915. return this;
  916. },
  917. addScalar: function ( s ) {
  918. this.x += s;
  919. this.y += s;
  920. this.z += s;
  921. return this;
  922. },
  923. addVectors: function ( a, b ) {
  924. this.x = a.x + b.x;
  925. this.y = a.y + b.y;
  926. this.z = a.z + b.z;
  927. return this;
  928. },
  929. sub: function ( v, w ) {
  930. if ( w !== undefined ) {
  931. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  932. return this.subVectors( v, w );
  933. }
  934. this.x -= v.x;
  935. this.y -= v.y;
  936. this.z -= v.z;
  937. return this;
  938. },
  939. subVectors: function ( a, b ) {
  940. this.x = a.x - b.x;
  941. this.y = a.y - b.y;
  942. this.z = a.z - b.z;
  943. return this;
  944. },
  945. multiply: function ( v, w ) {
  946. if ( w !== undefined ) {
  947. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  948. return this.multiplyVectors( v, w );
  949. }
  950. this.x *= v.x;
  951. this.y *= v.y;
  952. this.z *= v.z;
  953. return this;
  954. },
  955. multiplyScalar: function ( scalar ) {
  956. this.x *= scalar;
  957. this.y *= scalar;
  958. this.z *= scalar;
  959. return this;
  960. },
  961. multiplyVectors: function ( a, b ) {
  962. this.x = a.x * b.x;
  963. this.y = a.y * b.y;
  964. this.z = a.z * b.z;
  965. return this;
  966. },
  967. applyMatrix3: function ( m ) {
  968. var x = this.x;
  969. var y = this.y;
  970. var z = this.z;
  971. var e = m.elements;
  972. this.x = e[0] * x + e[3] * y + e[6] * z;
  973. this.y = e[1] * x + e[4] * y + e[7] * z;
  974. this.z = e[2] * x + e[5] * y + e[8] * z;
  975. return this;
  976. },
  977. applyMatrix4: function ( m ) {
  978. // input: THREE.Matrix4 affine matrix
  979. var x = this.x, y = this.y, z = this.z;
  980. var e = m.elements;
  981. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  982. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  983. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  984. return this;
  985. },
  986. applyProjection: function ( m ) {
  987. // input: THREE.Matrix4 projection matrix
  988. var x = this.x, y = this.y, z = this.z;
  989. var e = m.elements;
  990. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  991. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  992. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  993. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  994. return this;
  995. },
  996. applyQuaternion: function ( q ) {
  997. var x = this.x;
  998. var y = this.y;
  999. var z = this.z;
  1000. var qx = q.x;
  1001. var qy = q.y;
  1002. var qz = q.z;
  1003. var qw = q.w;
  1004. // calculate quat * vector
  1005. var ix = qw * x + qy * z - qz * y;
  1006. var iy = qw * y + qz * x - qx * z;
  1007. var iz = qw * z + qx * y - qy * x;
  1008. var iw = -qx * x - qy * y - qz * z;
  1009. // calculate result * inverse quat
  1010. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  1011. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  1012. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  1013. return this;
  1014. },
  1015. transformDirection: function ( m ) {
  1016. // input: THREE.Matrix4 affine matrix
  1017. // vector interpreted as a direction
  1018. var x = this.x, y = this.y, z = this.z;
  1019. var e = m.elements;
  1020. this.x = e[0] * x + e[4] * y + e[8] * z;
  1021. this.y = e[1] * x + e[5] * y + e[9] * z;
  1022. this.z = e[2] * x + e[6] * y + e[10] * z;
  1023. this.normalize();
  1024. return this;
  1025. },
  1026. divide: function ( v ) {
  1027. this.x /= v.x;
  1028. this.y /= v.y;
  1029. this.z /= v.z;
  1030. return this;
  1031. },
  1032. divideScalar: function ( scalar ) {
  1033. if ( scalar !== 0 ) {
  1034. var invScalar = 1 / scalar;
  1035. this.x *= invScalar;
  1036. this.y *= invScalar;
  1037. this.z *= invScalar;
  1038. } else {
  1039. this.x = 0;
  1040. this.y = 0;
  1041. this.z = 0;
  1042. }
  1043. return this;
  1044. },
  1045. min: function ( v ) {
  1046. if ( this.x > v.x ) {
  1047. this.x = v.x;
  1048. }
  1049. if ( this.y > v.y ) {
  1050. this.y = v.y;
  1051. }
  1052. if ( this.z > v.z ) {
  1053. this.z = v.z;
  1054. }
  1055. return this;
  1056. },
  1057. max: function ( v ) {
  1058. if ( this.x < v.x ) {
  1059. this.x = v.x;
  1060. }
  1061. if ( this.y < v.y ) {
  1062. this.y = v.y;
  1063. }
  1064. if ( this.z < v.z ) {
  1065. this.z = v.z;
  1066. }
  1067. return this;
  1068. },
  1069. clamp: function ( min, max ) {
  1070. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1071. if ( this.x < min.x ) {
  1072. this.x = min.x;
  1073. } else if ( this.x > max.x ) {
  1074. this.x = max.x;
  1075. }
  1076. if ( this.y < min.y ) {
  1077. this.y = min.y;
  1078. } else if ( this.y > max.y ) {
  1079. this.y = max.y;
  1080. }
  1081. if ( this.z < min.z ) {
  1082. this.z = min.z;
  1083. } else if ( this.z > max.z ) {
  1084. this.z = max.z;
  1085. }
  1086. return this;
  1087. },
  1088. negate: function () {
  1089. return this.multiplyScalar( - 1 );
  1090. },
  1091. dot: function ( v ) {
  1092. return this.x * v.x + this.y * v.y + this.z * v.z;
  1093. },
  1094. lengthSq: function () {
  1095. return this.x * this.x + this.y * this.y + this.z * this.z;
  1096. },
  1097. length: function () {
  1098. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1099. },
  1100. lengthManhattan: function () {
  1101. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1102. },
  1103. normalize: function () {
  1104. return this.divideScalar( this.length() );
  1105. },
  1106. setLength: function ( l ) {
  1107. var oldLength = this.length();
  1108. if ( oldLength !== 0 && l !== oldLength ) {
  1109. this.multiplyScalar( l / oldLength );
  1110. }
  1111. return this;
  1112. },
  1113. lerp: function ( v, alpha ) {
  1114. this.x += ( v.x - this.x ) * alpha;
  1115. this.y += ( v.y - this.y ) * alpha;
  1116. this.z += ( v.z - this.z ) * alpha;
  1117. return this;
  1118. },
  1119. cross: function ( v, w ) {
  1120. if ( w !== undefined ) {
  1121. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1122. return this.crossVectors( v, w );
  1123. }
  1124. var x = this.x, y = this.y, z = this.z;
  1125. this.x = y * v.z - z * v.y;
  1126. this.y = z * v.x - x * v.z;
  1127. this.z = x * v.y - y * v.x;
  1128. return this;
  1129. },
  1130. crossVectors: function ( a, b ) {
  1131. var ax = a.x, ay = a.y, az = a.z;
  1132. var bx = b.x, by = b.y, bz = b.z;
  1133. this.x = ay * bz - az * by;
  1134. this.y = az * bx - ax * bz;
  1135. this.z = ax * by - ay * bx;
  1136. return this;
  1137. },
  1138. angleTo: function ( v ) {
  1139. var theta = this.dot( v ) / ( this.length() * v.length() );
  1140. // clamp, to handle numerical problems
  1141. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1142. },
  1143. distanceTo: function ( v ) {
  1144. return Math.sqrt( this.distanceToSquared( v ) );
  1145. },
  1146. distanceToSquared: function ( v ) {
  1147. var dx = this.x - v.x;
  1148. var dy = this.y - v.y;
  1149. var dz = this.z - v.z;
  1150. return dx * dx + dy * dy + dz * dz;
  1151. },
  1152. setEulerFromRotationMatrix: function ( m, order ) {
  1153. console.error( "REMOVED: Vector3\'s setEulerFromRotationMatrix has been removed in favor of Euler.setFromRotationMatrix(), please update your code.");
  1154. },
  1155. setEulerFromQuaternion: function ( q, order ) {
  1156. console.error( "REMOVED: Vector3\'s setEulerFromQuaternion: has been removed in favor of Euler.setFromQuaternion(), please update your code.");
  1157. },
  1158. getPositionFromMatrix: function ( m ) {
  1159. console.warn( "DEPRECATED: Vector3\'s .getPositionFromMatrix() has been renamed to .setFromMatrixPosition(). Please update your code." );
  1160. return this.setFromMatrixPosition( m );
  1161. },
  1162. getScaleFromMatrix: function ( m ) {
  1163. console.warn( "DEPRECATED: Vector3\'s .getScaleFromMatrix() has been renamed to .setFromMatrixScale(). Please update your code." );
  1164. return this.setFromMatrixScale( m );
  1165. },
  1166. getColumnFromMatrix: function ( index, matrix ) {
  1167. console.warn( "DEPRECATED: Vector3\'s .getColumnFromMatrix() has been renamed to .setFromMatrixColumn(). Please update your code." );
  1168. return this.setFromMatrixColumn( index, matrix );
  1169. },
  1170. setFromMatrixPosition: function ( m ) {
  1171. this.x = m.elements[ 12 ];
  1172. this.y = m.elements[ 13 ];
  1173. this.z = m.elements[ 14 ];
  1174. return this;
  1175. },
  1176. setFromMatrixScale: function ( m ) {
  1177. var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
  1178. var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
  1179. var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
  1180. this.x = sx;
  1181. this.y = sy;
  1182. this.z = sz;
  1183. return this;
  1184. },
  1185. setFromMatrixColumn: function ( index, matrix ) {
  1186. var offset = index * 4;
  1187. var me = matrix.elements;
  1188. this.x = me[ offset ];
  1189. this.y = me[ offset + 1 ];
  1190. this.z = me[ offset + 2 ];
  1191. return this;
  1192. },
  1193. equals: function ( v ) {
  1194. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1195. },
  1196. fromArray: function ( array ) {
  1197. this.x = array[ 0 ];
  1198. this.y = array[ 1 ];
  1199. this.z = array[ 2 ];
  1200. return this;
  1201. },
  1202. toArray: function () {
  1203. return [ this.x, this.y, this.z ];
  1204. },
  1205. clone: function () {
  1206. return new THREE.Vector3( this.x, this.y, this.z );
  1207. }
  1208. };
  1209. THREE.extend( THREE.Vector3.prototype, {
  1210. applyEuler: function () {
  1211. var quaternion = new THREE.Quaternion();
  1212. return function ( euler ) {
  1213. if ( euler instanceof THREE.Euler === false ) {
  1214. console.error( 'ERROR: Vector3\'s .applyEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  1215. }
  1216. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1217. return this;
  1218. };
  1219. }(),
  1220. applyAxisAngle: function () {
  1221. var quaternion = new THREE.Quaternion();
  1222. return function ( axis, angle ) {
  1223. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1224. return this;
  1225. };
  1226. }(),
  1227. projectOnVector: function () {
  1228. var v1 = new THREE.Vector3();
  1229. return function ( vector ) {
  1230. v1.copy( vector ).normalize();
  1231. var d = this.dot( v1 );
  1232. return this.copy( v1 ).multiplyScalar( d );
  1233. };
  1234. }(),
  1235. projectOnPlane: function () {
  1236. var v1 = new THREE.Vector3();
  1237. return function ( planeNormal ) {
  1238. v1.copy( this ).projectOnVector( planeNormal );
  1239. return this.sub( v1 );
  1240. }
  1241. }(),
  1242. reflect: function () {
  1243. // reflect incident vector off plane orthogonal to normal
  1244. // normal is assumed to have unit length
  1245. var v1 = new THREE.Vector3();
  1246. return function ( normal ) {
  1247. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1248. }
  1249. }()
  1250. } );
  1251. /**
  1252. * @author supereggbert / http://www.paulbrunt.co.uk/
  1253. * @author philogb / http://blog.thejit.org/
  1254. * @author mikael emtinger / http://gomo.se/
  1255. * @author egraether / http://egraether.com/
  1256. * @author WestLangley / http://github.com/WestLangley
  1257. */
  1258. THREE.Vector4 = function ( x, y, z, w ) {
  1259. this.x = x || 0;
  1260. this.y = y || 0;
  1261. this.z = z || 0;
  1262. this.w = ( w !== undefined ) ? w : 1;
  1263. };
  1264. THREE.Vector4.prototype = {
  1265. constructor: THREE.Vector4,
  1266. set: function ( x, y, z, w ) {
  1267. this.x = x;
  1268. this.y = y;
  1269. this.z = z;
  1270. this.w = w;
  1271. return this;
  1272. },
  1273. setX: function ( x ) {
  1274. this.x = x;
  1275. return this;
  1276. },
  1277. setY: function ( y ) {
  1278. this.y = y;
  1279. return this;
  1280. },
  1281. setZ: function ( z ) {
  1282. this.z = z;
  1283. return this;
  1284. },
  1285. setW: function ( w ) {
  1286. this.w = w;
  1287. return this;
  1288. },
  1289. setComponent: function ( index, value ) {
  1290. switch ( index ) {
  1291. case 0: this.x = value; break;
  1292. case 1: this.y = value; break;
  1293. case 2: this.z = value; break;
  1294. case 3: this.w = value; break;
  1295. default: throw new Error( "index is out of range: " + index );
  1296. }
  1297. },
  1298. getComponent: function ( index ) {
  1299. switch ( index ) {
  1300. case 0: return this.x;
  1301. case 1: return this.y;
  1302. case 2: return this.z;
  1303. case 3: return this.w;
  1304. default: throw new Error( "index is out of range: " + index );
  1305. }
  1306. },
  1307. copy: function ( v ) {
  1308. this.x = v.x;
  1309. this.y = v.y;
  1310. this.z = v.z;
  1311. this.w = ( v.w !== undefined ) ? v.w : 1;
  1312. return this;
  1313. },
  1314. add: function ( v, w ) {
  1315. if ( w !== undefined ) {
  1316. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1317. return this.addVectors( v, w );
  1318. }
  1319. this.x += v.x;
  1320. this.y += v.y;
  1321. this.z += v.z;
  1322. this.w += v.w;
  1323. return this;
  1324. },
  1325. addScalar: function ( s ) {
  1326. this.x += s;
  1327. this.y += s;
  1328. this.z += s;
  1329. this.w += s;
  1330. return this;
  1331. },
  1332. addVectors: function ( a, b ) {
  1333. this.x = a.x + b.x;
  1334. this.y = a.y + b.y;
  1335. this.z = a.z + b.z;
  1336. this.w = a.w + b.w;
  1337. return this;
  1338. },
  1339. sub: function ( v, w ) {
  1340. if ( w !== undefined ) {
  1341. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1342. return this.subVectors( v, w );
  1343. }
  1344. this.x -= v.x;
  1345. this.y -= v.y;
  1346. this.z -= v.z;
  1347. this.w -= v.w;
  1348. return this;
  1349. },
  1350. subVectors: function ( a, b ) {
  1351. this.x = a.x - b.x;
  1352. this.y = a.y - b.y;
  1353. this.z = a.z - b.z;
  1354. this.w = a.w - b.w;
  1355. return this;
  1356. },
  1357. multiplyScalar: function ( scalar ) {
  1358. this.x *= scalar;
  1359. this.y *= scalar;
  1360. this.z *= scalar;
  1361. this.w *= scalar;
  1362. return this;
  1363. },
  1364. applyMatrix4: function ( m ) {
  1365. var x = this.x;
  1366. var y = this.y;
  1367. var z = this.z;
  1368. var w = this.w;
  1369. var e = m.elements;
  1370. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1371. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1372. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1373. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1374. return this;
  1375. },
  1376. divideScalar: function ( scalar ) {
  1377. if ( scalar !== 0 ) {
  1378. var invScalar = 1 / scalar;
  1379. this.x *= invScalar;
  1380. this.y *= invScalar;
  1381. this.z *= invScalar;
  1382. this.w *= invScalar;
  1383. } else {
  1384. this.x = 0;
  1385. this.y = 0;
  1386. this.z = 0;
  1387. this.w = 1;
  1388. }
  1389. return this;
  1390. },
  1391. setAxisAngleFromQuaternion: function ( q ) {
  1392. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1393. // q is assumed to be normalized
  1394. this.w = 2 * Math.acos( q.w );
  1395. var s = Math.sqrt( 1 - q.w * q.w );
  1396. if ( s < 0.0001 ) {
  1397. this.x = 1;
  1398. this.y = 0;
  1399. this.z = 0;
  1400. } else {
  1401. this.x = q.x / s;
  1402. this.y = q.y / s;
  1403. this.z = q.z / s;
  1404. }
  1405. return this;
  1406. },
  1407. setAxisAngleFromRotationMatrix: function ( m ) {
  1408. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1409. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1410. var angle, x, y, z, // variables for result
  1411. epsilon = 0.01, // margin to allow for rounding errors
  1412. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1413. te = m.elements,
  1414. m11 = te[0], m12 = te[4], m13 = te[8],
  1415. m21 = te[1], m22 = te[5], m23 = te[9],
  1416. m31 = te[2], m32 = te[6], m33 = te[10];
  1417. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1418. && ( Math.abs( m13 - m31 ) < epsilon )
  1419. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1420. // singularity found
  1421. // first check for identity matrix which must have +1 for all terms
  1422. // in leading diagonal and zero in other terms
  1423. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1424. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1425. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1426. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1427. // this singularity is identity matrix so angle = 0
  1428. this.set( 1, 0, 0, 0 );
  1429. return this; // zero angle, arbitrary axis
  1430. }
  1431. // otherwise this singularity is angle = 180
  1432. angle = Math.PI;
  1433. var xx = ( m11 + 1 ) / 2;
  1434. var yy = ( m22 + 1 ) / 2;
  1435. var zz = ( m33 + 1 ) / 2;
  1436. var xy = ( m12 + m21 ) / 4;
  1437. var xz = ( m13 + m31 ) / 4;
  1438. var yz = ( m23 + m32 ) / 4;
  1439. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1440. if ( xx < epsilon ) {
  1441. x = 0;
  1442. y = 0.707106781;
  1443. z = 0.707106781;
  1444. } else {
  1445. x = Math.sqrt( xx );
  1446. y = xy / x;
  1447. z = xz / x;
  1448. }
  1449. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1450. if ( yy < epsilon ) {
  1451. x = 0.707106781;
  1452. y = 0;
  1453. z = 0.707106781;
  1454. } else {
  1455. y = Math.sqrt( yy );
  1456. x = xy / y;
  1457. z = yz / y;
  1458. }
  1459. } else { // m33 is the largest diagonal term so base result on this
  1460. if ( zz < epsilon ) {
  1461. x = 0.707106781;
  1462. y = 0.707106781;
  1463. z = 0;
  1464. } else {
  1465. z = Math.sqrt( zz );
  1466. x = xz / z;
  1467. y = yz / z;
  1468. }
  1469. }
  1470. this.set( x, y, z, angle );
  1471. return this; // return 180 deg rotation
  1472. }
  1473. // as we have reached here there are no singularities so we can handle normally
  1474. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1475. + ( m13 - m31 ) * ( m13 - m31 )
  1476. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1477. if ( Math.abs( s ) < 0.001 ) s = 1;
  1478. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1479. // caught by singularity test above, but I've left it in just in case
  1480. this.x = ( m32 - m23 ) / s;
  1481. this.y = ( m13 - m31 ) / s;
  1482. this.z = ( m21 - m12 ) / s;
  1483. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1484. return this;
  1485. },
  1486. min: function ( v ) {
  1487. if ( this.x > v.x ) {
  1488. this.x = v.x;
  1489. }
  1490. if ( this.y > v.y ) {
  1491. this.y = v.y;
  1492. }
  1493. if ( this.z > v.z ) {
  1494. this.z = v.z;
  1495. }
  1496. if ( this.w > v.w ) {
  1497. this.w = v.w;
  1498. }
  1499. return this;
  1500. },
  1501. max: function ( v ) {
  1502. if ( this.x < v.x ) {
  1503. this.x = v.x;
  1504. }
  1505. if ( this.y < v.y ) {
  1506. this.y = v.y;
  1507. }
  1508. if ( this.z < v.z ) {
  1509. this.z = v.z;
  1510. }
  1511. if ( this.w < v.w ) {
  1512. this.w = v.w;
  1513. }
  1514. return this;
  1515. },
  1516. clamp: function ( min, max ) {
  1517. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1518. if ( this.x < min.x ) {
  1519. this.x = min.x;
  1520. } else if ( this.x > max.x ) {
  1521. this.x = max.x;
  1522. }
  1523. if ( this.y < min.y ) {
  1524. this.y = min.y;
  1525. } else if ( this.y > max.y ) {
  1526. this.y = max.y;
  1527. }
  1528. if ( this.z < min.z ) {
  1529. this.z = min.z;
  1530. } else if ( this.z > max.z ) {
  1531. this.z = max.z;
  1532. }
  1533. if ( this.w < min.w ) {
  1534. this.w = min.w;
  1535. } else if ( this.w > max.w ) {
  1536. this.w = max.w;
  1537. }
  1538. return this;
  1539. },
  1540. negate: function() {
  1541. return this.multiplyScalar( -1 );
  1542. },
  1543. dot: function ( v ) {
  1544. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1545. },
  1546. lengthSq: function () {
  1547. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1548. },
  1549. length: function () {
  1550. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1551. },
  1552. lengthManhattan: function () {
  1553. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1554. },
  1555. normalize: function () {
  1556. return this.divideScalar( this.length() );
  1557. },
  1558. setLength: function ( l ) {
  1559. var oldLength = this.length();
  1560. if ( oldLength !== 0 && l !== oldLength ) {
  1561. this.multiplyScalar( l / oldLength );
  1562. }
  1563. return this;
  1564. },
  1565. lerp: function ( v, alpha ) {
  1566. this.x += ( v.x - this.x ) * alpha;
  1567. this.y += ( v.y - this.y ) * alpha;
  1568. this.z += ( v.z - this.z ) * alpha;
  1569. this.w += ( v.w - this.w ) * alpha;
  1570. return this;
  1571. },
  1572. equals: function ( v ) {
  1573. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1574. },
  1575. fromArray: function ( array ) {
  1576. this.x = array[ 0 ];
  1577. this.y = array[ 1 ];
  1578. this.z = array[ 2 ];
  1579. this.w = array[ 3 ];
  1580. return this;
  1581. },
  1582. toArray: function () {
  1583. return [ this.x, this.y, this.z, this.w ];
  1584. },
  1585. clone: function () {
  1586. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1587. }
  1588. };
  1589. /**
  1590. * @author mrdoob / http://mrdoob.com/
  1591. * @author WestLangley / http://github.com/WestLangley
  1592. * @author bhouston / http://exocortex.com
  1593. */
  1594. THREE.Euler = function ( x, y, z, order ) {
  1595. this._x = x || 0;
  1596. this._y = y || 0;
  1597. this._z = z || 0;
  1598. this._order = order || THREE.Euler.DefaultOrder;
  1599. };
  1600. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1601. THREE.Euler.DefaultOrder = 'XYZ';
  1602. THREE.Euler.prototype = {
  1603. constructor: THREE.Euler,
  1604. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1605. _quaternion: undefined,
  1606. _updateQuaternion: function () {
  1607. if ( this._quaternion !== undefined ) {
  1608. this._quaternion.setFromEuler( this, false );
  1609. }
  1610. },
  1611. get x () {
  1612. return this._x;
  1613. },
  1614. set x ( value ) {
  1615. this._x = value;
  1616. this._updateQuaternion();
  1617. },
  1618. get y () {
  1619. return this._y;
  1620. },
  1621. set y ( value ) {
  1622. this._y = value;
  1623. this._updateQuaternion();
  1624. },
  1625. get z () {
  1626. return this._z;
  1627. },
  1628. set z ( value ) {
  1629. this._z = value;
  1630. this._updateQuaternion();
  1631. },
  1632. get order () {
  1633. return this._order;
  1634. },
  1635. set order ( value ) {
  1636. this._order = value;
  1637. this._updateQuaternion();
  1638. },
  1639. set: function ( x, y, z, order ) {
  1640. this._x = x;
  1641. this._y = y;
  1642. this._z = z;
  1643. this._order = order || this._order;
  1644. this._updateQuaternion();
  1645. return this;
  1646. },
  1647. copy: function ( euler ) {
  1648. this._x = euler._x;
  1649. this._y = euler._y;
  1650. this._z = euler._z;
  1651. this._order = euler._order;
  1652. this._updateQuaternion();
  1653. return this;
  1654. },
  1655. setFromRotationMatrix: function ( m, order ) {
  1656. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1657. // clamp, to handle numerical problems
  1658. function clamp( x ) {
  1659. return Math.min( Math.max( x, -1 ), 1 );
  1660. }
  1661. var te = m.elements;
  1662. var m11 = te[0], m12 = te[4], m13 = te[8];
  1663. var m21 = te[1], m22 = te[5], m23 = te[9];
  1664. var m31 = te[2], m32 = te[6], m33 = te[10];
  1665. order = order || this._order;
  1666. if ( order === 'XYZ' ) {
  1667. this._y = Math.asin( clamp( m13 ) );
  1668. if ( Math.abs( m13 ) < 0.99999 ) {
  1669. this._x = Math.atan2( - m23, m33 );
  1670. this._z = Math.atan2( - m12, m11 );
  1671. } else {
  1672. this._x = Math.atan2( m32, m22 );
  1673. this._z = 0;
  1674. }
  1675. } else if ( order === 'YXZ' ) {
  1676. this._x = Math.asin( - clamp( m23 ) );
  1677. if ( Math.abs( m23 ) < 0.99999 ) {
  1678. this._y = Math.atan2( m13, m33 );
  1679. this._z = Math.atan2( m21, m22 );
  1680. } else {
  1681. this._y = Math.atan2( - m31, m11 );
  1682. this._z = 0;
  1683. }
  1684. } else if ( order === 'ZXY' ) {
  1685. this._x = Math.asin( clamp( m32 ) );
  1686. if ( Math.abs( m32 ) < 0.99999 ) {
  1687. this._y = Math.atan2( - m31, m33 );
  1688. this._z = Math.atan2( - m12, m22 );
  1689. } else {
  1690. this._y = 0;
  1691. this._z = Math.atan2( m21, m11 );
  1692. }
  1693. } else if ( order === 'ZYX' ) {
  1694. this._y = Math.asin( - clamp( m31 ) );
  1695. if ( Math.abs( m31 ) < 0.99999 ) {
  1696. this._x = Math.atan2( m32, m33 );
  1697. this._z = Math.atan2( m21, m11 );
  1698. } else {
  1699. this._x = 0;
  1700. this._z = Math.atan2( - m12, m22 );
  1701. }
  1702. } else if ( order === 'YZX' ) {
  1703. this._z = Math.asin( clamp( m21 ) );
  1704. if ( Math.abs( m21 ) < 0.99999 ) {
  1705. this._x = Math.atan2( - m23, m22 );
  1706. this._y = Math.atan2( - m31, m11 );
  1707. } else {
  1708. this._x = 0;
  1709. this._y = Math.atan2( m13, m33 );
  1710. }
  1711. } else if ( order === 'XZY' ) {
  1712. this._z = Math.asin( - clamp( m12 ) );
  1713. if ( Math.abs( m12 ) < 0.99999 ) {
  1714. this._x = Math.atan2( m32, m22 );
  1715. this._y = Math.atan2( m13, m11 );
  1716. } else {
  1717. this._x = Math.atan2( - m23, m33 );
  1718. this._y = 0;
  1719. }
  1720. } else {
  1721. console.warn( 'WARNING: Euler.setFromRotationMatrix() given unsupported order: ' + order )
  1722. }
  1723. this._order = order;
  1724. this._updateQuaternion();
  1725. return this;
  1726. },
  1727. setFromQuaternion: function ( q, order, update ) {
  1728. // q is assumed to be normalized
  1729. // clamp, to handle numerical problems
  1730. function clamp( x ) {
  1731. return Math.min( Math.max( x, -1 ), 1 );
  1732. }
  1733. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1734. var sqx = q.x * q.x;
  1735. var sqy = q.y * q.y;
  1736. var sqz = q.z * q.z;
  1737. var sqw = q.w * q.w;
  1738. order = order || this._order;
  1739. if ( order === 'XYZ' ) {
  1740. this._x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1741. this._y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  1742. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1743. } else if ( order === 'YXZ' ) {
  1744. this._x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  1745. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1746. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1747. } else if ( order === 'ZXY' ) {
  1748. this._x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  1749. this._y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1750. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1751. } else if ( order === 'ZYX' ) {
  1752. this._x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1753. this._y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  1754. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1755. } else if ( order === 'YZX' ) {
  1756. this._x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1757. this._y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1758. this._z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  1759. } else if ( order === 'XZY' ) {
  1760. this._x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1761. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1762. this._z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  1763. } else {
  1764. console.warn( 'WARNING: Euler.setFromQuaternion() given unsupported order: ' + order )
  1765. }
  1766. this._order = order;
  1767. if ( update !== false ) this._updateQuaternion();
  1768. return this;
  1769. },
  1770. reorder: function () {
  1771. // WARNING: this discards revolution information -bhouston
  1772. var q = new THREE.Quaternion();
  1773. return function ( newOrder ) {
  1774. q.setFromEuler( this );
  1775. this.setFromQuaternion( q, newOrder );
  1776. };
  1777. }(),
  1778. fromArray: function ( array ) {
  1779. this._x = array[ 0 ];
  1780. this._y = array[ 1 ];
  1781. this._z = array[ 2 ];
  1782. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  1783. this._updateQuaternion();
  1784. return this;
  1785. },
  1786. toArray: function () {
  1787. return [ this._x, this._y, this._z, this._order ];
  1788. },
  1789. equals: function ( euler ) {
  1790. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  1791. },
  1792. clone: function () {
  1793. return new THREE.Euler( this._x, this._y, this._z, this._order );
  1794. }
  1795. };
  1796. /**
  1797. * @author bhouston / http://exocortex.com
  1798. */
  1799. THREE.Line3 = function ( start, end ) {
  1800. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1801. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1802. };
  1803. THREE.Line3.prototype = {
  1804. constructor: THREE.Line3,
  1805. set: function ( start, end ) {
  1806. this.start.copy( start );
  1807. this.end.copy( end );
  1808. return this;
  1809. },
  1810. copy: function ( line ) {
  1811. this.start.copy( line.start );
  1812. this.end.copy( line.end );
  1813. return this;
  1814. },
  1815. center: function ( optionalTarget ) {
  1816. var result = optionalTarget || new THREE.Vector3();
  1817. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1818. },
  1819. delta: function ( optionalTarget ) {
  1820. var result = optionalTarget || new THREE.Vector3();
  1821. return result.subVectors( this.end, this.start );
  1822. },
  1823. distanceSq: function () {
  1824. return this.start.distanceToSquared( this.end );
  1825. },
  1826. distance: function () {
  1827. return this.start.distanceTo( this.end );
  1828. },
  1829. at: function ( t, optionalTarget ) {
  1830. var result = optionalTarget || new THREE.Vector3();
  1831. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1832. },
  1833. closestPointToPointParameter: function() {
  1834. var startP = new THREE.Vector3();
  1835. var startEnd = new THREE.Vector3();
  1836. return function ( point, clampToLine ) {
  1837. startP.subVectors( point, this.start );
  1838. startEnd.subVectors( this.end, this.start );
  1839. var startEnd2 = startEnd.dot( startEnd );
  1840. var startEnd_startP = startEnd.dot( startP );
  1841. var t = startEnd_startP / startEnd2;
  1842. if ( clampToLine ) {
  1843. t = THREE.Math.clamp( t, 0, 1 );
  1844. }
  1845. return t;
  1846. };
  1847. }(),
  1848. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1849. var t = this.closestPointToPointParameter( point, clampToLine );
  1850. var result = optionalTarget || new THREE.Vector3();
  1851. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1852. },
  1853. applyMatrix4: function ( matrix ) {
  1854. this.start.applyMatrix4( matrix );
  1855. this.end.applyMatrix4( matrix );
  1856. return this;
  1857. },
  1858. equals: function ( line ) {
  1859. return line.start.equals( this.start ) && line.end.equals( this.end );
  1860. },
  1861. clone: function () {
  1862. return new THREE.Line3().copy( this );
  1863. }
  1864. };
  1865. /**
  1866. * @author bhouston / http://exocortex.com
  1867. */
  1868. THREE.Box2 = function ( min, max ) {
  1869. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1870. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1871. };
  1872. THREE.Box2.prototype = {
  1873. constructor: THREE.Box2,
  1874. set: function ( min, max ) {
  1875. this.min.copy( min );
  1876. this.max.copy( max );
  1877. return this;
  1878. },
  1879. setFromPoints: function ( points ) {
  1880. if ( points.length > 0 ) {
  1881. var point = points[ 0 ];
  1882. this.min.copy( point );
  1883. this.max.copy( point );
  1884. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1885. point = points[ i ];
  1886. if ( point.x < this.min.x ) {
  1887. this.min.x = point.x;
  1888. } else if ( point.x > this.max.x ) {
  1889. this.max.x = point.x;
  1890. }
  1891. if ( point.y < this.min.y ) {
  1892. this.min.y = point.y;
  1893. } else if ( point.y > this.max.y ) {
  1894. this.max.y = point.y;
  1895. }
  1896. }
  1897. } else {
  1898. this.makeEmpty();
  1899. }
  1900. return this;
  1901. },
  1902. setFromCenterAndSize: function () {
  1903. var v1 = new THREE.Vector2();
  1904. return function ( center, size ) {
  1905. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1906. this.min.copy( center ).sub( halfSize );
  1907. this.max.copy( center ).add( halfSize );
  1908. return this;
  1909. };
  1910. }(),
  1911. copy: function ( box ) {
  1912. this.min.copy( box.min );
  1913. this.max.copy( box.max );
  1914. return this;
  1915. },
  1916. makeEmpty: function () {
  1917. this.min.x = this.min.y = Infinity;
  1918. this.max.x = this.max.y = -Infinity;
  1919. return this;
  1920. },
  1921. empty: function () {
  1922. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1923. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1924. },
  1925. center: function ( optionalTarget ) {
  1926. var result = optionalTarget || new THREE.Vector2();
  1927. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1928. },
  1929. size: function ( optionalTarget ) {
  1930. var result = optionalTarget || new THREE.Vector2();
  1931. return result.subVectors( this.max, this.min );
  1932. },
  1933. expandByPoint: function ( point ) {
  1934. this.min.min( point );
  1935. this.max.max( point );
  1936. return this;
  1937. },
  1938. expandByVector: function ( vector ) {
  1939. this.min.sub( vector );
  1940. this.max.add( vector );
  1941. return this;
  1942. },
  1943. expandByScalar: function ( scalar ) {
  1944. this.min.addScalar( -scalar );
  1945. this.max.addScalar( scalar );
  1946. return this;
  1947. },
  1948. containsPoint: function ( point ) {
  1949. if ( point.x < this.min.x || point.x > this.max.x ||
  1950. point.y < this.min.y || point.y > this.max.y ) {
  1951. return false;
  1952. }
  1953. return true;
  1954. },
  1955. containsBox: function ( box ) {
  1956. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1957. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1958. return true;
  1959. }
  1960. return false;
  1961. },
  1962. getParameter: function ( point, optionalTarget ) {
  1963. // This can potentially have a divide by zero if the box
  1964. // has a size dimension of 0.
  1965. var result = optionalTarget || new THREE.Vector2();
  1966. return result.set(
  1967. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1968. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1969. );
  1970. },
  1971. isIntersectionBox: function ( box ) {
  1972. // using 6 splitting planes to rule out intersections.
  1973. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1974. box.max.y < this.min.y || box.min.y > this.max.y ) {
  1975. return false;
  1976. }
  1977. return true;
  1978. },
  1979. clampPoint: function ( point, optionalTarget ) {
  1980. var result = optionalTarget || new THREE.Vector2();
  1981. return result.copy( point ).clamp( this.min, this.max );
  1982. },
  1983. distanceToPoint: function () {
  1984. var v1 = new THREE.Vector2();
  1985. return function ( point ) {
  1986. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1987. return clampedPoint.sub( point ).length();
  1988. };
  1989. }(),
  1990. intersect: function ( box ) {
  1991. this.min.max( box.min );
  1992. this.max.min( box.max );
  1993. return this;
  1994. },
  1995. union: function ( box ) {
  1996. this.min.min( box.min );
  1997. this.max.max( box.max );
  1998. return this;
  1999. },
  2000. translate: function ( offset ) {
  2001. this.min.add( offset );
  2002. this.max.add( offset );
  2003. return this;
  2004. },
  2005. equals: function ( box ) {
  2006. return box.min.equals( this.min ) && box.max.equals( this.max );
  2007. },
  2008. clone: function () {
  2009. return new THREE.Box2().copy( this );
  2010. }
  2011. };
  2012. /**
  2013. * @author bhouston / http://exocortex.com
  2014. * @author WestLangley / http://github.com/WestLangley
  2015. */
  2016. THREE.Box3 = function ( min, max ) {
  2017. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2018. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  2019. };
  2020. THREE.Box3.prototype = {
  2021. constructor: THREE.Box3,
  2022. set: function ( min, max ) {
  2023. this.min.copy( min );
  2024. this.max.copy( max );
  2025. return this;
  2026. },
  2027. addPoint: function ( point ) {
  2028. if ( point.x < this.min.x ) {
  2029. this.min.x = point.x;
  2030. } else if ( point.x > this.max.x ) {
  2031. this.max.x = point.x;
  2032. }
  2033. if ( point.y < this.min.y ) {
  2034. this.min.y = point.y;
  2035. } else if ( point.y > this.max.y ) {
  2036. this.max.y = point.y;
  2037. }
  2038. if ( point.z < this.min.z ) {
  2039. this.min.z = point.z;
  2040. } else if ( point.z > this.max.z ) {
  2041. this.max.z = point.z;
  2042. }
  2043. },
  2044. setFromPoints: function ( points ) {
  2045. if ( points.length > 0 ) {
  2046. var point = points[ 0 ];
  2047. this.min.copy( point );
  2048. this.max.copy( point );
  2049. for ( var i = 1, il = points.length; i < il; i ++ ) {
  2050. this.addPoint( points[ i ] )
  2051. }
  2052. } else {
  2053. this.makeEmpty();
  2054. }
  2055. return this;
  2056. },
  2057. setFromCenterAndSize: function() {
  2058. var v1 = new THREE.Vector3();
  2059. return function ( center, size ) {
  2060. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2061. this.min.copy( center ).sub( halfSize );
  2062. this.max.copy( center ).add( halfSize );
  2063. return this;
  2064. };
  2065. }(),
  2066. setFromObject: function() {
  2067. // Computes the world-axis-aligned bounding box of an object (including its children),
  2068. // accounting for both the object's, and childrens', world transforms
  2069. var v1 = new THREE.Vector3();
  2070. return function( object ) {
  2071. var scope = this;
  2072. object.updateMatrixWorld( true );
  2073. this.makeEmpty();
  2074. object.traverse( function ( node ) {
  2075. if ( node.geometry !== undefined && node.geometry.vertices !== undefined ) {
  2076. var vertices = node.geometry.vertices;
  2077. for ( var i = 0, il = vertices.length; i < il; i++ ) {
  2078. v1.copy( vertices[ i ] );
  2079. v1.applyMatrix4( node.matrixWorld );
  2080. scope.expandByPoint( v1 );
  2081. }
  2082. }
  2083. } );
  2084. return this;
  2085. };
  2086. }(),
  2087. copy: function ( box ) {
  2088. this.min.copy( box.min );
  2089. this.max.copy( box.max );
  2090. return this;
  2091. },
  2092. makeEmpty: function () {
  2093. this.min.x = this.min.y = this.min.z = Infinity;
  2094. this.max.x = this.max.y = this.max.z = -Infinity;
  2095. return this;
  2096. },
  2097. empty: function () {
  2098. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2099. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2100. },
  2101. center: function ( optionalTarget ) {
  2102. var result = optionalTarget || new THREE.Vector3();
  2103. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2104. },
  2105. size: function ( optionalTarget ) {
  2106. var result = optionalTarget || new THREE.Vector3();
  2107. return result.subVectors( this.max, this.min );
  2108. },
  2109. expandByPoint: function ( point ) {
  2110. this.min.min( point );
  2111. this.max.max( point );
  2112. return this;
  2113. },
  2114. expandByVector: function ( vector ) {
  2115. this.min.sub( vector );
  2116. this.max.add( vector );
  2117. return this;
  2118. },
  2119. expandByScalar: function ( scalar ) {
  2120. this.min.addScalar( -scalar );
  2121. this.max.addScalar( scalar );
  2122. return this;
  2123. },
  2124. containsPoint: function ( point ) {
  2125. if ( point.x < this.min.x || point.x > this.max.x ||
  2126. point.y < this.min.y || point.y > this.max.y ||
  2127. point.z < this.min.z || point.z > this.max.z ) {
  2128. return false;
  2129. }
  2130. return true;
  2131. },
  2132. containsBox: function ( box ) {
  2133. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2134. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2135. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2136. return true;
  2137. }
  2138. return false;
  2139. },
  2140. getParameter: function ( point, optionalTarget ) {
  2141. // This can potentially have a divide by zero if the box
  2142. // has a size dimension of 0.
  2143. var result = optionalTarget || new THREE.Vector3();
  2144. return result.set(
  2145. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2146. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2147. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2148. );
  2149. },
  2150. isIntersectionBox: function ( box ) {
  2151. // using 6 splitting planes to rule out intersections.
  2152. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2153. box.max.y < this.min.y || box.min.y > this.max.y ||
  2154. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2155. return false;
  2156. }
  2157. return true;
  2158. },
  2159. clampPoint: function ( point, optionalTarget ) {
  2160. var result = optionalTarget || new THREE.Vector3();
  2161. return result.copy( point ).clamp( this.min, this.max );
  2162. },
  2163. distanceToPoint: function() {
  2164. var v1 = new THREE.Vector3();
  2165. return function ( point ) {
  2166. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2167. return clampedPoint.sub( point ).length();
  2168. };
  2169. }(),
  2170. getBoundingSphere: function() {
  2171. var v1 = new THREE.Vector3();
  2172. return function ( optionalTarget ) {
  2173. var result = optionalTarget || new THREE.Sphere();
  2174. result.center = this.center();
  2175. result.radius = this.size( v1 ).length() * 0.5;
  2176. return result;
  2177. };
  2178. }(),
  2179. intersect: function ( box ) {
  2180. this.min.max( box.min );
  2181. this.max.min( box.max );
  2182. return this;
  2183. },
  2184. union: function ( box ) {
  2185. this.min.min( box.min );
  2186. this.max.max( box.max );
  2187. return this;
  2188. },
  2189. applyMatrix4: function() {
  2190. var points = [
  2191. new THREE.Vector3(),
  2192. new THREE.Vector3(),
  2193. new THREE.Vector3(),
  2194. new THREE.Vector3(),
  2195. new THREE.Vector3(),
  2196. new THREE.Vector3(),
  2197. new THREE.Vector3(),
  2198. new THREE.Vector3()
  2199. ];
  2200. return function ( matrix ) {
  2201. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2202. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2203. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2204. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2205. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2206. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2207. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2208. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2209. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2210. this.makeEmpty();
  2211. this.setFromPoints( points );
  2212. return this;
  2213. };
  2214. }(),
  2215. translate: function ( offset ) {
  2216. this.min.add( offset );
  2217. this.max.add( offset );
  2218. return this;
  2219. },
  2220. equals: function ( box ) {
  2221. return box.min.equals( this.min ) && box.max.equals( this.max );
  2222. },
  2223. clone: function () {
  2224. return new THREE.Box3().copy( this );
  2225. }
  2226. };
  2227. /**
  2228. * @author alteredq / http://alteredqualia.com/
  2229. * @author WestLangley / http://github.com/WestLangley
  2230. * @author bhouston / http://exocortex.com
  2231. */
  2232. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2233. this.elements = new Float32Array(9);
  2234. this.set(
  2235. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  2236. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  2237. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  2238. );
  2239. };
  2240. THREE.Matrix3.prototype = {
  2241. constructor: THREE.Matrix3,
  2242. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2243. var te = this.elements;
  2244. te[0] = n11; te[3] = n12; te[6] = n13;
  2245. te[1] = n21; te[4] = n22; te[7] = n23;
  2246. te[2] = n31; te[5] = n32; te[8] = n33;
  2247. return this;
  2248. },
  2249. identity: function () {
  2250. this.set(
  2251. 1, 0, 0,
  2252. 0, 1, 0,
  2253. 0, 0, 1
  2254. );
  2255. return this;
  2256. },
  2257. copy: function ( m ) {
  2258. var me = m.elements;
  2259. this.set(
  2260. me[0], me[3], me[6],
  2261. me[1], me[4], me[7],
  2262. me[2], me[5], me[8]
  2263. );
  2264. return this;
  2265. },
  2266. multiplyVector3: function ( vector ) {
  2267. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2268. return vector.applyMatrix3( this );
  2269. },
  2270. multiplyVector3Array: function() {
  2271. var v1 = new THREE.Vector3();
  2272. return function ( a ) {
  2273. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2274. v1.x = a[ i ];
  2275. v1.y = a[ i + 1 ];
  2276. v1.z = a[ i + 2 ];
  2277. v1.applyMatrix3(this);
  2278. a[ i ] = v1.x;
  2279. a[ i + 1 ] = v1.y;
  2280. a[ i + 2 ] = v1.z;
  2281. }
  2282. return a;
  2283. };
  2284. }(),
  2285. multiplyScalar: function ( s ) {
  2286. var te = this.elements;
  2287. te[0] *= s; te[3] *= s; te[6] *= s;
  2288. te[1] *= s; te[4] *= s; te[7] *= s;
  2289. te[2] *= s; te[5] *= s; te[8] *= s;
  2290. return this;
  2291. },
  2292. determinant: function () {
  2293. var te = this.elements;
  2294. var a = te[0], b = te[1], c = te[2],
  2295. d = te[3], e = te[4], f = te[5],
  2296. g = te[6], h = te[7], i = te[8];
  2297. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2298. },
  2299. getInverse: function ( matrix, throwOnInvertible ) {
  2300. // input: THREE.Matrix4
  2301. // ( based on http://code.google.com/p/webgl-mjs/ )
  2302. var me = matrix.elements;
  2303. var te = this.elements;
  2304. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2305. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2306. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2307. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2308. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2309. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2310. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2311. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2312. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2313. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2314. // no inverse
  2315. if ( det === 0 ) {
  2316. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2317. if ( throwOnInvertible || false ) {
  2318. throw new Error( msg );
  2319. } else {
  2320. console.warn( msg );
  2321. }
  2322. this.identity();
  2323. return this;
  2324. }
  2325. this.multiplyScalar( 1.0 / det );
  2326. return this;
  2327. },
  2328. transpose: function () {
  2329. var tmp, m = this.elements;
  2330. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2331. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2332. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2333. return this;
  2334. },
  2335. getNormalMatrix: function ( m ) {
  2336. // input: THREE.Matrix4
  2337. this.getInverse( m ).transpose();
  2338. return this;
  2339. },
  2340. transposeIntoArray: function ( r ) {
  2341. var m = this.elements;
  2342. r[ 0 ] = m[ 0 ];
  2343. r[ 1 ] = m[ 3 ];
  2344. r[ 2 ] = m[ 6 ];
  2345. r[ 3 ] = m[ 1 ];
  2346. r[ 4 ] = m[ 4 ];
  2347. r[ 5 ] = m[ 7 ];
  2348. r[ 6 ] = m[ 2 ];
  2349. r[ 7 ] = m[ 5 ];
  2350. r[ 8 ] = m[ 8 ];
  2351. return this;
  2352. },
  2353. fromArray: function ( array ) {
  2354. this.elements.set( array );
  2355. return this;
  2356. },
  2357. toArray: function () {
  2358. var te = this.elements;
  2359. return [
  2360. te[ 0 ], te[ 1 ], te[ 2 ],
  2361. te[ 3 ], te[ 4 ], te[ 5 ],
  2362. te[ 6 ], te[ 7 ], te[ 8 ]
  2363. ];
  2364. },
  2365. clone: function () {
  2366. var te = this.elements;
  2367. return new THREE.Matrix3(
  2368. te[0], te[3], te[6],
  2369. te[1], te[4], te[7],
  2370. te[2], te[5], te[8]
  2371. );
  2372. }
  2373. };
  2374. /**
  2375. * @author mrdoob / http://mrdoob.com/
  2376. * @author supereggbert / http://www.paulbrunt.co.uk/
  2377. * @author philogb / http://blog.thejit.org/
  2378. * @author jordi_ros / http://plattsoft.com
  2379. * @author D1plo1d / http://github.com/D1plo1d
  2380. * @author alteredq / http://alteredqualia.com/
  2381. * @author mikael emtinger / http://gomo.se/
  2382. * @author timknip / http://www.floorplanner.com/
  2383. * @author bhouston / http://exocortex.com
  2384. * @author WestLangley / http://github.com/WestLangley
  2385. */
  2386. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2387. this.elements = new Float32Array( 16 );
  2388. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2389. // we should not support semi specification of Matrix4, it is just weird.
  2390. var te = this.elements;
  2391. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2392. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2393. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2394. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2395. };
  2396. THREE.Matrix4.prototype = {
  2397. constructor: THREE.Matrix4,
  2398. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2399. var te = this.elements;
  2400. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2401. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2402. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2403. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2404. return this;
  2405. },
  2406. identity: function () {
  2407. this.set(
  2408. 1, 0, 0, 0,
  2409. 0, 1, 0, 0,
  2410. 0, 0, 1, 0,
  2411. 0, 0, 0, 1
  2412. );
  2413. return this;
  2414. },
  2415. copy: function ( m ) {
  2416. this.elements.set( m.elements );
  2417. return this;
  2418. },
  2419. extractPosition: function ( m ) {
  2420. console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' );
  2421. return this.copyPosition( m );
  2422. },
  2423. copyPosition: function ( m ) {
  2424. var te = this.elements;
  2425. var me = m.elements;
  2426. te[12] = me[12];
  2427. te[13] = me[13];
  2428. te[14] = me[14];
  2429. return this;
  2430. },
  2431. extractRotation: function () {
  2432. var v1 = new THREE.Vector3();
  2433. return function ( m ) {
  2434. var te = this.elements;
  2435. var me = m.elements;
  2436. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2437. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2438. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2439. te[0] = me[0] * scaleX;
  2440. te[1] = me[1] * scaleX;
  2441. te[2] = me[2] * scaleX;
  2442. te[4] = me[4] * scaleY;
  2443. te[5] = me[5] * scaleY;
  2444. te[6] = me[6] * scaleY;
  2445. te[8] = me[8] * scaleZ;
  2446. te[9] = me[9] * scaleZ;
  2447. te[10] = me[10] * scaleZ;
  2448. return this;
  2449. };
  2450. }(),
  2451. makeRotationFromEuler: function ( euler ) {
  2452. if ( euler instanceof THREE.Euler === false ) {
  2453. console.error( 'ERROR: Matrix\'s .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  2454. }
  2455. var te = this.elements;
  2456. var x = euler.x, y = euler.y, z = euler.z;
  2457. var a = Math.cos( x ), b = Math.sin( x );
  2458. var c = Math.cos( y ), d = Math.sin( y );
  2459. var e = Math.cos( z ), f = Math.sin( z );
  2460. if ( euler.order === 'XYZ' ) {
  2461. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2462. te[0] = c * e;
  2463. te[4] = - c * f;
  2464. te[8] = d;
  2465. te[1] = af + be * d;
  2466. te[5] = ae - bf * d;
  2467. te[9] = - b * c;
  2468. te[2] = bf - ae * d;
  2469. te[6] = be + af * d;
  2470. te[10] = a * c;
  2471. } else if ( euler.order === 'YXZ' ) {
  2472. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2473. te[0] = ce + df * b;
  2474. te[4] = de * b - cf;
  2475. te[8] = a * d;
  2476. te[1] = a * f;
  2477. te[5] = a * e;
  2478. te[9] = - b;
  2479. te[2] = cf * b - de;
  2480. te[6] = df + ce * b;
  2481. te[10] = a * c;
  2482. } else if ( euler.order === 'ZXY' ) {
  2483. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2484. te[0] = ce - df * b;
  2485. te[4] = - a * f;
  2486. te[8] = de + cf * b;
  2487. te[1] = cf + de * b;
  2488. te[5] = a * e;
  2489. te[9] = df - ce * b;
  2490. te[2] = - a * d;
  2491. te[6] = b;
  2492. te[10] = a * c;
  2493. } else if ( euler.order === 'ZYX' ) {
  2494. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2495. te[0] = c * e;
  2496. te[4] = be * d - af;
  2497. te[8] = ae * d + bf;
  2498. te[1] = c * f;
  2499. te[5] = bf * d + ae;
  2500. te[9] = af * d - be;
  2501. te[2] = - d;
  2502. te[6] = b * c;
  2503. te[10] = a * c;
  2504. } else if ( euler.order === 'YZX' ) {
  2505. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2506. te[0] = c * e;
  2507. te[4] = bd - ac * f;
  2508. te[8] = bc * f + ad;
  2509. te[1] = f;
  2510. te[5] = a * e;
  2511. te[9] = - b * e;
  2512. te[2] = - d * e;
  2513. te[6] = ad * f + bc;
  2514. te[10] = ac - bd * f;
  2515. } else if ( euler.order === 'XZY' ) {
  2516. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2517. te[0] = c * e;
  2518. te[4] = - f;
  2519. te[8] = d * e;
  2520. te[1] = ac * f + bd;
  2521. te[5] = a * e;
  2522. te[9] = ad * f - bc;
  2523. te[2] = bc * f - ad;
  2524. te[6] = b * e;
  2525. te[10] = bd * f + ac;
  2526. }
  2527. // last column
  2528. te[3] = 0;
  2529. te[7] = 0;
  2530. te[11] = 0;
  2531. // bottom row
  2532. te[12] = 0;
  2533. te[13] = 0;
  2534. te[14] = 0;
  2535. te[15] = 1;
  2536. return this;
  2537. },
  2538. setRotationFromQuaternion: function ( q ) {
  2539. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' );
  2540. return this.makeRotationFromQuaternion( q );
  2541. },
  2542. makeRotationFromQuaternion: function ( q ) {
  2543. var te = this.elements;
  2544. var x = q.x, y = q.y, z = q.z, w = q.w;
  2545. var x2 = x + x, y2 = y + y, z2 = z + z;
  2546. var xx = x * x2, xy = x * y2, xz = x * z2;
  2547. var yy = y * y2, yz = y * z2, zz = z * z2;
  2548. var wx = w * x2, wy = w * y2, wz = w * z2;
  2549. te[0] = 1 - ( yy + zz );
  2550. te[4] = xy - wz;
  2551. te[8] = xz + wy;
  2552. te[1] = xy + wz;
  2553. te[5] = 1 - ( xx + zz );
  2554. te[9] = yz - wx;
  2555. te[2] = xz - wy;
  2556. te[6] = yz + wx;
  2557. te[10] = 1 - ( xx + yy );
  2558. // last column
  2559. te[3] = 0;
  2560. te[7] = 0;
  2561. te[11] = 0;
  2562. // bottom row
  2563. te[12] = 0;
  2564. te[13] = 0;
  2565. te[14] = 0;
  2566. te[15] = 1;
  2567. return this;
  2568. },
  2569. lookAt: function() {
  2570. var x = new THREE.Vector3();
  2571. var y = new THREE.Vector3();
  2572. var z = new THREE.Vector3();
  2573. return function ( eye, target, up ) {
  2574. var te = this.elements;
  2575. z.subVectors( eye, target ).normalize();
  2576. if ( z.length() === 0 ) {
  2577. z.z = 1;
  2578. }
  2579. x.crossVectors( up, z ).normalize();
  2580. if ( x.length() === 0 ) {
  2581. z.x += 0.0001;
  2582. x.crossVectors( up, z ).normalize();
  2583. }
  2584. y.crossVectors( z, x );
  2585. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2586. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2587. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2588. return this;
  2589. };
  2590. }(),
  2591. multiply: function ( m, n ) {
  2592. if ( n !== undefined ) {
  2593. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2594. return this.multiplyMatrices( m, n );
  2595. }
  2596. return this.multiplyMatrices( this, m );
  2597. },
  2598. multiplyMatrices: function ( a, b ) {
  2599. var ae = a.elements;
  2600. var be = b.elements;
  2601. var te = this.elements;
  2602. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2603. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2604. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2605. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2606. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2607. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2608. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2609. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2610. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2611. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2612. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2613. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2614. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2615. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2616. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2617. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2618. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2619. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2620. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2621. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2622. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2623. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2624. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2625. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2626. return this;
  2627. },
  2628. multiplyToArray: function ( a, b, r ) {
  2629. var te = this.elements;
  2630. this.multiplyMatrices( a, b );
  2631. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2632. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2633. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2634. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2635. return this;
  2636. },
  2637. multiplyScalar: function ( s ) {
  2638. var te = this.elements;
  2639. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2640. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2641. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2642. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2643. return this;
  2644. },
  2645. multiplyVector3: function ( vector ) {
  2646. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2647. return vector.applyProjection( this );
  2648. },
  2649. multiplyVector4: function ( vector ) {
  2650. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2651. return vector.applyMatrix4( this );
  2652. },
  2653. multiplyVector3Array: function() {
  2654. var v1 = new THREE.Vector3();
  2655. return function ( a ) {
  2656. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2657. v1.x = a[ i ];
  2658. v1.y = a[ i + 1 ];
  2659. v1.z = a[ i + 2 ];
  2660. v1.applyProjection( this );
  2661. a[ i ] = v1.x;
  2662. a[ i + 1 ] = v1.y;
  2663. a[ i + 2 ] = v1.z;
  2664. }
  2665. return a;
  2666. };
  2667. }(),
  2668. rotateAxis: function ( v ) {
  2669. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2670. v.transformDirection( this );
  2671. },
  2672. crossVector: function ( vector ) {
  2673. console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2674. return vector.applyMatrix4( this );
  2675. },
  2676. determinant: function () {
  2677. var te = this.elements;
  2678. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2679. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2680. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2681. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2682. //TODO: make this more efficient
  2683. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2684. return (
  2685. n41 * (
  2686. +n14 * n23 * n32
  2687. -n13 * n24 * n32
  2688. -n14 * n22 * n33
  2689. +n12 * n24 * n33
  2690. +n13 * n22 * n34
  2691. -n12 * n23 * n34
  2692. ) +
  2693. n42 * (
  2694. +n11 * n23 * n34
  2695. -n11 * n24 * n33
  2696. +n14 * n21 * n33
  2697. -n13 * n21 * n34
  2698. +n13 * n24 * n31
  2699. -n14 * n23 * n31
  2700. ) +
  2701. n43 * (
  2702. +n11 * n24 * n32
  2703. -n11 * n22 * n34
  2704. -n14 * n21 * n32
  2705. +n12 * n21 * n34
  2706. +n14 * n22 * n31
  2707. -n12 * n24 * n31
  2708. ) +
  2709. n44 * (
  2710. -n13 * n22 * n31
  2711. -n11 * n23 * n32
  2712. +n11 * n22 * n33
  2713. +n13 * n21 * n32
  2714. -n12 * n21 * n33
  2715. +n12 * n23 * n31
  2716. )
  2717. );
  2718. },
  2719. transpose: function () {
  2720. var te = this.elements;
  2721. var tmp;
  2722. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2723. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2724. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2725. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2726. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2727. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2728. return this;
  2729. },
  2730. flattenToArray: function ( flat ) {
  2731. var te = this.elements;
  2732. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2733. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2734. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2735. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2736. return flat;
  2737. },
  2738. flattenToArrayOffset: function( flat, offset ) {
  2739. var te = this.elements;
  2740. flat[ offset ] = te[0];
  2741. flat[ offset + 1 ] = te[1];
  2742. flat[ offset + 2 ] = te[2];
  2743. flat[ offset + 3 ] = te[3];
  2744. flat[ offset + 4 ] = te[4];
  2745. flat[ offset + 5 ] = te[5];
  2746. flat[ offset + 6 ] = te[6];
  2747. flat[ offset + 7 ] = te[7];
  2748. flat[ offset + 8 ] = te[8];
  2749. flat[ offset + 9 ] = te[9];
  2750. flat[ offset + 10 ] = te[10];
  2751. flat[ offset + 11 ] = te[11];
  2752. flat[ offset + 12 ] = te[12];
  2753. flat[ offset + 13 ] = te[13];
  2754. flat[ offset + 14 ] = te[14];
  2755. flat[ offset + 15 ] = te[15];
  2756. return flat;
  2757. },
  2758. getPosition: function() {
  2759. var v1 = new THREE.Vector3();
  2760. return function () {
  2761. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  2762. var te = this.elements;
  2763. return v1.set( te[12], te[13], te[14] );
  2764. };
  2765. }(),
  2766. setPosition: function ( v ) {
  2767. var te = this.elements;
  2768. te[12] = v.x;
  2769. te[13] = v.y;
  2770. te[14] = v.z;
  2771. return this;
  2772. },
  2773. getInverse: function ( m, throwOnInvertible ) {
  2774. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2775. var te = this.elements;
  2776. var me = m.elements;
  2777. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2778. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2779. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2780. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2781. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2782. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2783. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2784. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2785. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2786. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2787. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2788. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2789. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2790. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2791. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2792. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2793. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2794. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2795. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2796. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2797. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  2798. if ( det == 0 ) {
  2799. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2800. if ( throwOnInvertible || false ) {
  2801. throw new Error( msg );
  2802. } else {
  2803. console.warn( msg );
  2804. }
  2805. this.identity();
  2806. return this;
  2807. }
  2808. this.multiplyScalar( 1 / det );
  2809. return this;
  2810. },
  2811. translate: function ( v ) {
  2812. console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.');
  2813. },
  2814. rotateX: function ( angle ) {
  2815. console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.');
  2816. },
  2817. rotateY: function ( angle ) {
  2818. console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.');
  2819. },
  2820. rotateZ: function ( angle ) {
  2821. console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.');
  2822. },
  2823. rotateByAxis: function ( axis, angle ) {
  2824. console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.');
  2825. },
  2826. scale: function ( v ) {
  2827. var te = this.elements;
  2828. var x = v.x, y = v.y, z = v.z;
  2829. te[0] *= x; te[4] *= y; te[8] *= z;
  2830. te[1] *= x; te[5] *= y; te[9] *= z;
  2831. te[2] *= x; te[6] *= y; te[10] *= z;
  2832. te[3] *= x; te[7] *= y; te[11] *= z;
  2833. return this;
  2834. },
  2835. getMaxScaleOnAxis: function () {
  2836. var te = this.elements;
  2837. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2838. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2839. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2840. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2841. },
  2842. makeTranslation: function ( x, y, z ) {
  2843. this.set(
  2844. 1, 0, 0, x,
  2845. 0, 1, 0, y,
  2846. 0, 0, 1, z,
  2847. 0, 0, 0, 1
  2848. );
  2849. return this;
  2850. },
  2851. makeRotationX: function ( theta ) {
  2852. var c = Math.cos( theta ), s = Math.sin( theta );
  2853. this.set(
  2854. 1, 0, 0, 0,
  2855. 0, c, -s, 0,
  2856. 0, s, c, 0,
  2857. 0, 0, 0, 1
  2858. );
  2859. return this;
  2860. },
  2861. makeRotationY: function ( theta ) {
  2862. var c = Math.cos( theta ), s = Math.sin( theta );
  2863. this.set(
  2864. c, 0, s, 0,
  2865. 0, 1, 0, 0,
  2866. -s, 0, c, 0,
  2867. 0, 0, 0, 1
  2868. );
  2869. return this;
  2870. },
  2871. makeRotationZ: function ( theta ) {
  2872. var c = Math.cos( theta ), s = Math.sin( theta );
  2873. this.set(
  2874. c, -s, 0, 0,
  2875. s, c, 0, 0,
  2876. 0, 0, 1, 0,
  2877. 0, 0, 0, 1
  2878. );
  2879. return this;
  2880. },
  2881. makeRotationAxis: function ( axis, angle ) {
  2882. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2883. var c = Math.cos( angle );
  2884. var s = Math.sin( angle );
  2885. var t = 1 - c;
  2886. var x = axis.x, y = axis.y, z = axis.z;
  2887. var tx = t * x, ty = t * y;
  2888. this.set(
  2889. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2890. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2891. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2892. 0, 0, 0, 1
  2893. );
  2894. return this;
  2895. },
  2896. makeScale: function ( x, y, z ) {
  2897. this.set(
  2898. x, 0, 0, 0,
  2899. 0, y, 0, 0,
  2900. 0, 0, z, 0,
  2901. 0, 0, 0, 1
  2902. );
  2903. return this;
  2904. },
  2905. compose: function ( position, quaternion, scale ) {
  2906. this.makeRotationFromQuaternion( quaternion );
  2907. this.scale( scale );
  2908. this.setPosition( position );
  2909. return this;
  2910. },
  2911. decompose: function () {
  2912. var vector = new THREE.Vector3();
  2913. var matrix = new THREE.Matrix4();
  2914. return function ( position, quaternion, scale ) {
  2915. var te = this.elements;
  2916. var sx = vector.set( te[0], te[1], te[2] ).length();
  2917. var sy = vector.set( te[4], te[5], te[6] ).length();
  2918. var sz = vector.set( te[8], te[9], te[10] ).length();
  2919. // if determine is negative, we need to invert one scale
  2920. var det = this.determinant();
  2921. if( det < 0 ) {
  2922. sx = -sx;
  2923. }
  2924. position.x = te[12];
  2925. position.y = te[13];
  2926. position.z = te[14];
  2927. // scale the rotation part
  2928. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  2929. var invSX = 1 / sx;
  2930. var invSY = 1 / sy;
  2931. var invSZ = 1 / sz;
  2932. matrix.elements[0] *= invSX;
  2933. matrix.elements[1] *= invSX;
  2934. matrix.elements[2] *= invSX;
  2935. matrix.elements[4] *= invSY;
  2936. matrix.elements[5] *= invSY;
  2937. matrix.elements[6] *= invSY;
  2938. matrix.elements[8] *= invSZ;
  2939. matrix.elements[9] *= invSZ;
  2940. matrix.elements[10] *= invSZ;
  2941. quaternion.setFromRotationMatrix( matrix );
  2942. scale.x = sx;
  2943. scale.y = sy;
  2944. scale.z = sz;
  2945. return this;
  2946. };
  2947. }(),
  2948. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2949. var te = this.elements;
  2950. var x = 2 * near / ( right - left );
  2951. var y = 2 * near / ( top - bottom );
  2952. var a = ( right + left ) / ( right - left );
  2953. var b = ( top + bottom ) / ( top - bottom );
  2954. var c = - ( far + near ) / ( far - near );
  2955. var d = - 2 * far * near / ( far - near );
  2956. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2957. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2958. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2959. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2960. return this;
  2961. },
  2962. makePerspective: function ( fov, aspect, near, far ) {
  2963. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  2964. var ymin = - ymax;
  2965. var xmin = ymin * aspect;
  2966. var xmax = ymax * aspect;
  2967. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2968. },
  2969. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2970. var te = this.elements;
  2971. var w = right - left;
  2972. var h = top - bottom;
  2973. var p = far - near;
  2974. var x = ( right + left ) / w;
  2975. var y = ( top + bottom ) / h;
  2976. var z = ( far + near ) / p;
  2977. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2978. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2979. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  2980. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2981. return this;
  2982. },
  2983. fromArray: function ( array ) {
  2984. this.elements.set( array );
  2985. return this;
  2986. },
  2987. toArray: function () {
  2988. var te = this.elements;
  2989. return [
  2990. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  2991. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  2992. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  2993. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  2994. ];
  2995. },
  2996. clone: function () {
  2997. var te = this.elements;
  2998. return new THREE.Matrix4(
  2999. te[0], te[4], te[8], te[12],
  3000. te[1], te[5], te[9], te[13],
  3001. te[2], te[6], te[10], te[14],
  3002. te[3], te[7], te[11], te[15]
  3003. );
  3004. }
  3005. };
  3006. /**
  3007. * @author bhouston / http://exocortex.com
  3008. */
  3009. THREE.Ray = function ( origin, direction ) {
  3010. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  3011. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  3012. };
  3013. THREE.Ray.prototype = {
  3014. constructor: THREE.Ray,
  3015. set: function ( origin, direction ) {
  3016. this.origin.copy( origin );
  3017. this.direction.copy( direction );
  3018. return this;
  3019. },
  3020. copy: function ( ray ) {
  3021. this.origin.copy( ray.origin );
  3022. this.direction.copy( ray.direction );
  3023. return this;
  3024. },
  3025. at: function ( t, optionalTarget ) {
  3026. var result = optionalTarget || new THREE.Vector3();
  3027. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3028. },
  3029. recast: function () {
  3030. var v1 = new THREE.Vector3();
  3031. return function ( t ) {
  3032. this.origin.copy( this.at( t, v1 ) );
  3033. return this;
  3034. };
  3035. }(),
  3036. closestPointToPoint: function ( point, optionalTarget ) {
  3037. var result = optionalTarget || new THREE.Vector3();
  3038. result.subVectors( point, this.origin );
  3039. var directionDistance = result.dot( this.direction );
  3040. if ( directionDistance < 0 ) {
  3041. return result.copy( this.origin );
  3042. }
  3043. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3044. },
  3045. distanceToPoint: function () {
  3046. var v1 = new THREE.Vector3();
  3047. return function ( point ) {
  3048. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3049. // point behind the ray
  3050. if ( directionDistance < 0 ) {
  3051. return this.origin.distanceTo( point );
  3052. }
  3053. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3054. return v1.distanceTo( point );
  3055. };
  3056. }(),
  3057. distanceSqToSegment: function( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3058. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3059. // It returns the min distance between the ray and the segment
  3060. // defined by v0 and v1
  3061. // It can also set two optional targets :
  3062. // - The closest point on the ray
  3063. // - The closest point on the segment
  3064. var segCenter = v0.clone().add( v1 ).multiplyScalar( 0.5 );
  3065. var segDir = v1.clone().sub( v0 ).normalize();
  3066. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3067. var diff = this.origin.clone().sub( segCenter );
  3068. var a01 = - this.direction.dot( segDir );
  3069. var b0 = diff.dot( this.direction );
  3070. var b1 = - diff.dot( segDir );
  3071. var c = diff.lengthSq();
  3072. var det = Math.abs( 1 - a01 * a01 );
  3073. var s0, s1, sqrDist, extDet;
  3074. if ( det >= 0 ) {
  3075. // The ray and segment are not parallel.
  3076. s0 = a01 * b1 - b0;
  3077. s1 = a01 * b0 - b1;
  3078. extDet = segExtent * det;
  3079. if ( s0 >= 0 ) {
  3080. if ( s1 >= - extDet ) {
  3081. if ( s1 <= extDet ) {
  3082. // region 0
  3083. // Minimum at interior points of ray and segment.
  3084. var invDet = 1 / det;
  3085. s0 *= invDet;
  3086. s1 *= invDet;
  3087. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3088. } else {
  3089. // region 1
  3090. s1 = segExtent;
  3091. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3092. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3093. }
  3094. } else {
  3095. // region 5
  3096. s1 = - segExtent;
  3097. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3098. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3099. }
  3100. } else {
  3101. if ( s1 <= - extDet) {
  3102. // region 4
  3103. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3104. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3105. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3106. } else if ( s1 <= extDet ) {
  3107. // region 3
  3108. s0 = 0;
  3109. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3110. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3111. } else {
  3112. // region 2
  3113. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3114. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3115. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3116. }
  3117. }
  3118. } else {
  3119. // Ray and segment are parallel.
  3120. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3121. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3122. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3123. }
  3124. if ( optionalPointOnRay ) {
  3125. optionalPointOnRay.copy( this.direction.clone().multiplyScalar( s0 ).add( this.origin ) );
  3126. }
  3127. if ( optionalPointOnSegment ) {
  3128. optionalPointOnSegment.copy( segDir.clone().multiplyScalar( s1 ).add( segCenter ) );
  3129. }
  3130. return sqrDist;
  3131. },
  3132. isIntersectionSphere: function ( sphere ) {
  3133. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3134. },
  3135. isIntersectionPlane: function ( plane ) {
  3136. // check if the ray lies on the plane first
  3137. var distToPoint = plane.distanceToPoint( this.origin );
  3138. if ( distToPoint === 0 ) {
  3139. return true;
  3140. }
  3141. var denominator = plane.normal.dot( this.direction );
  3142. if ( denominator * distToPoint < 0 ) {
  3143. return true
  3144. }
  3145. // ray origin is behind the plane (and is pointing behind it)
  3146. return false;
  3147. },
  3148. distanceToPlane: function ( plane ) {
  3149. var denominator = plane.normal.dot( this.direction );
  3150. if ( denominator == 0 ) {
  3151. // line is coplanar, return origin
  3152. if( plane.distanceToPoint( this.origin ) == 0 ) {
  3153. return 0;
  3154. }
  3155. // Null is preferable to undefined since undefined means.... it is undefined
  3156. return null;
  3157. }
  3158. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3159. // Return if the ray never intersects the plane
  3160. return t >= 0 ? t : null;
  3161. },
  3162. intersectPlane: function ( plane, optionalTarget ) {
  3163. var t = this.distanceToPlane( plane );
  3164. if ( t === null ) {
  3165. return null;
  3166. }
  3167. return this.at( t, optionalTarget );
  3168. },
  3169. isIntersectionBox: function () {
  3170. var v = new THREE.Vector3();
  3171. return function ( box ) {
  3172. return this.intersectBox( box, v ) !== null;
  3173. }
  3174. }(),
  3175. intersectBox: function ( box , optionalTarget ) {
  3176. // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
  3177. var tmin,tmax,tymin,tymax,tzmin,tzmax;
  3178. var invdirx = 1/this.direction.x,
  3179. invdiry = 1/this.direction.y,
  3180. invdirz = 1/this.direction.z;
  3181. var origin = this.origin;
  3182. if (invdirx >= 0) {
  3183. tmin = (box.min.x - origin.x) * invdirx;
  3184. tmax = (box.max.x - origin.x) * invdirx;
  3185. } else {
  3186. tmin = (box.max.x - origin.x) * invdirx;
  3187. tmax = (box.min.x - origin.x) * invdirx;
  3188. }
  3189. if (invdiry >= 0) {
  3190. tymin = (box.min.y - origin.y) * invdiry;
  3191. tymax = (box.max.y - origin.y) * invdiry;
  3192. } else {
  3193. tymin = (box.max.y - origin.y) * invdiry;
  3194. tymax = (box.min.y - origin.y) * invdiry;
  3195. }
  3196. if ((tmin > tymax) || (tymin > tmax)) return null;
  3197. // These lines also handle the case where tmin or tmax is NaN
  3198. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3199. if (tymin > tmin || tmin !== tmin ) tmin = tymin;
  3200. if (tymax < tmax || tmax !== tmax ) tmax = tymax;
  3201. if (invdirz >= 0) {
  3202. tzmin = (box.min.z - origin.z) * invdirz;
  3203. tzmax = (box.max.z - origin.z) * invdirz;
  3204. } else {
  3205. tzmin = (box.max.z - origin.z) * invdirz;
  3206. tzmax = (box.min.z - origin.z) * invdirz;
  3207. }
  3208. if ((tmin > tzmax) || (tzmin > tmax)) return null;
  3209. if (tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3210. if (tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3211. //return point closest to the ray (positive side)
  3212. if ( tmax < 0 ) return null;
  3213. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3214. },
  3215. intersectTriangle: function() {
  3216. // Compute the offset origin, edges, and normal.
  3217. var diff = new THREE.Vector3();
  3218. var edge1 = new THREE.Vector3();
  3219. var edge2 = new THREE.Vector3();
  3220. var normal = new THREE.Vector3();
  3221. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3222. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3223. edge1.subVectors( b, a );
  3224. edge2.subVectors( c, a );
  3225. normal.crossVectors( edge1, edge2 );
  3226. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3227. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3228. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3229. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3230. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3231. var DdN = this.direction.dot( normal );
  3232. var sign;
  3233. if ( DdN > 0 ) {
  3234. if ( backfaceCulling ) return null;
  3235. sign = 1;
  3236. } else if ( DdN < 0 ) {
  3237. sign = - 1;
  3238. DdN = - DdN;
  3239. } else {
  3240. return null;
  3241. }
  3242. diff.subVectors( this.origin, a );
  3243. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3244. // b1 < 0, no intersection
  3245. if ( DdQxE2 < 0 ) {
  3246. return null;
  3247. }
  3248. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3249. // b2 < 0, no intersection
  3250. if ( DdE1xQ < 0 ) {
  3251. return null;
  3252. }
  3253. // b1+b2 > 1, no intersection
  3254. if ( DdQxE2 + DdE1xQ > DdN ) {
  3255. return null;
  3256. }
  3257. // Line intersects triangle, check if ray does.
  3258. var QdN = - sign * diff.dot( normal );
  3259. // t < 0, no intersection
  3260. if ( QdN < 0 ) {
  3261. return null;
  3262. }
  3263. // Ray intersects triangle.
  3264. return this.at( QdN / DdN, optionalTarget );
  3265. }
  3266. }(),
  3267. applyMatrix4: function ( matrix4 ) {
  3268. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3269. this.origin.applyMatrix4( matrix4 );
  3270. this.direction.sub( this.origin );
  3271. this.direction.normalize();
  3272. return this;
  3273. },
  3274. equals: function ( ray ) {
  3275. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3276. },
  3277. clone: function () {
  3278. return new THREE.Ray().copy( this );
  3279. }
  3280. };
  3281. /**
  3282. * @author bhouston / http://exocortex.com
  3283. * @author mrdoob / http://mrdoob.com/
  3284. */
  3285. THREE.Sphere = function ( center, radius ) {
  3286. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3287. this.radius = ( radius !== undefined ) ? radius : 0;
  3288. };
  3289. THREE.Sphere.prototype = {
  3290. constructor: THREE.Sphere,
  3291. set: function ( center, radius ) {
  3292. this.center.copy( center );
  3293. this.radius = radius;
  3294. return this;
  3295. },
  3296. setFromPoints: function () {
  3297. var box = new THREE.Box3();
  3298. return function ( points, optionalCenter ) {
  3299. var center = this.center;
  3300. if ( optionalCenter !== undefined ) {
  3301. center.copy( optionalCenter );
  3302. } else {
  3303. box.setFromPoints( points ).center( center );
  3304. }
  3305. var maxRadiusSq = 0;
  3306. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3307. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3308. }
  3309. this.radius = Math.sqrt( maxRadiusSq );
  3310. return this;
  3311. };
  3312. }(),
  3313. copy: function ( sphere ) {
  3314. this.center.copy( sphere.center );
  3315. this.radius = sphere.radius;
  3316. return this;
  3317. },
  3318. empty: function () {
  3319. return ( this.radius <= 0 );
  3320. },
  3321. containsPoint: function ( point ) {
  3322. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3323. },
  3324. distanceToPoint: function ( point ) {
  3325. return ( point.distanceTo( this.center ) - this.radius );
  3326. },
  3327. intersectsSphere: function ( sphere ) {
  3328. var radiusSum = this.radius + sphere.radius;
  3329. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3330. },
  3331. clampPoint: function ( point, optionalTarget ) {
  3332. var deltaLengthSq = this.center.distanceToSquared( point );
  3333. var result = optionalTarget || new THREE.Vector3();
  3334. result.copy( point );
  3335. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3336. result.sub( this.center ).normalize();
  3337. result.multiplyScalar( this.radius ).add( this.center );
  3338. }
  3339. return result;
  3340. },
  3341. getBoundingBox: function ( optionalTarget ) {
  3342. var box = optionalTarget || new THREE.Box3();
  3343. box.set( this.center, this.center );
  3344. box.expandByScalar( this.radius );
  3345. return box;
  3346. },
  3347. applyMatrix4: function ( matrix ) {
  3348. this.center.applyMatrix4( matrix );
  3349. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3350. return this;
  3351. },
  3352. translate: function ( offset ) {
  3353. this.center.add( offset );
  3354. return this;
  3355. },
  3356. equals: function ( sphere ) {
  3357. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3358. },
  3359. clone: function () {
  3360. return new THREE.Sphere().copy( this );
  3361. }
  3362. };
  3363. /**
  3364. * @author mrdoob / http://mrdoob.com/
  3365. * @author alteredq / http://alteredqualia.com/
  3366. * @author bhouston / http://exocortex.com
  3367. */
  3368. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3369. this.planes = [
  3370. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3371. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3372. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3373. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3374. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3375. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3376. ];
  3377. };
  3378. THREE.Frustum.prototype = {
  3379. constructor: THREE.Frustum,
  3380. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3381. var planes = this.planes;
  3382. planes[0].copy( p0 );
  3383. planes[1].copy( p1 );
  3384. planes[2].copy( p2 );
  3385. planes[3].copy( p3 );
  3386. planes[4].copy( p4 );
  3387. planes[5].copy( p5 );
  3388. return this;
  3389. },
  3390. copy: function ( frustum ) {
  3391. var planes = this.planes;
  3392. for( var i = 0; i < 6; i ++ ) {
  3393. planes[i].copy( frustum.planes[i] );
  3394. }
  3395. return this;
  3396. },
  3397. setFromMatrix: function ( m ) {
  3398. var planes = this.planes;
  3399. var me = m.elements;
  3400. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  3401. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  3402. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  3403. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  3404. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3405. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3406. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3407. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3408. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3409. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3410. return this;
  3411. },
  3412. intersectsObject: function () {
  3413. var sphere = new THREE.Sphere();
  3414. return function ( object ) {
  3415. var geometry = object.geometry;
  3416. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3417. sphere.copy( geometry.boundingSphere );
  3418. sphere.applyMatrix4( object.matrixWorld );
  3419. return this.intersectsSphere( sphere );
  3420. };
  3421. }(),
  3422. intersectsSphere: function ( sphere ) {
  3423. var planes = this.planes;
  3424. var center = sphere.center;
  3425. var negRadius = -sphere.radius;
  3426. for ( var i = 0; i < 6; i ++ ) {
  3427. var distance = planes[ i ].distanceToPoint( center );
  3428. if ( distance < negRadius ) {
  3429. return false;
  3430. }
  3431. }
  3432. return true;
  3433. },
  3434. intersectsBox : function() {
  3435. var p1 = new THREE.Vector3(),
  3436. p2 = new THREE.Vector3();
  3437. return function( box ) {
  3438. var planes = this.planes;
  3439. for ( var i = 0; i < 6 ; i ++ ) {
  3440. var plane = planes[i];
  3441. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3442. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3443. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3444. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3445. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3446. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3447. var d1 = plane.distanceToPoint( p1 );
  3448. var d2 = plane.distanceToPoint( p2 );
  3449. // if both outside plane, no intersection
  3450. if ( d1 < 0 && d2 < 0 ) {
  3451. return false;
  3452. }
  3453. }
  3454. return true;
  3455. };
  3456. }(),
  3457. containsPoint: function ( point ) {
  3458. var planes = this.planes;
  3459. for ( var i = 0; i < 6; i ++ ) {
  3460. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3461. return false;
  3462. }
  3463. }
  3464. return true;
  3465. },
  3466. clone: function () {
  3467. return new THREE.Frustum().copy( this );
  3468. }
  3469. };
  3470. /**
  3471. * @author bhouston / http://exocortex.com
  3472. */
  3473. THREE.Plane = function ( normal, constant ) {
  3474. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3475. this.constant = ( constant !== undefined ) ? constant : 0;
  3476. };
  3477. THREE.Plane.prototype = {
  3478. constructor: THREE.Plane,
  3479. set: function ( normal, constant ) {
  3480. this.normal.copy( normal );
  3481. this.constant = constant;
  3482. return this;
  3483. },
  3484. setComponents: function ( x, y, z, w ) {
  3485. this.normal.set( x, y, z );
  3486. this.constant = w;
  3487. return this;
  3488. },
  3489. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3490. this.normal.copy( normal );
  3491. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3492. return this;
  3493. },
  3494. setFromCoplanarPoints: function() {
  3495. var v1 = new THREE.Vector3();
  3496. var v2 = new THREE.Vector3();
  3497. return function ( a, b, c ) {
  3498. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3499. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3500. this.setFromNormalAndCoplanarPoint( normal, a );
  3501. return this;
  3502. };
  3503. }(),
  3504. copy: function ( plane ) {
  3505. this.normal.copy( plane.normal );
  3506. this.constant = plane.constant;
  3507. return this;
  3508. },
  3509. normalize: function () {
  3510. // Note: will lead to a divide by zero if the plane is invalid.
  3511. var inverseNormalLength = 1.0 / this.normal.length();
  3512. this.normal.multiplyScalar( inverseNormalLength );
  3513. this.constant *= inverseNormalLength;
  3514. return this;
  3515. },
  3516. negate: function () {
  3517. this.constant *= -1;
  3518. this.normal.negate();
  3519. return this;
  3520. },
  3521. distanceToPoint: function ( point ) {
  3522. return this.normal.dot( point ) + this.constant;
  3523. },
  3524. distanceToSphere: function ( sphere ) {
  3525. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3526. },
  3527. projectPoint: function ( point, optionalTarget ) {
  3528. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3529. },
  3530. orthoPoint: function ( point, optionalTarget ) {
  3531. var perpendicularMagnitude = this.distanceToPoint( point );
  3532. var result = optionalTarget || new THREE.Vector3();
  3533. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3534. },
  3535. isIntersectionLine: function ( line ) {
  3536. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3537. var startSign = this.distanceToPoint( line.start );
  3538. var endSign = this.distanceToPoint( line.end );
  3539. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3540. },
  3541. intersectLine: function() {
  3542. var v1 = new THREE.Vector3();
  3543. return function ( line, optionalTarget ) {
  3544. var result = optionalTarget || new THREE.Vector3();
  3545. var direction = line.delta( v1 );
  3546. var denominator = this.normal.dot( direction );
  3547. if ( denominator == 0 ) {
  3548. // line is coplanar, return origin
  3549. if( this.distanceToPoint( line.start ) == 0 ) {
  3550. return result.copy( line.start );
  3551. }
  3552. // Unsure if this is the correct method to handle this case.
  3553. return undefined;
  3554. }
  3555. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3556. if( t < 0 || t > 1 ) {
  3557. return undefined;
  3558. }
  3559. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3560. };
  3561. }(),
  3562. coplanarPoint: function ( optionalTarget ) {
  3563. var result = optionalTarget || new THREE.Vector3();
  3564. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3565. },
  3566. applyMatrix4: function() {
  3567. var v1 = new THREE.Vector3();
  3568. var v2 = new THREE.Vector3();
  3569. var m1 = new THREE.Matrix3();
  3570. return function ( matrix, optionalNormalMatrix ) {
  3571. // compute new normal based on theory here:
  3572. // http://www.songho.ca/opengl/gl_normaltransform.html
  3573. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  3574. var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix );
  3575. var newCoplanarPoint = this.coplanarPoint( v2 );
  3576. newCoplanarPoint.applyMatrix4( matrix );
  3577. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3578. return this;
  3579. };
  3580. }(),
  3581. translate: function ( offset ) {
  3582. this.constant = this.constant - offset.dot( this.normal );
  3583. return this;
  3584. },
  3585. equals: function ( plane ) {
  3586. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3587. },
  3588. clone: function () {
  3589. return new THREE.Plane().copy( this );
  3590. }
  3591. };
  3592. /**
  3593. * @author alteredq / http://alteredqualia.com/
  3594. * @author mrdoob / http://mrdoob.com/
  3595. */
  3596. THREE.Math = {
  3597. PI2: Math.PI * 2,
  3598. generateUUID: function () {
  3599. // http://www.broofa.com/Tools/Math.uuid.htm
  3600. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  3601. var uuid = new Array(36);
  3602. var rnd = 0, r;
  3603. return function () {
  3604. for ( var i = 0; i < 36; i ++ ) {
  3605. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3606. uuid[ i ] = '-';
  3607. } else if ( i == 14 ) {
  3608. uuid[ i ] = '4';
  3609. } else {
  3610. if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
  3611. r = rnd & 0xf;
  3612. rnd = rnd >> 4;
  3613. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  3614. }
  3615. }
  3616. return uuid.join('');
  3617. };
  3618. }(),
  3619. // Clamp value to range <a, b>
  3620. clamp: function ( x, a, b ) {
  3621. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3622. },
  3623. // Clamp value to range <a, inf)
  3624. clampBottom: function ( x, a ) {
  3625. return x < a ? a : x;
  3626. },
  3627. // Linear mapping from range <a1, a2> to range <b1, b2>
  3628. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3629. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3630. },
  3631. // http://en.wikipedia.org/wiki/Smoothstep
  3632. smoothstep: function ( x, min, max ) {
  3633. if ( x <= min ) return 0;
  3634. if ( x >= max ) return 1;
  3635. x = ( x - min )/( max - min );
  3636. return x*x*(3 - 2*x);
  3637. },
  3638. smootherstep: function ( x, min, max ) {
  3639. if ( x <= min ) return 0;
  3640. if ( x >= max ) return 1;
  3641. x = ( x - min )/( max - min );
  3642. return x*x*x*(x*(x*6 - 15) + 10);
  3643. },
  3644. // Random float from <0, 1> with 16 bits of randomness
  3645. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3646. random16: function () {
  3647. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3648. },
  3649. // Random integer from <low, high> interval
  3650. randInt: function ( low, high ) {
  3651. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3652. },
  3653. // Random float from <low, high> interval
  3654. randFloat: function ( low, high ) {
  3655. return low + Math.random() * ( high - low );
  3656. },
  3657. // Random float from <-range/2, range/2> interval
  3658. randFloatSpread: function ( range ) {
  3659. return range * ( 0.5 - Math.random() );
  3660. },
  3661. sign: function ( x ) {
  3662. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : 0;
  3663. },
  3664. degToRad: function() {
  3665. var degreeToRadiansFactor = Math.PI / 180;
  3666. return function ( degrees ) {
  3667. return degrees * degreeToRadiansFactor;
  3668. };
  3669. }(),
  3670. radToDeg: function() {
  3671. var radianToDegreesFactor = 180 / Math.PI;
  3672. return function ( radians ) {
  3673. return radians * radianToDegreesFactor;
  3674. };
  3675. }(),
  3676. isPowerOfTwo: function ( value ) {
  3677. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  3678. }
  3679. };
  3680. /**
  3681. * Spline from Tween.js, slightly optimized (and trashed)
  3682. * http://sole.github.com/tween.js/examples/05_spline.html
  3683. *
  3684. * @author mrdoob / http://mrdoob.com/
  3685. * @author alteredq / http://alteredqualia.com/
  3686. */
  3687. THREE.Spline = function ( points ) {
  3688. this.points = points;
  3689. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3690. point, intPoint, weight, w2, w3,
  3691. pa, pb, pc, pd;
  3692. this.initFromArray = function( a ) {
  3693. this.points = [];
  3694. for ( var i = 0; i < a.length; i++ ) {
  3695. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3696. }
  3697. };
  3698. this.getPoint = function ( k ) {
  3699. point = ( this.points.length - 1 ) * k;
  3700. intPoint = Math.floor( point );
  3701. weight = point - intPoint;
  3702. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3703. c[ 1 ] = intPoint;
  3704. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3705. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3706. pa = this.points[ c[ 0 ] ];
  3707. pb = this.points[ c[ 1 ] ];
  3708. pc = this.points[ c[ 2 ] ];
  3709. pd = this.points[ c[ 3 ] ];
  3710. w2 = weight * weight;
  3711. w3 = weight * w2;
  3712. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3713. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3714. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3715. return v3;
  3716. };
  3717. this.getControlPointsArray = function () {
  3718. var i, p, l = this.points.length,
  3719. coords = [];
  3720. for ( i = 0; i < l; i ++ ) {
  3721. p = this.points[ i ];
  3722. coords[ i ] = [ p.x, p.y, p.z ];
  3723. }
  3724. return coords;
  3725. };
  3726. // approximate length by summing linear segments
  3727. this.getLength = function ( nSubDivisions ) {
  3728. var i, index, nSamples, position,
  3729. point = 0, intPoint = 0, oldIntPoint = 0,
  3730. oldPosition = new THREE.Vector3(),
  3731. tmpVec = new THREE.Vector3(),
  3732. chunkLengths = [],
  3733. totalLength = 0;
  3734. // first point has 0 length
  3735. chunkLengths[ 0 ] = 0;
  3736. if ( !nSubDivisions ) nSubDivisions = 100;
  3737. nSamples = this.points.length * nSubDivisions;
  3738. oldPosition.copy( this.points[ 0 ] );
  3739. for ( i = 1; i < nSamples; i ++ ) {
  3740. index = i / nSamples;
  3741. position = this.getPoint( index );
  3742. tmpVec.copy( position );
  3743. totalLength += tmpVec.distanceTo( oldPosition );
  3744. oldPosition.copy( position );
  3745. point = ( this.points.length - 1 ) * index;
  3746. intPoint = Math.floor( point );
  3747. if ( intPoint != oldIntPoint ) {
  3748. chunkLengths[ intPoint ] = totalLength;
  3749. oldIntPoint = intPoint;
  3750. }
  3751. }
  3752. // last point ends with total length
  3753. chunkLengths[ chunkLengths.length ] = totalLength;
  3754. return { chunks: chunkLengths, total: totalLength };
  3755. };
  3756. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3757. var i, j,
  3758. index, indexCurrent, indexNext,
  3759. linearDistance, realDistance,
  3760. sampling, position,
  3761. newpoints = [],
  3762. tmpVec = new THREE.Vector3(),
  3763. sl = this.getLength();
  3764. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3765. for ( i = 1; i < this.points.length; i++ ) {
  3766. //tmpVec.copy( this.points[ i - 1 ] );
  3767. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3768. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3769. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3770. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3771. indexNext = i / ( this.points.length - 1 );
  3772. for ( j = 1; j < sampling - 1; j++ ) {
  3773. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3774. position = this.getPoint( index );
  3775. newpoints.push( tmpVec.copy( position ).clone() );
  3776. }
  3777. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3778. }
  3779. this.points = newpoints;
  3780. };
  3781. // Catmull-Rom
  3782. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3783. var v0 = ( p2 - p0 ) * 0.5,
  3784. v1 = ( p3 - p1 ) * 0.5;
  3785. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3786. };
  3787. };
  3788. /**
  3789. * @author bhouston / http://exocortex.com
  3790. * @author mrdoob / http://mrdoob.com/
  3791. */
  3792. THREE.Triangle = function ( a, b, c ) {
  3793. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3794. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3795. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3796. };
  3797. THREE.Triangle.normal = function() {
  3798. var v0 = new THREE.Vector3();
  3799. return function ( a, b, c, optionalTarget ) {
  3800. var result = optionalTarget || new THREE.Vector3();
  3801. result.subVectors( c, b );
  3802. v0.subVectors( a, b );
  3803. result.cross( v0 );
  3804. var resultLengthSq = result.lengthSq();
  3805. if( resultLengthSq > 0 ) {
  3806. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3807. }
  3808. return result.set( 0, 0, 0 );
  3809. };
  3810. }();
  3811. // static/instance method to calculate barycoordinates
  3812. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3813. THREE.Triangle.barycoordFromPoint = function() {
  3814. var v0 = new THREE.Vector3();
  3815. var v1 = new THREE.Vector3();
  3816. var v2 = new THREE.Vector3();
  3817. return function ( point, a, b, c, optionalTarget ) {
  3818. v0.subVectors( c, a );
  3819. v1.subVectors( b, a );
  3820. v2.subVectors( point, a );
  3821. var dot00 = v0.dot( v0 );
  3822. var dot01 = v0.dot( v1 );
  3823. var dot02 = v0.dot( v2 );
  3824. var dot11 = v1.dot( v1 );
  3825. var dot12 = v1.dot( v2 );
  3826. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3827. var result = optionalTarget || new THREE.Vector3();
  3828. // colinear or singular triangle
  3829. if( denom == 0 ) {
  3830. // arbitrary location outside of triangle?
  3831. // not sure if this is the best idea, maybe should be returning undefined
  3832. return result.set( -2, -1, -1 );
  3833. }
  3834. var invDenom = 1 / denom;
  3835. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3836. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3837. // barycoordinates must always sum to 1
  3838. return result.set( 1 - u - v, v, u );
  3839. };
  3840. }();
  3841. THREE.Triangle.containsPoint = function() {
  3842. var v1 = new THREE.Vector3();
  3843. return function ( point, a, b, c ) {
  3844. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3845. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3846. };
  3847. }();
  3848. THREE.Triangle.prototype = {
  3849. constructor: THREE.Triangle,
  3850. set: function ( a, b, c ) {
  3851. this.a.copy( a );
  3852. this.b.copy( b );
  3853. this.c.copy( c );
  3854. return this;
  3855. },
  3856. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3857. this.a.copy( points[i0] );
  3858. this.b.copy( points[i1] );
  3859. this.c.copy( points[i2] );
  3860. return this;
  3861. },
  3862. copy: function ( triangle ) {
  3863. this.a.copy( triangle.a );
  3864. this.b.copy( triangle.b );
  3865. this.c.copy( triangle.c );
  3866. return this;
  3867. },
  3868. area: function() {
  3869. var v0 = new THREE.Vector3();
  3870. var v1 = new THREE.Vector3();
  3871. return function () {
  3872. v0.subVectors( this.c, this.b );
  3873. v1.subVectors( this.a, this.b );
  3874. return v0.cross( v1 ).length() * 0.5;
  3875. };
  3876. }(),
  3877. midpoint: function ( optionalTarget ) {
  3878. var result = optionalTarget || new THREE.Vector3();
  3879. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3880. },
  3881. normal: function ( optionalTarget ) {
  3882. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3883. },
  3884. plane: function ( optionalTarget ) {
  3885. var result = optionalTarget || new THREE.Plane();
  3886. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3887. },
  3888. barycoordFromPoint: function ( point, optionalTarget ) {
  3889. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3890. },
  3891. containsPoint: function ( point ) {
  3892. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3893. },
  3894. equals: function ( triangle ) {
  3895. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3896. },
  3897. clone: function () {
  3898. return new THREE.Triangle().copy( this );
  3899. }
  3900. };
  3901. /**
  3902. * @author mrdoob / http://mrdoob.com/
  3903. */
  3904. THREE.Vertex = function ( v ) {
  3905. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3906. return v;
  3907. };
  3908. /**
  3909. * @author mrdoob / http://mrdoob.com/
  3910. */
  3911. THREE.UV = function ( u, v ) {
  3912. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3913. return new THREE.Vector2( u, v );
  3914. };
  3915. /**
  3916. * @author alteredq / http://alteredqualia.com/
  3917. */
  3918. THREE.Clock = function ( autoStart ) {
  3919. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3920. this.startTime = 0;
  3921. this.oldTime = 0;
  3922. this.elapsedTime = 0;
  3923. this.running = false;
  3924. };
  3925. THREE.Clock.prototype = {
  3926. constructor: THREE.Clock,
  3927. start: function () {
  3928. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  3929. ? self.performance.now()
  3930. : Date.now();
  3931. this.oldTime = this.startTime;
  3932. this.running = true;
  3933. },
  3934. stop: function () {
  3935. this.getElapsedTime();
  3936. this.running = false;
  3937. },
  3938. getElapsedTime: function () {
  3939. this.getDelta();
  3940. return this.elapsedTime;
  3941. },
  3942. getDelta: function () {
  3943. var diff = 0;
  3944. if ( this.autoStart && ! this.running ) {
  3945. this.start();
  3946. }
  3947. if ( this.running ) {
  3948. var newTime = self.performance !== undefined && self.performance.now !== undefined
  3949. ? self.performance.now()
  3950. : Date.now();
  3951. diff = 0.001 * ( newTime - this.oldTime );
  3952. this.oldTime = newTime;
  3953. this.elapsedTime += diff;
  3954. }
  3955. return diff;
  3956. }
  3957. };
  3958. /**
  3959. * https://github.com/mrdoob/eventdispatcher.js/
  3960. */
  3961. THREE.EventDispatcher = function () {}
  3962. THREE.EventDispatcher.prototype = {
  3963. constructor: THREE.EventDispatcher,
  3964. apply: function ( object ) {
  3965. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  3966. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  3967. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  3968. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  3969. },
  3970. addEventListener: function ( type, listener ) {
  3971. if ( this._listeners === undefined ) this._listeners = {};
  3972. var listeners = this._listeners;
  3973. if ( listeners[ type ] === undefined ) {
  3974. listeners[ type ] = [];
  3975. }
  3976. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3977. listeners[ type ].push( listener );
  3978. }
  3979. },
  3980. hasEventListener: function ( type, listener ) {
  3981. if ( this._listeners === undefined ) return false;
  3982. var listeners = this._listeners;
  3983. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  3984. return true;
  3985. }
  3986. return false;
  3987. },
  3988. removeEventListener: function ( type, listener ) {
  3989. if ( this._listeners === undefined ) return;
  3990. var listeners = this._listeners;
  3991. var listenerArray = listeners[ type ];
  3992. if ( listenerArray !== undefined ) {
  3993. var index = listenerArray.indexOf( listener );
  3994. if ( index !== - 1 ) {
  3995. listenerArray.splice( index, 1 );
  3996. }
  3997. }
  3998. },
  3999. dispatchEvent: function () {
  4000. var array = [];
  4001. return function ( event ) {
  4002. if ( this._listeners === undefined ) return;
  4003. var listeners = this._listeners;
  4004. var listenerArray = listeners[ event.type ];
  4005. if ( listenerArray !== undefined ) {
  4006. event.target = this;
  4007. var length = listenerArray.length;
  4008. for ( var i = 0; i < length; i ++ ) {
  4009. array[ i ] = listenerArray[ i ];
  4010. }
  4011. for ( var i = 0; i < length; i ++ ) {
  4012. array[ i ].call( this, event );
  4013. }
  4014. }
  4015. };
  4016. }()
  4017. };
  4018. /**
  4019. * @author mrdoob / http://mrdoob.com/
  4020. * @author bhouston / http://exocortex.com/
  4021. * @author stephomi / http://stephaneginier.com/
  4022. */
  4023. ( function ( THREE ) {
  4024. THREE.Raycaster = function ( origin, direction, near, far ) {
  4025. this.ray = new THREE.Ray( origin, direction );
  4026. // direction is assumed to be normalized (for accurate distance calculations)
  4027. this.near = near || 0;
  4028. this.far = far || Infinity;
  4029. };
  4030. var sphere = new THREE.Sphere();
  4031. var localRay = new THREE.Ray();
  4032. var facePlane = new THREE.Plane();
  4033. var intersectPoint = new THREE.Vector3();
  4034. var matrixPosition = new THREE.Vector3();
  4035. var inverseMatrix = new THREE.Matrix4();
  4036. var descSort = function ( a, b ) {
  4037. return a.distance - b.distance;
  4038. };
  4039. var vA = new THREE.Vector3();
  4040. var vB = new THREE.Vector3();
  4041. var vC = new THREE.Vector3();
  4042. var intersectObject = function ( object, raycaster, intersects ) {
  4043. if ( object instanceof THREE.Sprite ) {
  4044. matrixPosition.setFromMatrixPosition( object.matrixWorld );
  4045. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  4046. if ( distance > object.scale.x ) {
  4047. return intersects;
  4048. }
  4049. intersects.push( {
  4050. distance: distance,
  4051. point: object.position,
  4052. face: null,
  4053. object: object
  4054. } );
  4055. } else if ( object instanceof THREE.LOD ) {
  4056. matrixPosition.setFromMatrixPosition( object.matrixWorld );
  4057. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  4058. intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );
  4059. } else if ( object instanceof THREE.Mesh ) {
  4060. var geometry = object.geometry;
  4061. // Checking boundingSphere distance to ray
  4062. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4063. sphere.copy( geometry.boundingSphere );
  4064. sphere.applyMatrix4( object.matrixWorld );
  4065. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4066. return intersects;
  4067. }
  4068. // Check boundingBox before continuing
  4069. inverseMatrix.getInverse( object.matrixWorld );
  4070. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4071. if ( geometry.boundingBox !== null ) {
  4072. if ( localRay.isIntersectionBox( geometry.boundingBox ) === false ) {
  4073. return intersects;
  4074. }
  4075. }
  4076. if ( geometry instanceof THREE.BufferGeometry ) {
  4077. var material = object.material;
  4078. if ( material === undefined ) return intersects;
  4079. var a, b, c;
  4080. var precision = raycaster.precision;
  4081. if ( geometry.attributes.index !== undefined ) {
  4082. var offsets = geometry.offsets;
  4083. var indices = geometry.attributes.index.array;
  4084. var positions = geometry.attributes.position.array;
  4085. var offLength = geometry.offsets.length;
  4086. var fl = geometry.attributes.index.array.length / 3;
  4087. for ( var oi = 0; oi < offLength; ++oi ) {
  4088. var start = offsets[ oi ].start;
  4089. var count = offsets[ oi ].count;
  4090. var index = offsets[ oi ].index;
  4091. for ( var i = start, il = start + count; i < il; i += 3 ) {
  4092. a = index + indices[ i ];
  4093. b = index + indices[ i + 1 ];
  4094. c = index + indices[ i + 2 ];
  4095. vA.set(
  4096. positions[ a * 3 ],
  4097. positions[ a * 3 + 1 ],
  4098. positions[ a * 3 + 2 ]
  4099. );
  4100. vB.set(
  4101. positions[ b * 3 ],
  4102. positions[ b * 3 + 1 ],
  4103. positions[ b * 3 + 2 ]
  4104. );
  4105. vC.set(
  4106. positions[ c * 3 ],
  4107. positions[ c * 3 + 1 ],
  4108. positions[ c * 3 + 2 ]
  4109. );
  4110. if ( material.side === THREE.BackSide ) {
  4111. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4112. } else {
  4113. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4114. }
  4115. if ( intersectionPoint === null ) continue;
  4116. intersectionPoint.applyMatrix4( object.matrixWorld );
  4117. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4118. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4119. intersects.push( {
  4120. distance: distance,
  4121. point: intersectionPoint,
  4122. face: null,
  4123. faceIndex: null,
  4124. object: object
  4125. } );
  4126. }
  4127. }
  4128. } else {
  4129. var offsets = geometry.offsets;
  4130. var positions = geometry.attributes.position.array;
  4131. var offLength = geometry.offsets.length;
  4132. var fl = geometry.attributes.position.array.length;
  4133. for ( var i = 0; i < fl; i += 3 ) {
  4134. a = i;
  4135. b = i + 1;
  4136. c = i + 2;
  4137. vA.set(
  4138. positions[ a * 3 ],
  4139. positions[ a * 3 + 1 ],
  4140. positions[ a * 3 + 2 ]
  4141. );
  4142. vB.set(
  4143. positions[ b * 3 ],
  4144. positions[ b * 3 + 1 ],
  4145. positions[ b * 3 + 2 ]
  4146. );
  4147. vC.set(
  4148. positions[ c * 3 ],
  4149. positions[ c * 3 + 1 ],
  4150. positions[ c * 3 + 2 ]
  4151. );
  4152. if ( material.side === THREE.BackSide ) {
  4153. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4154. } else {
  4155. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4156. }
  4157. if ( intersectionPoint === null ) continue;
  4158. intersectionPoint.applyMatrix4( object.matrixWorld );
  4159. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4160. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4161. intersects.push( {
  4162. distance: distance,
  4163. point: intersectionPoint,
  4164. face: null,
  4165. faceIndex: null,
  4166. object: object
  4167. } );
  4168. }
  4169. }
  4170. } else if ( geometry instanceof THREE.Geometry ) {
  4171. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4172. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  4173. var a, b, c, d;
  4174. var precision = raycaster.precision;
  4175. var vertices = geometry.vertices;
  4176. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  4177. var face = geometry.faces[ f ];
  4178. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  4179. if ( material === undefined ) continue;
  4180. a = vertices[ face.a ];
  4181. b = vertices[ face.b ];
  4182. c = vertices[ face.c ];
  4183. if ( material.morphTargets === true ) {
  4184. var morphTargets = geometry.morphTargets;
  4185. var morphInfluences = object.morphTargetInfluences;
  4186. vA.set( 0, 0, 0 );
  4187. vB.set( 0, 0, 0 );
  4188. vC.set( 0, 0, 0 );
  4189. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  4190. var influence = morphInfluences[ t ];
  4191. if ( influence === 0 ) continue;
  4192. var targets = morphTargets[ t ].vertices;
  4193. vA.x += ( targets[ face.a ].x - a.x ) * influence;
  4194. vA.y += ( targets[ face.a ].y - a.y ) * influence;
  4195. vA.z += ( targets[ face.a ].z - a.z ) * influence;
  4196. vB.x += ( targets[ face.b ].x - b.x ) * influence;
  4197. vB.y += ( targets[ face.b ].y - b.y ) * influence;
  4198. vB.z += ( targets[ face.b ].z - b.z ) * influence;
  4199. vC.x += ( targets[ face.c ].x - c.x ) * influence;
  4200. vC.y += ( targets[ face.c ].y - c.y ) * influence;
  4201. vC.z += ( targets[ face.c ].z - c.z ) * influence;
  4202. }
  4203. vA.add( a );
  4204. vB.add( b );
  4205. vC.add( c );
  4206. a = vA;
  4207. b = vB;
  4208. c = vC;
  4209. }
  4210. if ( material.side === THREE.BackSide ) {
  4211. var intersectionPoint = localRay.intersectTriangle( c, b, a, true );
  4212. } else {
  4213. var intersectionPoint = localRay.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide );
  4214. }
  4215. if ( intersectionPoint === null ) continue;
  4216. intersectionPoint.applyMatrix4( object.matrixWorld );
  4217. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4218. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4219. intersects.push( {
  4220. distance: distance,
  4221. point: intersectionPoint,
  4222. face: face,
  4223. faceIndex: f,
  4224. object: object
  4225. } );
  4226. }
  4227. }
  4228. } else if ( object instanceof THREE.Line ) {
  4229. var precision = raycaster.linePrecision;
  4230. var precisionSq = precision * precision;
  4231. var geometry = object.geometry;
  4232. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4233. // Checking boundingSphere distance to ray
  4234. sphere.copy( geometry.boundingSphere );
  4235. sphere.applyMatrix4( object.matrixWorld );
  4236. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4237. return intersects;
  4238. }
  4239. inverseMatrix.getInverse( object.matrixWorld );
  4240. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4241. /* if ( geometry instanceof THREE.BufferGeometry ) {
  4242. } else */ if ( geometry instanceof THREE.Geometry ) {
  4243. var vertices = geometry.vertices;
  4244. var nbVertices = vertices.length;
  4245. var interSegment = new THREE.Vector3();
  4246. var interRay = new THREE.Vector3();
  4247. var step = object.type === THREE.LineStrip ? 1 : 2;
  4248. for ( var i = 0; i < nbVertices - 1; i = i + step ) {
  4249. var distSq = localRay.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  4250. if ( distSq > precisionSq ) continue;
  4251. var distance = localRay.origin.distanceTo( interRay );
  4252. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  4253. intersects.push( {
  4254. distance: distance,
  4255. // What do we want? intersection point on the ray or on the segment??
  4256. // point: raycaster.ray.at( distance ),
  4257. point: interSegment.clone().applyMatrix4( object.matrixWorld ),
  4258. face: null,
  4259. faceIndex: null,
  4260. object: object
  4261. } );
  4262. }
  4263. }
  4264. }
  4265. };
  4266. var intersectDescendants = function ( object, raycaster, intersects ) {
  4267. var descendants = object.getDescendants();
  4268. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  4269. intersectObject( descendants[ i ], raycaster, intersects );
  4270. }
  4271. };
  4272. //
  4273. THREE.Raycaster.prototype.precision = 0.0001;
  4274. THREE.Raycaster.prototype.linePrecision = 1;
  4275. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  4276. this.ray.set( origin, direction );
  4277. // direction is assumed to be normalized (for accurate distance calculations)
  4278. };
  4279. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  4280. var intersects = [];
  4281. if ( recursive === true ) {
  4282. intersectDescendants( object, this, intersects );
  4283. }
  4284. intersectObject( object, this, intersects );
  4285. intersects.sort( descSort );
  4286. return intersects;
  4287. };
  4288. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  4289. var intersects = [];
  4290. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4291. intersectObject( objects[ i ], this, intersects );
  4292. if ( recursive === true ) {
  4293. intersectDescendants( objects[ i ], this, intersects );
  4294. }
  4295. }
  4296. intersects.sort( descSort );
  4297. return intersects;
  4298. };
  4299. }( THREE ) );
  4300. /**
  4301. * @author mrdoob / http://mrdoob.com/
  4302. * @author mikael emtinger / http://gomo.se/
  4303. * @author alteredq / http://alteredqualia.com/
  4304. * @author WestLangley / http://github.com/WestLangley
  4305. */
  4306. THREE.Object3D = function () {
  4307. this.id = THREE.Object3DIdCount ++;
  4308. this.uuid = THREE.Math.generateUUID();
  4309. this.name = '';
  4310. this.parent = undefined;
  4311. this.children = [];
  4312. this.up = new THREE.Vector3( 0, 1, 0 );
  4313. this.position = new THREE.Vector3();
  4314. this._rotation = new THREE.Euler();
  4315. this._quaternion = new THREE.Quaternion();
  4316. this.scale = new THREE.Vector3( 1, 1, 1 );
  4317. // keep rotation and quaternion in sync
  4318. this._rotation._quaternion = this.quaternion;
  4319. this._quaternion._euler = this.rotation;
  4320. this.renderDepth = null;
  4321. this.rotationAutoUpdate = true;
  4322. this.matrix = new THREE.Matrix4();
  4323. this.matrixWorld = new THREE.Matrix4();
  4324. this.matrixAutoUpdate = true;
  4325. this.matrixWorldNeedsUpdate = true;
  4326. this.visible = true;
  4327. this.castShadow = false;
  4328. this.receiveShadow = false;
  4329. this.frustumCulled = true;
  4330. this.userData = {};
  4331. };
  4332. THREE.Object3D.prototype = {
  4333. constructor: THREE.Object3D,
  4334. get rotation () {
  4335. return this._rotation;
  4336. },
  4337. set rotation ( value ) {
  4338. this._rotation = value;
  4339. this._rotation._quaternion = this._quaternion;
  4340. this._quaternion._euler = this._rotation;
  4341. this._rotation._updateQuaternion();
  4342. },
  4343. get quaternion () {
  4344. return this._quaternion;
  4345. },
  4346. set quaternion ( value ) {
  4347. this._quaternion = value;
  4348. this._quaternion._euler = this._rotation;
  4349. this._rotation._quaternion = this._quaternion;
  4350. this._quaternion._updateEuler();
  4351. },
  4352. get eulerOrder () {
  4353. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4354. return this.rotation.order;
  4355. },
  4356. set eulerOrder ( value ) {
  4357. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4358. this.rotation.order = value;
  4359. },
  4360. get useQuaternion () {
  4361. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4362. },
  4363. set useQuaternion ( value ) {
  4364. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4365. },
  4366. applyMatrix: function ( matrix ) {
  4367. this.matrix.multiplyMatrices( matrix, this.matrix );
  4368. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4369. },
  4370. setRotationFromAxisAngle: function ( axis, angle ) {
  4371. // assumes axis is normalized
  4372. this.quaternion.setFromAxisAngle( axis, angle );
  4373. },
  4374. setRotationFromEuler: function ( euler ) {
  4375. this.quaternion.setFromEuler( euler, true );
  4376. },
  4377. setRotationFromMatrix: function ( m ) {
  4378. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4379. this.quaternion.setFromRotationMatrix( m );
  4380. },
  4381. setRotationFromQuaternion: function ( q ) {
  4382. // assumes q is normalized
  4383. this.quaternion.copy( q );
  4384. },
  4385. rotateOnAxis: function() {
  4386. // rotate object on axis in object space
  4387. // axis is assumed to be normalized
  4388. var q1 = new THREE.Quaternion();
  4389. return function ( axis, angle ) {
  4390. q1.setFromAxisAngle( axis, angle );
  4391. this.quaternion.multiply( q1 );
  4392. return this;
  4393. }
  4394. }(),
  4395. rotateX: function () {
  4396. var v1 = new THREE.Vector3( 1, 0, 0 );
  4397. return function ( angle ) {
  4398. return this.rotateOnAxis( v1, angle );
  4399. };
  4400. }(),
  4401. rotateY: function () {
  4402. var v1 = new THREE.Vector3( 0, 1, 0 );
  4403. return function ( angle ) {
  4404. return this.rotateOnAxis( v1, angle );
  4405. };
  4406. }(),
  4407. rotateZ: function () {
  4408. var v1 = new THREE.Vector3( 0, 0, 1 );
  4409. return function ( angle ) {
  4410. return this.rotateOnAxis( v1, angle );
  4411. };
  4412. }(),
  4413. translateOnAxis: function () {
  4414. // translate object by distance along axis in object space
  4415. // axis is assumed to be normalized
  4416. var v1 = new THREE.Vector3();
  4417. return function ( axis, distance ) {
  4418. v1.copy( axis );
  4419. v1.applyQuaternion( this.quaternion );
  4420. this.position.add( v1.multiplyScalar( distance ) );
  4421. return this;
  4422. }
  4423. }(),
  4424. translate: function ( distance, axis ) {
  4425. console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
  4426. return this.translateOnAxis( axis, distance );
  4427. },
  4428. translateX: function () {
  4429. var v1 = new THREE.Vector3( 1, 0, 0 );
  4430. return function ( distance ) {
  4431. return this.translateOnAxis( v1, distance );
  4432. };
  4433. }(),
  4434. translateY: function () {
  4435. var v1 = new THREE.Vector3( 0, 1, 0 );
  4436. return function ( distance ) {
  4437. return this.translateOnAxis( v1, distance );
  4438. };
  4439. }(),
  4440. translateZ: function () {
  4441. var v1 = new THREE.Vector3( 0, 0, 1 );
  4442. return function ( distance ) {
  4443. return this.translateOnAxis( v1, distance );
  4444. };
  4445. }(),
  4446. localToWorld: function ( vector ) {
  4447. return vector.applyMatrix4( this.matrixWorld );
  4448. },
  4449. worldToLocal: function () {
  4450. var m1 = new THREE.Matrix4();
  4451. return function ( vector ) {
  4452. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4453. };
  4454. }(),
  4455. lookAt: function () {
  4456. // This routine does not support objects with rotated and/or translated parent(s)
  4457. var m1 = new THREE.Matrix4();
  4458. return function ( vector ) {
  4459. m1.lookAt( vector, this.position, this.up );
  4460. this.quaternion.setFromRotationMatrix( m1 );
  4461. };
  4462. }(),
  4463. add: function ( object ) {
  4464. if ( object === this ) {
  4465. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  4466. return;
  4467. }
  4468. if ( object instanceof THREE.Object3D ) {
  4469. if ( object.parent !== undefined ) {
  4470. object.parent.remove( object );
  4471. }
  4472. object.parent = this;
  4473. object.dispatchEvent( { type: 'added' } );
  4474. this.children.push( object );
  4475. // add to scene
  4476. var scene = this;
  4477. while ( scene.parent !== undefined ) {
  4478. scene = scene.parent;
  4479. }
  4480. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4481. scene.__addObject( object );
  4482. }
  4483. }
  4484. },
  4485. remove: function ( object ) {
  4486. var index = this.children.indexOf( object );
  4487. if ( index !== - 1 ) {
  4488. object.parent = undefined;
  4489. object.dispatchEvent( { type: 'removed' } );
  4490. this.children.splice( index, 1 );
  4491. // remove from scene
  4492. var scene = this;
  4493. while ( scene.parent !== undefined ) {
  4494. scene = scene.parent;
  4495. }
  4496. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4497. scene.__removeObject( object );
  4498. }
  4499. }
  4500. },
  4501. traverse: function ( callback ) {
  4502. callback( this );
  4503. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4504. this.children[ i ].traverse( callback );
  4505. }
  4506. },
  4507. getObjectById: function ( id, recursive ) {
  4508. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4509. var child = this.children[ i ];
  4510. if ( child.id === id ) {
  4511. return child;
  4512. }
  4513. if ( recursive === true ) {
  4514. child = child.getObjectById( id, recursive );
  4515. if ( child !== undefined ) {
  4516. return child;
  4517. }
  4518. }
  4519. }
  4520. return undefined;
  4521. },
  4522. getObjectByName: function ( name, recursive ) {
  4523. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4524. var child = this.children[ i ];
  4525. if ( child.name === name ) {
  4526. return child;
  4527. }
  4528. if ( recursive === true ) {
  4529. child = child.getObjectByName( name, recursive );
  4530. if ( child !== undefined ) {
  4531. return child;
  4532. }
  4533. }
  4534. }
  4535. return undefined;
  4536. },
  4537. getChildByName: function ( name, recursive ) {
  4538. console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
  4539. return this.getObjectByName( name, recursive );
  4540. },
  4541. getDescendants: function ( array ) {
  4542. if ( array === undefined ) array = [];
  4543. Array.prototype.push.apply( array, this.children );
  4544. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4545. this.children[ i ].getDescendants( array );
  4546. }
  4547. return array;
  4548. },
  4549. updateMatrix: function () {
  4550. this.matrix.compose( this.position, this.quaternion, this.scale );
  4551. this.matrixWorldNeedsUpdate = true;
  4552. },
  4553. updateMatrixWorld: function ( force ) {
  4554. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4555. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4556. if ( this.parent === undefined ) {
  4557. this.matrixWorld.copy( this.matrix );
  4558. } else {
  4559. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4560. }
  4561. this.matrixWorldNeedsUpdate = false;
  4562. force = true;
  4563. }
  4564. // update children
  4565. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4566. this.children[ i ].updateMatrixWorld( force );
  4567. }
  4568. },
  4569. clone: function ( object, recursive ) {
  4570. if ( object === undefined ) object = new THREE.Object3D();
  4571. if ( recursive === undefined ) recursive = true;
  4572. object.name = this.name;
  4573. object.up.copy( this.up );
  4574. object.position.copy( this.position );
  4575. object.quaternion.copy( this.quaternion );
  4576. object.scale.copy( this.scale );
  4577. object.renderDepth = this.renderDepth;
  4578. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4579. object.matrix.copy( this.matrix );
  4580. object.matrixWorld.copy( this.matrixWorld );
  4581. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4582. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4583. object.visible = this.visible;
  4584. object.castShadow = this.castShadow;
  4585. object.receiveShadow = this.receiveShadow;
  4586. object.frustumCulled = this.frustumCulled;
  4587. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4588. if ( recursive === true ) {
  4589. for ( var i = 0; i < this.children.length; i ++ ) {
  4590. var child = this.children[ i ];
  4591. object.add( child.clone() );
  4592. }
  4593. }
  4594. return object;
  4595. }
  4596. };
  4597. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  4598. THREE.Object3DIdCount = 0;
  4599. /**
  4600. * @author mrdoob / http://mrdoob.com/
  4601. * @author supereggbert / http://www.paulbrunt.co.uk/
  4602. * @author julianwa / https://github.com/julianwa
  4603. */
  4604. THREE.Projector = function () {
  4605. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  4606. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  4607. _face, _faceCount, _facePool = [], _facePoolLength = 0,
  4608. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  4609. _sprite, _spriteCount, _spritePool = [], _spritePoolLength = 0,
  4610. _renderData = { objects: [], lights: [], elements: [] },
  4611. _vA = new THREE.Vector3(),
  4612. _vB = new THREE.Vector3(),
  4613. _vC = new THREE.Vector3(),
  4614. _vector3 = new THREE.Vector3(),
  4615. _vector4 = new THREE.Vector4(),
  4616. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  4617. _boundingBox = new THREE.Box3(),
  4618. _points3 = new Array( 3 ),
  4619. _points4 = new Array( 4 ),
  4620. _viewMatrix = new THREE.Matrix4(),
  4621. _viewProjectionMatrix = new THREE.Matrix4(),
  4622. _modelMatrix,
  4623. _modelViewProjectionMatrix = new THREE.Matrix4(),
  4624. _normalMatrix = new THREE.Matrix3(),
  4625. _frustum = new THREE.Frustum(),
  4626. _clippedVertex1PositionScreen = new THREE.Vector4(),
  4627. _clippedVertex2PositionScreen = new THREE.Vector4();
  4628. this.projectVector = function ( vector, camera ) {
  4629. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4630. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  4631. return vector.applyProjection( _viewProjectionMatrix );
  4632. };
  4633. this.unprojectVector = function () {
  4634. var projectionMatrixInverse = new THREE.Matrix4();
  4635. return function ( vector, camera ) {
  4636. projectionMatrixInverse.getInverse( camera.projectionMatrix );
  4637. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, projectionMatrixInverse );
  4638. return vector.applyProjection( _viewProjectionMatrix );
  4639. };
  4640. }();
  4641. this.pickingRay = function ( vector, camera ) {
  4642. // set two vectors with opposing z values
  4643. vector.z = -1.0;
  4644. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4645. this.unprojectVector( vector, camera );
  4646. this.unprojectVector( end, camera );
  4647. // find direction from vector to end
  4648. end.sub( vector ).normalize();
  4649. return new THREE.Raycaster( vector, end );
  4650. };
  4651. var projectObject = function ( object ) {
  4652. if ( object.visible === false ) return;
  4653. if ( object instanceof THREE.Light ) {
  4654. _renderData.lights.push( object );
  4655. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Sprite ) {
  4656. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4657. _object = getNextObjectInPool();
  4658. _object.id = object.id;
  4659. _object.object = object;
  4660. if ( object.renderDepth !== null ) {
  4661. _object.z = object.renderDepth;
  4662. } else {
  4663. _vector3.setFromMatrixPosition( object.matrixWorld );
  4664. _vector3.applyProjection( _viewProjectionMatrix );
  4665. _object.z = _vector3.z;
  4666. }
  4667. _renderData.objects.push( _object );
  4668. }
  4669. }
  4670. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  4671. projectObject( object.children[ i ] );
  4672. }
  4673. };
  4674. var projectGraph = function ( root, sortObjects ) {
  4675. _objectCount = 0;
  4676. _renderData.objects.length = 0;
  4677. _renderData.lights.length = 0;
  4678. projectObject( root );
  4679. if ( sortObjects === true ) {
  4680. _renderData.objects.sort( painterSort );
  4681. }
  4682. };
  4683. var RenderList = function () {
  4684. var normals = [];
  4685. var object = null;
  4686. var normalMatrix = new THREE.Matrix3();
  4687. var setObject = function ( value ) {
  4688. object = value;
  4689. normalMatrix.getNormalMatrix( object.matrixWorld );
  4690. normals.length = 0;
  4691. };
  4692. var projectVertex = function ( vertex ) {
  4693. var position = vertex.position;
  4694. var positionWorld = vertex.positionWorld;
  4695. var positionScreen = vertex.positionScreen;
  4696. positionWorld.copy( position ).applyMatrix4( _modelMatrix );
  4697. positionScreen.copy( positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4698. var invW = 1 / positionScreen.w;
  4699. positionScreen.x *= invW;
  4700. positionScreen.y *= invW;
  4701. positionScreen.z *= invW;
  4702. vertex.visible = positionScreen.x >= -1 && positionScreen.x <= 1 &&
  4703. positionScreen.y >= -1 && positionScreen.y <= 1 &&
  4704. positionScreen.z >= -1 && positionScreen.z <= 1;
  4705. };
  4706. var pushVertex = function ( x, y, z ) {
  4707. _vertex = getNextVertexInPool();
  4708. _vertex.position.set( x, y, z );
  4709. projectVertex( _vertex );
  4710. };
  4711. var pushNormal = function ( x, y, z ) {
  4712. normals.push( x, y, z );
  4713. };
  4714. var checkTriangleVisibility = function ( v1, v2, v3 ) {
  4715. _points3[ 0 ] = v1.positionScreen;
  4716. _points3[ 1 ] = v2.positionScreen;
  4717. _points3[ 2 ] = v3.positionScreen;
  4718. if ( v1.visible === true || v2.visible === true || v3.visible === true ||
  4719. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
  4720. return ( ( v3.positionScreen.x - v1.positionScreen.x ) *
  4721. ( v2.positionScreen.y - v1.positionScreen.y ) -
  4722. ( v3.positionScreen.y - v1.positionScreen.y ) *
  4723. ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4724. }
  4725. return false;
  4726. };
  4727. var pushLine = function ( a, b ) {
  4728. var v1 = _vertexPool[ a ];
  4729. var v2 = _vertexPool[ b ];
  4730. _line = getNextLineInPool();
  4731. _line.id = object.id;
  4732. _line.v1.copy( v1 );
  4733. _line.v2.copy( v2 );
  4734. _line.z = ( v1.positionScreen.z + v2.positionScreen.z ) / 2;
  4735. _line.material = object.material;
  4736. _renderData.elements.push( _line );
  4737. };
  4738. var pushTriangle = function ( a, b, c ) {
  4739. var v1 = _vertexPool[ a ];
  4740. var v2 = _vertexPool[ b ];
  4741. var v3 = _vertexPool[ c ];
  4742. if ( checkTriangleVisibility( v1, v2, v3 ) === true ) {
  4743. _face = getNextFaceInPool();
  4744. _face.id = object.id;
  4745. _face.v1.copy( v1 );
  4746. _face.v2.copy( v2 );
  4747. _face.v3.copy( v3 );
  4748. _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
  4749. for ( var i = 0; i < 3; i ++ ) {
  4750. var offset = arguments[ i ] * 3;
  4751. var normal = _face.vertexNormalsModel[ i ];
  4752. normal.set( normals[ offset + 0 ], normals[ offset + 1 ], normals[ offset + 2 ] );
  4753. normal.applyMatrix3( normalMatrix ).normalize();
  4754. }
  4755. _face.vertexNormalsLength = 3;
  4756. _face.material = object.material;
  4757. _renderData.elements.push( _face );
  4758. }
  4759. };
  4760. return {
  4761. setObject: setObject,
  4762. projectVertex: projectVertex,
  4763. checkTriangleVisibility: checkTriangleVisibility,
  4764. pushVertex: pushVertex,
  4765. pushNormal: pushNormal,
  4766. pushLine: pushLine,
  4767. pushTriangle: pushTriangle
  4768. }
  4769. };
  4770. var renderList = new RenderList();
  4771. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4772. var object, geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, uvs,
  4773. isFaceMaterial, objectMaterials;
  4774. _faceCount = 0;
  4775. _lineCount = 0;
  4776. _spriteCount = 0;
  4777. _renderData.elements.length = 0;
  4778. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4779. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4780. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4781. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4782. _frustum.setFromMatrix( _viewProjectionMatrix );
  4783. projectGraph( scene, sortObjects );
  4784. for ( var o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4785. object = _renderData.objects[ o ].object;
  4786. geometry = object.geometry;
  4787. renderList.setObject( object );
  4788. _modelMatrix = object.matrixWorld;
  4789. _vertexCount = 0;
  4790. if ( object instanceof THREE.Mesh ) {
  4791. if ( geometry instanceof THREE.BufferGeometry ) {
  4792. var attributes = geometry.attributes;
  4793. var offsets = geometry.offsets;
  4794. if ( attributes.position === undefined ) continue;
  4795. var positions = attributes.position.array;
  4796. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  4797. renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  4798. }
  4799. var normals = attributes.normal.array;
  4800. for ( var i = 0, l = normals.length; i < l; i += 3 ) {
  4801. renderList.pushNormal( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] );
  4802. }
  4803. if ( attributes.index !== undefined ) {
  4804. var indices = attributes.index.array;
  4805. if ( offsets.length > 0 ) {
  4806. for ( var o = 0; o < offsets.length; o ++ ) {
  4807. var offset = offsets[ o ];
  4808. var index = offset.index;
  4809. for ( var i = offset.start, l = offset.start + offset.count; i < l; i += 3 ) {
  4810. renderList.pushTriangle( indices[ i ] + index, indices[ i + 1 ] + index, indices[ i + 2 ] + index );
  4811. }
  4812. }
  4813. } else {
  4814. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  4815. renderList.pushTriangle( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  4816. }
  4817. }
  4818. } else {
  4819. for ( var i = 0, l = positions.length / 3; i < l; i += 3 ) {
  4820. renderList.pushTriangle( i, i + 1, i + 2 );
  4821. }
  4822. }
  4823. } else if ( geometry instanceof THREE.Geometry2 ) {
  4824. vertices = geometry.vertices;
  4825. for ( var i = 0, j = 0, l = vertices.length; i < l; i += 9, j += 3 ) {
  4826. renderList.pushVertex( vertices[ i + 0 ], vertices[ i + 1 ], vertices[ i + 2 ] );
  4827. renderList.pushVertex( vertices[ i + 3 ], vertices[ i + 4 ], vertices[ i + 5 ] );
  4828. renderList.pushVertex( vertices[ i + 6 ], vertices[ i + 7 ], vertices[ i + 8 ] );
  4829. renderList.pushTriangle( j + 0, j + 1, j + 2 );
  4830. }
  4831. } else if ( geometry instanceof THREE.Geometry ) {
  4832. vertices = geometry.vertices;
  4833. faces = geometry.faces;
  4834. faceVertexUvs = geometry.faceVertexUvs;
  4835. _normalMatrix.getNormalMatrix( _modelMatrix );
  4836. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4837. objectMaterials = isFaceMaterial === true ? object.material : null;
  4838. for ( var v = 0, vl = vertices.length; v < vl; v ++ ) {
  4839. var vertex = vertices[ v ];
  4840. renderList.pushVertex( vertex.x, vertex.y, vertex.z );
  4841. }
  4842. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  4843. face = faces[ f ];
  4844. var material = isFaceMaterial === true
  4845. ? objectMaterials.materials[ face.materialIndex ]
  4846. : object.material;
  4847. if ( material === undefined ) continue;
  4848. var side = material.side;
  4849. var v1 = _vertexPool[ face.a ];
  4850. var v2 = _vertexPool[ face.b ];
  4851. var v3 = _vertexPool[ face.c ];
  4852. if ( material.morphTargets === true ) {
  4853. var morphTargets = geometry.morphTargets;
  4854. var morphInfluences = object.morphTargetInfluences;
  4855. var v1p = v1.position;
  4856. var v2p = v2.position;
  4857. var v3p = v3.position;
  4858. _vA.set( 0, 0, 0 );
  4859. _vB.set( 0, 0, 0 );
  4860. _vC.set( 0, 0, 0 );
  4861. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  4862. var influence = morphInfluences[ t ];
  4863. if ( influence === 0 ) continue;
  4864. var targets = morphTargets[ t ].vertices;
  4865. _vA.x += ( targets[ face.a ].x - v1p.x ) * influence;
  4866. _vA.y += ( targets[ face.a ].y - v1p.y ) * influence;
  4867. _vA.z += ( targets[ face.a ].z - v1p.z ) * influence;
  4868. _vB.x += ( targets[ face.b ].x - v2p.x ) * influence;
  4869. _vB.y += ( targets[ face.b ].y - v2p.y ) * influence;
  4870. _vB.z += ( targets[ face.b ].z - v2p.z ) * influence;
  4871. _vC.x += ( targets[ face.c ].x - v3p.x ) * influence;
  4872. _vC.y += ( targets[ face.c ].y - v3p.y ) * influence;
  4873. _vC.z += ( targets[ face.c ].z - v3p.z ) * influence;
  4874. }
  4875. v1.position.add( _vA );
  4876. v2.position.add( _vB );
  4877. v3.position.add( _vC );
  4878. renderList.projectVertex( v1 );
  4879. renderList.projectVertex( v2 );
  4880. renderList.projectVertex( v3 );
  4881. }
  4882. var visible = renderList.checkTriangleVisibility( v1, v2, v3 );
  4883. if ( visible === ( side === THREE.BackSide ) ) continue;
  4884. _face = getNextFaceInPool();
  4885. _face.id = object.id;
  4886. _face.v1.copy( v1 );
  4887. _face.v2.copy( v2 );
  4888. _face.v3.copy( v3 );
  4889. _face.normalModel.copy( face.normal );
  4890. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4891. _face.normalModel.negate();
  4892. }
  4893. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4894. _face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix );
  4895. faceVertexNormals = face.vertexNormals;
  4896. for ( var n = 0, nl = Math.min( faceVertexNormals.length, 3 ); n < nl; n ++ ) {
  4897. var normalModel = _face.vertexNormalsModel[ n ];
  4898. normalModel.copy( faceVertexNormals[ n ] );
  4899. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4900. normalModel.negate();
  4901. }
  4902. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4903. }
  4904. _face.vertexNormalsLength = faceVertexNormals.length;
  4905. for ( var c = 0, cl = Math.min( faceVertexUvs.length, 3 ); c < cl; c ++ ) {
  4906. uvs = faceVertexUvs[ c ][ f ];
  4907. if ( uvs === undefined ) continue;
  4908. for ( var u = 0, ul = uvs.length; u < ul; u ++ ) {
  4909. _face.uvs[ c ][ u ] = uvs[ u ];
  4910. }
  4911. }
  4912. _face.color = face.color;
  4913. _face.material = material;
  4914. _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
  4915. _renderData.elements.push( _face );
  4916. }
  4917. }
  4918. } else if ( object instanceof THREE.Line ) {
  4919. if ( geometry instanceof THREE.BufferGeometry ) {
  4920. var attributes = geometry.attributes;
  4921. if ( attributes.position !== undefined ) {
  4922. var positions = attributes.position.array;
  4923. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  4924. renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  4925. }
  4926. if ( attributes.index !== undefined ) {
  4927. var indices = attributes.index.array;
  4928. for ( var i = 0, l = indices.length; i < l; i += 2 ) {
  4929. renderList.pushLine( indices[ i ], indices[ i + 1 ] );
  4930. }
  4931. } else {
  4932. for ( var i = 0, l = ( positions.length / 3 ) - 1; i < l; i ++ ) {
  4933. renderList.pushLine( i, i + 1 );
  4934. }
  4935. }
  4936. }
  4937. } else if ( geometry instanceof THREE.Geometry ) {
  4938. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  4939. vertices = object.geometry.vertices;
  4940. if ( vertices.length === 0 ) continue;
  4941. v1 = getNextVertexInPool();
  4942. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  4943. // Handle LineStrip and LinePieces
  4944. var step = object.type === THREE.LinePieces ? 2 : 1;
  4945. for ( var v = 1, vl = vertices.length; v < vl; v ++ ) {
  4946. v1 = getNextVertexInPool();
  4947. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  4948. if ( ( v + 1 ) % step > 0 ) continue;
  4949. v2 = _vertexPool[ _vertexCount - 2 ];
  4950. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  4951. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  4952. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  4953. // Perform the perspective divide
  4954. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  4955. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  4956. _line = getNextLineInPool();
  4957. _line.id = object.id;
  4958. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  4959. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  4960. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  4961. _line.material = object.material;
  4962. if ( object.material.vertexColors === THREE.VertexColors ) {
  4963. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  4964. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  4965. }
  4966. _renderData.elements.push( _line );
  4967. }
  4968. }
  4969. }
  4970. } else if ( object instanceof THREE.Sprite ) {
  4971. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  4972. _vector4.applyMatrix4( _viewProjectionMatrix );
  4973. var invW = 1 / _vector4.w;
  4974. _vector4.z *= invW;
  4975. if ( _vector4.z >= -1 && _vector4.z <= 1 ) {
  4976. _sprite = getNextSpriteInPool();
  4977. _sprite.id = object.id;
  4978. _sprite.x = _vector4.x * invW;
  4979. _sprite.y = _vector4.y * invW;
  4980. _sprite.z = _vector4.z;
  4981. _sprite.object = object;
  4982. _sprite.rotation = object.rotation;
  4983. _sprite.scale.x = object.scale.x * Math.abs( _sprite.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  4984. _sprite.scale.y = object.scale.y * Math.abs( _sprite.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  4985. _sprite.material = object.material;
  4986. _renderData.elements.push( _sprite );
  4987. }
  4988. }
  4989. }
  4990. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4991. return _renderData;
  4992. };
  4993. // Pools
  4994. function getNextObjectInPool() {
  4995. if ( _objectCount === _objectPoolLength ) {
  4996. var object = new THREE.RenderableObject();
  4997. _objectPool.push( object );
  4998. _objectPoolLength ++;
  4999. _objectCount ++;
  5000. return object;
  5001. }
  5002. return _objectPool[ _objectCount ++ ];
  5003. }
  5004. function getNextVertexInPool() {
  5005. if ( _vertexCount === _vertexPoolLength ) {
  5006. var vertex = new THREE.RenderableVertex();
  5007. _vertexPool.push( vertex );
  5008. _vertexPoolLength ++;
  5009. _vertexCount ++;
  5010. return vertex;
  5011. }
  5012. return _vertexPool[ _vertexCount ++ ];
  5013. }
  5014. function getNextFaceInPool() {
  5015. if ( _faceCount === _facePoolLength ) {
  5016. var face = new THREE.RenderableFace();
  5017. _facePool.push( face );
  5018. _facePoolLength ++;
  5019. _faceCount ++;
  5020. return face;
  5021. }
  5022. return _facePool[ _faceCount ++ ];
  5023. }
  5024. function getNextLineInPool() {
  5025. if ( _lineCount === _linePoolLength ) {
  5026. var line = new THREE.RenderableLine();
  5027. _linePool.push( line );
  5028. _linePoolLength ++;
  5029. _lineCount ++
  5030. return line;
  5031. }
  5032. return _linePool[ _lineCount ++ ];
  5033. }
  5034. function getNextSpriteInPool() {
  5035. if ( _spriteCount === _spritePoolLength ) {
  5036. var sprite = new THREE.RenderableSprite();
  5037. _spritePool.push( sprite );
  5038. _spritePoolLength ++;
  5039. _spriteCount ++
  5040. return sprite;
  5041. }
  5042. return _spritePool[ _spriteCount ++ ];
  5043. }
  5044. //
  5045. function painterSort( a, b ) {
  5046. if ( a.z !== b.z ) {
  5047. return b.z - a.z;
  5048. } else if ( a.id !== b.id ) {
  5049. return a.id - b.id;
  5050. } else {
  5051. return 0;
  5052. }
  5053. }
  5054. function clipLine( s1, s2 ) {
  5055. var alpha1 = 0, alpha2 = 1,
  5056. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  5057. // Z = -1 and Z = +1, respectively.
  5058. bc1near = s1.z + s1.w,
  5059. bc2near = s2.z + s2.w,
  5060. bc1far = - s1.z + s1.w,
  5061. bc2far = - s2.z + s2.w;
  5062. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  5063. // Both vertices lie entirely within all clip planes.
  5064. return true;
  5065. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  5066. // Both vertices lie entirely outside one of the clip planes.
  5067. return false;
  5068. } else {
  5069. // The line segment spans at least one clip plane.
  5070. if ( bc1near < 0 ) {
  5071. // v1 lies outside the near plane, v2 inside
  5072. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  5073. } else if ( bc2near < 0 ) {
  5074. // v2 lies outside the near plane, v1 inside
  5075. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  5076. }
  5077. if ( bc1far < 0 ) {
  5078. // v1 lies outside the far plane, v2 inside
  5079. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  5080. } else if ( bc2far < 0 ) {
  5081. // v2 lies outside the far plane, v2 inside
  5082. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  5083. }
  5084. if ( alpha2 < alpha1 ) {
  5085. // The line segment spans two boundaries, but is outside both of them.
  5086. // (This can't happen when we're only clipping against just near/far but good
  5087. // to leave the check here for future usage if other clip planes are added.)
  5088. return false;
  5089. } else {
  5090. // Update the s1 and s2 vertices to match the clipped line segment.
  5091. s1.lerp( s2, alpha1 );
  5092. s2.lerp( s1, 1 - alpha2 );
  5093. return true;
  5094. }
  5095. }
  5096. }
  5097. };
  5098. /**
  5099. * @author mrdoob / http://mrdoob.com/
  5100. * @author alteredq / http://alteredqualia.com/
  5101. */
  5102. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  5103. this.a = a;
  5104. this.b = b;
  5105. this.c = c;
  5106. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  5107. this.vertexNormals = normal instanceof Array ? normal : [ ];
  5108. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  5109. this.vertexColors = color instanceof Array ? color : [];
  5110. this.vertexTangents = [];
  5111. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  5112. this.centroid = new THREE.Vector3();
  5113. };
  5114. THREE.Face3.prototype = {
  5115. constructor: THREE.Face3,
  5116. clone: function () {
  5117. var face = new THREE.Face3( this.a, this.b, this.c );
  5118. face.normal.copy( this.normal );
  5119. face.color.copy( this.color );
  5120. face.centroid.copy( this.centroid );
  5121. face.materialIndex = this.materialIndex;
  5122. var i, il;
  5123. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  5124. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  5125. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  5126. return face;
  5127. }
  5128. };
  5129. /**
  5130. * @author mrdoob / http://mrdoob.com/
  5131. */
  5132. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  5133. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.')
  5134. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  5135. };
  5136. /**
  5137. * @author mrdoob / http://mrdoob.com/
  5138. * @author kile / http://kile.stravaganza.org/
  5139. * @author alteredq / http://alteredqualia.com/
  5140. * @author mikael emtinger / http://gomo.se/
  5141. * @author zz85 / http://www.lab4games.net/zz85/blog
  5142. * @author bhouston / http://exocortex.com
  5143. */
  5144. THREE.Geometry = function () {
  5145. this.id = THREE.GeometryIdCount ++;
  5146. this.uuid = THREE.Math.generateUUID();
  5147. this.name = '';
  5148. this.vertices = [];
  5149. this.colors = []; // one-to-one vertex colors, used in ParticleSystem and Line
  5150. this.faces = [];
  5151. this.faceVertexUvs = [[]];
  5152. this.morphTargets = [];
  5153. this.morphColors = [];
  5154. this.morphNormals = [];
  5155. this.skinWeights = [];
  5156. this.skinIndices = [];
  5157. this.lineDistances = [];
  5158. this.boundingBox = null;
  5159. this.boundingSphere = null;
  5160. this.hasTangents = false;
  5161. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  5162. // update flags
  5163. this.verticesNeedUpdate = false;
  5164. this.elementsNeedUpdate = false;
  5165. this.uvsNeedUpdate = false;
  5166. this.normalsNeedUpdate = false;
  5167. this.tangentsNeedUpdate = false;
  5168. this.colorsNeedUpdate = false;
  5169. this.lineDistancesNeedUpdate = false;
  5170. this.buffersNeedUpdate = false;
  5171. };
  5172. THREE.Geometry.prototype = {
  5173. constructor: THREE.Geometry,
  5174. applyMatrix: function ( matrix ) {
  5175. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5176. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  5177. var vertex = this.vertices[ i ];
  5178. vertex.applyMatrix4( matrix );
  5179. }
  5180. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  5181. var face = this.faces[ i ];
  5182. face.normal.applyMatrix3( normalMatrix ).normalize();
  5183. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  5184. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  5185. }
  5186. face.centroid.applyMatrix4( matrix );
  5187. }
  5188. if ( this.boundingBox instanceof THREE.Box3 ) {
  5189. this.computeBoundingBox();
  5190. }
  5191. if ( this.boundingSphere instanceof THREE.Sphere ) {
  5192. this.computeBoundingSphere();
  5193. }
  5194. },
  5195. computeCentroids: function () {
  5196. var f, fl, face;
  5197. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5198. face = this.faces[ f ];
  5199. face.centroid.set( 0, 0, 0 );
  5200. face.centroid.add( this.vertices[ face.a ] );
  5201. face.centroid.add( this.vertices[ face.b ] );
  5202. face.centroid.add( this.vertices[ face.c ] );
  5203. face.centroid.divideScalar( 3 );
  5204. }
  5205. },
  5206. computeFaceNormals: function () {
  5207. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5208. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5209. var face = this.faces[ f ];
  5210. var vA = this.vertices[ face.a ];
  5211. var vB = this.vertices[ face.b ];
  5212. var vC = this.vertices[ face.c ];
  5213. cb.subVectors( vC, vB );
  5214. ab.subVectors( vA, vB );
  5215. cb.cross( ab );
  5216. cb.normalize();
  5217. face.normal.copy( cb );
  5218. }
  5219. },
  5220. computeVertexNormals: function ( areaWeighted ) {
  5221. var v, vl, f, fl, face, vertices;
  5222. vertices = new Array( this.vertices.length );
  5223. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5224. vertices[ v ] = new THREE.Vector3();
  5225. }
  5226. if ( areaWeighted ) {
  5227. // vertex normals weighted by triangle areas
  5228. // http://www.iquilezles.org/www/articles/normals/normals.htm
  5229. var vA, vB, vC, vD;
  5230. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  5231. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  5232. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5233. face = this.faces[ f ];
  5234. vA = this.vertices[ face.a ];
  5235. vB = this.vertices[ face.b ];
  5236. vC = this.vertices[ face.c ];
  5237. cb.subVectors( vC, vB );
  5238. ab.subVectors( vA, vB );
  5239. cb.cross( ab );
  5240. vertices[ face.a ].add( cb );
  5241. vertices[ face.b ].add( cb );
  5242. vertices[ face.c ].add( cb );
  5243. }
  5244. } else {
  5245. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5246. face = this.faces[ f ];
  5247. vertices[ face.a ].add( face.normal );
  5248. vertices[ face.b ].add( face.normal );
  5249. vertices[ face.c ].add( face.normal );
  5250. }
  5251. }
  5252. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5253. vertices[ v ].normalize();
  5254. }
  5255. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5256. face = this.faces[ f ];
  5257. face.vertexNormals[ 0 ] = vertices[ face.a ].clone();
  5258. face.vertexNormals[ 1 ] = vertices[ face.b ].clone();
  5259. face.vertexNormals[ 2 ] = vertices[ face.c ].clone();
  5260. }
  5261. },
  5262. computeMorphNormals: function () {
  5263. var i, il, f, fl, face;
  5264. // save original normals
  5265. // - create temp variables on first access
  5266. // otherwise just copy (for faster repeated calls)
  5267. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5268. face = this.faces[ f ];
  5269. if ( ! face.__originalFaceNormal ) {
  5270. face.__originalFaceNormal = face.normal.clone();
  5271. } else {
  5272. face.__originalFaceNormal.copy( face.normal );
  5273. }
  5274. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  5275. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  5276. if ( ! face.__originalVertexNormals[ i ] ) {
  5277. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  5278. } else {
  5279. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  5280. }
  5281. }
  5282. }
  5283. // use temp geometry to compute face and vertex normals for each morph
  5284. var tmpGeo = new THREE.Geometry();
  5285. tmpGeo.faces = this.faces;
  5286. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  5287. // create on first access
  5288. if ( ! this.morphNormals[ i ] ) {
  5289. this.morphNormals[ i ] = {};
  5290. this.morphNormals[ i ].faceNormals = [];
  5291. this.morphNormals[ i ].vertexNormals = [];
  5292. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  5293. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  5294. var faceNormal, vertexNormals;
  5295. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5296. face = this.faces[ f ];
  5297. faceNormal = new THREE.Vector3();
  5298. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  5299. dstNormalsFace.push( faceNormal );
  5300. dstNormalsVertex.push( vertexNormals );
  5301. }
  5302. }
  5303. var morphNormals = this.morphNormals[ i ];
  5304. // set vertices to morph target
  5305. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  5306. // compute morph normals
  5307. tmpGeo.computeFaceNormals();
  5308. tmpGeo.computeVertexNormals();
  5309. // store morph normals
  5310. var faceNormal, vertexNormals;
  5311. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5312. face = this.faces[ f ];
  5313. faceNormal = morphNormals.faceNormals[ f ];
  5314. vertexNormals = morphNormals.vertexNormals[ f ];
  5315. faceNormal.copy( face.normal );
  5316. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  5317. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  5318. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  5319. }
  5320. }
  5321. // restore original normals
  5322. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5323. face = this.faces[ f ];
  5324. face.normal = face.__originalFaceNormal;
  5325. face.vertexNormals = face.__originalVertexNormals;
  5326. }
  5327. },
  5328. computeTangents: function () {
  5329. // based on http://www.terathon.com/code/tangent.html
  5330. // tangents go to vertices
  5331. var f, fl, v, vl, i, il, vertexIndex,
  5332. face, uv, vA, vB, vC, uvA, uvB, uvC,
  5333. x1, x2, y1, y2, z1, z2,
  5334. s1, s2, t1, t2, r, t, test,
  5335. tan1 = [], tan2 = [],
  5336. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  5337. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  5338. n = new THREE.Vector3(), w;
  5339. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5340. tan1[ v ] = new THREE.Vector3();
  5341. tan2[ v ] = new THREE.Vector3();
  5342. }
  5343. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  5344. vA = context.vertices[ a ];
  5345. vB = context.vertices[ b ];
  5346. vC = context.vertices[ c ];
  5347. uvA = uv[ ua ];
  5348. uvB = uv[ ub ];
  5349. uvC = uv[ uc ];
  5350. x1 = vB.x - vA.x;
  5351. x2 = vC.x - vA.x;
  5352. y1 = vB.y - vA.y;
  5353. y2 = vC.y - vA.y;
  5354. z1 = vB.z - vA.z;
  5355. z2 = vC.z - vA.z;
  5356. s1 = uvB.x - uvA.x;
  5357. s2 = uvC.x - uvA.x;
  5358. t1 = uvB.y - uvA.y;
  5359. t2 = uvC.y - uvA.y;
  5360. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5361. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  5362. ( t2 * y1 - t1 * y2 ) * r,
  5363. ( t2 * z1 - t1 * z2 ) * r );
  5364. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  5365. ( s1 * y2 - s2 * y1 ) * r,
  5366. ( s1 * z2 - s2 * z1 ) * r );
  5367. tan1[ a ].add( sdir );
  5368. tan1[ b ].add( sdir );
  5369. tan1[ c ].add( sdir );
  5370. tan2[ a ].add( tdir );
  5371. tan2[ b ].add( tdir );
  5372. tan2[ c ].add( tdir );
  5373. }
  5374. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5375. face = this.faces[ f ];
  5376. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  5377. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  5378. }
  5379. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  5380. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5381. face = this.faces[ f ];
  5382. for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i++ ) {
  5383. n.copy( face.vertexNormals[ i ] );
  5384. vertexIndex = face[ faceIndex[ i ] ];
  5385. t = tan1[ vertexIndex ];
  5386. // Gram-Schmidt orthogonalize
  5387. tmp.copy( t );
  5388. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5389. // Calculate handedness
  5390. tmp2.crossVectors( face.vertexNormals[ i ], t );
  5391. test = tmp2.dot( tan2[ vertexIndex ] );
  5392. w = (test < 0.0) ? -1.0 : 1.0;
  5393. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  5394. }
  5395. }
  5396. this.hasTangents = true;
  5397. },
  5398. computeLineDistances: function ( ) {
  5399. var d = 0;
  5400. var vertices = this.vertices;
  5401. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5402. if ( i > 0 ) {
  5403. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  5404. }
  5405. this.lineDistances[ i ] = d;
  5406. }
  5407. },
  5408. computeBoundingBox: function () {
  5409. if ( this.boundingBox === null ) {
  5410. this.boundingBox = new THREE.Box3();
  5411. }
  5412. this.boundingBox.setFromPoints( this.vertices );
  5413. },
  5414. computeBoundingSphere: function () {
  5415. if ( this.boundingSphere === null ) {
  5416. this.boundingSphere = new THREE.Sphere();
  5417. }
  5418. this.boundingSphere.setFromPoints( this.vertices );
  5419. },
  5420. /*
  5421. * Checks for duplicate vertices with hashmap.
  5422. * Duplicated vertices are removed
  5423. * and faces' vertices are updated.
  5424. */
  5425. mergeVertices: function () {
  5426. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  5427. var unique = [], changes = [];
  5428. var v, key;
  5429. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  5430. var precision = Math.pow( 10, precisionPoints );
  5431. var i,il, face;
  5432. var indices, k, j, jl, u;
  5433. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  5434. v = this.vertices[ i ];
  5435. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  5436. if ( verticesMap[ key ] === undefined ) {
  5437. verticesMap[ key ] = i;
  5438. unique.push( this.vertices[ i ] );
  5439. changes[ i ] = unique.length - 1;
  5440. } else {
  5441. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  5442. changes[ i ] = changes[ verticesMap[ key ] ];
  5443. }
  5444. };
  5445. // if faces are completely degenerate after merging vertices, we
  5446. // have to remove them from the geometry.
  5447. var faceIndicesToRemove = [];
  5448. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  5449. face = this.faces[ i ];
  5450. face.a = changes[ face.a ];
  5451. face.b = changes[ face.b ];
  5452. face.c = changes[ face.c ];
  5453. indices = [ face.a, face.b, face.c ];
  5454. var dupIndex = -1;
  5455. // if any duplicate vertices are found in a Face3
  5456. // we have to remove the face as nothing can be saved
  5457. for ( var n = 0; n < 3; n ++ ) {
  5458. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  5459. dupIndex = n;
  5460. faceIndicesToRemove.push( i );
  5461. break;
  5462. }
  5463. }
  5464. }
  5465. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  5466. var idx = faceIndicesToRemove[ i ];
  5467. this.faces.splice( idx, 1 );
  5468. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  5469. this.faceVertexUvs[ j ].splice( idx, 1 );
  5470. }
  5471. }
  5472. // Use unique set of vertices
  5473. var diff = this.vertices.length - unique.length;
  5474. this.vertices = unique;
  5475. return diff;
  5476. },
  5477. clone: function () {
  5478. var geometry = new THREE.Geometry();
  5479. var vertices = this.vertices;
  5480. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5481. geometry.vertices.push( vertices[ i ].clone() );
  5482. }
  5483. var faces = this.faces;
  5484. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  5485. geometry.faces.push( faces[ i ].clone() );
  5486. }
  5487. var uvs = this.faceVertexUvs[ 0 ];
  5488. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  5489. var uv = uvs[ i ], uvCopy = [];
  5490. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  5491. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  5492. }
  5493. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  5494. }
  5495. return geometry;
  5496. },
  5497. dispose: function () {
  5498. this.dispatchEvent( { type: 'dispose' } );
  5499. }
  5500. };
  5501. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  5502. THREE.GeometryIdCount = 0;
  5503. /**
  5504. * @author mrdoob / http://mrdoob.com/
  5505. */
  5506. THREE.Geometry2 = function ( size ) {
  5507. this.id = THREE.GeometryIdCount ++;
  5508. this.uuid = THREE.Math.generateUUID();
  5509. this.name = '';
  5510. this.vertices = size !== undefined ? new Float32Array( size * 3 ) : [];
  5511. this.normals = size !== undefined ? new Float32Array( size * 3 ) : [];
  5512. this.uvs = size !== undefined ? new Float32Array( size * 2 ) : [];
  5513. this.boundingBox = null;
  5514. this.boundingSphere = null;
  5515. };
  5516. THREE.Geometry2.prototype = {
  5517. constructor: THREE.Geometry2,
  5518. applyMatrix: function ( matrix ) {
  5519. matrix.multiplyVector3Array( this.vertices );
  5520. },
  5521. computeBoundingBox: function () {
  5522. if ( this.boundingBox === null ) {
  5523. this.boundingBox = new THREE.Box3();
  5524. }
  5525. var vertices = this.vertices;
  5526. var bb = this.boundingBox;
  5527. if ( vertices.length >= 3 ) {
  5528. bb.min.x = bb.max.x = vertices[ 0 ];
  5529. bb.min.y = bb.max.y = vertices[ 1 ];
  5530. bb.min.z = bb.max.z = vertices[ 2 ];
  5531. }
  5532. for ( var i = 3, il = vertices.length; i < il; i += 3 ) {
  5533. var x = vertices[ i ];
  5534. var y = vertices[ i + 1 ];
  5535. var z = vertices[ i + 2 ];
  5536. // bounding box
  5537. if ( x < bb.min.x ) {
  5538. bb.min.x = x;
  5539. } else if ( x > bb.max.x ) {
  5540. bb.max.x = x;
  5541. }
  5542. if ( y < bb.min.y ) {
  5543. bb.min.y = y;
  5544. } else if ( y > bb.max.y ) {
  5545. bb.max.y = y;
  5546. }
  5547. if ( z < bb.min.z ) {
  5548. bb.min.z = z;
  5549. } else if ( z > bb.max.z ) {
  5550. bb.max.z = z;
  5551. }
  5552. }
  5553. },
  5554. computeBoundingSphere: function () {
  5555. var box = new THREE.Box3();
  5556. var vector = new THREE.Vector3();
  5557. return function () {
  5558. if ( this.boundingSphere === null ) {
  5559. this.boundingSphere = new THREE.Sphere();
  5560. }
  5561. box.makeEmpty();
  5562. var vertices = this.vertices;
  5563. var center = this.boundingSphere.center;
  5564. for ( var i = 0, il = vertices.length; i < il; i += 3 ) {
  5565. vector.set( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] );
  5566. box.addPoint( vector );
  5567. }
  5568. box.center( center );
  5569. var maxRadiusSq = 0;
  5570. for ( var i = 0, il = vertices.length; i < il; i += 3 ) {
  5571. vector.set( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] );
  5572. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  5573. }
  5574. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5575. }
  5576. }(),
  5577. dispose: function () {
  5578. this.dispatchEvent( { type: 'dispose' } );
  5579. }
  5580. };
  5581. THREE.EventDispatcher.prototype.apply( THREE.Geometry2.prototype );
  5582. /**
  5583. * @author alteredq / http://alteredqualia.com/
  5584. */
  5585. THREE.BufferGeometry = function () {
  5586. this.id = THREE.GeometryIdCount ++;
  5587. this.uuid = THREE.Math.generateUUID();
  5588. this.name = '';
  5589. // attributes
  5590. this.attributes = {};
  5591. // offsets for chunks when using indexed elements
  5592. this.offsets = [];
  5593. // boundings
  5594. this.boundingBox = null;
  5595. this.boundingSphere = null;
  5596. this.hasTangents = false;
  5597. };
  5598. THREE.BufferGeometry.prototype = {
  5599. constructor: THREE.BufferGeometry,
  5600. addAttribute: function ( name, type, numItems, itemSize ) {
  5601. this.attributes[ name ] = {
  5602. itemSize: itemSize,
  5603. array: new type( numItems * itemSize )
  5604. };
  5605. },
  5606. applyMatrix: function ( matrix ) {
  5607. var positionArray;
  5608. var normalArray;
  5609. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  5610. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  5611. if ( positionArray !== undefined ) {
  5612. matrix.multiplyVector3Array( positionArray );
  5613. this.verticesNeedUpdate = true;
  5614. }
  5615. if ( normalArray !== undefined ) {
  5616. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5617. normalMatrix.multiplyVector3Array( normalArray );
  5618. this.normalizeNormals();
  5619. this.normalsNeedUpdate = true;
  5620. }
  5621. },
  5622. computeBoundingBox: function () {
  5623. if ( this.boundingBox === null ) {
  5624. this.boundingBox = new THREE.Box3();
  5625. }
  5626. var positions = this.attributes[ "position" ].array;
  5627. if ( positions ) {
  5628. var bb = this.boundingBox;
  5629. if( positions.length >= 3 ) {
  5630. bb.min.x = bb.max.x = positions[ 0 ];
  5631. bb.min.y = bb.max.y = positions[ 1 ];
  5632. bb.min.z = bb.max.z = positions[ 2 ];
  5633. }
  5634. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  5635. var x = positions[ i ];
  5636. var y = positions[ i + 1 ];
  5637. var z = positions[ i + 2 ];
  5638. // bounding box
  5639. if ( x < bb.min.x ) {
  5640. bb.min.x = x;
  5641. } else if ( x > bb.max.x ) {
  5642. bb.max.x = x;
  5643. }
  5644. if ( y < bb.min.y ) {
  5645. bb.min.y = y;
  5646. } else if ( y > bb.max.y ) {
  5647. bb.max.y = y;
  5648. }
  5649. if ( z < bb.min.z ) {
  5650. bb.min.z = z;
  5651. } else if ( z > bb.max.z ) {
  5652. bb.max.z = z;
  5653. }
  5654. }
  5655. }
  5656. if ( positions === undefined || positions.length === 0 ) {
  5657. this.boundingBox.min.set( 0, 0, 0 );
  5658. this.boundingBox.max.set( 0, 0, 0 );
  5659. }
  5660. },
  5661. computeBoundingSphere: function () {
  5662. var box = new THREE.Box3();
  5663. var vector = new THREE.Vector3();
  5664. return function () {
  5665. if ( this.boundingSphere === null ) {
  5666. this.boundingSphere = new THREE.Sphere();
  5667. }
  5668. var positions = this.attributes[ "position" ].array;
  5669. if ( positions ) {
  5670. box.makeEmpty();
  5671. var center = this.boundingSphere.center;
  5672. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5673. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5674. box.addPoint( vector );
  5675. }
  5676. box.center( center );
  5677. var maxRadiusSq = 0;
  5678. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5679. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5680. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  5681. }
  5682. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5683. }
  5684. }
  5685. }(),
  5686. computeVertexNormals: function () {
  5687. if ( this.attributes[ "position" ] ) {
  5688. var i, il;
  5689. var j, jl;
  5690. var nVertexElements = this.attributes[ "position" ].array.length;
  5691. if ( this.attributes[ "normal" ] === undefined ) {
  5692. this.attributes[ "normal" ] = {
  5693. itemSize: 3,
  5694. array: new Float32Array( nVertexElements )
  5695. };
  5696. } else {
  5697. // reset existing normals to zero
  5698. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  5699. this.attributes[ "normal" ].array[ i ] = 0;
  5700. }
  5701. }
  5702. var positions = this.attributes[ "position" ].array;
  5703. var normals = this.attributes[ "normal" ].array;
  5704. var vA, vB, vC, x, y, z,
  5705. pA = new THREE.Vector3(),
  5706. pB = new THREE.Vector3(),
  5707. pC = new THREE.Vector3(),
  5708. cb = new THREE.Vector3(),
  5709. ab = new THREE.Vector3();
  5710. // indexed elements
  5711. if ( this.attributes[ "index" ] ) {
  5712. var indices = this.attributes[ "index" ].array;
  5713. var offsets = this.offsets;
  5714. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5715. var start = offsets[ j ].start;
  5716. var count = offsets[ j ].count;
  5717. var index = offsets[ j ].index;
  5718. for ( i = start, il = start + count; i < il; i += 3 ) {
  5719. vA = index + indices[ i ];
  5720. vB = index + indices[ i + 1 ];
  5721. vC = index + indices[ i + 2 ];
  5722. x = positions[ vA * 3 ];
  5723. y = positions[ vA * 3 + 1 ];
  5724. z = positions[ vA * 3 + 2 ];
  5725. pA.set( x, y, z );
  5726. x = positions[ vB * 3 ];
  5727. y = positions[ vB * 3 + 1 ];
  5728. z = positions[ vB * 3 + 2 ];
  5729. pB.set( x, y, z );
  5730. x = positions[ vC * 3 ];
  5731. y = positions[ vC * 3 + 1 ];
  5732. z = positions[ vC * 3 + 2 ];
  5733. pC.set( x, y, z );
  5734. cb.subVectors( pC, pB );
  5735. ab.subVectors( pA, pB );
  5736. cb.cross( ab );
  5737. normals[ vA * 3 ] += cb.x;
  5738. normals[ vA * 3 + 1 ] += cb.y;
  5739. normals[ vA * 3 + 2 ] += cb.z;
  5740. normals[ vB * 3 ] += cb.x;
  5741. normals[ vB * 3 + 1 ] += cb.y;
  5742. normals[ vB * 3 + 2 ] += cb.z;
  5743. normals[ vC * 3 ] += cb.x;
  5744. normals[ vC * 3 + 1 ] += cb.y;
  5745. normals[ vC * 3 + 2 ] += cb.z;
  5746. }
  5747. }
  5748. // non-indexed elements (unconnected triangle soup)
  5749. } else {
  5750. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5751. x = positions[ i ];
  5752. y = positions[ i + 1 ];
  5753. z = positions[ i + 2 ];
  5754. pA.set( x, y, z );
  5755. x = positions[ i + 3 ];
  5756. y = positions[ i + 4 ];
  5757. z = positions[ i + 5 ];
  5758. pB.set( x, y, z );
  5759. x = positions[ i + 6 ];
  5760. y = positions[ i + 7 ];
  5761. z = positions[ i + 8 ];
  5762. pC.set( x, y, z );
  5763. cb.subVectors( pC, pB );
  5764. ab.subVectors( pA, pB );
  5765. cb.cross( ab );
  5766. normals[ i ] = cb.x;
  5767. normals[ i + 1 ] = cb.y;
  5768. normals[ i + 2 ] = cb.z;
  5769. normals[ i + 3 ] = cb.x;
  5770. normals[ i + 4 ] = cb.y;
  5771. normals[ i + 5 ] = cb.z;
  5772. normals[ i + 6 ] = cb.x;
  5773. normals[ i + 7 ] = cb.y;
  5774. normals[ i + 8 ] = cb.z;
  5775. }
  5776. }
  5777. this.normalizeNormals();
  5778. this.normalsNeedUpdate = true;
  5779. }
  5780. },
  5781. normalizeNormals: function () {
  5782. var normals = this.attributes[ "normal" ].array;
  5783. var x, y, z, n;
  5784. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5785. x = normals[ i ];
  5786. y = normals[ i + 1 ];
  5787. z = normals[ i + 2 ];
  5788. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5789. normals[ i ] *= n;
  5790. normals[ i + 1 ] *= n;
  5791. normals[ i + 2 ] *= n;
  5792. }
  5793. },
  5794. computeTangents: function () {
  5795. // based on http://www.terathon.com/code/tangent.html
  5796. // (per vertex tangents)
  5797. if ( this.attributes[ "index" ] === undefined ||
  5798. this.attributes[ "position" ] === undefined ||
  5799. this.attributes[ "normal" ] === undefined ||
  5800. this.attributes[ "uv" ] === undefined ) {
  5801. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5802. return;
  5803. }
  5804. var indices = this.attributes[ "index" ].array;
  5805. var positions = this.attributes[ "position" ].array;
  5806. var normals = this.attributes[ "normal" ].array;
  5807. var uvs = this.attributes[ "uv" ].array;
  5808. var nVertices = positions.length / 3;
  5809. if ( this.attributes[ "tangent" ] === undefined ) {
  5810. var nTangentElements = 4 * nVertices;
  5811. this.attributes[ "tangent" ] = {
  5812. itemSize: 4,
  5813. array: new Float32Array( nTangentElements )
  5814. };
  5815. }
  5816. var tangents = this.attributes[ "tangent" ].array;
  5817. var tan1 = [], tan2 = [];
  5818. for ( var k = 0; k < nVertices; k ++ ) {
  5819. tan1[ k ] = new THREE.Vector3();
  5820. tan2[ k ] = new THREE.Vector3();
  5821. }
  5822. var xA, yA, zA,
  5823. xB, yB, zB,
  5824. xC, yC, zC,
  5825. uA, vA,
  5826. uB, vB,
  5827. uC, vC,
  5828. x1, x2, y1, y2, z1, z2,
  5829. s1, s2, t1, t2, r;
  5830. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5831. function handleTriangle( a, b, c ) {
  5832. xA = positions[ a * 3 ];
  5833. yA = positions[ a * 3 + 1 ];
  5834. zA = positions[ a * 3 + 2 ];
  5835. xB = positions[ b * 3 ];
  5836. yB = positions[ b * 3 + 1 ];
  5837. zB = positions[ b * 3 + 2 ];
  5838. xC = positions[ c * 3 ];
  5839. yC = positions[ c * 3 + 1 ];
  5840. zC = positions[ c * 3 + 2 ];
  5841. uA = uvs[ a * 2 ];
  5842. vA = uvs[ a * 2 + 1 ];
  5843. uB = uvs[ b * 2 ];
  5844. vB = uvs[ b * 2 + 1 ];
  5845. uC = uvs[ c * 2 ];
  5846. vC = uvs[ c * 2 + 1 ];
  5847. x1 = xB - xA;
  5848. x2 = xC - xA;
  5849. y1 = yB - yA;
  5850. y2 = yC - yA;
  5851. z1 = zB - zA;
  5852. z2 = zC - zA;
  5853. s1 = uB - uA;
  5854. s2 = uC - uA;
  5855. t1 = vB - vA;
  5856. t2 = vC - vA;
  5857. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5858. sdir.set(
  5859. ( t2 * x1 - t1 * x2 ) * r,
  5860. ( t2 * y1 - t1 * y2 ) * r,
  5861. ( t2 * z1 - t1 * z2 ) * r
  5862. );
  5863. tdir.set(
  5864. ( s1 * x2 - s2 * x1 ) * r,
  5865. ( s1 * y2 - s2 * y1 ) * r,
  5866. ( s1 * z2 - s2 * z1 ) * r
  5867. );
  5868. tan1[ a ].add( sdir );
  5869. tan1[ b ].add( sdir );
  5870. tan1[ c ].add( sdir );
  5871. tan2[ a ].add( tdir );
  5872. tan2[ b ].add( tdir );
  5873. tan2[ c ].add( tdir );
  5874. }
  5875. var i, il;
  5876. var j, jl;
  5877. var iA, iB, iC;
  5878. var offsets = this.offsets;
  5879. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5880. var start = offsets[ j ].start;
  5881. var count = offsets[ j ].count;
  5882. var index = offsets[ j ].index;
  5883. for ( i = start, il = start + count; i < il; i += 3 ) {
  5884. iA = index + indices[ i ];
  5885. iB = index + indices[ i + 1 ];
  5886. iC = index + indices[ i + 2 ];
  5887. handleTriangle( iA, iB, iC );
  5888. }
  5889. }
  5890. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5891. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5892. var w, t, test;
  5893. function handleVertex( v ) {
  5894. n.x = normals[ v * 3 ];
  5895. n.y = normals[ v * 3 + 1 ];
  5896. n.z = normals[ v * 3 + 2 ];
  5897. n2.copy( n );
  5898. t = tan1[ v ];
  5899. // Gram-Schmidt orthogonalize
  5900. tmp.copy( t );
  5901. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5902. // Calculate handedness
  5903. tmp2.crossVectors( n2, t );
  5904. test = tmp2.dot( tan2[ v ] );
  5905. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5906. tangents[ v * 4 ] = tmp.x;
  5907. tangents[ v * 4 + 1 ] = tmp.y;
  5908. tangents[ v * 4 + 2 ] = tmp.z;
  5909. tangents[ v * 4 + 3 ] = w;
  5910. }
  5911. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5912. var start = offsets[ j ].start;
  5913. var count = offsets[ j ].count;
  5914. var index = offsets[ j ].index;
  5915. for ( i = start, il = start + count; i < il; i += 3 ) {
  5916. iA = index + indices[ i ];
  5917. iB = index + indices[ i + 1 ];
  5918. iC = index + indices[ i + 2 ];
  5919. handleVertex( iA );
  5920. handleVertex( iB );
  5921. handleVertex( iC );
  5922. }
  5923. }
  5924. this.hasTangents = true;
  5925. this.tangentsNeedUpdate = true;
  5926. },
  5927. /*
  5928. computeOffsets
  5929. Compute the draw offset for large models by chunking the index buffer into chunks of 65k addressable vertices.
  5930. This method will effectively rewrite the index buffer and remap all attributes to match the new indices.
  5931. WARNING: This method will also expand the vertex count to prevent sprawled triangles across draw offsets.
  5932. indexBufferSize - Defaults to 65535, but allows for larger or smaller chunks.
  5933. */
  5934. computeOffsets: function(indexBufferSize) {
  5935. var size = indexBufferSize;
  5936. if(indexBufferSize === undefined)
  5937. size = 65535; //WebGL limits type of index buffer values to 16-bit.
  5938. var s = Date.now();
  5939. var indices = this.attributes['index'].array;
  5940. var vertices = this.attributes['position'].array;
  5941. var verticesCount = (vertices.length/3);
  5942. var facesCount = (indices.length/3);
  5943. /*
  5944. console.log("Computing buffers in offsets of "+size+" -> indices:"+indices.length+" vertices:"+vertices.length);
  5945. console.log("Faces to process: "+(indices.length/3));
  5946. console.log("Reordering "+verticesCount+" vertices.");
  5947. */
  5948. var sortedIndices = new Uint16Array( indices.length ); //16-bit buffers
  5949. var indexPtr = 0;
  5950. var vertexPtr = 0;
  5951. var offsets = [ { start:0, count:0, index:0 } ];
  5952. var offset = offsets[0];
  5953. var duplicatedVertices = 0;
  5954. var newVerticeMaps = 0;
  5955. var faceVertices = new Int32Array(6);
  5956. var vertexMap = new Int32Array( vertices.length );
  5957. var revVertexMap = new Int32Array( vertices.length );
  5958. for(var j = 0; j < vertices.length; j++) { vertexMap[j] = -1; revVertexMap[j] = -1; }
  5959. /*
  5960. Traverse every face and reorder vertices in the proper offsets of 65k.
  5961. We can have more than 65k entries in the index buffer per offset, but only reference 65k values.
  5962. */
  5963. for(var findex = 0; findex < facesCount; findex++) {
  5964. newVerticeMaps = 0;
  5965. for(var vo = 0; vo < 3; vo++) {
  5966. var vid = indices[ findex*3 + vo ];
  5967. if(vertexMap[vid] == -1) {
  5968. //Unmapped vertice
  5969. faceVertices[vo*2] = vid;
  5970. faceVertices[vo*2+1] = -1;
  5971. newVerticeMaps++;
  5972. } else if(vertexMap[vid] < offset.index) {
  5973. //Reused vertices from previous block (duplicate)
  5974. faceVertices[vo*2] = vid;
  5975. faceVertices[vo*2+1] = -1;
  5976. duplicatedVertices++;
  5977. } else {
  5978. //Reused vertice in the current block
  5979. faceVertices[vo*2] = vid;
  5980. faceVertices[vo*2+1] = vertexMap[vid];
  5981. }
  5982. }
  5983. var faceMax = vertexPtr + newVerticeMaps;
  5984. if(faceMax > (offset.index + size)) {
  5985. var new_offset = { start:indexPtr, count:0, index:vertexPtr };
  5986. offsets.push(new_offset);
  5987. offset = new_offset;
  5988. //Re-evaluate reused vertices in light of new offset.
  5989. for(var v = 0; v < 6; v+=2) {
  5990. var new_vid = faceVertices[v+1];
  5991. if(new_vid > -1 && new_vid < offset.index)
  5992. faceVertices[v+1] = -1;
  5993. }
  5994. }
  5995. //Reindex the face.
  5996. for(var v = 0; v < 6; v+=2) {
  5997. var vid = faceVertices[v];
  5998. var new_vid = faceVertices[v+1];
  5999. if(new_vid === -1)
  6000. new_vid = vertexPtr++;
  6001. vertexMap[vid] = new_vid;
  6002. revVertexMap[new_vid] = vid;
  6003. sortedIndices[indexPtr++] = new_vid - offset.index; //XXX overflows at 16bit
  6004. offset.count++;
  6005. }
  6006. }
  6007. /* Move all attribute values to map to the new computed indices , also expand the vertice stack to match our new vertexPtr. */
  6008. this.reorderBuffers(sortedIndices, revVertexMap, vertexPtr);
  6009. this.offsets = offsets;
  6010. /*
  6011. var orderTime = Date.now();
  6012. console.log("Reorder time: "+(orderTime-s)+"ms");
  6013. console.log("Duplicated "+duplicatedVertices+" vertices.");
  6014. console.log("Compute Buffers time: "+(Date.now()-s)+"ms");
  6015. console.log("Draw offsets: "+offsets.length);
  6016. */
  6017. return offsets;
  6018. },
  6019. /*
  6020. reoderBuffers:
  6021. Reorder attributes based on a new indexBuffer and indexMap.
  6022. indexBuffer - Uint16Array of the new ordered indices.
  6023. indexMap - Int32Array where the position is the new vertex ID and the value the old vertex ID for each vertex.
  6024. vertexCount - Amount of total vertices considered in this reordering (in case you want to grow the vertice stack).
  6025. */
  6026. reorderBuffers: function(indexBuffer, indexMap, vertexCount) {
  6027. /* Create a copy of all attributes for reordering. */
  6028. var sortedAttributes = {};
  6029. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  6030. for( var attr in this.attributes ) {
  6031. if(attr == 'index')
  6032. continue;
  6033. var sourceArray = this.attributes[attr].array;
  6034. for ( var i = 0, il = types.length; i < il; i++ ) {
  6035. var type = types[i];
  6036. if (sourceArray instanceof type) {
  6037. sortedAttributes[attr] = new type( this.attributes[attr].itemSize * vertexCount );
  6038. break;
  6039. }
  6040. }
  6041. }
  6042. /* Move attribute positions based on the new index map */
  6043. for(var new_vid = 0; new_vid < vertexCount; new_vid++) {
  6044. var vid = indexMap[new_vid];
  6045. for ( var attr in this.attributes ) {
  6046. if(attr == 'index')
  6047. continue;
  6048. var attrArray = this.attributes[attr].array;
  6049. var attrSize = this.attributes[attr].itemSize;
  6050. var sortedAttr = sortedAttributes[attr];
  6051. for(var k = 0; k < attrSize; k++)
  6052. sortedAttr[ new_vid * attrSize + k ] = attrArray[ vid * attrSize + k ];
  6053. }
  6054. }
  6055. /* Carry the new sorted buffers locally */
  6056. this.attributes['index'].array = indexBuffer;
  6057. for ( var attr in this.attributes ) {
  6058. if(attr == 'index')
  6059. continue;
  6060. this.attributes[attr].array = sortedAttributes[attr];
  6061. this.attributes[attr].numItems = this.attributes[attr].itemSize * vertexCount;
  6062. }
  6063. },
  6064. clone: function () {
  6065. var geometry = new THREE.BufferGeometry();
  6066. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  6067. for ( var attr in this.attributes ) {
  6068. var sourceAttr = this.attributes[ attr ];
  6069. var sourceArray = sourceAttr.array;
  6070. var attribute = {
  6071. itemSize: sourceAttr.itemSize,
  6072. array: null
  6073. };
  6074. for ( var i = 0, il = types.length; i < il; i ++ ) {
  6075. var type = types[ i ];
  6076. if ( sourceArray instanceof type ) {
  6077. attribute.array = new type( sourceArray );
  6078. break;
  6079. }
  6080. }
  6081. geometry.attributes[ attr ] = attribute;
  6082. }
  6083. for ( var i = 0, il = this.offsets.length; i < il; i ++ ) {
  6084. var offset = this.offsets[ i ];
  6085. geometry.offsets.push( {
  6086. start: offset.start,
  6087. index: offset.index,
  6088. count: offset.count
  6089. } );
  6090. }
  6091. return geometry;
  6092. },
  6093. dispose: function () {
  6094. this.dispatchEvent( { type: 'dispose' } );
  6095. }
  6096. };
  6097. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  6098. /**
  6099. * @author mrdoob / http://mrdoob.com/
  6100. * @author mikael emtinger / http://gomo.se/
  6101. * @author WestLangley / http://github.com/WestLangley
  6102. */
  6103. THREE.Camera = function () {
  6104. THREE.Object3D.call( this );
  6105. this.matrixWorldInverse = new THREE.Matrix4();
  6106. this.projectionMatrix = new THREE.Matrix4();
  6107. };
  6108. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  6109. THREE.Camera.prototype.lookAt = function () {
  6110. // This routine does not support cameras with rotated and/or translated parent(s)
  6111. var m1 = new THREE.Matrix4();
  6112. return function ( vector ) {
  6113. m1.lookAt( this.position, vector, this.up );
  6114. this.quaternion.setFromRotationMatrix( m1 );
  6115. };
  6116. }();
  6117. THREE.Camera.prototype.clone = function (camera) {
  6118. if ( camera === undefined ) camera = new THREE.Camera();
  6119. THREE.Object3D.prototype.clone.call( this, camera );
  6120. camera.matrixWorldInverse.copy( this.matrixWorldInverse );
  6121. camera.projectionMatrix.copy( this.projectionMatrix );
  6122. return camera;
  6123. };
  6124. /**
  6125. * @author alteredq / http://alteredqualia.com/
  6126. */
  6127. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  6128. THREE.Camera.call( this );
  6129. this.left = left;
  6130. this.right = right;
  6131. this.top = top;
  6132. this.bottom = bottom;
  6133. this.near = ( near !== undefined ) ? near : 0.1;
  6134. this.far = ( far !== undefined ) ? far : 2000;
  6135. this.updateProjectionMatrix();
  6136. };
  6137. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  6138. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  6139. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  6140. };
  6141. THREE.OrthographicCamera.prototype.clone = function () {
  6142. var camera = new THREE.OrthographicCamera();
  6143. THREE.Camera.prototype.clone.call( this, camera );
  6144. camera.left = this.left;
  6145. camera.right = this.right;
  6146. camera.top = this.top;
  6147. camera.bottom = this.bottom;
  6148. camera.near = this.near;
  6149. camera.far = this.far;
  6150. return camera;
  6151. };
  6152. /**
  6153. * @author mrdoob / http://mrdoob.com/
  6154. * @author greggman / http://games.greggman.com/
  6155. * @author zz85 / http://www.lab4games.net/zz85/blog
  6156. */
  6157. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  6158. THREE.Camera.call( this );
  6159. this.fov = fov !== undefined ? fov : 50;
  6160. this.aspect = aspect !== undefined ? aspect : 1;
  6161. this.near = near !== undefined ? near : 0.1;
  6162. this.far = far !== undefined ? far : 2000;
  6163. this.updateProjectionMatrix();
  6164. };
  6165. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  6166. /**
  6167. * Uses Focal Length (in mm) to estimate and set FOV
  6168. * 35mm (fullframe) camera is used if frame size is not specified;
  6169. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  6170. */
  6171. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  6172. if ( frameHeight === undefined ) frameHeight = 24;
  6173. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  6174. this.updateProjectionMatrix();
  6175. }
  6176. /**
  6177. * Sets an offset in a larger frustum. This is useful for multi-window or
  6178. * multi-monitor/multi-machine setups.
  6179. *
  6180. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6181. * the monitors are in grid like this
  6182. *
  6183. * +---+---+---+
  6184. * | A | B | C |
  6185. * +---+---+---+
  6186. * | D | E | F |
  6187. * +---+---+---+
  6188. *
  6189. * then for each monitor you would call it like this
  6190. *
  6191. * var w = 1920;
  6192. * var h = 1080;
  6193. * var fullWidth = w * 3;
  6194. * var fullHeight = h * 2;
  6195. *
  6196. * --A--
  6197. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6198. * --B--
  6199. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6200. * --C--
  6201. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6202. * --D--
  6203. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6204. * --E--
  6205. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  6206. * --F--
  6207. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  6208. *
  6209. * Note there is no reason monitors have to be the same size or in a grid.
  6210. */
  6211. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  6212. this.fullWidth = fullWidth;
  6213. this.fullHeight = fullHeight;
  6214. this.x = x;
  6215. this.y = y;
  6216. this.width = width;
  6217. this.height = height;
  6218. this.updateProjectionMatrix();
  6219. };
  6220. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  6221. if ( this.fullWidth ) {
  6222. var aspect = this.fullWidth / this.fullHeight;
  6223. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  6224. var bottom = -top;
  6225. var left = aspect * bottom;
  6226. var right = aspect * top;
  6227. var width = Math.abs( right - left );
  6228. var height = Math.abs( top - bottom );
  6229. this.projectionMatrix.makeFrustum(
  6230. left + this.x * width / this.fullWidth,
  6231. left + ( this.x + this.width ) * width / this.fullWidth,
  6232. top - ( this.y + this.height ) * height / this.fullHeight,
  6233. top - this.y * height / this.fullHeight,
  6234. this.near,
  6235. this.far
  6236. );
  6237. } else {
  6238. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  6239. }
  6240. };
  6241. THREE.PerspectiveCamera.prototype.clone = function () {
  6242. var camera = new THREE.PerspectiveCamera();
  6243. THREE.Camera.prototype.clone.call( this, camera );
  6244. camera.fov = this.fov;
  6245. camera.aspect = this.aspect;
  6246. camera.near = this.near;
  6247. camera.far = this.far;
  6248. return camera;
  6249. };
  6250. /**
  6251. * @author mrdoob / http://mrdoob.com/
  6252. * @author alteredq / http://alteredqualia.com/
  6253. */
  6254. THREE.Light = function ( color ) {
  6255. THREE.Object3D.call( this );
  6256. this.color = new THREE.Color( color );
  6257. };
  6258. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  6259. THREE.Light.prototype.clone = function ( light ) {
  6260. if ( light === undefined ) light = new THREE.Light();
  6261. THREE.Object3D.prototype.clone.call( this, light );
  6262. light.color.copy( this.color );
  6263. return light;
  6264. };
  6265. /**
  6266. * @author mrdoob / http://mrdoob.com/
  6267. */
  6268. THREE.AmbientLight = function ( color ) {
  6269. THREE.Light.call( this, color );
  6270. };
  6271. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  6272. THREE.AmbientLight.prototype.clone = function () {
  6273. var light = new THREE.AmbientLight();
  6274. THREE.Light.prototype.clone.call( this, light );
  6275. return light;
  6276. };
  6277. /**
  6278. * @author MPanknin / http://www.redplant.de/
  6279. * @author alteredq / http://alteredqualia.com/
  6280. */
  6281. THREE.AreaLight = function ( color, intensity ) {
  6282. THREE.Light.call( this, color );
  6283. this.normal = new THREE.Vector3( 0, -1, 0 );
  6284. this.right = new THREE.Vector3( 1, 0, 0 );
  6285. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6286. this.width = 1.0;
  6287. this.height = 1.0;
  6288. this.constantAttenuation = 1.5;
  6289. this.linearAttenuation = 0.5;
  6290. this.quadraticAttenuation = 0.1;
  6291. };
  6292. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  6293. /**
  6294. * @author mrdoob / http://mrdoob.com/
  6295. * @author alteredq / http://alteredqualia.com/
  6296. */
  6297. THREE.DirectionalLight = function ( color, intensity ) {
  6298. THREE.Light.call( this, color );
  6299. this.position.set( 0, 1, 0 );
  6300. this.target = new THREE.Object3D();
  6301. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6302. this.castShadow = false;
  6303. this.onlyShadow = false;
  6304. //
  6305. this.shadowCameraNear = 50;
  6306. this.shadowCameraFar = 5000;
  6307. this.shadowCameraLeft = -500;
  6308. this.shadowCameraRight = 500;
  6309. this.shadowCameraTop = 500;
  6310. this.shadowCameraBottom = -500;
  6311. this.shadowCameraVisible = false;
  6312. this.shadowBias = 0;
  6313. this.shadowDarkness = 0.5;
  6314. this.shadowMapWidth = 512;
  6315. this.shadowMapHeight = 512;
  6316. //
  6317. this.shadowCascade = false;
  6318. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  6319. this.shadowCascadeCount = 2;
  6320. this.shadowCascadeBias = [ 0, 0, 0 ];
  6321. this.shadowCascadeWidth = [ 512, 512, 512 ];
  6322. this.shadowCascadeHeight = [ 512, 512, 512 ];
  6323. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  6324. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  6325. this.shadowCascadeArray = [];
  6326. //
  6327. this.shadowMap = null;
  6328. this.shadowMapSize = null;
  6329. this.shadowCamera = null;
  6330. this.shadowMatrix = null;
  6331. };
  6332. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  6333. THREE.DirectionalLight.prototype.clone = function () {
  6334. var light = new THREE.DirectionalLight();
  6335. THREE.Light.prototype.clone.call( this, light );
  6336. light.target = this.target.clone();
  6337. light.intensity = this.intensity;
  6338. light.castShadow = this.castShadow;
  6339. light.onlyShadow = this.onlyShadow;
  6340. return light;
  6341. };
  6342. /**
  6343. * @author alteredq / http://alteredqualia.com/
  6344. */
  6345. THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
  6346. THREE.Light.call( this, skyColor );
  6347. this.position.set( 0, 100, 0 );
  6348. this.groundColor = new THREE.Color( groundColor );
  6349. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6350. };
  6351. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  6352. THREE.HemisphereLight.prototype.clone = function () {
  6353. var light = new THREE.HemisphereLight();
  6354. THREE.Light.prototype.clone.call( this, light );
  6355. light.groundColor.copy( this.groundColor );
  6356. light.intensity = this.intensity;
  6357. return light;
  6358. };
  6359. /**
  6360. * @author mrdoob / http://mrdoob.com/
  6361. */
  6362. THREE.PointLight = function ( color, intensity, distance ) {
  6363. THREE.Light.call( this, color );
  6364. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6365. this.distance = ( distance !== undefined ) ? distance : 0;
  6366. };
  6367. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  6368. THREE.PointLight.prototype.clone = function () {
  6369. var light = new THREE.PointLight();
  6370. THREE.Light.prototype.clone.call( this, light );
  6371. light.intensity = this.intensity;
  6372. light.distance = this.distance;
  6373. return light;
  6374. };
  6375. /**
  6376. * @author alteredq / http://alteredqualia.com/
  6377. */
  6378. THREE.SpotLight = function ( color, intensity, distance, angle, exponent ) {
  6379. THREE.Light.call( this, color );
  6380. this.position.set( 0, 1, 0 );
  6381. this.target = new THREE.Object3D();
  6382. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6383. this.distance = ( distance !== undefined ) ? distance : 0;
  6384. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  6385. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  6386. this.castShadow = false;
  6387. this.onlyShadow = false;
  6388. //
  6389. this.shadowCameraNear = 50;
  6390. this.shadowCameraFar = 5000;
  6391. this.shadowCameraFov = 50;
  6392. this.shadowCameraVisible = false;
  6393. this.shadowBias = 0;
  6394. this.shadowDarkness = 0.5;
  6395. this.shadowMapWidth = 512;
  6396. this.shadowMapHeight = 512;
  6397. //
  6398. this.shadowMap = null;
  6399. this.shadowMapSize = null;
  6400. this.shadowCamera = null;
  6401. this.shadowMatrix = null;
  6402. };
  6403. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  6404. THREE.SpotLight.prototype.clone = function () {
  6405. var light = new THREE.SpotLight();
  6406. THREE.Light.prototype.clone.call( this, light );
  6407. light.target = this.target.clone();
  6408. light.intensity = this.intensity;
  6409. light.distance = this.distance;
  6410. light.angle = this.angle;
  6411. light.exponent = this.exponent;
  6412. light.castShadow = this.castShadow;
  6413. light.onlyShadow = this.onlyShadow;
  6414. return light;
  6415. };
  6416. /**
  6417. * @author alteredq / http://alteredqualia.com/
  6418. */
  6419. THREE.Loader = function ( showStatus ) {
  6420. this.showStatus = showStatus;
  6421. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  6422. this.onLoadStart = function () {};
  6423. this.onLoadProgress = function () {};
  6424. this.onLoadComplete = function () {};
  6425. };
  6426. THREE.Loader.prototype = {
  6427. constructor: THREE.Loader,
  6428. crossOrigin: undefined,
  6429. addStatusElement: function () {
  6430. var e = document.createElement( "div" );
  6431. e.style.position = "absolute";
  6432. e.style.right = "0px";
  6433. e.style.top = "0px";
  6434. e.style.fontSize = "0.8em";
  6435. e.style.textAlign = "left";
  6436. e.style.background = "rgba(0,0,0,0.25)";
  6437. e.style.color = "#fff";
  6438. e.style.width = "120px";
  6439. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  6440. e.style.zIndex = 1000;
  6441. e.innerHTML = "Loading ...";
  6442. return e;
  6443. },
  6444. updateProgress: function ( progress ) {
  6445. var message = "Loaded ";
  6446. if ( progress.total ) {
  6447. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  6448. } else {
  6449. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  6450. }
  6451. this.statusDomElement.innerHTML = message;
  6452. },
  6453. extractUrlBase: function ( url ) {
  6454. var parts = url.split( '/' );
  6455. if ( parts.length === 1 ) return './';
  6456. parts.pop();
  6457. return parts.join( '/' ) + '/';
  6458. },
  6459. initMaterials: function ( materials, texturePath ) {
  6460. var array = [];
  6461. for ( var i = 0; i < materials.length; ++ i ) {
  6462. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  6463. }
  6464. return array;
  6465. },
  6466. needsTangents: function ( materials ) {
  6467. for( var i = 0, il = materials.length; i < il; i ++ ) {
  6468. var m = materials[ i ];
  6469. if ( m instanceof THREE.ShaderMaterial ) return true;
  6470. }
  6471. return false;
  6472. },
  6473. createMaterial: function ( m, texturePath ) {
  6474. var _this = this;
  6475. function is_pow2( n ) {
  6476. var l = Math.log( n ) / Math.LN2;
  6477. return Math.floor( l ) == l;
  6478. }
  6479. function nearest_pow2( n ) {
  6480. var l = Math.log( n ) / Math.LN2;
  6481. return Math.pow( 2, Math.round( l ) );
  6482. }
  6483. function load_image( where, url ) {
  6484. var image = new Image();
  6485. image.onload = function () {
  6486. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  6487. var width = nearest_pow2( this.width );
  6488. var height = nearest_pow2( this.height );
  6489. where.image.width = width;
  6490. where.image.height = height;
  6491. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  6492. } else {
  6493. where.image = this;
  6494. }
  6495. where.needsUpdate = true;
  6496. };
  6497. if ( _this.crossOrigin !== undefined ) image.crossOrigin = _this.crossOrigin;
  6498. image.src = url;
  6499. }
  6500. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  6501. var isCompressed = /\.dds$/i.test( sourceFile );
  6502. var fullPath = texturePath + sourceFile;
  6503. if ( isCompressed ) {
  6504. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  6505. where[ name ] = texture;
  6506. } else {
  6507. var texture = document.createElement( 'canvas' );
  6508. where[ name ] = new THREE.Texture( texture );
  6509. }
  6510. where[ name ].sourceFile = sourceFile;
  6511. if( repeat ) {
  6512. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  6513. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  6514. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  6515. }
  6516. if ( offset ) {
  6517. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  6518. }
  6519. if ( wrap ) {
  6520. var wrapMap = {
  6521. "repeat": THREE.RepeatWrapping,
  6522. "mirror": THREE.MirroredRepeatWrapping
  6523. }
  6524. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  6525. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  6526. }
  6527. if ( anisotropy ) {
  6528. where[ name ].anisotropy = anisotropy;
  6529. }
  6530. if ( ! isCompressed ) {
  6531. load_image( where[ name ], fullPath );
  6532. }
  6533. }
  6534. function rgb2hex( rgb ) {
  6535. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  6536. }
  6537. // defaults
  6538. var mtype = "MeshLambertMaterial";
  6539. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  6540. // parameters from model file
  6541. if ( m.shading ) {
  6542. var shading = m.shading.toLowerCase();
  6543. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  6544. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  6545. }
  6546. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  6547. mpars.blending = THREE[ m.blending ];
  6548. }
  6549. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  6550. mpars.transparent = m.transparent;
  6551. }
  6552. if ( m.depthTest !== undefined ) {
  6553. mpars.depthTest = m.depthTest;
  6554. }
  6555. if ( m.depthWrite !== undefined ) {
  6556. mpars.depthWrite = m.depthWrite;
  6557. }
  6558. if ( m.visible !== undefined ) {
  6559. mpars.visible = m.visible;
  6560. }
  6561. if ( m.flipSided !== undefined ) {
  6562. mpars.side = THREE.BackSide;
  6563. }
  6564. if ( m.doubleSided !== undefined ) {
  6565. mpars.side = THREE.DoubleSide;
  6566. }
  6567. if ( m.wireframe !== undefined ) {
  6568. mpars.wireframe = m.wireframe;
  6569. }
  6570. if ( m.vertexColors !== undefined ) {
  6571. if ( m.vertexColors === "face" ) {
  6572. mpars.vertexColors = THREE.FaceColors;
  6573. } else if ( m.vertexColors ) {
  6574. mpars.vertexColors = THREE.VertexColors;
  6575. }
  6576. }
  6577. // colors
  6578. if ( m.colorDiffuse ) {
  6579. mpars.color = rgb2hex( m.colorDiffuse );
  6580. } else if ( m.DbgColor ) {
  6581. mpars.color = m.DbgColor;
  6582. }
  6583. if ( m.colorSpecular ) {
  6584. mpars.specular = rgb2hex( m.colorSpecular );
  6585. }
  6586. if ( m.colorAmbient ) {
  6587. mpars.ambient = rgb2hex( m.colorAmbient );
  6588. }
  6589. // modifiers
  6590. if ( m.transparency ) {
  6591. mpars.opacity = m.transparency;
  6592. }
  6593. if ( m.specularCoef ) {
  6594. mpars.shininess = m.specularCoef;
  6595. }
  6596. // textures
  6597. if ( m.mapDiffuse && texturePath ) {
  6598. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  6599. }
  6600. if ( m.mapLight && texturePath ) {
  6601. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  6602. }
  6603. if ( m.mapBump && texturePath ) {
  6604. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  6605. }
  6606. if ( m.mapNormal && texturePath ) {
  6607. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  6608. }
  6609. if ( m.mapSpecular && texturePath ) {
  6610. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  6611. }
  6612. //
  6613. if ( m.mapBumpScale ) {
  6614. mpars.bumpScale = m.mapBumpScale;
  6615. }
  6616. // special case for normal mapped material
  6617. if ( m.mapNormal ) {
  6618. var shader = THREE.ShaderLib[ "normalmap" ];
  6619. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6620. uniforms[ "tNormal" ].value = mpars.normalMap;
  6621. if ( m.mapNormalFactor ) {
  6622. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  6623. }
  6624. if ( mpars.map ) {
  6625. uniforms[ "tDiffuse" ].value = mpars.map;
  6626. uniforms[ "enableDiffuse" ].value = true;
  6627. }
  6628. if ( mpars.specularMap ) {
  6629. uniforms[ "tSpecular" ].value = mpars.specularMap;
  6630. uniforms[ "enableSpecular" ].value = true;
  6631. }
  6632. if ( mpars.lightMap ) {
  6633. uniforms[ "tAO" ].value = mpars.lightMap;
  6634. uniforms[ "enableAO" ].value = true;
  6635. }
  6636. // for the moment don't handle displacement texture
  6637. uniforms[ "diffuse" ].value.setHex( mpars.color );
  6638. uniforms[ "specular" ].value.setHex( mpars.specular );
  6639. uniforms[ "ambient" ].value.setHex( mpars.ambient );
  6640. uniforms[ "shininess" ].value = mpars.shininess;
  6641. if ( mpars.opacity !== undefined ) {
  6642. uniforms[ "opacity" ].value = mpars.opacity;
  6643. }
  6644. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6645. var material = new THREE.ShaderMaterial( parameters );
  6646. if ( mpars.transparent ) {
  6647. material.transparent = true;
  6648. }
  6649. } else {
  6650. var material = new THREE[ mtype ]( mpars );
  6651. }
  6652. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6653. return material;
  6654. }
  6655. };
  6656. /**
  6657. * @author mrdoob / http://mrdoob.com/
  6658. */
  6659. THREE.XHRLoader = function ( manager ) {
  6660. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6661. };
  6662. THREE.XHRLoader.prototype = {
  6663. constructor: THREE.XHRLoader,
  6664. load: function ( url, onLoad, onProgress, onError ) {
  6665. var scope = this;
  6666. var request = new XMLHttpRequest();
  6667. if ( onLoad !== undefined ) {
  6668. request.addEventListener( 'load', function ( event ) {
  6669. onLoad( event.target.responseText );
  6670. scope.manager.itemEnd( url );
  6671. }, false );
  6672. }
  6673. if ( onProgress !== undefined ) {
  6674. request.addEventListener( 'progress', function ( event ) {
  6675. onProgress( event );
  6676. }, false );
  6677. }
  6678. if ( onError !== undefined ) {
  6679. request.addEventListener( 'error', function ( event ) {
  6680. onError( event );
  6681. }, false );
  6682. }
  6683. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  6684. request.open( 'GET', url, true );
  6685. request.send( null );
  6686. scope.manager.itemStart( url );
  6687. },
  6688. setCrossOrigin: function ( value ) {
  6689. this.crossOrigin = value;
  6690. }
  6691. };
  6692. /**
  6693. * @author mrdoob / http://mrdoob.com/
  6694. */
  6695. THREE.ImageLoader = function ( manager ) {
  6696. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6697. };
  6698. THREE.ImageLoader.prototype = {
  6699. constructor: THREE.ImageLoader,
  6700. load: function ( url, onLoad, onProgress, onError ) {
  6701. var scope = this;
  6702. var image = document.createElement( 'img' );
  6703. if ( onLoad !== undefined ) {
  6704. image.addEventListener( 'load', function ( event ) {
  6705. scope.manager.itemEnd( url );
  6706. onLoad( this );
  6707. }, false );
  6708. }
  6709. if ( onProgress !== undefined ) {
  6710. image.addEventListener( 'progress', function ( event ) {
  6711. onProgress( event );
  6712. }, false );
  6713. }
  6714. if ( onError !== undefined ) {
  6715. image.addEventListener( 'error', function ( event ) {
  6716. onError( event );
  6717. }, false );
  6718. }
  6719. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  6720. image.src = url;
  6721. scope.manager.itemStart( url );
  6722. return image;
  6723. },
  6724. setCrossOrigin: function ( value ) {
  6725. this.crossOrigin = value;
  6726. }
  6727. }
  6728. /**
  6729. * @author mrdoob / http://mrdoob.com/
  6730. * @author alteredq / http://alteredqualia.com/
  6731. */
  6732. THREE.JSONLoader = function ( showStatus ) {
  6733. THREE.Loader.call( this, showStatus );
  6734. this.withCredentials = false;
  6735. };
  6736. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  6737. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  6738. var scope = this;
  6739. // todo: unify load API to for easier SceneLoader use
  6740. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  6741. this.onLoadStart();
  6742. this.loadAjaxJSON( this, url, callback, texturePath );
  6743. };
  6744. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  6745. var xhr = new XMLHttpRequest();
  6746. var length = 0;
  6747. xhr.onreadystatechange = function () {
  6748. if ( xhr.readyState === xhr.DONE ) {
  6749. if ( xhr.status === 200 || xhr.status === 0 ) {
  6750. if ( xhr.responseText ) {
  6751. var json = JSON.parse( xhr.responseText );
  6752. if ( json.metadata.type === 'scene' ) {
  6753. console.error( 'THREE.JSONLoader: "' + url + '" seems to be a Scene. Use THREE.SceneLoader instead.' );
  6754. return;
  6755. }
  6756. var result = context.parse( json, texturePath );
  6757. callback( result.geometry, result.materials );
  6758. } else {
  6759. console.error( 'THREE.JSONLoader: "' + url + '" seems to be unreachable or the file is empty.' );
  6760. }
  6761. // in context of more complex asset initialization
  6762. // do not block on single failed file
  6763. // maybe should go even one more level up
  6764. context.onLoadComplete();
  6765. } else {
  6766. console.error( 'THREE.JSONLoader: Couldn\'t load "' + url + '" (' + xhr.status + ')' );
  6767. }
  6768. } else if ( xhr.readyState === xhr.LOADING ) {
  6769. if ( callbackProgress ) {
  6770. if ( length === 0 ) {
  6771. length = xhr.getResponseHeader( 'Content-Length' );
  6772. }
  6773. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  6774. }
  6775. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  6776. if ( callbackProgress !== undefined ) {
  6777. length = xhr.getResponseHeader( "Content-Length" );
  6778. }
  6779. }
  6780. };
  6781. xhr.open( "GET", url, true );
  6782. xhr.withCredentials = this.withCredentials;
  6783. xhr.send( null );
  6784. };
  6785. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  6786. var scope = this,
  6787. geometry = new THREE.Geometry(),
  6788. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  6789. parseModel( scale );
  6790. parseSkin();
  6791. parseMorphing( scale );
  6792. geometry.computeCentroids();
  6793. geometry.computeFaceNormals();
  6794. geometry.computeBoundingSphere();
  6795. function parseModel( scale ) {
  6796. function isBitSet( value, position ) {
  6797. return value & ( 1 << position );
  6798. }
  6799. var i, j, fi,
  6800. offset, zLength,
  6801. colorIndex, normalIndex, uvIndex, materialIndex,
  6802. type,
  6803. isQuad,
  6804. hasMaterial,
  6805. hasFaceVertexUv,
  6806. hasFaceNormal, hasFaceVertexNormal,
  6807. hasFaceColor, hasFaceVertexColor,
  6808. vertex, face, faceA, faceB, color, hex, normal,
  6809. uvLayer, uv, u, v,
  6810. faces = json.faces,
  6811. vertices = json.vertices,
  6812. normals = json.normals,
  6813. colors = json.colors,
  6814. nUvLayers = 0;
  6815. if ( json.uvs !== undefined ) {
  6816. // disregard empty arrays
  6817. for ( i = 0; i < json.uvs.length; i++ ) {
  6818. if ( json.uvs[ i ].length ) nUvLayers ++;
  6819. }
  6820. for ( i = 0; i < nUvLayers; i++ ) {
  6821. geometry.faceVertexUvs[ i ] = [];
  6822. }
  6823. }
  6824. offset = 0;
  6825. zLength = vertices.length;
  6826. while ( offset < zLength ) {
  6827. vertex = new THREE.Vector3();
  6828. vertex.x = vertices[ offset ++ ] * scale;
  6829. vertex.y = vertices[ offset ++ ] * scale;
  6830. vertex.z = vertices[ offset ++ ] * scale;
  6831. geometry.vertices.push( vertex );
  6832. }
  6833. offset = 0;
  6834. zLength = faces.length;
  6835. while ( offset < zLength ) {
  6836. type = faces[ offset ++ ];
  6837. isQuad = isBitSet( type, 0 );
  6838. hasMaterial = isBitSet( type, 1 );
  6839. hasFaceVertexUv = isBitSet( type, 3 );
  6840. hasFaceNormal = isBitSet( type, 4 );
  6841. hasFaceVertexNormal = isBitSet( type, 5 );
  6842. hasFaceColor = isBitSet( type, 6 );
  6843. hasFaceVertexColor = isBitSet( type, 7 );
  6844. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  6845. if ( isQuad ) {
  6846. faceA = new THREE.Face3();
  6847. faceA.a = faces[ offset ];
  6848. faceA.b = faces[ offset + 1 ];
  6849. faceA.c = faces[ offset + 3 ];
  6850. faceB = new THREE.Face3();
  6851. faceB.a = faces[ offset + 1 ];
  6852. faceB.b = faces[ offset + 2 ];
  6853. faceB.c = faces[ offset + 3 ];
  6854. offset += 4;
  6855. if ( hasMaterial ) {
  6856. materialIndex = faces[ offset ++ ];
  6857. faceA.materialIndex = materialIndex;
  6858. faceB.materialIndex = materialIndex;
  6859. }
  6860. // to get face <=> uv index correspondence
  6861. fi = geometry.faces.length;
  6862. if ( hasFaceVertexUv ) {
  6863. for ( i = 0; i < nUvLayers; i++ ) {
  6864. uvLayer = json.uvs[ i ];
  6865. geometry.faceVertexUvs[ i ][ fi ] = [];
  6866. geometry.faceVertexUvs[ i ][ fi + 1 ] = []
  6867. for ( j = 0; j < 4; j ++ ) {
  6868. uvIndex = faces[ offset ++ ];
  6869. u = uvLayer[ uvIndex * 2 ];
  6870. v = uvLayer[ uvIndex * 2 + 1 ];
  6871. uv = new THREE.Vector2( u, v );
  6872. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  6873. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  6874. }
  6875. }
  6876. }
  6877. if ( hasFaceNormal ) {
  6878. normalIndex = faces[ offset ++ ] * 3;
  6879. faceA.normal.set(
  6880. normals[ normalIndex ++ ],
  6881. normals[ normalIndex ++ ],
  6882. normals[ normalIndex ]
  6883. );
  6884. faceB.normal.copy( faceA.normal );
  6885. }
  6886. if ( hasFaceVertexNormal ) {
  6887. for ( i = 0; i < 4; i++ ) {
  6888. normalIndex = faces[ offset ++ ] * 3;
  6889. normal = new THREE.Vector3(
  6890. normals[ normalIndex ++ ],
  6891. normals[ normalIndex ++ ],
  6892. normals[ normalIndex ]
  6893. );
  6894. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  6895. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  6896. }
  6897. }
  6898. if ( hasFaceColor ) {
  6899. colorIndex = faces[ offset ++ ];
  6900. hex = colors[ colorIndex ];
  6901. faceA.color.setHex( hex );
  6902. faceB.color.setHex( hex );
  6903. }
  6904. if ( hasFaceVertexColor ) {
  6905. for ( i = 0; i < 4; i++ ) {
  6906. colorIndex = faces[ offset ++ ];
  6907. hex = colors[ colorIndex ];
  6908. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  6909. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  6910. }
  6911. }
  6912. geometry.faces.push( faceA );
  6913. geometry.faces.push( faceB );
  6914. } else {
  6915. face = new THREE.Face3();
  6916. face.a = faces[ offset ++ ];
  6917. face.b = faces[ offset ++ ];
  6918. face.c = faces[ offset ++ ];
  6919. if ( hasMaterial ) {
  6920. materialIndex = faces[ offset ++ ];
  6921. face.materialIndex = materialIndex;
  6922. }
  6923. // to get face <=> uv index correspondence
  6924. fi = geometry.faces.length;
  6925. if ( hasFaceVertexUv ) {
  6926. for ( i = 0; i < nUvLayers; i++ ) {
  6927. uvLayer = json.uvs[ i ];
  6928. geometry.faceVertexUvs[ i ][ fi ] = [];
  6929. for ( j = 0; j < 3; j ++ ) {
  6930. uvIndex = faces[ offset ++ ];
  6931. u = uvLayer[ uvIndex * 2 ];
  6932. v = uvLayer[ uvIndex * 2 + 1 ];
  6933. uv = new THREE.Vector2( u, v );
  6934. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  6935. }
  6936. }
  6937. }
  6938. if ( hasFaceNormal ) {
  6939. normalIndex = faces[ offset ++ ] * 3;
  6940. face.normal.set(
  6941. normals[ normalIndex ++ ],
  6942. normals[ normalIndex ++ ],
  6943. normals[ normalIndex ]
  6944. );
  6945. }
  6946. if ( hasFaceVertexNormal ) {
  6947. for ( i = 0; i < 3; i++ ) {
  6948. normalIndex = faces[ offset ++ ] * 3;
  6949. normal = new THREE.Vector3(
  6950. normals[ normalIndex ++ ],
  6951. normals[ normalIndex ++ ],
  6952. normals[ normalIndex ]
  6953. );
  6954. face.vertexNormals.push( normal );
  6955. }
  6956. }
  6957. if ( hasFaceColor ) {
  6958. colorIndex = faces[ offset ++ ];
  6959. face.color.setHex( colors[ colorIndex ] );
  6960. }
  6961. if ( hasFaceVertexColor ) {
  6962. for ( i = 0; i < 3; i++ ) {
  6963. colorIndex = faces[ offset ++ ];
  6964. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  6965. }
  6966. }
  6967. geometry.faces.push( face );
  6968. }
  6969. }
  6970. };
  6971. function parseSkin() {
  6972. if ( json.skinWeights ) {
  6973. for ( var i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  6974. var x = json.skinWeights[ i ];
  6975. var y = json.skinWeights[ i + 1 ];
  6976. var z = 0;
  6977. var w = 0;
  6978. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  6979. }
  6980. }
  6981. if ( json.skinIndices ) {
  6982. for ( var i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  6983. var a = json.skinIndices[ i ];
  6984. var b = json.skinIndices[ i + 1 ];
  6985. var c = 0;
  6986. var d = 0;
  6987. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  6988. }
  6989. }
  6990. geometry.bones = json.bones;
  6991. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  6992. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  6993. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  6994. }
  6995. // could change this to json.animations[0] or remove completely
  6996. geometry.animation = json.animation;
  6997. geometry.animations = json.animations;
  6998. };
  6999. function parseMorphing( scale ) {
  7000. if ( json.morphTargets !== undefined ) {
  7001. var i, l, v, vl, dstVertices, srcVertices;
  7002. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  7003. geometry.morphTargets[ i ] = {};
  7004. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  7005. geometry.morphTargets[ i ].vertices = [];
  7006. dstVertices = geometry.morphTargets[ i ].vertices;
  7007. srcVertices = json.morphTargets [ i ].vertices;
  7008. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  7009. var vertex = new THREE.Vector3();
  7010. vertex.x = srcVertices[ v ] * scale;
  7011. vertex.y = srcVertices[ v + 1 ] * scale;
  7012. vertex.z = srcVertices[ v + 2 ] * scale;
  7013. dstVertices.push( vertex );
  7014. }
  7015. }
  7016. }
  7017. if ( json.morphColors !== undefined ) {
  7018. var i, l, c, cl, dstColors, srcColors, color;
  7019. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  7020. geometry.morphColors[ i ] = {};
  7021. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  7022. geometry.morphColors[ i ].colors = [];
  7023. dstColors = geometry.morphColors[ i ].colors;
  7024. srcColors = json.morphColors [ i ].colors;
  7025. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  7026. color = new THREE.Color( 0xffaa00 );
  7027. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  7028. dstColors.push( color );
  7029. }
  7030. }
  7031. }
  7032. };
  7033. if ( json.materials === undefined ) {
  7034. return { geometry: geometry };
  7035. } else {
  7036. var materials = this.initMaterials( json.materials, texturePath );
  7037. if ( this.needsTangents( materials ) ) {
  7038. geometry.computeTangents();
  7039. }
  7040. return { geometry: geometry, materials: materials };
  7041. }
  7042. };
  7043. /**
  7044. * @author mrdoob / http://mrdoob.com/
  7045. */
  7046. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  7047. var scope = this;
  7048. var loaded = 0, total = 0;
  7049. this.onLoad = onLoad;
  7050. this.onProgress = onProgress;
  7051. this.onError = onError;
  7052. this.itemStart = function ( url ) {
  7053. total ++;
  7054. };
  7055. this.itemEnd = function ( url ) {
  7056. loaded ++;
  7057. if ( scope.onProgress !== undefined ) {
  7058. scope.onProgress( url, loaded, total );
  7059. }
  7060. if ( loaded === total && scope.onLoad !== undefined ) {
  7061. scope.onLoad();
  7062. }
  7063. };
  7064. };
  7065. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  7066. /**
  7067. * @author mrdoob / http://mrdoob.com/
  7068. */
  7069. THREE.BufferGeometryLoader = function ( manager ) {
  7070. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7071. };
  7072. THREE.BufferGeometryLoader.prototype = {
  7073. constructor: THREE.BufferGeometryLoader,
  7074. load: function ( url, onLoad, onProgress, onError ) {
  7075. var scope = this;
  7076. var loader = new THREE.XHRLoader();
  7077. loader.setCrossOrigin( this.crossOrigin );
  7078. loader.load( url, function ( text ) {
  7079. onLoad( scope.parse( JSON.parse( text ) ) );
  7080. } );
  7081. },
  7082. setCrossOrigin: function ( value ) {
  7083. this.crossOrigin = value;
  7084. },
  7085. parse: function ( json ) {
  7086. var geometry = new THREE.BufferGeometry();
  7087. var attributes = json.attributes;
  7088. var offsets = json.offsets;
  7089. var boundingSphere = json.boundingSphere;
  7090. for ( var key in attributes ) {
  7091. var attribute = attributes[ key ];
  7092. geometry.attributes[ key ] = {
  7093. itemSize: attribute.itemSize,
  7094. array: new self[ attribute.type ]( attribute.array )
  7095. }
  7096. }
  7097. if ( offsets !== undefined ) {
  7098. geometry.offsets = JSON.parse( JSON.stringify( offsets ) );
  7099. }
  7100. if ( boundingSphere !== undefined ) {
  7101. geometry.boundingSphere = new THREE.Sphere(
  7102. new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ),
  7103. boundingSphere.radius
  7104. );
  7105. }
  7106. return geometry;
  7107. }
  7108. };
  7109. /**
  7110. * @author mrdoob / http://mrdoob.com/
  7111. */
  7112. THREE.GeometryLoader = function ( manager ) {
  7113. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7114. };
  7115. THREE.GeometryLoader.prototype = {
  7116. constructor: THREE.GeometryLoader,
  7117. load: function ( url, onLoad, onProgress, onError ) {
  7118. var scope = this;
  7119. var loader = new THREE.XHRLoader();
  7120. loader.setCrossOrigin( this.crossOrigin );
  7121. loader.load( url, function ( text ) {
  7122. onLoad( scope.parse( JSON.parse( text ) ) );
  7123. } );
  7124. },
  7125. setCrossOrigin: function ( value ) {
  7126. this.crossOrigin = value;
  7127. },
  7128. parse: function ( json ) {
  7129. }
  7130. };
  7131. /**
  7132. * @author mrdoob / http://mrdoob.com/
  7133. */
  7134. THREE.MaterialLoader = function ( manager ) {
  7135. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7136. };
  7137. THREE.MaterialLoader.prototype = {
  7138. constructor: THREE.MaterialLoader,
  7139. load: function ( url, onLoad, onProgress, onError ) {
  7140. var scope = this;
  7141. var loader = new THREE.XHRLoader();
  7142. loader.setCrossOrigin( this.crossOrigin );
  7143. loader.load( url, function ( text ) {
  7144. onLoad( scope.parse( JSON.parse( text ) ) );
  7145. } );
  7146. },
  7147. setCrossOrigin: function ( value ) {
  7148. this.crossOrigin = value;
  7149. },
  7150. parse: function ( json ) {
  7151. var material = new THREE[ json.type ];
  7152. if ( json.color !== undefined ) material.color.setHex( json.color );
  7153. if ( json.ambient !== undefined ) material.ambient.setHex( json.ambient );
  7154. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  7155. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  7156. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  7157. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  7158. if ( json.blending !== undefined ) material.blending = json.blending;
  7159. if ( json.side !== undefined ) material.side = json.side;
  7160. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  7161. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  7162. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  7163. if ( json.materials !== undefined ) {
  7164. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  7165. material.materials.push( this.parse( json.materials[ i ] ) );
  7166. }
  7167. }
  7168. return material;
  7169. }
  7170. };
  7171. /**
  7172. * @author mrdoob / http://mrdoob.com/
  7173. */
  7174. THREE.ObjectLoader = function ( manager ) {
  7175. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7176. };
  7177. THREE.ObjectLoader.prototype = {
  7178. constructor: THREE.ObjectLoader,
  7179. load: function ( url, onLoad, onProgress, onError ) {
  7180. var scope = this;
  7181. var loader = new THREE.XHRLoader( scope.manager );
  7182. loader.setCrossOrigin( this.crossOrigin );
  7183. loader.load( url, function ( text ) {
  7184. onLoad( scope.parse( JSON.parse( text ) ) );
  7185. } );
  7186. },
  7187. setCrossOrigin: function ( value ) {
  7188. this.crossOrigin = value;
  7189. },
  7190. parse: function ( json ) {
  7191. var geometries = this.parseGeometries( json.geometries );
  7192. var materials = this.parseMaterials( json.materials );
  7193. var object = this.parseObject( json.object, geometries, materials );
  7194. return object;
  7195. },
  7196. parseGeometries: function ( json ) {
  7197. var geometries = {};
  7198. if ( json !== undefined ) {
  7199. var geometryLoader = new THREE.JSONLoader();
  7200. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  7201. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7202. var geometry;
  7203. var data = json[ i ];
  7204. switch ( data.type ) {
  7205. case 'PlaneGeometry':
  7206. geometry = new THREE.PlaneGeometry(
  7207. data.width,
  7208. data.height,
  7209. data.widthSegments,
  7210. data.heightSegments
  7211. );
  7212. break;
  7213. case 'BoxGeometry':
  7214. case 'CubeGeometry': // DEPRECATED
  7215. geometry = new THREE.BoxGeometry(
  7216. data.width,
  7217. data.height,
  7218. data.depth,
  7219. data.widthSegments,
  7220. data.heightSegments,
  7221. data.depthSegments
  7222. );
  7223. break;
  7224. case 'CircleGeometry':
  7225. geometry = new THREE.CircleGeometry(
  7226. data.radius,
  7227. data.segments
  7228. );
  7229. break;
  7230. case 'CylinderGeometry':
  7231. geometry = new THREE.CylinderGeometry(
  7232. data.radiusTop,
  7233. data.radiusBottom,
  7234. data.height,
  7235. data.radialSegments,
  7236. data.heightSegments,
  7237. data.openEnded
  7238. );
  7239. break;
  7240. case 'SphereGeometry':
  7241. geometry = new THREE.SphereGeometry(
  7242. data.radius,
  7243. data.widthSegments,
  7244. data.heightSegments,
  7245. data.phiStart,
  7246. data.phiLength,
  7247. data.thetaStart,
  7248. data.thetaLength
  7249. );
  7250. break;
  7251. case 'IcosahedronGeometry':
  7252. geometry = new THREE.IcosahedronGeometry(
  7253. data.radius,
  7254. data.detail
  7255. );
  7256. break;
  7257. case 'TorusGeometry':
  7258. geometry = new THREE.TorusGeometry(
  7259. data.radius,
  7260. data.tube,
  7261. data.radialSegments,
  7262. data.tubularSegments,
  7263. data.arc
  7264. );
  7265. break;
  7266. case 'TorusKnotGeometry':
  7267. geometry = new THREE.TorusKnotGeometry(
  7268. data.radius,
  7269. data.tube,
  7270. data.radialSegments,
  7271. data.tubularSegments,
  7272. data.p,
  7273. data.q,
  7274. data.heightScale
  7275. );
  7276. break;
  7277. case 'BufferGeometry':
  7278. geometry = bufferGeometryLoader.parse( data.data );
  7279. break;
  7280. case 'Geometry':
  7281. geometry = geometryLoader.parse( data.data ).geometry;
  7282. break;
  7283. }
  7284. geometry.uuid = data.uuid;
  7285. if ( data.name !== undefined ) geometry.name = data.name;
  7286. geometries[ data.uuid ] = geometry;
  7287. }
  7288. }
  7289. return geometries;
  7290. },
  7291. parseMaterials: function ( json ) {
  7292. var materials = {};
  7293. if ( json !== undefined ) {
  7294. var loader = new THREE.MaterialLoader();
  7295. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7296. var data = json[ i ];
  7297. var material = loader.parse( data );
  7298. material.uuid = data.uuid;
  7299. if ( data.name !== undefined ) material.name = data.name;
  7300. materials[ data.uuid ] = material;
  7301. }
  7302. }
  7303. return materials;
  7304. },
  7305. parseObject: function () {
  7306. var matrix = new THREE.Matrix4();
  7307. return function ( data, geometries, materials ) {
  7308. var object;
  7309. switch ( data.type ) {
  7310. case 'Scene':
  7311. object = new THREE.Scene();
  7312. break;
  7313. case 'PerspectiveCamera':
  7314. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  7315. break;
  7316. case 'OrthographicCamera':
  7317. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  7318. break;
  7319. case 'AmbientLight':
  7320. object = new THREE.AmbientLight( data.color );
  7321. break;
  7322. case 'DirectionalLight':
  7323. object = new THREE.DirectionalLight( data.color, data.intensity );
  7324. break;
  7325. case 'PointLight':
  7326. object = new THREE.PointLight( data.color, data.intensity, data.distance );
  7327. break;
  7328. case 'SpotLight':
  7329. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent );
  7330. break;
  7331. case 'HemisphereLight':
  7332. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  7333. break;
  7334. case 'Mesh':
  7335. var geometry = geometries[ data.geometry ];
  7336. var material = materials[ data.material ];
  7337. if ( geometry === undefined ) {
  7338. console.error( 'THREE.ObjectLoader: Undefined geometry ' + data.geometry );
  7339. }
  7340. if ( material === undefined ) {
  7341. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  7342. }
  7343. object = new THREE.Mesh( geometry, material );
  7344. break;
  7345. case 'Sprite':
  7346. var material = materials[ data.material ];
  7347. if ( material === undefined ) {
  7348. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  7349. }
  7350. object = new THREE.Sprite( material );
  7351. break;
  7352. default:
  7353. object = new THREE.Object3D();
  7354. }
  7355. object.uuid = data.uuid;
  7356. if ( data.name !== undefined ) object.name = data.name;
  7357. if ( data.matrix !== undefined ) {
  7358. matrix.fromArray( data.matrix );
  7359. matrix.decompose( object.position, object.quaternion, object.scale );
  7360. } else {
  7361. if ( data.position !== undefined ) object.position.fromArray( data.position );
  7362. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  7363. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  7364. }
  7365. if ( data.visible !== undefined ) object.visible = data.visible;
  7366. if ( data.userData !== undefined ) object.userData = data.userData;
  7367. if ( data.children !== undefined ) {
  7368. for ( var child in data.children ) {
  7369. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  7370. }
  7371. }
  7372. return object;
  7373. }
  7374. }()
  7375. };
  7376. /**
  7377. * @author alteredq / http://alteredqualia.com/
  7378. */
  7379. THREE.SceneLoader = function () {
  7380. this.onLoadStart = function () {};
  7381. this.onLoadProgress = function() {};
  7382. this.onLoadComplete = function () {};
  7383. this.callbackSync = function () {};
  7384. this.callbackProgress = function () {};
  7385. this.geometryHandlers = {};
  7386. this.hierarchyHandlers = {};
  7387. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  7388. };
  7389. THREE.SceneLoader.prototype = {
  7390. constructor: THREE.SceneLoader,
  7391. load: function ( url, onLoad, onProgress, onError ) {
  7392. var scope = this;
  7393. var loader = new THREE.XHRLoader( scope.manager );
  7394. loader.setCrossOrigin( this.crossOrigin );
  7395. loader.load( url, function ( text ) {
  7396. scope.parse( JSON.parse( text ), onLoad, url );
  7397. } );
  7398. },
  7399. setCrossOrigin: function ( value ) {
  7400. this.crossOrigin = value;
  7401. },
  7402. addGeometryHandler: function ( typeID, loaderClass ) {
  7403. this.geometryHandlers[ typeID ] = { "loaderClass": loaderClass };
  7404. },
  7405. addHierarchyHandler: function ( typeID, loaderClass ) {
  7406. this.hierarchyHandlers[ typeID ] = { "loaderClass": loaderClass };
  7407. },
  7408. parse: function ( json, callbackFinished, url ) {
  7409. var scope = this;
  7410. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  7411. var geometry, material, camera, fog,
  7412. texture, images, color,
  7413. light, hex, intensity,
  7414. counter_models, counter_textures,
  7415. total_models, total_textures,
  7416. result;
  7417. var target_array = [];
  7418. var data = json;
  7419. // async geometry loaders
  7420. for ( var typeID in this.geometryHandlers ) {
  7421. var loaderClass = this.geometryHandlers[ typeID ][ "loaderClass" ];
  7422. this.geometryHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  7423. }
  7424. // async hierachy loaders
  7425. for ( var typeID in this.hierarchyHandlers ) {
  7426. var loaderClass = this.hierarchyHandlers[ typeID ][ "loaderClass" ];
  7427. this.hierarchyHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  7428. }
  7429. counter_models = 0;
  7430. counter_textures = 0;
  7431. result = {
  7432. scene: new THREE.Scene(),
  7433. geometries: {},
  7434. face_materials: {},
  7435. materials: {},
  7436. textures: {},
  7437. objects: {},
  7438. cameras: {},
  7439. lights: {},
  7440. fogs: {},
  7441. empties: {},
  7442. groups: {}
  7443. };
  7444. if ( data.transform ) {
  7445. var position = data.transform.position,
  7446. rotation = data.transform.rotation,
  7447. scale = data.transform.scale;
  7448. if ( position ) {
  7449. result.scene.position.fromArray( position );
  7450. }
  7451. if ( rotation ) {
  7452. result.scene.rotation.fromArray( rotation );
  7453. }
  7454. if ( scale ) {
  7455. result.scene.scale.fromArray( scale );
  7456. }
  7457. if ( position || rotation || scale ) {
  7458. result.scene.updateMatrix();
  7459. result.scene.updateMatrixWorld();
  7460. }
  7461. }
  7462. function get_url( source_url, url_type ) {
  7463. if ( url_type == "relativeToHTML" ) {
  7464. return source_url;
  7465. } else {
  7466. return urlBase + "/" + source_url;
  7467. }
  7468. };
  7469. // toplevel loader function, delegates to handle_children
  7470. function handle_objects() {
  7471. handle_children( result.scene, data.objects );
  7472. }
  7473. // handle all the children from the loaded json and attach them to given parent
  7474. function handle_children( parent, children ) {
  7475. var mat, dst, pos, rot, scl, quat;
  7476. for ( var objID in children ) {
  7477. // check by id if child has already been handled,
  7478. // if not, create new object
  7479. var object = result.objects[ objID ];
  7480. var objJSON = children[ objID ];
  7481. if ( object === undefined ) {
  7482. // meshes
  7483. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7484. if ( objJSON.loading === undefined ) {
  7485. var reservedTypes = {
  7486. "type": 1, "url": 1, "material": 1,
  7487. "position": 1, "rotation": 1, "scale" : 1,
  7488. "visible": 1, "children": 1, "userData": 1,
  7489. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1
  7490. };
  7491. var loaderParameters = {};
  7492. for ( var parType in objJSON ) {
  7493. if ( ! ( parType in reservedTypes ) ) {
  7494. loaderParameters[ parType ] = objJSON[ parType ];
  7495. }
  7496. }
  7497. material = result.materials[ objJSON.material ];
  7498. objJSON.loading = true;
  7499. var loader = scope.hierarchyHandlers[ objJSON.type ][ "loaderObject" ];
  7500. // ColladaLoader
  7501. if ( loader.options ) {
  7502. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  7503. // UTF8Loader
  7504. // OBJLoader
  7505. } else {
  7506. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  7507. }
  7508. }
  7509. } else if ( objJSON.geometry !== undefined ) {
  7510. geometry = result.geometries[ objJSON.geometry ];
  7511. // geometry already loaded
  7512. if ( geometry ) {
  7513. var needsTangents = false;
  7514. material = result.materials[ objJSON.material ];
  7515. needsTangents = material instanceof THREE.ShaderMaterial;
  7516. pos = objJSON.position;
  7517. rot = objJSON.rotation;
  7518. scl = objJSON.scale;
  7519. mat = objJSON.matrix;
  7520. quat = objJSON.quaternion;
  7521. // use materials from the model file
  7522. // if there is no material specified in the object
  7523. if ( ! objJSON.material ) {
  7524. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7525. }
  7526. // use materials from the model file
  7527. // if there is just empty face material
  7528. // (must create new material as each model has its own face material)
  7529. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  7530. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7531. }
  7532. if ( material instanceof THREE.MeshFaceMaterial ) {
  7533. for ( var i = 0; i < material.materials.length; i ++ ) {
  7534. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  7535. }
  7536. }
  7537. if ( needsTangents ) {
  7538. geometry.computeTangents();
  7539. }
  7540. if ( objJSON.skin ) {
  7541. object = new THREE.SkinnedMesh( geometry, material );
  7542. } else if ( objJSON.morph ) {
  7543. object = new THREE.MorphAnimMesh( geometry, material );
  7544. if ( objJSON.duration !== undefined ) {
  7545. object.duration = objJSON.duration;
  7546. }
  7547. if ( objJSON.time !== undefined ) {
  7548. object.time = objJSON.time;
  7549. }
  7550. if ( objJSON.mirroredLoop !== undefined ) {
  7551. object.mirroredLoop = objJSON.mirroredLoop;
  7552. }
  7553. if ( material.morphNormals ) {
  7554. geometry.computeMorphNormals();
  7555. }
  7556. } else {
  7557. object = new THREE.Mesh( geometry, material );
  7558. }
  7559. object.name = objID;
  7560. if ( mat ) {
  7561. object.matrixAutoUpdate = false;
  7562. object.matrix.set(
  7563. mat[0], mat[1], mat[2], mat[3],
  7564. mat[4], mat[5], mat[6], mat[7],
  7565. mat[8], mat[9], mat[10], mat[11],
  7566. mat[12], mat[13], mat[14], mat[15]
  7567. );
  7568. } else {
  7569. object.position.fromArray( pos );
  7570. if ( quat ) {
  7571. object.quaternion.fromArray( quat );
  7572. } else {
  7573. object.rotation.fromArray( rot );
  7574. }
  7575. object.scale.fromArray( scl );
  7576. }
  7577. object.visible = objJSON.visible;
  7578. object.castShadow = objJSON.castShadow;
  7579. object.receiveShadow = objJSON.receiveShadow;
  7580. parent.add( object );
  7581. result.objects[ objID ] = object;
  7582. }
  7583. // lights
  7584. } else if ( objJSON.type === "AmbientLight" || objJSON.type === "PointLight" ||
  7585. objJSON.type === "DirectionalLight" || objJSON.type === "SpotLight" ||
  7586. objJSON.type === "HemisphereLight" || objJSON.type === "AreaLight" ) {
  7587. var color = objJSON.color;
  7588. var intensity = objJSON.intensity;
  7589. var distance = objJSON.distance;
  7590. var position = objJSON.position;
  7591. var rotation = objJSON.rotation;
  7592. switch ( objJSON.type ) {
  7593. case 'AmbientLight':
  7594. light = new THREE.AmbientLight( color );
  7595. break;
  7596. case 'PointLight':
  7597. light = new THREE.PointLight( color, intensity, distance );
  7598. light.position.fromArray( position );
  7599. break;
  7600. case 'DirectionalLight':
  7601. light = new THREE.DirectionalLight( color, intensity );
  7602. light.position.fromArray( objJSON.direction );
  7603. break;
  7604. case 'SpotLight':
  7605. light = new THREE.SpotLight( color, intensity, distance, 1 );
  7606. light.angle = objJSON.angle;
  7607. light.position.fromArray( position );
  7608. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  7609. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  7610. break;
  7611. case 'HemisphereLight':
  7612. light = new THREE.DirectionalLight( color, intensity, distance );
  7613. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  7614. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  7615. break;
  7616. case 'AreaLight':
  7617. light = new THREE.AreaLight(color, intensity);
  7618. light.position.fromArray( position );
  7619. light.width = objJSON.size;
  7620. light.height = objJSON.size_y;
  7621. break;
  7622. }
  7623. parent.add( light );
  7624. light.name = objID;
  7625. result.lights[ objID ] = light;
  7626. result.objects[ objID ] = light;
  7627. // cameras
  7628. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  7629. pos = objJSON.position;
  7630. rot = objJSON.rotation;
  7631. quat = objJSON.quaternion;
  7632. if ( objJSON.type === "PerspectiveCamera" ) {
  7633. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  7634. } else if ( objJSON.type === "OrthographicCamera" ) {
  7635. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  7636. }
  7637. camera.name = objID;
  7638. camera.position.fromArray( pos );
  7639. if ( quat !== undefined ) {
  7640. camera.quaternion.fromArray( quat );
  7641. } else if ( rot !== undefined ) {
  7642. camera.rotation.fromArray( rot );
  7643. }
  7644. parent.add( camera );
  7645. result.cameras[ objID ] = camera;
  7646. result.objects[ objID ] = camera;
  7647. // pure Object3D
  7648. } else {
  7649. pos = objJSON.position;
  7650. rot = objJSON.rotation;
  7651. scl = objJSON.scale;
  7652. quat = objJSON.quaternion;
  7653. object = new THREE.Object3D();
  7654. object.name = objID;
  7655. object.position.fromArray( pos );
  7656. if ( quat ) {
  7657. object.quaternion.fromArray( quat );
  7658. } else {
  7659. object.rotation.fromArray( rot );
  7660. }
  7661. object.scale.fromArray( scl );
  7662. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  7663. parent.add( object );
  7664. result.objects[ objID ] = object;
  7665. result.empties[ objID ] = object;
  7666. }
  7667. if ( object ) {
  7668. if ( objJSON.userData !== undefined ) {
  7669. for ( var key in objJSON.userData ) {
  7670. var value = objJSON.userData[ key ];
  7671. object.userData[ key ] = value;
  7672. }
  7673. }
  7674. if ( objJSON.groups !== undefined ) {
  7675. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  7676. var groupID = objJSON.groups[ i ];
  7677. if ( result.groups[ groupID ] === undefined ) {
  7678. result.groups[ groupID ] = [];
  7679. }
  7680. result.groups[ groupID ].push( objID );
  7681. }
  7682. }
  7683. }
  7684. }
  7685. if ( object !== undefined && objJSON.children !== undefined ) {
  7686. handle_children( object, objJSON.children );
  7687. }
  7688. }
  7689. };
  7690. function handle_mesh( geo, mat, id ) {
  7691. result.geometries[ id ] = geo;
  7692. result.face_materials[ id ] = mat;
  7693. handle_objects();
  7694. };
  7695. function handle_hierarchy( node, id, parent, material, obj ) {
  7696. var p = obj.position;
  7697. var r = obj.rotation;
  7698. var q = obj.quaternion;
  7699. var s = obj.scale;
  7700. node.position.fromArray( p );
  7701. if ( q ) {
  7702. node.quaternion.fromArray( q );
  7703. } else {
  7704. node.rotation.fromArray( r );
  7705. }
  7706. node.scale.fromArray( s );
  7707. // override children materials
  7708. // if object material was specified in JSON explicitly
  7709. if ( material ) {
  7710. node.traverse( function ( child ) {
  7711. child.material = material;
  7712. } );
  7713. }
  7714. // override children visibility
  7715. // with root node visibility as specified in JSON
  7716. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  7717. node.traverse( function ( child ) {
  7718. child.visible = visible;
  7719. } );
  7720. parent.add( node );
  7721. node.name = id;
  7722. result.objects[ id ] = node;
  7723. handle_objects();
  7724. };
  7725. function create_callback_geometry( id ) {
  7726. return function ( geo, mat ) {
  7727. geo.name = id;
  7728. handle_mesh( geo, mat, id );
  7729. counter_models -= 1;
  7730. scope.onLoadComplete();
  7731. async_callback_gate();
  7732. }
  7733. };
  7734. function create_callback_hierachy( id, parent, material, obj ) {
  7735. return function ( event ) {
  7736. var result;
  7737. // loaders which use EventDispatcher
  7738. if ( event.content ) {
  7739. result = event.content;
  7740. // ColladaLoader
  7741. } else if ( event.dae ) {
  7742. result = event.scene;
  7743. // UTF8Loader
  7744. } else {
  7745. result = event;
  7746. }
  7747. handle_hierarchy( result, id, parent, material, obj );
  7748. counter_models -= 1;
  7749. scope.onLoadComplete();
  7750. async_callback_gate();
  7751. }
  7752. };
  7753. function create_callback_embed( id ) {
  7754. return function ( geo, mat ) {
  7755. geo.name = id;
  7756. result.geometries[ id ] = geo;
  7757. result.face_materials[ id ] = mat;
  7758. }
  7759. };
  7760. function async_callback_gate() {
  7761. var progress = {
  7762. totalModels : total_models,
  7763. totalTextures : total_textures,
  7764. loadedModels : total_models - counter_models,
  7765. loadedTextures : total_textures - counter_textures
  7766. };
  7767. scope.callbackProgress( progress, result );
  7768. scope.onLoadProgress();
  7769. if ( counter_models === 0 && counter_textures === 0 ) {
  7770. finalize();
  7771. callbackFinished( result );
  7772. }
  7773. };
  7774. function finalize() {
  7775. // take care of targets which could be asynchronously loaded objects
  7776. for ( var i = 0; i < target_array.length; i ++ ) {
  7777. var ta = target_array[ i ];
  7778. var target = result.objects[ ta.targetName ];
  7779. if ( target ) {
  7780. ta.object.target = target;
  7781. } else {
  7782. // if there was error and target of specified name doesn't exist in the scene file
  7783. // create instead dummy target
  7784. // (target must be added to scene explicitly as parent is already added)
  7785. ta.object.target = new THREE.Object3D();
  7786. result.scene.add( ta.object.target );
  7787. }
  7788. ta.object.target.userData.targetInverse = ta.object;
  7789. }
  7790. };
  7791. var callbackTexture = function ( count ) {
  7792. counter_textures -= count;
  7793. async_callback_gate();
  7794. scope.onLoadComplete();
  7795. };
  7796. // must use this instead of just directly calling callbackTexture
  7797. // because of closure in the calling context loop
  7798. var generateTextureCallback = function ( count ) {
  7799. return function () {
  7800. callbackTexture( count );
  7801. };
  7802. };
  7803. function traverse_json_hierarchy( objJSON, callback ) {
  7804. callback( objJSON );
  7805. if ( objJSON.children !== undefined ) {
  7806. for ( var objChildID in objJSON.children ) {
  7807. traverse_json_hierarchy( objJSON.children[ objChildID ], callback );
  7808. }
  7809. }
  7810. };
  7811. // first go synchronous elements
  7812. // fogs
  7813. var fogID, fogJSON;
  7814. for ( fogID in data.fogs ) {
  7815. fogJSON = data.fogs[ fogID ];
  7816. if ( fogJSON.type === "linear" ) {
  7817. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  7818. } else if ( fogJSON.type === "exp2" ) {
  7819. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  7820. }
  7821. color = fogJSON.color;
  7822. fog.color.setRGB( color[0], color[1], color[2] );
  7823. result.fogs[ fogID ] = fog;
  7824. }
  7825. // now come potentially asynchronous elements
  7826. // geometries
  7827. // count how many geometries will be loaded asynchronously
  7828. var geoID, geoJSON;
  7829. for ( geoID in data.geometries ) {
  7830. geoJSON = data.geometries[ geoID ];
  7831. if ( geoJSON.type in this.geometryHandlers ) {
  7832. counter_models += 1;
  7833. scope.onLoadStart();
  7834. }
  7835. }
  7836. // count how many hierarchies will be loaded asynchronously
  7837. for ( var objID in data.objects ) {
  7838. traverse_json_hierarchy( data.objects[ objID ], function ( objJSON ) {
  7839. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7840. counter_models += 1;
  7841. scope.onLoadStart();
  7842. }
  7843. });
  7844. }
  7845. total_models = counter_models;
  7846. for ( geoID in data.geometries ) {
  7847. geoJSON = data.geometries[ geoID ];
  7848. if ( geoJSON.type === "cube" ) {
  7849. geometry = new THREE.BoxGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  7850. geometry.name = geoID;
  7851. result.geometries[ geoID ] = geometry;
  7852. } else if ( geoJSON.type === "plane" ) {
  7853. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  7854. geometry.name = geoID;
  7855. result.geometries[ geoID ] = geometry;
  7856. } else if ( geoJSON.type === "sphere" ) {
  7857. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  7858. geometry.name = geoID;
  7859. result.geometries[ geoID ] = geometry;
  7860. } else if ( geoJSON.type === "cylinder" ) {
  7861. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  7862. geometry.name = geoID;
  7863. result.geometries[ geoID ] = geometry;
  7864. } else if ( geoJSON.type === "torus" ) {
  7865. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  7866. geometry.name = geoID;
  7867. result.geometries[ geoID ] = geometry;
  7868. } else if ( geoJSON.type === "icosahedron" ) {
  7869. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  7870. geometry.name = geoID;
  7871. result.geometries[ geoID ] = geometry;
  7872. } else if ( geoJSON.type in this.geometryHandlers ) {
  7873. var loaderParameters = {};
  7874. for ( var parType in geoJSON ) {
  7875. if ( parType !== "type" && parType !== "url" ) {
  7876. loaderParameters[ parType ] = geoJSON[ parType ];
  7877. }
  7878. }
  7879. var loader = this.geometryHandlers[ geoJSON.type ][ "loaderObject" ];
  7880. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  7881. } else if ( geoJSON.type === "embedded" ) {
  7882. var modelJson = data.embeds[ geoJSON.id ],
  7883. texture_path = "";
  7884. // pass metadata along to jsonLoader so it knows the format version
  7885. modelJson.metadata = data.metadata;
  7886. if ( modelJson ) {
  7887. var jsonLoader = this.geometryHandlers[ "ascii" ][ "loaderObject" ];
  7888. var model = jsonLoader.parse( modelJson, texture_path );
  7889. create_callback_embed( geoID )( model.geometry, model.materials );
  7890. }
  7891. }
  7892. }
  7893. // textures
  7894. // count how many textures will be loaded asynchronously
  7895. var textureID, textureJSON;
  7896. for ( textureID in data.textures ) {
  7897. textureJSON = data.textures[ textureID ];
  7898. if ( textureJSON.url instanceof Array ) {
  7899. counter_textures += textureJSON.url.length;
  7900. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  7901. scope.onLoadStart();
  7902. }
  7903. } else {
  7904. counter_textures += 1;
  7905. scope.onLoadStart();
  7906. }
  7907. }
  7908. total_textures = counter_textures;
  7909. for ( textureID in data.textures ) {
  7910. textureJSON = data.textures[ textureID ];
  7911. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  7912. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  7913. }
  7914. if ( textureJSON.url instanceof Array ) {
  7915. var count = textureJSON.url.length;
  7916. var url_array = [];
  7917. for( var i = 0; i < count; i ++ ) {
  7918. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  7919. }
  7920. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  7921. if ( isCompressed ) {
  7922. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7923. } else {
  7924. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7925. }
  7926. } else {
  7927. var isCompressed = /\.dds$/i.test( textureJSON.url );
  7928. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  7929. var textureCallback = generateTextureCallback( 1 );
  7930. if ( isCompressed ) {
  7931. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  7932. } else {
  7933. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  7934. }
  7935. if ( THREE[ textureJSON.minFilter ] !== undefined )
  7936. texture.minFilter = THREE[ textureJSON.minFilter ];
  7937. if ( THREE[ textureJSON.magFilter ] !== undefined )
  7938. texture.magFilter = THREE[ textureJSON.magFilter ];
  7939. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  7940. if ( textureJSON.repeat ) {
  7941. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  7942. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  7943. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  7944. }
  7945. if ( textureJSON.offset ) {
  7946. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  7947. }
  7948. // handle wrap after repeat so that default repeat can be overriden
  7949. if ( textureJSON.wrap ) {
  7950. var wrapMap = {
  7951. "repeat": THREE.RepeatWrapping,
  7952. "mirror": THREE.MirroredRepeatWrapping
  7953. }
  7954. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  7955. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  7956. }
  7957. }
  7958. result.textures[ textureID ] = texture;
  7959. }
  7960. // materials
  7961. var matID, matJSON;
  7962. var parID;
  7963. for ( matID in data.materials ) {
  7964. matJSON = data.materials[ matID ];
  7965. for ( parID in matJSON.parameters ) {
  7966. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  7967. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  7968. } else if ( parID === "shading" ) {
  7969. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  7970. } else if ( parID === "side" ) {
  7971. if ( matJSON.parameters[ parID ] == "double" ) {
  7972. matJSON.parameters[ parID ] = THREE.DoubleSide;
  7973. } else if ( matJSON.parameters[ parID ] == "back" ) {
  7974. matJSON.parameters[ parID ] = THREE.BackSide;
  7975. } else {
  7976. matJSON.parameters[ parID ] = THREE.FrontSide;
  7977. }
  7978. } else if ( parID === "blending" ) {
  7979. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  7980. } else if ( parID === "combine" ) {
  7981. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  7982. } else if ( parID === "vertexColors" ) {
  7983. if ( matJSON.parameters[ parID ] == "face" ) {
  7984. matJSON.parameters[ parID ] = THREE.FaceColors;
  7985. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  7986. } else if ( matJSON.parameters[ parID ] ) {
  7987. matJSON.parameters[ parID ] = THREE.VertexColors;
  7988. }
  7989. } else if ( parID === "wrapRGB" ) {
  7990. var v3 = matJSON.parameters[ parID ];
  7991. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  7992. }
  7993. }
  7994. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  7995. matJSON.parameters.transparent = true;
  7996. }
  7997. if ( matJSON.parameters.normalMap ) {
  7998. var shader = THREE.ShaderLib[ "normalmap" ];
  7999. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  8000. var diffuse = matJSON.parameters.color;
  8001. var specular = matJSON.parameters.specular;
  8002. var ambient = matJSON.parameters.ambient;
  8003. var shininess = matJSON.parameters.shininess;
  8004. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  8005. if ( matJSON.parameters.normalScale ) {
  8006. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  8007. }
  8008. if ( matJSON.parameters.map ) {
  8009. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  8010. uniforms[ "enableDiffuse" ].value = true;
  8011. }
  8012. if ( matJSON.parameters.envMap ) {
  8013. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  8014. uniforms[ "enableReflection" ].value = true;
  8015. uniforms[ "reflectivity" ].value = matJSON.parameters.reflectivity;
  8016. }
  8017. if ( matJSON.parameters.lightMap ) {
  8018. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  8019. uniforms[ "enableAO" ].value = true;
  8020. }
  8021. if ( matJSON.parameters.specularMap ) {
  8022. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  8023. uniforms[ "enableSpecular" ].value = true;
  8024. }
  8025. if ( matJSON.parameters.displacementMap ) {
  8026. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  8027. uniforms[ "enableDisplacement" ].value = true;
  8028. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  8029. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  8030. }
  8031. uniforms[ "diffuse" ].value.setHex( diffuse );
  8032. uniforms[ "specular" ].value.setHex( specular );
  8033. uniforms[ "ambient" ].value.setHex( ambient );
  8034. uniforms[ "shininess" ].value = shininess;
  8035. if ( matJSON.parameters.opacity ) {
  8036. uniforms[ "opacity" ].value = matJSON.parameters.opacity;
  8037. }
  8038. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  8039. material = new THREE.ShaderMaterial( parameters );
  8040. } else {
  8041. material = new THREE[ matJSON.type ]( matJSON.parameters );
  8042. }
  8043. material.name = matID;
  8044. result.materials[ matID ] = material;
  8045. }
  8046. // second pass through all materials to initialize MeshFaceMaterials
  8047. // that could be referring to other materials out of order
  8048. for ( matID in data.materials ) {
  8049. matJSON = data.materials[ matID ];
  8050. if ( matJSON.parameters.materials ) {
  8051. var materialArray = [];
  8052. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  8053. var label = matJSON.parameters.materials[ i ];
  8054. materialArray.push( result.materials[ label ] );
  8055. }
  8056. result.materials[ matID ].materials = materialArray;
  8057. }
  8058. }
  8059. // objects ( synchronous init of procedural primitives )
  8060. handle_objects();
  8061. // defaults
  8062. if ( result.cameras && data.defaults.camera ) {
  8063. result.currentCamera = result.cameras[ data.defaults.camera ];
  8064. }
  8065. if ( result.fogs && data.defaults.fog ) {
  8066. result.scene.fog = result.fogs[ data.defaults.fog ];
  8067. }
  8068. // synchronous callback
  8069. scope.callbackSync( result );
  8070. // just in case there are no async elements
  8071. async_callback_gate();
  8072. }
  8073. }
  8074. /**
  8075. * @author mrdoob / http://mrdoob.com/
  8076. */
  8077. THREE.TextureLoader = function ( manager ) {
  8078. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  8079. };
  8080. THREE.TextureLoader.prototype = {
  8081. constructor: THREE.TextureLoader,
  8082. load: function ( url, onLoad, onProgress, onError ) {
  8083. var scope = this;
  8084. var loader = new THREE.ImageLoader( scope.manager );
  8085. loader.setCrossOrigin( this.crossOrigin );
  8086. loader.load( url, function ( image ) {
  8087. var texture = new THREE.Texture( image );
  8088. texture.needsUpdate = true;
  8089. if ( onLoad !== undefined ) {
  8090. onLoad( texture );
  8091. }
  8092. } );
  8093. },
  8094. setCrossOrigin: function ( value ) {
  8095. this.crossOrigin = value;
  8096. }
  8097. };
  8098. /**
  8099. * @author mrdoob / http://mrdoob.com/
  8100. * @author alteredq / http://alteredqualia.com/
  8101. */
  8102. THREE.Material = function () {
  8103. this.id = THREE.MaterialIdCount ++;
  8104. this.uuid = THREE.Math.generateUUID();
  8105. this.name = '';
  8106. this.side = THREE.FrontSide;
  8107. this.opacity = 1;
  8108. this.transparent = false;
  8109. this.blending = THREE.NormalBlending;
  8110. this.blendSrc = THREE.SrcAlphaFactor;
  8111. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  8112. this.blendEquation = THREE.AddEquation;
  8113. this.depthTest = true;
  8114. this.depthWrite = true;
  8115. this.polygonOffset = false;
  8116. this.polygonOffsetFactor = 0;
  8117. this.polygonOffsetUnits = 0;
  8118. this.alphaTest = 0;
  8119. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  8120. this.visible = true;
  8121. this.needsUpdate = true;
  8122. };
  8123. THREE.Material.prototype = {
  8124. constructor: THREE.Material,
  8125. setValues: function ( values ) {
  8126. if ( values === undefined ) return;
  8127. for ( var key in values ) {
  8128. var newValue = values[ key ];
  8129. if ( newValue === undefined ) {
  8130. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  8131. continue;
  8132. }
  8133. if ( key in this ) {
  8134. var currentValue = this[ key ];
  8135. if ( currentValue instanceof THREE.Color ) {
  8136. currentValue.set( newValue );
  8137. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  8138. currentValue.copy( newValue );
  8139. } else if ( key == 'overdraw') {
  8140. // ensure overdraw is backwards-compatable with legacy boolean type
  8141. this[ key ] = Number(newValue);
  8142. } else {
  8143. this[ key ] = newValue;
  8144. }
  8145. }
  8146. }
  8147. },
  8148. clone: function ( material ) {
  8149. if ( material === undefined ) material = new THREE.Material();
  8150. material.name = this.name;
  8151. material.side = this.side;
  8152. material.opacity = this.opacity;
  8153. material.transparent = this.transparent;
  8154. material.blending = this.blending;
  8155. material.blendSrc = this.blendSrc;
  8156. material.blendDst = this.blendDst;
  8157. material.blendEquation = this.blendEquation;
  8158. material.depthTest = this.depthTest;
  8159. material.depthWrite = this.depthWrite;
  8160. material.polygonOffset = this.polygonOffset;
  8161. material.polygonOffsetFactor = this.polygonOffsetFactor;
  8162. material.polygonOffsetUnits = this.polygonOffsetUnits;
  8163. material.alphaTest = this.alphaTest;
  8164. material.overdraw = this.overdraw;
  8165. material.visible = this.visible;
  8166. return material;
  8167. },
  8168. dispose: function () {
  8169. this.dispatchEvent( { type: 'dispose' } );
  8170. }
  8171. };
  8172. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  8173. THREE.MaterialIdCount = 0;
  8174. /**
  8175. * @author mrdoob / http://mrdoob.com/
  8176. * @author alteredq / http://alteredqualia.com/
  8177. *
  8178. * parameters = {
  8179. * color: <hex>,
  8180. * opacity: <float>,
  8181. *
  8182. * blending: THREE.NormalBlending,
  8183. * depthTest: <bool>,
  8184. * depthWrite: <bool>,
  8185. *
  8186. * linewidth: <float>,
  8187. * linecap: "round",
  8188. * linejoin: "round",
  8189. *
  8190. * vertexColors: <bool>
  8191. *
  8192. * fog: <bool>
  8193. * }
  8194. */
  8195. THREE.LineBasicMaterial = function ( parameters ) {
  8196. THREE.Material.call( this );
  8197. this.color = new THREE.Color( 0xffffff );
  8198. this.linewidth = 1;
  8199. this.linecap = 'round';
  8200. this.linejoin = 'round';
  8201. this.vertexColors = false;
  8202. this.fog = true;
  8203. this.setValues( parameters );
  8204. };
  8205. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8206. THREE.LineBasicMaterial.prototype.clone = function () {
  8207. var material = new THREE.LineBasicMaterial();
  8208. THREE.Material.prototype.clone.call( this, material );
  8209. material.color.copy( this.color );
  8210. material.linewidth = this.linewidth;
  8211. material.linecap = this.linecap;
  8212. material.linejoin = this.linejoin;
  8213. material.vertexColors = this.vertexColors;
  8214. material.fog = this.fog;
  8215. return material;
  8216. };
  8217. /**
  8218. * @author alteredq / http://alteredqualia.com/
  8219. *
  8220. * parameters = {
  8221. * color: <hex>,
  8222. * opacity: <float>,
  8223. *
  8224. * blending: THREE.NormalBlending,
  8225. * depthTest: <bool>,
  8226. * depthWrite: <bool>,
  8227. *
  8228. * linewidth: <float>,
  8229. *
  8230. * scale: <float>,
  8231. * dashSize: <float>,
  8232. * gapSize: <float>,
  8233. *
  8234. * vertexColors: <bool>
  8235. *
  8236. * fog: <bool>
  8237. * }
  8238. */
  8239. THREE.LineDashedMaterial = function ( parameters ) {
  8240. THREE.Material.call( this );
  8241. this.color = new THREE.Color( 0xffffff );
  8242. this.linewidth = 1;
  8243. this.scale = 1;
  8244. this.dashSize = 3;
  8245. this.gapSize = 1;
  8246. this.vertexColors = false;
  8247. this.fog = true;
  8248. this.setValues( parameters );
  8249. };
  8250. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  8251. THREE.LineDashedMaterial.prototype.clone = function () {
  8252. var material = new THREE.LineDashedMaterial();
  8253. THREE.Material.prototype.clone.call( this, material );
  8254. material.color.copy( this.color );
  8255. material.linewidth = this.linewidth;
  8256. material.scale = this.scale;
  8257. material.dashSize = this.dashSize;
  8258. material.gapSize = this.gapSize;
  8259. material.vertexColors = this.vertexColors;
  8260. material.fog = this.fog;
  8261. return material;
  8262. };
  8263. /**
  8264. * @author mrdoob / http://mrdoob.com/
  8265. * @author alteredq / http://alteredqualia.com/
  8266. *
  8267. * parameters = {
  8268. * color: <hex>,
  8269. * opacity: <float>,
  8270. * map: new THREE.Texture( <Image> ),
  8271. *
  8272. * lightMap: new THREE.Texture( <Image> ),
  8273. *
  8274. * specularMap: new THREE.Texture( <Image> ),
  8275. *
  8276. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8277. * combine: THREE.Multiply,
  8278. * reflectivity: <float>,
  8279. * refractionRatio: <float>,
  8280. *
  8281. * shading: THREE.SmoothShading,
  8282. * blending: THREE.NormalBlending,
  8283. * depthTest: <bool>,
  8284. * depthWrite: <bool>,
  8285. *
  8286. * wireframe: <boolean>,
  8287. * wireframeLinewidth: <float>,
  8288. *
  8289. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8290. *
  8291. * skinning: <bool>,
  8292. * morphTargets: <bool>,
  8293. *
  8294. * fog: <bool>
  8295. * }
  8296. */
  8297. THREE.MeshBasicMaterial = function ( parameters ) {
  8298. THREE.Material.call( this );
  8299. this.color = new THREE.Color( 0xffffff ); // emissive
  8300. this.map = null;
  8301. this.lightMap = null;
  8302. this.specularMap = null;
  8303. this.envMap = null;
  8304. this.combine = THREE.MultiplyOperation;
  8305. this.reflectivity = 1;
  8306. this.refractionRatio = 0.98;
  8307. this.fog = true;
  8308. this.shading = THREE.SmoothShading;
  8309. this.wireframe = false;
  8310. this.wireframeLinewidth = 1;
  8311. this.wireframeLinecap = 'round';
  8312. this.wireframeLinejoin = 'round';
  8313. this.vertexColors = THREE.NoColors;
  8314. this.skinning = false;
  8315. this.morphTargets = false;
  8316. this.setValues( parameters );
  8317. };
  8318. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8319. THREE.MeshBasicMaterial.prototype.clone = function () {
  8320. var material = new THREE.MeshBasicMaterial();
  8321. THREE.Material.prototype.clone.call( this, material );
  8322. material.color.copy( this.color );
  8323. material.map = this.map;
  8324. material.lightMap = this.lightMap;
  8325. material.specularMap = this.specularMap;
  8326. material.envMap = this.envMap;
  8327. material.combine = this.combine;
  8328. material.reflectivity = this.reflectivity;
  8329. material.refractionRatio = this.refractionRatio;
  8330. material.fog = this.fog;
  8331. material.shading = this.shading;
  8332. material.wireframe = this.wireframe;
  8333. material.wireframeLinewidth = this.wireframeLinewidth;
  8334. material.wireframeLinecap = this.wireframeLinecap;
  8335. material.wireframeLinejoin = this.wireframeLinejoin;
  8336. material.vertexColors = this.vertexColors;
  8337. material.skinning = this.skinning;
  8338. material.morphTargets = this.morphTargets;
  8339. return material;
  8340. };
  8341. /**
  8342. * @author mrdoob / http://mrdoob.com/
  8343. * @author alteredq / http://alteredqualia.com/
  8344. *
  8345. * parameters = {
  8346. * color: <hex>,
  8347. * ambient: <hex>,
  8348. * emissive: <hex>,
  8349. * opacity: <float>,
  8350. *
  8351. * map: new THREE.Texture( <Image> ),
  8352. *
  8353. * lightMap: new THREE.Texture( <Image> ),
  8354. *
  8355. * specularMap: new THREE.Texture( <Image> ),
  8356. *
  8357. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8358. * combine: THREE.Multiply,
  8359. * reflectivity: <float>,
  8360. * refractionRatio: <float>,
  8361. *
  8362. * shading: THREE.SmoothShading,
  8363. * blending: THREE.NormalBlending,
  8364. * depthTest: <bool>,
  8365. * depthWrite: <bool>,
  8366. *
  8367. * wireframe: <boolean>,
  8368. * wireframeLinewidth: <float>,
  8369. *
  8370. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8371. *
  8372. * skinning: <bool>,
  8373. * morphTargets: <bool>,
  8374. * morphNormals: <bool>,
  8375. *
  8376. * fog: <bool>
  8377. * }
  8378. */
  8379. THREE.MeshLambertMaterial = function ( parameters ) {
  8380. THREE.Material.call( this );
  8381. this.color = new THREE.Color( 0xffffff ); // diffuse
  8382. this.ambient = new THREE.Color( 0xffffff );
  8383. this.emissive = new THREE.Color( 0x000000 );
  8384. this.wrapAround = false;
  8385. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8386. this.map = null;
  8387. this.lightMap = null;
  8388. this.specularMap = null;
  8389. this.envMap = null;
  8390. this.combine = THREE.MultiplyOperation;
  8391. this.reflectivity = 1;
  8392. this.refractionRatio = 0.98;
  8393. this.fog = true;
  8394. this.shading = THREE.SmoothShading;
  8395. this.wireframe = false;
  8396. this.wireframeLinewidth = 1;
  8397. this.wireframeLinecap = 'round';
  8398. this.wireframeLinejoin = 'round';
  8399. this.vertexColors = THREE.NoColors;
  8400. this.skinning = false;
  8401. this.morphTargets = false;
  8402. this.morphNormals = false;
  8403. this.setValues( parameters );
  8404. };
  8405. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  8406. THREE.MeshLambertMaterial.prototype.clone = function () {
  8407. var material = new THREE.MeshLambertMaterial();
  8408. THREE.Material.prototype.clone.call( this, material );
  8409. material.color.copy( this.color );
  8410. material.ambient.copy( this.ambient );
  8411. material.emissive.copy( this.emissive );
  8412. material.wrapAround = this.wrapAround;
  8413. material.wrapRGB.copy( this.wrapRGB );
  8414. material.map = this.map;
  8415. material.lightMap = this.lightMap;
  8416. material.specularMap = this.specularMap;
  8417. material.envMap = this.envMap;
  8418. material.combine = this.combine;
  8419. material.reflectivity = this.reflectivity;
  8420. material.refractionRatio = this.refractionRatio;
  8421. material.fog = this.fog;
  8422. material.shading = this.shading;
  8423. material.wireframe = this.wireframe;
  8424. material.wireframeLinewidth = this.wireframeLinewidth;
  8425. material.wireframeLinecap = this.wireframeLinecap;
  8426. material.wireframeLinejoin = this.wireframeLinejoin;
  8427. material.vertexColors = this.vertexColors;
  8428. material.skinning = this.skinning;
  8429. material.morphTargets = this.morphTargets;
  8430. material.morphNormals = this.morphNormals;
  8431. return material;
  8432. };
  8433. /**
  8434. * @author mrdoob / http://mrdoob.com/
  8435. * @author alteredq / http://alteredqualia.com/
  8436. *
  8437. * parameters = {
  8438. * color: <hex>,
  8439. * ambient: <hex>,
  8440. * emissive: <hex>,
  8441. * specular: <hex>,
  8442. * shininess: <float>,
  8443. * opacity: <float>,
  8444. *
  8445. * map: new THREE.Texture( <Image> ),
  8446. *
  8447. * lightMap: new THREE.Texture( <Image> ),
  8448. *
  8449. * bumpMap: new THREE.Texture( <Image> ),
  8450. * bumpScale: <float>,
  8451. *
  8452. * normalMap: new THREE.Texture( <Image> ),
  8453. * normalScale: <Vector2>,
  8454. *
  8455. * specularMap: new THREE.Texture( <Image> ),
  8456. *
  8457. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8458. * combine: THREE.Multiply,
  8459. * reflectivity: <float>,
  8460. * refractionRatio: <float>,
  8461. *
  8462. * shading: THREE.SmoothShading,
  8463. * blending: THREE.NormalBlending,
  8464. * depthTest: <bool>,
  8465. * depthWrite: <bool>,
  8466. *
  8467. * wireframe: <boolean>,
  8468. * wireframeLinewidth: <float>,
  8469. *
  8470. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8471. *
  8472. * skinning: <bool>,
  8473. * morphTargets: <bool>,
  8474. * morphNormals: <bool>,
  8475. *
  8476. * fog: <bool>
  8477. * }
  8478. */
  8479. THREE.MeshPhongMaterial = function ( parameters ) {
  8480. THREE.Material.call( this );
  8481. this.color = new THREE.Color( 0xffffff ); // diffuse
  8482. this.ambient = new THREE.Color( 0xffffff );
  8483. this.emissive = new THREE.Color( 0x000000 );
  8484. this.specular = new THREE.Color( 0x111111 );
  8485. this.shininess = 30;
  8486. this.metal = false;
  8487. this.wrapAround = false;
  8488. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8489. this.map = null;
  8490. this.lightMap = null;
  8491. this.bumpMap = null;
  8492. this.bumpScale = 1;
  8493. this.normalMap = null;
  8494. this.normalScale = new THREE.Vector2( 1, 1 );
  8495. this.specularMap = null;
  8496. this.envMap = null;
  8497. this.combine = THREE.MultiplyOperation;
  8498. this.reflectivity = 1;
  8499. this.refractionRatio = 0.98;
  8500. this.fog = true;
  8501. this.shading = THREE.SmoothShading;
  8502. this.wireframe = false;
  8503. this.wireframeLinewidth = 1;
  8504. this.wireframeLinecap = 'round';
  8505. this.wireframeLinejoin = 'round';
  8506. this.vertexColors = THREE.NoColors;
  8507. this.skinning = false;
  8508. this.morphTargets = false;
  8509. this.morphNormals = false;
  8510. this.setValues( parameters );
  8511. };
  8512. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  8513. THREE.MeshPhongMaterial.prototype.clone = function () {
  8514. var material = new THREE.MeshPhongMaterial();
  8515. THREE.Material.prototype.clone.call( this, material );
  8516. material.color.copy( this.color );
  8517. material.ambient.copy( this.ambient );
  8518. material.emissive.copy( this.emissive );
  8519. material.specular.copy( this.specular );
  8520. material.shininess = this.shininess;
  8521. material.metal = this.metal;
  8522. material.wrapAround = this.wrapAround;
  8523. material.wrapRGB.copy( this.wrapRGB );
  8524. material.map = this.map;
  8525. material.lightMap = this.lightMap;
  8526. material.bumpMap = this.bumpMap;
  8527. material.bumpScale = this.bumpScale;
  8528. material.normalMap = this.normalMap;
  8529. material.normalScale.copy( this.normalScale );
  8530. material.specularMap = this.specularMap;
  8531. material.envMap = this.envMap;
  8532. material.combine = this.combine;
  8533. material.reflectivity = this.reflectivity;
  8534. material.refractionRatio = this.refractionRatio;
  8535. material.fog = this.fog;
  8536. material.shading = this.shading;
  8537. material.wireframe = this.wireframe;
  8538. material.wireframeLinewidth = this.wireframeLinewidth;
  8539. material.wireframeLinecap = this.wireframeLinecap;
  8540. material.wireframeLinejoin = this.wireframeLinejoin;
  8541. material.vertexColors = this.vertexColors;
  8542. material.skinning = this.skinning;
  8543. material.morphTargets = this.morphTargets;
  8544. material.morphNormals = this.morphNormals;
  8545. return material;
  8546. };
  8547. /**
  8548. * @author mrdoob / http://mrdoob.com/
  8549. * @author alteredq / http://alteredqualia.com/
  8550. *
  8551. * parameters = {
  8552. * opacity: <float>,
  8553. *
  8554. * blending: THREE.NormalBlending,
  8555. * depthTest: <bool>,
  8556. * depthWrite: <bool>,
  8557. *
  8558. * wireframe: <boolean>,
  8559. * wireframeLinewidth: <float>
  8560. * }
  8561. */
  8562. THREE.MeshDepthMaterial = function ( parameters ) {
  8563. THREE.Material.call( this );
  8564. this.wireframe = false;
  8565. this.wireframeLinewidth = 1;
  8566. this.setValues( parameters );
  8567. };
  8568. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  8569. THREE.MeshDepthMaterial.prototype.clone = function () {
  8570. var material = new THREE.MeshDepthMaterial();
  8571. THREE.Material.prototype.clone.call( this, material );
  8572. material.wireframe = this.wireframe;
  8573. material.wireframeLinewidth = this.wireframeLinewidth;
  8574. return material;
  8575. };
  8576. /**
  8577. * @author mrdoob / http://mrdoob.com/
  8578. *
  8579. * parameters = {
  8580. * opacity: <float>,
  8581. *
  8582. * shading: THREE.FlatShading,
  8583. * blending: THREE.NormalBlending,
  8584. * depthTest: <bool>,
  8585. * depthWrite: <bool>,
  8586. *
  8587. * wireframe: <boolean>,
  8588. * wireframeLinewidth: <float>
  8589. * }
  8590. */
  8591. THREE.MeshNormalMaterial = function ( parameters ) {
  8592. THREE.Material.call( this, parameters );
  8593. this.shading = THREE.FlatShading;
  8594. this.wireframe = false;
  8595. this.wireframeLinewidth = 1;
  8596. this.morphTargets = false;
  8597. this.setValues( parameters );
  8598. };
  8599. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  8600. THREE.MeshNormalMaterial.prototype.clone = function () {
  8601. var material = new THREE.MeshNormalMaterial();
  8602. THREE.Material.prototype.clone.call( this, material );
  8603. material.shading = this.shading;
  8604. material.wireframe = this.wireframe;
  8605. material.wireframeLinewidth = this.wireframeLinewidth;
  8606. return material;
  8607. };
  8608. /**
  8609. * @author mrdoob / http://mrdoob.com/
  8610. */
  8611. THREE.MeshFaceMaterial = function ( materials ) {
  8612. this.materials = materials instanceof Array ? materials : [];
  8613. };
  8614. THREE.MeshFaceMaterial.prototype.clone = function () {
  8615. var material = new THREE.MeshFaceMaterial();
  8616. for ( var i = 0; i < this.materials.length; i ++ ) {
  8617. material.materials.push( this.materials[ i ].clone() );
  8618. }
  8619. return material;
  8620. };
  8621. /**
  8622. * @author mrdoob / http://mrdoob.com/
  8623. * @author alteredq / http://alteredqualia.com/
  8624. *
  8625. * parameters = {
  8626. * color: <hex>,
  8627. * opacity: <float>,
  8628. * map: new THREE.Texture( <Image> ),
  8629. *
  8630. * size: <float>,
  8631. *
  8632. * blending: THREE.NormalBlending,
  8633. * depthTest: <bool>,
  8634. * depthWrite: <bool>,
  8635. *
  8636. * vertexColors: <bool>,
  8637. *
  8638. * fog: <bool>
  8639. * }
  8640. */
  8641. THREE.ParticleSystemMaterial = function ( parameters ) {
  8642. THREE.Material.call( this );
  8643. this.color = new THREE.Color( 0xffffff );
  8644. this.map = null;
  8645. this.size = 1;
  8646. this.sizeAttenuation = true;
  8647. this.vertexColors = false;
  8648. this.fog = true;
  8649. this.setValues( parameters );
  8650. };
  8651. THREE.ParticleSystemMaterial.prototype = Object.create( THREE.Material.prototype );
  8652. THREE.ParticleSystemMaterial.prototype.clone = function () {
  8653. var material = new THREE.ParticleSystemMaterial();
  8654. THREE.Material.prototype.clone.call( this, material );
  8655. material.color.copy( this.color );
  8656. material.map = this.map;
  8657. material.size = this.size;
  8658. material.sizeAttenuation = this.sizeAttenuation;
  8659. material.vertexColors = this.vertexColors;
  8660. material.fog = this.fog;
  8661. return material;
  8662. };
  8663. // backwards compatibility
  8664. THREE.ParticleBasicMaterial = THREE.ParticleSystemMaterial;
  8665. /**
  8666. * @author alteredq / http://alteredqualia.com/
  8667. *
  8668. * parameters = {
  8669. * fragmentShader: <string>,
  8670. * vertexShader: <string>,
  8671. *
  8672. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  8673. *
  8674. * defines: { "label" : "value" },
  8675. *
  8676. * shading: THREE.SmoothShading,
  8677. * blending: THREE.NormalBlending,
  8678. * depthTest: <bool>,
  8679. * depthWrite: <bool>,
  8680. *
  8681. * wireframe: <boolean>,
  8682. * wireframeLinewidth: <float>,
  8683. *
  8684. * lights: <bool>,
  8685. *
  8686. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8687. *
  8688. * skinning: <bool>,
  8689. * morphTargets: <bool>,
  8690. * morphNormals: <bool>,
  8691. *
  8692. * fog: <bool>
  8693. * }
  8694. */
  8695. THREE.ShaderMaterial = function ( parameters ) {
  8696. THREE.Material.call( this );
  8697. this.fragmentShader = "void main() {}";
  8698. this.vertexShader = "void main() {}";
  8699. this.uniforms = {};
  8700. this.defines = {};
  8701. this.attributes = null;
  8702. this.shading = THREE.SmoothShading;
  8703. this.linewidth = 1;
  8704. this.wireframe = false;
  8705. this.wireframeLinewidth = 1;
  8706. this.fog = false; // set to use scene fog
  8707. this.lights = false; // set to use scene lights
  8708. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  8709. this.skinning = false; // set to use skinning attribute streams
  8710. this.morphTargets = false; // set to use morph targets
  8711. this.morphNormals = false; // set to use morph normals
  8712. // When rendered geometry doesn't include these attributes but the material does,
  8713. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8714. this.defaultAttributeValues = {
  8715. "color" : [ 1, 1, 1],
  8716. "uv" : [ 0, 0 ],
  8717. "uv2" : [ 0, 0 ]
  8718. };
  8719. // By default, bind position to attribute index 0. In WebGL, attribute 0
  8720. // should always be used to avoid potentially expensive emulation.
  8721. this.index0AttributeName = "position";
  8722. this.setValues( parameters );
  8723. };
  8724. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  8725. THREE.ShaderMaterial.prototype.clone = function () {
  8726. var material = new THREE.ShaderMaterial();
  8727. THREE.Material.prototype.clone.call( this, material );
  8728. material.fragmentShader = this.fragmentShader;
  8729. material.vertexShader = this.vertexShader;
  8730. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  8731. material.attributes = this.attributes;
  8732. material.defines = this.defines;
  8733. material.shading = this.shading;
  8734. material.wireframe = this.wireframe;
  8735. material.wireframeLinewidth = this.wireframeLinewidth;
  8736. material.fog = this.fog;
  8737. material.lights = this.lights;
  8738. material.vertexColors = this.vertexColors;
  8739. material.skinning = this.skinning;
  8740. material.morphTargets = this.morphTargets;
  8741. material.morphNormals = this.morphNormals;
  8742. return material;
  8743. };
  8744. /**
  8745. * @author alteredq / http://alteredqualia.com/
  8746. *
  8747. * parameters = {
  8748. * color: <hex>,
  8749. * opacity: <float>,
  8750. * map: new THREE.Texture( <Image> ),
  8751. *
  8752. * blending: THREE.NormalBlending,
  8753. * depthTest: <bool>,
  8754. * depthWrite: <bool>,
  8755. *
  8756. * uvOffset: new THREE.Vector2(),
  8757. * uvScale: new THREE.Vector2(),
  8758. *
  8759. * fog: <bool>
  8760. * }
  8761. */
  8762. THREE.SpriteMaterial = function ( parameters ) {
  8763. THREE.Material.call( this );
  8764. // defaults
  8765. this.color = new THREE.Color( 0xffffff );
  8766. this.map = null;
  8767. this.rotation = 0;
  8768. this.fog = false;
  8769. // set parameters
  8770. this.setValues( parameters );
  8771. };
  8772. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  8773. THREE.SpriteMaterial.prototype.clone = function () {
  8774. var material = new THREE.SpriteMaterial();
  8775. THREE.Material.prototype.clone.call( this, material );
  8776. material.color.copy( this.color );
  8777. material.map = this.map;
  8778. material.rotation = this.rotation;
  8779. material.fog = this.fog;
  8780. return material;
  8781. };
  8782. /**
  8783. * @author mrdoob / http://mrdoob.com/
  8784. *
  8785. * parameters = {
  8786. * color: <hex>,
  8787. * program: <function>,
  8788. * opacity: <float>,
  8789. * blending: THREE.NormalBlending
  8790. * }
  8791. */
  8792. THREE.SpriteCanvasMaterial = function ( parameters ) {
  8793. THREE.Material.call( this );
  8794. this.color = new THREE.Color( 0xffffff );
  8795. this.program = function ( context, color ) {};
  8796. this.setValues( parameters );
  8797. };
  8798. THREE.SpriteCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  8799. THREE.SpriteCanvasMaterial.prototype.clone = function () {
  8800. var material = new THREE.SpriteCanvasMaterial();
  8801. THREE.Material.prototype.clone.call( this, material );
  8802. material.color.copy( this.color );
  8803. material.program = this.program;
  8804. return material;
  8805. };
  8806. // backwards compatibility
  8807. THREE.ParticleCanvasMaterial = THREE.SpriteCanvasMaterial;
  8808. /**
  8809. * @author mrdoob / http://mrdoob.com/
  8810. * @author alteredq / http://alteredqualia.com/
  8811. * @author szimek / https://github.com/szimek/
  8812. */
  8813. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8814. this.id = THREE.TextureIdCount ++;
  8815. this.uuid = THREE.Math.generateUUID();
  8816. this.name = '';
  8817. this.image = image;
  8818. this.mipmaps = [];
  8819. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  8820. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  8821. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  8822. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  8823. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  8824. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  8825. this.format = format !== undefined ? format : THREE.RGBAFormat;
  8826. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  8827. this.offset = new THREE.Vector2( 0, 0 );
  8828. this.repeat = new THREE.Vector2( 1, 1 );
  8829. this.generateMipmaps = true;
  8830. this.premultiplyAlpha = false;
  8831. this.flipY = true;
  8832. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  8833. this._needsUpdate = false;
  8834. this.onUpdate = null;
  8835. };
  8836. THREE.Texture.prototype = {
  8837. constructor: THREE.Texture,
  8838. get needsUpdate () {
  8839. return this._needsUpdate;
  8840. },
  8841. set needsUpdate ( value ) {
  8842. if ( value === true ) this.update();
  8843. this._needsUpdate = value;
  8844. },
  8845. clone: function ( texture ) {
  8846. if ( texture === undefined ) texture = new THREE.Texture();
  8847. texture.image = this.image;
  8848. texture.mipmaps = this.mipmaps.slice(0);
  8849. texture.mapping = this.mapping;
  8850. texture.wrapS = this.wrapS;
  8851. texture.wrapT = this.wrapT;
  8852. texture.magFilter = this.magFilter;
  8853. texture.minFilter = this.minFilter;
  8854. texture.anisotropy = this.anisotropy;
  8855. texture.format = this.format;
  8856. texture.type = this.type;
  8857. texture.offset.copy( this.offset );
  8858. texture.repeat.copy( this.repeat );
  8859. texture.generateMipmaps = this.generateMipmaps;
  8860. texture.premultiplyAlpha = this.premultiplyAlpha;
  8861. texture.flipY = this.flipY;
  8862. texture.unpackAlignment = this.unpackAlignment;
  8863. return texture;
  8864. },
  8865. update: function () {
  8866. this.dispatchEvent( { type: 'update' } );
  8867. },
  8868. dispose: function () {
  8869. this.dispatchEvent( { type: 'dispose' } );
  8870. }
  8871. };
  8872. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  8873. THREE.TextureIdCount = 0;
  8874. /**
  8875. * @author alteredq / http://alteredqualia.com/
  8876. */
  8877. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8878. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8879. this.image = { width: width, height: height };
  8880. this.mipmaps = mipmaps;
  8881. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  8882. };
  8883. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  8884. THREE.CompressedTexture.prototype.clone = function () {
  8885. var texture = new THREE.CompressedTexture();
  8886. THREE.Texture.prototype.clone.call( this, texture );
  8887. return texture;
  8888. };
  8889. /**
  8890. * @author alteredq / http://alteredqualia.com/
  8891. */
  8892. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8893. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8894. this.image = { data: data, width: width, height: height };
  8895. };
  8896. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  8897. THREE.DataTexture.prototype.clone = function () {
  8898. var texture = new THREE.DataTexture();
  8899. THREE.Texture.prototype.clone.call( this, texture );
  8900. return texture;
  8901. };
  8902. /**
  8903. * @author alteredq / http://alteredqualia.com/
  8904. */
  8905. THREE.ParticleSystem = function ( geometry, material ) {
  8906. THREE.Object3D.call( this );
  8907. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8908. this.material = material !== undefined ? material : new THREE.ParticleSystemMaterial( { color: Math.random() * 0xffffff } );
  8909. this.sortParticles = false;
  8910. this.frustumCulled = false;
  8911. };
  8912. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  8913. THREE.ParticleSystem.prototype.clone = function ( object ) {
  8914. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  8915. object.sortParticles = this.sortParticles;
  8916. THREE.Object3D.prototype.clone.call( this, object );
  8917. return object;
  8918. };
  8919. /**
  8920. * @author mrdoob / http://mrdoob.com/
  8921. */
  8922. THREE.Line = function ( geometry, material, type ) {
  8923. THREE.Object3D.call( this );
  8924. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8925. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  8926. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  8927. };
  8928. THREE.LineStrip = 0;
  8929. THREE.LinePieces = 1;
  8930. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  8931. THREE.Line.prototype.clone = function ( object ) {
  8932. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  8933. THREE.Object3D.prototype.clone.call( this, object );
  8934. return object;
  8935. };
  8936. /**
  8937. * @author mrdoob / http://mrdoob.com/
  8938. * @author alteredq / http://alteredqualia.com/
  8939. * @author mikael emtinger / http://gomo.se/
  8940. * @author jonobr1 / http://jonobr1.com/
  8941. */
  8942. THREE.Mesh = function ( geometry, material ) {
  8943. THREE.Object3D.call( this );
  8944. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8945. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  8946. this.updateMorphTargets();
  8947. };
  8948. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  8949. THREE.Mesh.prototype.updateMorphTargets = function () {
  8950. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  8951. this.morphTargetBase = -1;
  8952. this.morphTargetForcedOrder = [];
  8953. this.morphTargetInfluences = [];
  8954. this.morphTargetDictionary = {};
  8955. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  8956. this.morphTargetInfluences.push( 0 );
  8957. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  8958. }
  8959. }
  8960. };
  8961. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  8962. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  8963. return this.morphTargetDictionary[ name ];
  8964. }
  8965. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  8966. return 0;
  8967. };
  8968. THREE.Mesh.prototype.clone = function ( object ) {
  8969. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  8970. THREE.Object3D.prototype.clone.call( this, object );
  8971. return object;
  8972. };
  8973. /**
  8974. * @author mikael emtinger / http://gomo.se/
  8975. * @author alteredq / http://alteredqualia.com/
  8976. */
  8977. THREE.Bone = function( belongsToSkin ) {
  8978. THREE.Object3D.call( this );
  8979. this.skin = belongsToSkin;
  8980. this.skinMatrix = new THREE.Matrix4();
  8981. };
  8982. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  8983. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  8984. // update local
  8985. if ( this.matrixAutoUpdate ) {
  8986. forceUpdate |= this.updateMatrix();
  8987. }
  8988. // update skin matrix
  8989. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  8990. if( parentSkinMatrix ) {
  8991. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  8992. } else {
  8993. this.skinMatrix.copy( this.matrix );
  8994. }
  8995. this.matrixWorldNeedsUpdate = false;
  8996. forceUpdate = true;
  8997. }
  8998. // update children
  8999. var child, i, l = this.children.length;
  9000. for ( i = 0; i < l; i ++ ) {
  9001. this.children[ i ].update( this.skinMatrix, forceUpdate );
  9002. }
  9003. };
  9004. /**
  9005. * @author mikael emtinger / http://gomo.se/
  9006. * @author alteredq / http://alteredqualia.com/
  9007. */
  9008. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  9009. THREE.Mesh.call( this, geometry, material );
  9010. //
  9011. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  9012. // init bones
  9013. this.identityMatrix = new THREE.Matrix4();
  9014. this.bones = [];
  9015. this.boneMatrices = [];
  9016. var b, bone, gbone, p, q, s;
  9017. if ( this.geometry && this.geometry.bones !== undefined ) {
  9018. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  9019. gbone = this.geometry.bones[ b ];
  9020. p = gbone.pos;
  9021. q = gbone.rotq;
  9022. s = gbone.scl;
  9023. bone = this.addBone();
  9024. bone.name = gbone.name;
  9025. bone.position.set( p[0], p[1], p[2] );
  9026. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  9027. if ( s !== undefined ) {
  9028. bone.scale.set( s[0], s[1], s[2] );
  9029. } else {
  9030. bone.scale.set( 1, 1, 1 );
  9031. }
  9032. }
  9033. for ( b = 0; b < this.bones.length; b ++ ) {
  9034. gbone = this.geometry.bones[ b ];
  9035. bone = this.bones[ b ];
  9036. if ( gbone.parent === -1 ) {
  9037. this.add( bone );
  9038. } else {
  9039. this.bones[ gbone.parent ].add( bone );
  9040. }
  9041. }
  9042. //
  9043. var nBones = this.bones.length;
  9044. if ( this.useVertexTexture ) {
  9045. // layout (1 matrix = 4 pixels)
  9046. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  9047. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  9048. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  9049. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  9050. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  9051. var size;
  9052. if ( nBones > 256 )
  9053. size = 64;
  9054. else if ( nBones > 64 )
  9055. size = 32;
  9056. else if ( nBones > 16 )
  9057. size = 16;
  9058. else
  9059. size = 8;
  9060. this.boneTextureWidth = size;
  9061. this.boneTextureHeight = size;
  9062. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  9063. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  9064. this.boneTexture.minFilter = THREE.NearestFilter;
  9065. this.boneTexture.magFilter = THREE.NearestFilter;
  9066. this.boneTexture.generateMipmaps = false;
  9067. this.boneTexture.flipY = false;
  9068. } else {
  9069. this.boneMatrices = new Float32Array( 16 * nBones );
  9070. }
  9071. this.pose();
  9072. }
  9073. };
  9074. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  9075. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  9076. if ( bone === undefined ) {
  9077. bone = new THREE.Bone( this );
  9078. }
  9079. this.bones.push( bone );
  9080. return bone;
  9081. };
  9082. THREE.SkinnedMesh.prototype.updateMatrixWorld = function () {
  9083. var offsetMatrix = new THREE.Matrix4();
  9084. return function ( force ) {
  9085. this.matrixAutoUpdate && this.updateMatrix();
  9086. // update matrixWorld
  9087. if ( this.matrixWorldNeedsUpdate || force ) {
  9088. if ( this.parent ) {
  9089. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9090. } else {
  9091. this.matrixWorld.copy( this.matrix );
  9092. }
  9093. this.matrixWorldNeedsUpdate = false;
  9094. force = true;
  9095. }
  9096. // update children
  9097. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  9098. var child = this.children[ i ];
  9099. if ( child instanceof THREE.Bone ) {
  9100. child.update( this.identityMatrix, false );
  9101. } else {
  9102. child.updateMatrixWorld( true );
  9103. }
  9104. }
  9105. // make a snapshot of the bones' rest position
  9106. if ( this.boneInverses == undefined ) {
  9107. this.boneInverses = [];
  9108. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9109. var inverse = new THREE.Matrix4();
  9110. inverse.getInverse( this.bones[ b ].skinMatrix );
  9111. this.boneInverses.push( inverse );
  9112. }
  9113. }
  9114. // flatten bone matrices to array
  9115. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9116. // compute the offset between the current and the original transform;
  9117. // TODO: we could get rid of this multiplication step if the skinMatrix
  9118. // was already representing the offset; however, this requires some
  9119. // major changes to the animation system
  9120. offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  9121. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  9122. }
  9123. if ( this.useVertexTexture ) {
  9124. this.boneTexture.needsUpdate = true;
  9125. }
  9126. };
  9127. }();
  9128. THREE.SkinnedMesh.prototype.pose = function () {
  9129. this.updateMatrixWorld( true );
  9130. this.normalizeSkinWeights();
  9131. };
  9132. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  9133. if ( this.geometry instanceof THREE.Geometry ) {
  9134. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  9135. var sw = this.geometry.skinWeights[ i ];
  9136. var scale = 1.0 / sw.lengthManhattan();
  9137. if ( scale !== Infinity ) {
  9138. sw.multiplyScalar( scale );
  9139. } else {
  9140. sw.set( 1 ); // this will be normalized by the shader anyway
  9141. }
  9142. }
  9143. } else {
  9144. // skinning weights assumed to be normalized for THREE.BufferGeometry
  9145. }
  9146. };
  9147. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  9148. if ( object === undefined ) {
  9149. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  9150. }
  9151. THREE.Mesh.prototype.clone.call( this, object );
  9152. return object;
  9153. };
  9154. /**
  9155. * @author alteredq / http://alteredqualia.com/
  9156. */
  9157. THREE.MorphAnimMesh = function ( geometry, material ) {
  9158. THREE.Mesh.call( this, geometry, material );
  9159. // API
  9160. this.duration = 1000; // milliseconds
  9161. this.mirroredLoop = false;
  9162. this.time = 0;
  9163. // internals
  9164. this.lastKeyframe = 0;
  9165. this.currentKeyframe = 0;
  9166. this.direction = 1;
  9167. this.directionBackwards = false;
  9168. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  9169. };
  9170. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  9171. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  9172. this.startKeyframe = start;
  9173. this.endKeyframe = end;
  9174. this.length = this.endKeyframe - this.startKeyframe + 1;
  9175. };
  9176. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  9177. this.direction = 1;
  9178. this.directionBackwards = false;
  9179. };
  9180. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  9181. this.direction = -1;
  9182. this.directionBackwards = true;
  9183. };
  9184. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  9185. var geometry = this.geometry;
  9186. if ( ! geometry.animations ) geometry.animations = {};
  9187. var firstAnimation, animations = geometry.animations;
  9188. var pattern = /([a-z]+)(\d+)/;
  9189. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  9190. var morph = geometry.morphTargets[ i ];
  9191. var parts = morph.name.match( pattern );
  9192. if ( parts && parts.length > 1 ) {
  9193. var label = parts[ 1 ];
  9194. var num = parts[ 2 ];
  9195. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  9196. var animation = animations[ label ];
  9197. if ( i < animation.start ) animation.start = i;
  9198. if ( i > animation.end ) animation.end = i;
  9199. if ( ! firstAnimation ) firstAnimation = label;
  9200. }
  9201. }
  9202. geometry.firstAnimation = firstAnimation;
  9203. };
  9204. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  9205. if ( ! this.geometry.animations ) this.geometry.animations = {};
  9206. this.geometry.animations[ label ] = { start: start, end: end };
  9207. };
  9208. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  9209. var animation = this.geometry.animations[ label ];
  9210. if ( animation ) {
  9211. this.setFrameRange( animation.start, animation.end );
  9212. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  9213. this.time = 0;
  9214. } else {
  9215. console.warn( "animation[" + label + "] undefined" );
  9216. }
  9217. };
  9218. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  9219. var frameTime = this.duration / this.length;
  9220. this.time += this.direction * delta;
  9221. if ( this.mirroredLoop ) {
  9222. if ( this.time > this.duration || this.time < 0 ) {
  9223. this.direction *= -1;
  9224. if ( this.time > this.duration ) {
  9225. this.time = this.duration;
  9226. this.directionBackwards = true;
  9227. }
  9228. if ( this.time < 0 ) {
  9229. this.time = 0;
  9230. this.directionBackwards = false;
  9231. }
  9232. }
  9233. } else {
  9234. this.time = this.time % this.duration;
  9235. if ( this.time < 0 ) this.time += this.duration;
  9236. }
  9237. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  9238. if ( keyframe !== this.currentKeyframe ) {
  9239. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  9240. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  9241. this.morphTargetInfluences[ keyframe ] = 0;
  9242. this.lastKeyframe = this.currentKeyframe;
  9243. this.currentKeyframe = keyframe;
  9244. }
  9245. var mix = ( this.time % frameTime ) / frameTime;
  9246. if ( this.directionBackwards ) {
  9247. mix = 1 - mix;
  9248. }
  9249. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  9250. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  9251. };
  9252. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  9253. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  9254. object.duration = this.duration;
  9255. object.mirroredLoop = this.mirroredLoop;
  9256. object.time = this.time;
  9257. object.lastKeyframe = this.lastKeyframe;
  9258. object.currentKeyframe = this.currentKeyframe;
  9259. object.direction = this.direction;
  9260. object.directionBackwards = this.directionBackwards;
  9261. THREE.Mesh.prototype.clone.call( this, object );
  9262. return object;
  9263. };
  9264. /**
  9265. * @author mikael emtinger / http://gomo.se/
  9266. * @author alteredq / http://alteredqualia.com/
  9267. * @author mrdoob / http://mrdoob.com/
  9268. */
  9269. THREE.LOD = function () {
  9270. THREE.Object3D.call( this );
  9271. this.objects = [];
  9272. };
  9273. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  9274. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  9275. if ( distance === undefined ) distance = 0;
  9276. distance = Math.abs( distance );
  9277. for ( var l = 0; l < this.objects.length; l ++ ) {
  9278. if ( distance < this.objects[ l ].distance ) {
  9279. break;
  9280. }
  9281. }
  9282. this.objects.splice( l, 0, { distance: distance, object: object } );
  9283. this.add( object );
  9284. };
  9285. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  9286. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9287. if ( distance < this.objects[ i ].distance ) {
  9288. break;
  9289. }
  9290. }
  9291. return this.objects[ i - 1 ].object;
  9292. };
  9293. THREE.LOD.prototype.update = function () {
  9294. var v1 = new THREE.Vector3();
  9295. var v2 = new THREE.Vector3();
  9296. return function ( camera ) {
  9297. if ( this.objects.length > 1 ) {
  9298. v1.setFromMatrixPosition( camera.matrixWorld );
  9299. v2.setFromMatrixPosition( this.matrixWorld );
  9300. var distance = v1.distanceTo( v2 );
  9301. this.objects[ 0 ].object.visible = true;
  9302. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9303. if ( distance >= this.objects[ i ].distance ) {
  9304. this.objects[ i - 1 ].object.visible = false;
  9305. this.objects[ i ].object.visible = true;
  9306. } else {
  9307. break;
  9308. }
  9309. }
  9310. for( ; i < l; i ++ ) {
  9311. this.objects[ i ].object.visible = false;
  9312. }
  9313. }
  9314. };
  9315. }();
  9316. THREE.LOD.prototype.clone = function ( object ) {
  9317. if ( object === undefined ) object = new THREE.LOD();
  9318. THREE.Object3D.prototype.clone.call( this, object );
  9319. for ( var i = 0, l = this.objects.length; i < l; i ++ ) {
  9320. var x = this.objects[i].object.clone();
  9321. x.visible = i === 0;
  9322. object.addLevel( x, this.objects[i].distance );
  9323. }
  9324. return object;
  9325. };
  9326. /**
  9327. * @author mikael emtinger / http://gomo.se/
  9328. * @author alteredq / http://alteredqualia.com/
  9329. */
  9330. THREE.Sprite = ( function () {
  9331. var geometry = new THREE.Geometry2( 3 );
  9332. geometry.vertices.set( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0 ] );
  9333. return function ( material ) {
  9334. THREE.Object3D.call( this );
  9335. this.geometry = geometry;
  9336. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  9337. };
  9338. } )();
  9339. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  9340. /*
  9341. * Custom update matrix
  9342. */
  9343. THREE.Sprite.prototype.updateMatrix = function () {
  9344. this.matrix.compose( this.position, this.quaternion, this.scale );
  9345. this.matrixWorldNeedsUpdate = true;
  9346. };
  9347. THREE.Sprite.prototype.clone = function ( object ) {
  9348. if ( object === undefined ) object = new THREE.Sprite( this.material );
  9349. THREE.Object3D.prototype.clone.call( this, object );
  9350. return object;
  9351. };
  9352. // Backwards compatibility
  9353. THREE.Particle = THREE.Sprite;
  9354. /**
  9355. * @author mrdoob / http://mrdoob.com/
  9356. */
  9357. THREE.Scene = function () {
  9358. THREE.Object3D.call( this );
  9359. this.fog = null;
  9360. this.overrideMaterial = null;
  9361. this.autoUpdate = true; // checked by the renderer
  9362. this.matrixAutoUpdate = false;
  9363. this.__lights = [];
  9364. this.__objectsAdded = [];
  9365. this.__objectsRemoved = [];
  9366. };
  9367. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  9368. THREE.Scene.prototype.__addObject = function ( object ) {
  9369. if ( object instanceof THREE.Light ) {
  9370. if ( this.__lights.indexOf( object ) === - 1 ) {
  9371. this.__lights.push( object );
  9372. }
  9373. if ( object.target && object.target.parent === undefined ) {
  9374. this.add( object.target );
  9375. }
  9376. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  9377. this.__objectsAdded.push( object );
  9378. // check if previously removed
  9379. var i = this.__objectsRemoved.indexOf( object );
  9380. if ( i !== -1 ) {
  9381. this.__objectsRemoved.splice( i, 1 );
  9382. }
  9383. }
  9384. this.dispatchEvent( { type: 'objectAdded', object: object } );
  9385. object.dispatchEvent( { type: 'addedToScene', scene: this } );
  9386. for ( var c = 0; c < object.children.length; c ++ ) {
  9387. this.__addObject( object.children[ c ] );
  9388. }
  9389. };
  9390. THREE.Scene.prototype.__removeObject = function ( object ) {
  9391. if ( object instanceof THREE.Light ) {
  9392. var i = this.__lights.indexOf( object );
  9393. if ( i !== -1 ) {
  9394. this.__lights.splice( i, 1 );
  9395. }
  9396. if ( object.shadowCascadeArray ) {
  9397. for ( var x = 0; x < object.shadowCascadeArray.length; x ++ ) {
  9398. this.__removeObject( object.shadowCascadeArray[ x ] );
  9399. }
  9400. }
  9401. } else if ( !( object instanceof THREE.Camera ) ) {
  9402. this.__objectsRemoved.push( object );
  9403. // check if previously added
  9404. var i = this.__objectsAdded.indexOf( object );
  9405. if ( i !== -1 ) {
  9406. this.__objectsAdded.splice( i, 1 );
  9407. }
  9408. }
  9409. this.dispatchEvent( { type: 'objectRemoved', object: object } );
  9410. object.dispatchEvent( { type: 'removedFromScene', scene: this } );
  9411. for ( var c = 0; c < object.children.length; c ++ ) {
  9412. this.__removeObject( object.children[ c ] );
  9413. }
  9414. };
  9415. THREE.Scene.prototype.clone = function ( object ) {
  9416. if ( object === undefined ) object = new THREE.Scene();
  9417. THREE.Object3D.prototype.clone.call(this, object);
  9418. if ( this.fog !== null ) object.fog = this.fog.clone();
  9419. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  9420. object.autoUpdate = this.autoUpdate;
  9421. object.matrixAutoUpdate = this.matrixAutoUpdate;
  9422. return object;
  9423. };
  9424. /**
  9425. * @author mrdoob / http://mrdoob.com/
  9426. * @author alteredq / http://alteredqualia.com/
  9427. */
  9428. THREE.Fog = function ( color, near, far ) {
  9429. this.name = '';
  9430. this.color = new THREE.Color( color );
  9431. this.near = ( near !== undefined ) ? near : 1;
  9432. this.far = ( far !== undefined ) ? far : 1000;
  9433. };
  9434. THREE.Fog.prototype.clone = function () {
  9435. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  9436. };
  9437. /**
  9438. * @author mrdoob / http://mrdoob.com/
  9439. * @author alteredq / http://alteredqualia.com/
  9440. */
  9441. THREE.FogExp2 = function ( color, density ) {
  9442. this.name = '';
  9443. this.color = new THREE.Color( color );
  9444. this.density = ( density !== undefined ) ? density : 0.00025;
  9445. };
  9446. THREE.FogExp2.prototype.clone = function () {
  9447. return new THREE.FogExp2( this.color.getHex(), this.density );
  9448. };
  9449. /**
  9450. * @author mrdoob / http://mrdoob.com/
  9451. */
  9452. THREE.CanvasRenderer = function ( parameters ) {
  9453. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  9454. var smoothstep = THREE.Math.smoothstep;
  9455. parameters = parameters || {};
  9456. var _this = this,
  9457. _renderData, _elements, _lights,
  9458. _projector = new THREE.Projector(),
  9459. _canvas = parameters.canvas !== undefined
  9460. ? parameters.canvas
  9461. : document.createElement( 'canvas' ),
  9462. _canvasWidth = _canvas.width,
  9463. _canvasHeight = _canvas.height,
  9464. _canvasWidthHalf = Math.floor( _canvasWidth / 2 ),
  9465. _canvasHeightHalf = Math.floor( _canvasHeight / 2 ),
  9466. _context = _canvas.getContext( '2d' ),
  9467. _clearColor = new THREE.Color( 0x000000 ),
  9468. _clearAlpha = 0,
  9469. _contextGlobalAlpha = 1,
  9470. _contextGlobalCompositeOperation = 0,
  9471. _contextStrokeStyle = null,
  9472. _contextFillStyle = null,
  9473. _contextLineWidth = null,
  9474. _contextLineCap = null,
  9475. _contextLineJoin = null,
  9476. _contextDashSize = null,
  9477. _contextGapSize = 0,
  9478. _camera,
  9479. _v1, _v2, _v3, _v4,
  9480. _v5 = new THREE.RenderableVertex(),
  9481. _v6 = new THREE.RenderableVertex(),
  9482. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  9483. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  9484. _color = new THREE.Color(),
  9485. _color1 = new THREE.Color(),
  9486. _color2 = new THREE.Color(),
  9487. _color3 = new THREE.Color(),
  9488. _color4 = new THREE.Color(),
  9489. _diffuseColor = new THREE.Color(),
  9490. _emissiveColor = new THREE.Color(),
  9491. _lightColor = new THREE.Color(),
  9492. _patterns = {},
  9493. _near, _far,
  9494. _image, _uvs,
  9495. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  9496. _clipBox = new THREE.Box2(),
  9497. _clearBox = new THREE.Box2(),
  9498. _elemBox = new THREE.Box2(),
  9499. _ambientLight = new THREE.Color(),
  9500. _directionalLights = new THREE.Color(),
  9501. _pointLights = new THREE.Color(),
  9502. _vector3 = new THREE.Vector3(), // Needed for PointLight
  9503. _normal = new THREE.Vector3(),
  9504. _normalViewMatrix = new THREE.Matrix3(),
  9505. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  9506. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  9507. _pixelMap = document.createElement( 'canvas' );
  9508. _pixelMap.width = _pixelMap.height = 2;
  9509. _pixelMapContext = _pixelMap.getContext( '2d' );
  9510. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  9511. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  9512. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  9513. _pixelMapData = _pixelMapImage.data;
  9514. _gradientMap = document.createElement( 'canvas' );
  9515. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  9516. _gradientMapContext = _gradientMap.getContext( '2d' );
  9517. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  9518. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  9519. _gradientMapQuality --; // Fix UVs
  9520. // dash+gap fallbacks for Firefox and everything else
  9521. if ( _context.setLineDash === undefined ) {
  9522. if ( _context.mozDash !== undefined ) {
  9523. _context.setLineDash = function ( values ) {
  9524. _context.mozDash = values[ 0 ] !== null ? values : null;
  9525. }
  9526. } else {
  9527. _context.setLineDash = function () {}
  9528. }
  9529. }
  9530. this.domElement = _canvas;
  9531. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  9532. ? parameters.devicePixelRatio
  9533. : self.devicePixelRatio !== undefined
  9534. ? self.devicePixelRatio
  9535. : 1;
  9536. this.autoClear = true;
  9537. this.sortObjects = true;
  9538. this.sortElements = true;
  9539. this.info = {
  9540. render: {
  9541. vertices: 0,
  9542. faces: 0
  9543. }
  9544. }
  9545. // WebGLRenderer compatibility
  9546. this.supportsVertexTextures = function () {};
  9547. this.setFaceCulling = function () {};
  9548. this.setSize = function ( width, height, updateStyle ) {
  9549. _canvasWidth = width * this.devicePixelRatio;
  9550. _canvasHeight = height * this.devicePixelRatio;
  9551. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  9552. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  9553. _canvas.width = _canvasWidth;
  9554. _canvas.height = _canvasHeight;
  9555. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  9556. _canvas.style.width = width + 'px';
  9557. _canvas.style.height = height + 'px';
  9558. }
  9559. _clipBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf ),
  9560. _clipBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9561. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  9562. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9563. _contextGlobalAlpha = 1;
  9564. _contextGlobalCompositeOperation = 0;
  9565. _contextStrokeStyle = null;
  9566. _contextFillStyle = null;
  9567. _contextLineWidth = null;
  9568. _contextLineCap = null;
  9569. _contextLineJoin = null;
  9570. };
  9571. this.setClearColor = function ( color, alpha ) {
  9572. _clearColor.set( color );
  9573. _clearAlpha = alpha !== undefined ? alpha : 1;
  9574. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  9575. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9576. };
  9577. this.setClearColorHex = function ( hex, alpha ) {
  9578. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  9579. this.setClearColor( hex, alpha );
  9580. };
  9581. this.getMaxAnisotropy = function () {
  9582. return 0;
  9583. };
  9584. this.clear = function () {
  9585. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  9586. if ( _clearBox.empty() === false ) {
  9587. _clearBox.intersect( _clipBox );
  9588. _clearBox.expandByScalar( 2 );
  9589. if ( _clearAlpha < 1 ) {
  9590. _context.clearRect(
  9591. _clearBox.min.x | 0,
  9592. _clearBox.min.y | 0,
  9593. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9594. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9595. );
  9596. }
  9597. if ( _clearAlpha > 0 ) {
  9598. setBlending( THREE.NormalBlending );
  9599. setOpacity( 1 );
  9600. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  9601. _context.fillRect(
  9602. _clearBox.min.x | 0,
  9603. _clearBox.min.y | 0,
  9604. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9605. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9606. );
  9607. }
  9608. _clearBox.makeEmpty();
  9609. }
  9610. };
  9611. // compatibility
  9612. this.clearColor = function () {};
  9613. this.clearDepth = function () {};
  9614. this.clearStencil = function () {};
  9615. this.render = function ( scene, camera ) {
  9616. if ( camera instanceof THREE.Camera === false ) {
  9617. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  9618. return;
  9619. }
  9620. if ( this.autoClear === true ) this.clear();
  9621. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  9622. _this.info.render.vertices = 0;
  9623. _this.info.render.faces = 0;
  9624. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  9625. _elements = _renderData.elements;
  9626. _lights = _renderData.lights;
  9627. _camera = camera;
  9628. _normalViewMatrix.getNormalMatrix( camera.matrixWorldInverse );
  9629. /* DEBUG
  9630. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  9631. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  9632. */
  9633. calculateLights();
  9634. for ( var e = 0, el = _elements.length; e < el; e ++ ) {
  9635. var element = _elements[ e ];
  9636. var material = element.material;
  9637. if ( material === undefined || material.visible === false ) continue;
  9638. _elemBox.makeEmpty();
  9639. if ( element instanceof THREE.RenderableSprite ) {
  9640. _v1 = element;
  9641. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  9642. renderSprite( _v1, element, material );
  9643. } else if ( element instanceof THREE.RenderableLine ) {
  9644. _v1 = element.v1; _v2 = element.v2;
  9645. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9646. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9647. _elemBox.setFromPoints( [
  9648. _v1.positionScreen,
  9649. _v2.positionScreen
  9650. ] );
  9651. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9652. renderLine( _v1, _v2, element, material );
  9653. }
  9654. } else if ( element instanceof THREE.RenderableFace ) {
  9655. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  9656. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  9657. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  9658. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  9659. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9660. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9661. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  9662. if ( material.overdraw > 0 ) {
  9663. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  9664. expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
  9665. expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
  9666. }
  9667. _elemBox.setFromPoints( [
  9668. _v1.positionScreen,
  9669. _v2.positionScreen,
  9670. _v3.positionScreen
  9671. ] );
  9672. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9673. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  9674. }
  9675. }
  9676. /* DEBUG
  9677. setLineWidth( 1 );
  9678. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  9679. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  9680. */
  9681. _clearBox.union( _elemBox );
  9682. }
  9683. /* DEBUG
  9684. setLineWidth( 1 );
  9685. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  9686. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  9687. */
  9688. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  9689. };
  9690. //
  9691. function calculateLights() {
  9692. _ambientLight.setRGB( 0, 0, 0 );
  9693. _directionalLights.setRGB( 0, 0, 0 );
  9694. _pointLights.setRGB( 0, 0, 0 );
  9695. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9696. var light = _lights[ l ];
  9697. var lightColor = light.color;
  9698. if ( light instanceof THREE.AmbientLight ) {
  9699. _ambientLight.add( lightColor );
  9700. } else if ( light instanceof THREE.DirectionalLight ) {
  9701. // for sprites
  9702. _directionalLights.add( lightColor );
  9703. } else if ( light instanceof THREE.PointLight ) {
  9704. // for sprites
  9705. _pointLights.add( lightColor );
  9706. }
  9707. }
  9708. }
  9709. function calculateLight( position, normal, color ) {
  9710. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9711. var light = _lights[ l ];
  9712. _lightColor.copy( light.color );
  9713. if ( light instanceof THREE.DirectionalLight ) {
  9714. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld ).normalize();
  9715. var amount = normal.dot( lightPosition );
  9716. if ( amount <= 0 ) continue;
  9717. amount *= light.intensity;
  9718. color.add( _lightColor.multiplyScalar( amount ) );
  9719. } else if ( light instanceof THREE.PointLight ) {
  9720. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld );
  9721. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  9722. if ( amount <= 0 ) continue;
  9723. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  9724. if ( amount == 0 ) continue;
  9725. amount *= light.intensity;
  9726. color.add( _lightColor.multiplyScalar( amount ) );
  9727. }
  9728. }
  9729. }
  9730. function renderSprite( v1, element, material ) {
  9731. setOpacity( material.opacity );
  9732. setBlending( material.blending );
  9733. var scaleX = element.scale.x * _canvasWidthHalf;
  9734. var scaleY = element.scale.y * _canvasHeightHalf;
  9735. var dist = 0.5 * Math.sqrt( scaleX * scaleX + scaleY * scaleY ); // allow for rotated sprite
  9736. _elemBox.min.set( v1.x - dist, v1.y - dist );
  9737. _elemBox.max.set( v1.x + dist, v1.y + dist );
  9738. if ( material instanceof THREE.SpriteMaterial ||
  9739. material instanceof THREE.ParticleSystemMaterial ) { // Backwards compatibility
  9740. var texture = material.map;
  9741. if ( texture !== null ) {
  9742. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  9743. if ( texture.image !== undefined && texture.image.width > 0 ) {
  9744. textureToPattern( texture );
  9745. }
  9746. texture.addEventListener( 'update', onTextureUpdate );
  9747. }
  9748. var pattern = _patterns[ texture.id ];
  9749. if ( pattern !== undefined ) {
  9750. setFillStyle( pattern );
  9751. } else {
  9752. setFillStyle( 'rgba( 0, 0, 0, 1 )' );
  9753. }
  9754. //
  9755. var bitmap = texture.image;
  9756. var ox = bitmap.width * texture.offset.x;
  9757. var oy = bitmap.height * texture.offset.y;
  9758. var sx = bitmap.width * texture.repeat.x;
  9759. var sy = bitmap.height * texture.repeat.y;
  9760. var cx = scaleX / sx;
  9761. var cy = scaleY / sy;
  9762. _context.save();
  9763. _context.translate( v1.x, v1.y );
  9764. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9765. _context.translate( - scaleX / 2, - scaleY / 2 );
  9766. _context.scale( cx, cy );
  9767. _context.translate( - ox, - oy );
  9768. _context.fillRect( ox, oy, sx, sy );
  9769. _context.restore();
  9770. } else { // no texture
  9771. setFillStyle( material.color.getStyle() );
  9772. _context.save();
  9773. _context.translate( v1.x, v1.y );
  9774. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9775. _context.scale( scaleX, - scaleY );
  9776. _context.fillRect( - 0.5, - 0.5, 1, 1 );
  9777. _context.restore();
  9778. }
  9779. } else if ( material instanceof THREE.SpriteCanvasMaterial ) {
  9780. setStrokeStyle( material.color.getStyle() );
  9781. setFillStyle( material.color.getStyle() );
  9782. _context.save();
  9783. _context.translate( v1.x, v1.y );
  9784. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9785. _context.scale( scaleX, scaleY );
  9786. material.program( _context );
  9787. _context.restore();
  9788. }
  9789. /* DEBUG
  9790. setStrokeStyle( 'rgb(255,255,0)' );
  9791. _context.beginPath();
  9792. _context.moveTo( v1.x - 10, v1.y );
  9793. _context.lineTo( v1.x + 10, v1.y );
  9794. _context.moveTo( v1.x, v1.y - 10 );
  9795. _context.lineTo( v1.x, v1.y + 10 );
  9796. _context.stroke();
  9797. */
  9798. }
  9799. function renderLine( v1, v2, element, material ) {
  9800. setOpacity( material.opacity );
  9801. setBlending( material.blending );
  9802. _context.beginPath();
  9803. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  9804. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  9805. if ( material instanceof THREE.LineBasicMaterial ) {
  9806. setLineWidth( material.linewidth );
  9807. setLineCap( material.linecap );
  9808. setLineJoin( material.linejoin );
  9809. if ( material.vertexColors !== THREE.VertexColors ) {
  9810. setStrokeStyle( material.color.getStyle() );
  9811. } else {
  9812. var colorStyle1 = element.vertexColors[0].getStyle();
  9813. var colorStyle2 = element.vertexColors[1].getStyle();
  9814. if ( colorStyle1 === colorStyle2 ) {
  9815. setStrokeStyle( colorStyle1 );
  9816. } else {
  9817. try {
  9818. var grad = _context.createLinearGradient(
  9819. v1.positionScreen.x,
  9820. v1.positionScreen.y,
  9821. v2.positionScreen.x,
  9822. v2.positionScreen.y
  9823. );
  9824. grad.addColorStop( 0, colorStyle1 );
  9825. grad.addColorStop( 1, colorStyle2 );
  9826. } catch ( exception ) {
  9827. grad = colorStyle1;
  9828. }
  9829. setStrokeStyle( grad );
  9830. }
  9831. }
  9832. _context.stroke();
  9833. _elemBox.expandByScalar( material.linewidth * 2 );
  9834. } else if ( material instanceof THREE.LineDashedMaterial ) {
  9835. setLineWidth( material.linewidth );
  9836. setLineCap( material.linecap );
  9837. setLineJoin( material.linejoin );
  9838. setStrokeStyle( material.color.getStyle() );
  9839. setDashAndGap( material.dashSize, material.gapSize );
  9840. _context.stroke();
  9841. _elemBox.expandByScalar( material.linewidth * 2 );
  9842. setDashAndGap( null, null );
  9843. }
  9844. }
  9845. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  9846. _this.info.render.vertices += 3;
  9847. _this.info.render.faces ++;
  9848. setOpacity( material.opacity );
  9849. setBlending( material.blending );
  9850. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9851. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9852. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9853. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  9854. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  9855. _diffuseColor.copy( material.color );
  9856. _emissiveColor.copy( material.emissive );
  9857. if ( material.vertexColors === THREE.FaceColors ) {
  9858. _diffuseColor.multiply( element.color );
  9859. }
  9860. if ( material.wireframe === false && material.shading === THREE.SmoothShading && element.vertexNormalsLength === 3 ) {
  9861. _color1.copy( _ambientLight );
  9862. _color2.copy( _ambientLight );
  9863. _color3.copy( _ambientLight );
  9864. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  9865. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  9866. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  9867. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  9868. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  9869. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  9870. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9871. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9872. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9873. } else {
  9874. _color.copy( _ambientLight );
  9875. calculateLight( element.centroidModel, element.normalModel, _color );
  9876. _color.multiply( _diffuseColor ).add( _emissiveColor );
  9877. material.wireframe === true
  9878. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9879. : fillPath( _color );
  9880. }
  9881. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  9882. if ( material.map !== null ) {
  9883. if ( material.map.mapping instanceof THREE.UVMapping ) {
  9884. _uvs = element.uvs[ 0 ];
  9885. 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 );
  9886. }
  9887. } else if ( material.envMap !== null ) {
  9888. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  9889. _normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix );
  9890. _uv1x = 0.5 * _normal.x + 0.5;
  9891. _uv1y = 0.5 * _normal.y + 0.5;
  9892. _normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix );
  9893. _uv2x = 0.5 * _normal.x + 0.5;
  9894. _uv2y = 0.5 * _normal.y + 0.5;
  9895. _normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix );
  9896. _uv3x = 0.5 * _normal.x + 0.5;
  9897. _uv3y = 0.5 * _normal.y + 0.5;
  9898. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  9899. }/* else if ( material.envMap.mapping === THREE.SphericalRefractionMapping ) {
  9900. }*/
  9901. } else {
  9902. _color.copy( material.color );
  9903. if ( material.vertexColors === THREE.FaceColors ) {
  9904. _color.multiply( element.color );
  9905. }
  9906. material.wireframe === true
  9907. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9908. : fillPath( _color );
  9909. }
  9910. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  9911. _near = _camera.near;
  9912. _far = _camera.far;
  9913. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  9914. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  9915. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  9916. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9917. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9918. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9919. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  9920. if ( material.shading === THREE.FlatShading ) {
  9921. _normal.copy( element.normalModel ).applyMatrix3( _normalViewMatrix );
  9922. _color.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9923. material.wireframe === true
  9924. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9925. : fillPath( _color );
  9926. } else if ( material.shading === THREE.SmoothShading ) {
  9927. _normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix );
  9928. _color1.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9929. _normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix );
  9930. _color2.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9931. _normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix );
  9932. _color3.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9933. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9934. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9935. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9936. }
  9937. }
  9938. }
  9939. //
  9940. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  9941. _context.beginPath();
  9942. _context.moveTo( x0, y0 );
  9943. _context.lineTo( x1, y1 );
  9944. _context.lineTo( x2, y2 );
  9945. _context.closePath();
  9946. }
  9947. function strokePath( color, linewidth, linecap, linejoin ) {
  9948. setLineWidth( linewidth );
  9949. setLineCap( linecap );
  9950. setLineJoin( linejoin );
  9951. setStrokeStyle( color.getStyle() );
  9952. _context.stroke();
  9953. _elemBox.expandByScalar( linewidth * 2 );
  9954. }
  9955. function fillPath( color ) {
  9956. setFillStyle( color.getStyle() );
  9957. _context.fill();
  9958. }
  9959. function onTextureUpdate ( event ) {
  9960. textureToPattern( event.target );
  9961. }
  9962. function textureToPattern( texture ) {
  9963. var repeatX = texture.wrapS === THREE.RepeatWrapping;
  9964. var repeatY = texture.wrapT === THREE.RepeatWrapping;
  9965. var image = texture.image;
  9966. var canvas = document.createElement( 'canvas' );
  9967. canvas.width = image.width;
  9968. canvas.height = image.height;
  9969. var context = canvas.getContext( '2d' );
  9970. context.setTransform( 1, 0, 0, - 1, 0, image.height );
  9971. context.drawImage( image, 0, 0 );
  9972. _patterns[ texture.id ] = _context.createPattern(
  9973. canvas, repeatX === true && repeatY === true
  9974. ? 'repeat'
  9975. : repeatX === true && repeatY === false
  9976. ? 'repeat-x'
  9977. : repeatX === false && repeatY === true
  9978. ? 'repeat-y'
  9979. : 'no-repeat'
  9980. );
  9981. }
  9982. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  9983. if ( texture instanceof THREE.DataTexture ) return;
  9984. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  9985. if ( texture.image !== undefined && texture.image.width > 0 ) {
  9986. textureToPattern( texture );
  9987. }
  9988. texture.addEventListener( 'update', onTextureUpdate );
  9989. }
  9990. var pattern = _patterns[ texture.id ];
  9991. if ( pattern !== undefined ) {
  9992. setFillStyle( pattern );
  9993. } else {
  9994. setFillStyle( 'rgba(0,0,0,1)' );
  9995. _context.fill();
  9996. return;
  9997. }
  9998. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9999. var a, b, c, d, e, f, det, idet,
  10000. offsetX = texture.offset.x / texture.repeat.x,
  10001. offsetY = texture.offset.y / texture.repeat.y,
  10002. width = texture.image.width * texture.repeat.x,
  10003. height = texture.image.height * texture.repeat.y;
  10004. u0 = ( u0 + offsetX ) * width;
  10005. v0 = ( v0 + offsetY ) * height;
  10006. u1 = ( u1 + offsetX ) * width;
  10007. v1 = ( v1 + offsetY ) * height;
  10008. u2 = ( u2 + offsetX ) * width;
  10009. v2 = ( v2 + offsetY ) * height;
  10010. x1 -= x0; y1 -= y0;
  10011. x2 -= x0; y2 -= y0;
  10012. u1 -= u0; v1 -= v0;
  10013. u2 -= u0; v2 -= v0;
  10014. det = u1 * v2 - u2 * v1;
  10015. if ( det === 0 ) return;
  10016. idet = 1 / det;
  10017. a = ( v2 * x1 - v1 * x2 ) * idet;
  10018. b = ( v2 * y1 - v1 * y2 ) * idet;
  10019. c = ( u1 * x2 - u2 * x1 ) * idet;
  10020. d = ( u1 * y2 - u2 * y1 ) * idet;
  10021. e = x0 - a * u0 - c * v0;
  10022. f = y0 - b * u0 - d * v0;
  10023. _context.save();
  10024. _context.transform( a, b, c, d, e, f );
  10025. _context.fill();
  10026. _context.restore();
  10027. }
  10028. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  10029. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  10030. var a, b, c, d, e, f, det, idet,
  10031. width = image.width - 1,
  10032. height = image.height - 1;
  10033. u0 *= width; v0 *= height;
  10034. u1 *= width; v1 *= height;
  10035. u2 *= width; v2 *= height;
  10036. x1 -= x0; y1 -= y0;
  10037. x2 -= x0; y2 -= y0;
  10038. u1 -= u0; v1 -= v0;
  10039. u2 -= u0; v2 -= v0;
  10040. det = u1 * v2 - u2 * v1;
  10041. idet = 1 / det;
  10042. a = ( v2 * x1 - v1 * x2 ) * idet;
  10043. b = ( v2 * y1 - v1 * y2 ) * idet;
  10044. c = ( u1 * x2 - u2 * x1 ) * idet;
  10045. d = ( u1 * y2 - u2 * y1 ) * idet;
  10046. e = x0 - a * u0 - c * v0;
  10047. f = y0 - b * u0 - d * v0;
  10048. _context.save();
  10049. _context.transform( a, b, c, d, e, f );
  10050. _context.clip();
  10051. _context.drawImage( image, 0, 0 );
  10052. _context.restore();
  10053. }
  10054. function getGradientTexture( color1, color2, color3, color4 ) {
  10055. // http://mrdoob.com/blog/post/710
  10056. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  10057. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  10058. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  10059. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  10060. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  10061. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  10062. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  10063. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  10064. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  10065. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  10066. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  10067. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  10068. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  10069. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  10070. return _gradientMap;
  10071. }
  10072. // Hide anti-alias gaps
  10073. function expand( v1, v2, pixels ) {
  10074. var x = v2.x - v1.x, y = v2.y - v1.y,
  10075. det = x * x + y * y, idet;
  10076. if ( det === 0 ) return;
  10077. idet = pixels / Math.sqrt( det );
  10078. x *= idet; y *= idet;
  10079. v2.x += x; v2.y += y;
  10080. v1.x -= x; v1.y -= y;
  10081. }
  10082. // Context cached methods.
  10083. function setOpacity( value ) {
  10084. if ( _contextGlobalAlpha !== value ) {
  10085. _context.globalAlpha = value;
  10086. _contextGlobalAlpha = value;
  10087. }
  10088. }
  10089. function setBlending( value ) {
  10090. if ( _contextGlobalCompositeOperation !== value ) {
  10091. if ( value === THREE.NormalBlending ) {
  10092. _context.globalCompositeOperation = 'source-over';
  10093. } else if ( value === THREE.AdditiveBlending ) {
  10094. _context.globalCompositeOperation = 'lighter';
  10095. } else if ( value === THREE.SubtractiveBlending ) {
  10096. _context.globalCompositeOperation = 'darker';
  10097. }
  10098. _contextGlobalCompositeOperation = value;
  10099. }
  10100. }
  10101. function setLineWidth( value ) {
  10102. if ( _contextLineWidth !== value ) {
  10103. _context.lineWidth = value;
  10104. _contextLineWidth = value;
  10105. }
  10106. }
  10107. function setLineCap( value ) {
  10108. // "butt", "round", "square"
  10109. if ( _contextLineCap !== value ) {
  10110. _context.lineCap = value;
  10111. _contextLineCap = value;
  10112. }
  10113. }
  10114. function setLineJoin( value ) {
  10115. // "round", "bevel", "miter"
  10116. if ( _contextLineJoin !== value ) {
  10117. _context.lineJoin = value;
  10118. _contextLineJoin = value;
  10119. }
  10120. }
  10121. function setStrokeStyle( value ) {
  10122. if ( _contextStrokeStyle !== value ) {
  10123. _context.strokeStyle = value;
  10124. _contextStrokeStyle = value;
  10125. }
  10126. }
  10127. function setFillStyle( value ) {
  10128. if ( _contextFillStyle !== value ) {
  10129. _context.fillStyle = value;
  10130. _contextFillStyle = value;
  10131. }
  10132. }
  10133. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  10134. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  10135. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  10136. _contextDashSize = dashSizeValue;
  10137. _contextGapSize = gapSizeValue;
  10138. }
  10139. }
  10140. };
  10141. /**
  10142. * Shader chunks for WebLG Shader library
  10143. *
  10144. * @author alteredq / http://alteredqualia.com/
  10145. * @author mrdoob / http://mrdoob.com/
  10146. * @author mikael emtinger / http://gomo.se/
  10147. */
  10148. THREE.ShaderChunk = {
  10149. // FOG
  10150. fog_pars_fragment: [
  10151. "#ifdef USE_FOG",
  10152. "uniform vec3 fogColor;",
  10153. "#ifdef FOG_EXP2",
  10154. "uniform float fogDensity;",
  10155. "#else",
  10156. "uniform float fogNear;",
  10157. "uniform float fogFar;",
  10158. "#endif",
  10159. "#endif"
  10160. ].join("\n"),
  10161. fog_fragment: [
  10162. "#ifdef USE_FOG",
  10163. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10164. "#ifdef FOG_EXP2",
  10165. "const float LOG2 = 1.442695;",
  10166. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  10167. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  10168. "#else",
  10169. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  10170. "#endif",
  10171. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  10172. "#endif"
  10173. ].join("\n"),
  10174. // ENVIRONMENT MAP
  10175. envmap_pars_fragment: [
  10176. "#ifdef USE_ENVMAP",
  10177. "uniform float reflectivity;",
  10178. "uniform samplerCube envMap;",
  10179. "uniform float flipEnvMap;",
  10180. "uniform int combine;",
  10181. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  10182. "uniform bool useRefract;",
  10183. "uniform float refractionRatio;",
  10184. "#else",
  10185. "varying vec3 vReflect;",
  10186. "#endif",
  10187. "#endif"
  10188. ].join("\n"),
  10189. envmap_fragment: [
  10190. "#ifdef USE_ENVMAP",
  10191. "vec3 reflectVec;",
  10192. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  10193. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  10194. "if ( useRefract ) {",
  10195. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  10196. "} else { ",
  10197. "reflectVec = reflect( cameraToVertex, normal );",
  10198. "}",
  10199. "#else",
  10200. "reflectVec = vReflect;",
  10201. "#endif",
  10202. "#ifdef DOUBLE_SIDED",
  10203. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10204. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  10205. "#else",
  10206. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  10207. "#endif",
  10208. "#ifdef GAMMA_INPUT",
  10209. "cubeColor.xyz *= cubeColor.xyz;",
  10210. "#endif",
  10211. "if ( combine == 1 ) {",
  10212. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  10213. "} else if ( combine == 2 ) {",
  10214. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  10215. "} else {",
  10216. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  10217. "}",
  10218. "#endif"
  10219. ].join("\n"),
  10220. envmap_pars_vertex: [
  10221. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  10222. "varying vec3 vReflect;",
  10223. "uniform float refractionRatio;",
  10224. "uniform bool useRefract;",
  10225. "#endif"
  10226. ].join("\n"),
  10227. worldpos_vertex : [
  10228. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  10229. "#ifdef USE_SKINNING",
  10230. "vec4 worldPosition = modelMatrix * skinned;",
  10231. "#endif",
  10232. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  10233. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  10234. "#endif",
  10235. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  10236. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  10237. "#endif",
  10238. "#endif"
  10239. ].join("\n"),
  10240. envmap_vertex : [
  10241. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  10242. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  10243. "worldNormal = normalize( worldNormal );",
  10244. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  10245. "if ( useRefract ) {",
  10246. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  10247. "} else {",
  10248. "vReflect = reflect( cameraToVertex, worldNormal );",
  10249. "}",
  10250. "#endif"
  10251. ].join("\n"),
  10252. // COLOR MAP (particles)
  10253. map_particle_pars_fragment: [
  10254. "#ifdef USE_MAP",
  10255. "uniform sampler2D map;",
  10256. "#endif"
  10257. ].join("\n"),
  10258. map_particle_fragment: [
  10259. "#ifdef USE_MAP",
  10260. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  10261. "#endif"
  10262. ].join("\n"),
  10263. // COLOR MAP (triangles)
  10264. map_pars_vertex: [
  10265. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10266. "varying vec2 vUv;",
  10267. "uniform vec4 offsetRepeat;",
  10268. "#endif"
  10269. ].join("\n"),
  10270. map_pars_fragment: [
  10271. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10272. "varying vec2 vUv;",
  10273. "#endif",
  10274. "#ifdef USE_MAP",
  10275. "uniform sampler2D map;",
  10276. "#endif"
  10277. ].join("\n"),
  10278. map_vertex: [
  10279. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10280. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  10281. "#endif"
  10282. ].join("\n"),
  10283. map_fragment: [
  10284. "#ifdef USE_MAP",
  10285. "vec4 texelColor = texture2D( map, vUv );",
  10286. "#ifdef GAMMA_INPUT",
  10287. "texelColor.xyz *= texelColor.xyz;",
  10288. "#endif",
  10289. "gl_FragColor = gl_FragColor * texelColor;",
  10290. "#endif"
  10291. ].join("\n"),
  10292. // LIGHT MAP
  10293. lightmap_pars_fragment: [
  10294. "#ifdef USE_LIGHTMAP",
  10295. "varying vec2 vUv2;",
  10296. "uniform sampler2D lightMap;",
  10297. "#endif"
  10298. ].join("\n"),
  10299. lightmap_pars_vertex: [
  10300. "#ifdef USE_LIGHTMAP",
  10301. "varying vec2 vUv2;",
  10302. "#endif"
  10303. ].join("\n"),
  10304. lightmap_fragment: [
  10305. "#ifdef USE_LIGHTMAP",
  10306. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  10307. "#endif"
  10308. ].join("\n"),
  10309. lightmap_vertex: [
  10310. "#ifdef USE_LIGHTMAP",
  10311. "vUv2 = uv2;",
  10312. "#endif"
  10313. ].join("\n"),
  10314. // BUMP MAP
  10315. bumpmap_pars_fragment: [
  10316. "#ifdef USE_BUMPMAP",
  10317. "uniform sampler2D bumpMap;",
  10318. "uniform float bumpScale;",
  10319. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  10320. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  10321. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  10322. "vec2 dHdxy_fwd() {",
  10323. "vec2 dSTdx = dFdx( vUv );",
  10324. "vec2 dSTdy = dFdy( vUv );",
  10325. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  10326. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  10327. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  10328. "return vec2( dBx, dBy );",
  10329. "}",
  10330. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  10331. "vec3 vSigmaX = dFdx( surf_pos );",
  10332. "vec3 vSigmaY = dFdy( surf_pos );",
  10333. "vec3 vN = surf_norm;", // normalized
  10334. "vec3 R1 = cross( vSigmaY, vN );",
  10335. "vec3 R2 = cross( vN, vSigmaX );",
  10336. "float fDet = dot( vSigmaX, R1 );",
  10337. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  10338. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  10339. "}",
  10340. "#endif"
  10341. ].join("\n"),
  10342. // NORMAL MAP
  10343. normalmap_pars_fragment: [
  10344. "#ifdef USE_NORMALMAP",
  10345. "uniform sampler2D normalMap;",
  10346. "uniform vec2 normalScale;",
  10347. // Per-Pixel Tangent Space Normal Mapping
  10348. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  10349. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  10350. "vec3 q0 = dFdx( eye_pos.xyz );",
  10351. "vec3 q1 = dFdy( eye_pos.xyz );",
  10352. "vec2 st0 = dFdx( vUv.st );",
  10353. "vec2 st1 = dFdy( vUv.st );",
  10354. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  10355. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  10356. "vec3 N = normalize( surf_norm );",
  10357. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  10358. "mapN.xy = normalScale * mapN.xy;",
  10359. "mat3 tsn = mat3( S, T, N );",
  10360. "return normalize( tsn * mapN );",
  10361. "}",
  10362. "#endif"
  10363. ].join("\n"),
  10364. // SPECULAR MAP
  10365. specularmap_pars_fragment: [
  10366. "#ifdef USE_SPECULARMAP",
  10367. "uniform sampler2D specularMap;",
  10368. "#endif"
  10369. ].join("\n"),
  10370. specularmap_fragment: [
  10371. "float specularStrength;",
  10372. "#ifdef USE_SPECULARMAP",
  10373. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  10374. "specularStrength = texelSpecular.r;",
  10375. "#else",
  10376. "specularStrength = 1.0;",
  10377. "#endif"
  10378. ].join("\n"),
  10379. // LIGHTS LAMBERT
  10380. lights_lambert_pars_vertex: [
  10381. "uniform vec3 ambient;",
  10382. "uniform vec3 diffuse;",
  10383. "uniform vec3 emissive;",
  10384. "uniform vec3 ambientLightColor;",
  10385. "#if MAX_DIR_LIGHTS > 0",
  10386. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10387. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10388. "#endif",
  10389. "#if MAX_HEMI_LIGHTS > 0",
  10390. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10391. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10392. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10393. "#endif",
  10394. "#if MAX_POINT_LIGHTS > 0",
  10395. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10396. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10397. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10398. "#endif",
  10399. "#if MAX_SPOT_LIGHTS > 0",
  10400. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10401. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10402. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10403. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10404. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10405. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10406. "#endif",
  10407. "#ifdef WRAP_AROUND",
  10408. "uniform vec3 wrapRGB;",
  10409. "#endif"
  10410. ].join("\n"),
  10411. lights_lambert_vertex: [
  10412. "vLightFront = vec3( 0.0 );",
  10413. "#ifdef DOUBLE_SIDED",
  10414. "vLightBack = vec3( 0.0 );",
  10415. "#endif",
  10416. "transformedNormal = normalize( transformedNormal );",
  10417. "#if MAX_DIR_LIGHTS > 0",
  10418. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10419. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10420. "vec3 dirVector = normalize( lDirection.xyz );",
  10421. "float dotProduct = dot( transformedNormal, dirVector );",
  10422. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10423. "#ifdef DOUBLE_SIDED",
  10424. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10425. "#ifdef WRAP_AROUND",
  10426. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10427. "#endif",
  10428. "#endif",
  10429. "#ifdef WRAP_AROUND",
  10430. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10431. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  10432. "#ifdef DOUBLE_SIDED",
  10433. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  10434. "#endif",
  10435. "#endif",
  10436. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  10437. "#ifdef DOUBLE_SIDED",
  10438. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  10439. "#endif",
  10440. "}",
  10441. "#endif",
  10442. "#if MAX_POINT_LIGHTS > 0",
  10443. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10444. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10445. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10446. "float lDistance = 1.0;",
  10447. "if ( pointLightDistance[ i ] > 0.0 )",
  10448. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10449. "lVector = normalize( lVector );",
  10450. "float dotProduct = dot( transformedNormal, lVector );",
  10451. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10452. "#ifdef DOUBLE_SIDED",
  10453. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10454. "#ifdef WRAP_AROUND",
  10455. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10456. "#endif",
  10457. "#endif",
  10458. "#ifdef WRAP_AROUND",
  10459. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10460. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  10461. "#ifdef DOUBLE_SIDED",
  10462. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  10463. "#endif",
  10464. "#endif",
  10465. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  10466. "#ifdef DOUBLE_SIDED",
  10467. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  10468. "#endif",
  10469. "}",
  10470. "#endif",
  10471. "#if MAX_SPOT_LIGHTS > 0",
  10472. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10473. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10474. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10475. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  10476. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10477. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10478. "float lDistance = 1.0;",
  10479. "if ( spotLightDistance[ i ] > 0.0 )",
  10480. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10481. "lVector = normalize( lVector );",
  10482. "float dotProduct = dot( transformedNormal, lVector );",
  10483. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10484. "#ifdef DOUBLE_SIDED",
  10485. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10486. "#ifdef WRAP_AROUND",
  10487. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10488. "#endif",
  10489. "#endif",
  10490. "#ifdef WRAP_AROUND",
  10491. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10492. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  10493. "#ifdef DOUBLE_SIDED",
  10494. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  10495. "#endif",
  10496. "#endif",
  10497. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  10498. "#ifdef DOUBLE_SIDED",
  10499. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  10500. "#endif",
  10501. "}",
  10502. "}",
  10503. "#endif",
  10504. "#if MAX_HEMI_LIGHTS > 0",
  10505. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10506. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10507. "vec3 lVector = normalize( lDirection.xyz );",
  10508. "float dotProduct = dot( transformedNormal, lVector );",
  10509. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10510. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  10511. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10512. "#ifdef DOUBLE_SIDED",
  10513. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  10514. "#endif",
  10515. "}",
  10516. "#endif",
  10517. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  10518. "#ifdef DOUBLE_SIDED",
  10519. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  10520. "#endif"
  10521. ].join("\n"),
  10522. // LIGHTS PHONG
  10523. lights_phong_pars_vertex: [
  10524. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10525. "varying vec3 vWorldPosition;",
  10526. "#endif"
  10527. ].join("\n"),
  10528. lights_phong_vertex: [
  10529. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10530. "vWorldPosition = worldPosition.xyz;",
  10531. "#endif"
  10532. ].join("\n"),
  10533. lights_phong_pars_fragment: [
  10534. "uniform vec3 ambientLightColor;",
  10535. "#if MAX_DIR_LIGHTS > 0",
  10536. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10537. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10538. "#endif",
  10539. "#if MAX_HEMI_LIGHTS > 0",
  10540. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10541. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10542. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10543. "#endif",
  10544. "#if MAX_POINT_LIGHTS > 0",
  10545. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10546. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10547. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10548. "#endif",
  10549. "#if MAX_SPOT_LIGHTS > 0",
  10550. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10551. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10552. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10553. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10554. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10555. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10556. "#endif",
  10557. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10558. "varying vec3 vWorldPosition;",
  10559. "#endif",
  10560. "#ifdef WRAP_AROUND",
  10561. "uniform vec3 wrapRGB;",
  10562. "#endif",
  10563. "varying vec3 vViewPosition;",
  10564. "varying vec3 vNormal;"
  10565. ].join("\n"),
  10566. lights_phong_fragment: [
  10567. "vec3 normal = normalize( vNormal );",
  10568. "vec3 viewPosition = normalize( vViewPosition );",
  10569. "#ifdef DOUBLE_SIDED",
  10570. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10571. "#endif",
  10572. "#ifdef USE_NORMALMAP",
  10573. "normal = perturbNormal2Arb( -vViewPosition, normal );",
  10574. "#elif defined( USE_BUMPMAP )",
  10575. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  10576. "#endif",
  10577. "#if MAX_POINT_LIGHTS > 0",
  10578. "vec3 pointDiffuse = vec3( 0.0 );",
  10579. "vec3 pointSpecular = vec3( 0.0 );",
  10580. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10581. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10582. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10583. "float lDistance = 1.0;",
  10584. "if ( pointLightDistance[ i ] > 0.0 )",
  10585. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10586. "lVector = normalize( lVector );",
  10587. // diffuse
  10588. "float dotProduct = dot( normal, lVector );",
  10589. "#ifdef WRAP_AROUND",
  10590. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  10591. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10592. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10593. "#else",
  10594. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  10595. "#endif",
  10596. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  10597. // specular
  10598. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  10599. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10600. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  10601. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10602. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10603. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  10604. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  10605. "}",
  10606. "#endif",
  10607. "#if MAX_SPOT_LIGHTS > 0",
  10608. "vec3 spotDiffuse = vec3( 0.0 );",
  10609. "vec3 spotSpecular = vec3( 0.0 );",
  10610. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10611. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10612. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10613. "float lDistance = 1.0;",
  10614. "if ( spotLightDistance[ i ] > 0.0 )",
  10615. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10616. "lVector = normalize( lVector );",
  10617. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10618. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10619. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10620. // diffuse
  10621. "float dotProduct = dot( normal, lVector );",
  10622. "#ifdef WRAP_AROUND",
  10623. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  10624. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10625. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10626. "#else",
  10627. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  10628. "#endif",
  10629. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  10630. // specular
  10631. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  10632. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10633. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  10634. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10635. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10636. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  10637. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  10638. "}",
  10639. "}",
  10640. "#endif",
  10641. "#if MAX_DIR_LIGHTS > 0",
  10642. "vec3 dirDiffuse = vec3( 0.0 );",
  10643. "vec3 dirSpecular = vec3( 0.0 );" ,
  10644. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10645. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10646. "vec3 dirVector = normalize( lDirection.xyz );",
  10647. // diffuse
  10648. "float dotProduct = dot( normal, dirVector );",
  10649. "#ifdef WRAP_AROUND",
  10650. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  10651. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10652. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  10653. "#else",
  10654. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  10655. "#endif",
  10656. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  10657. // specular
  10658. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10659. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10660. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  10661. /*
  10662. // fresnel term from skin shader
  10663. "const float F0 = 0.128;",
  10664. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  10665. "float exponential = pow( base, 5.0 );",
  10666. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  10667. */
  10668. /*
  10669. // fresnel term from fresnel shader
  10670. "const float mFresnelBias = 0.08;",
  10671. "const float mFresnelScale = 0.3;",
  10672. "const float mFresnelPower = 5.0;",
  10673. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  10674. */
  10675. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10676. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10677. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  10678. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  10679. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10680. "}",
  10681. "#endif",
  10682. "#if MAX_HEMI_LIGHTS > 0",
  10683. "vec3 hemiDiffuse = vec3( 0.0 );",
  10684. "vec3 hemiSpecular = vec3( 0.0 );" ,
  10685. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10686. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10687. "vec3 lVector = normalize( lDirection.xyz );",
  10688. // diffuse
  10689. "float dotProduct = dot( normal, lVector );",
  10690. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10691. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10692. "hemiDiffuse += diffuse * hemiColor;",
  10693. // specular (sky light)
  10694. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10695. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10696. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  10697. // specular (ground light)
  10698. "vec3 lVectorGround = -lVector;",
  10699. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10700. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10701. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  10702. "float dotProductGround = dot( normal, lVectorGround );",
  10703. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10704. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10705. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  10706. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  10707. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10708. "}",
  10709. "#endif",
  10710. "vec3 totalDiffuse = vec3( 0.0 );",
  10711. "vec3 totalSpecular = vec3( 0.0 );",
  10712. "#if MAX_DIR_LIGHTS > 0",
  10713. "totalDiffuse += dirDiffuse;",
  10714. "totalSpecular += dirSpecular;",
  10715. "#endif",
  10716. "#if MAX_HEMI_LIGHTS > 0",
  10717. "totalDiffuse += hemiDiffuse;",
  10718. "totalSpecular += hemiSpecular;",
  10719. "#endif",
  10720. "#if MAX_POINT_LIGHTS > 0",
  10721. "totalDiffuse += pointDiffuse;",
  10722. "totalSpecular += pointSpecular;",
  10723. "#endif",
  10724. "#if MAX_SPOT_LIGHTS > 0",
  10725. "totalDiffuse += spotDiffuse;",
  10726. "totalSpecular += spotSpecular;",
  10727. "#endif",
  10728. "#ifdef METAL",
  10729. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  10730. "#else",
  10731. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  10732. "#endif"
  10733. ].join("\n"),
  10734. // VERTEX COLORS
  10735. color_pars_fragment: [
  10736. "#ifdef USE_COLOR",
  10737. "varying vec3 vColor;",
  10738. "#endif"
  10739. ].join("\n"),
  10740. color_fragment: [
  10741. "#ifdef USE_COLOR",
  10742. "gl_FragColor = gl_FragColor * vec4( vColor, 1.0 );",
  10743. "#endif"
  10744. ].join("\n"),
  10745. color_pars_vertex: [
  10746. "#ifdef USE_COLOR",
  10747. "varying vec3 vColor;",
  10748. "#endif"
  10749. ].join("\n"),
  10750. color_vertex: [
  10751. "#ifdef USE_COLOR",
  10752. "#ifdef GAMMA_INPUT",
  10753. "vColor = color * color;",
  10754. "#else",
  10755. "vColor = color;",
  10756. "#endif",
  10757. "#endif"
  10758. ].join("\n"),
  10759. // SKINNING
  10760. skinning_pars_vertex: [
  10761. "#ifdef USE_SKINNING",
  10762. "#ifdef BONE_TEXTURE",
  10763. "uniform sampler2D boneTexture;",
  10764. "uniform int boneTextureWidth;",
  10765. "uniform int boneTextureHeight;",
  10766. "mat4 getBoneMatrix( const in float i ) {",
  10767. "float j = i * 4.0;",
  10768. "float x = mod( j, float( boneTextureWidth ) );",
  10769. "float y = floor( j / float( boneTextureWidth ) );",
  10770. "float dx = 1.0 / float( boneTextureWidth );",
  10771. "float dy = 1.0 / float( boneTextureHeight );",
  10772. "y = dy * ( y + 0.5 );",
  10773. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  10774. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  10775. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  10776. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  10777. "mat4 bone = mat4( v1, v2, v3, v4 );",
  10778. "return bone;",
  10779. "}",
  10780. "#else",
  10781. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  10782. "mat4 getBoneMatrix( const in float i ) {",
  10783. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  10784. "return bone;",
  10785. "}",
  10786. "#endif",
  10787. "#endif"
  10788. ].join("\n"),
  10789. skinbase_vertex: [
  10790. "#ifdef USE_SKINNING",
  10791. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  10792. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  10793. "mat4 boneMatZ = getBoneMatrix( skinIndex.z );",
  10794. "mat4 boneMatW = getBoneMatrix( skinIndex.w );",
  10795. "#endif"
  10796. ].join("\n"),
  10797. skinning_vertex: [
  10798. "#ifdef USE_SKINNING",
  10799. "#ifdef USE_MORPHTARGETS",
  10800. "vec4 skinVertex = vec4( morphed, 1.0 );",
  10801. "#else",
  10802. "vec4 skinVertex = vec4( position, 1.0 );",
  10803. "#endif",
  10804. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10805. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10806. "skinned += boneMatZ * skinVertex * skinWeight.z;",
  10807. "skinned += boneMatW * skinVertex * skinWeight.w;",
  10808. "#endif"
  10809. ].join("\n"),
  10810. // MORPHING
  10811. morphtarget_pars_vertex: [
  10812. "#ifdef USE_MORPHTARGETS",
  10813. "#ifndef USE_MORPHNORMALS",
  10814. "uniform float morphTargetInfluences[ 8 ];",
  10815. "#else",
  10816. "uniform float morphTargetInfluences[ 4 ];",
  10817. "#endif",
  10818. "#endif"
  10819. ].join("\n"),
  10820. morphtarget_vertex: [
  10821. "#ifdef USE_MORPHTARGETS",
  10822. "vec3 morphed = vec3( 0.0 );",
  10823. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  10824. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  10825. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  10826. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  10827. "#ifndef USE_MORPHNORMALS",
  10828. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  10829. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  10830. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  10831. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  10832. "#endif",
  10833. "morphed += position;",
  10834. "#endif"
  10835. ].join("\n"),
  10836. default_vertex : [
  10837. "vec4 mvPosition;",
  10838. "#ifdef USE_SKINNING",
  10839. "mvPosition = modelViewMatrix * skinned;",
  10840. "#endif",
  10841. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  10842. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  10843. "#endif",
  10844. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  10845. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10846. "#endif",
  10847. "gl_Position = projectionMatrix * mvPosition;"
  10848. ].join("\n"),
  10849. morphnormal_vertex: [
  10850. "#ifdef USE_MORPHNORMALS",
  10851. "vec3 morphedNormal = vec3( 0.0 );",
  10852. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  10853. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  10854. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  10855. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  10856. "morphedNormal += normal;",
  10857. "#endif"
  10858. ].join("\n"),
  10859. skinnormal_vertex: [
  10860. "#ifdef USE_SKINNING",
  10861. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  10862. "skinMatrix += skinWeight.y * boneMatY;",
  10863. "#ifdef USE_MORPHNORMALS",
  10864. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  10865. "#else",
  10866. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  10867. "#endif",
  10868. "#endif"
  10869. ].join("\n"),
  10870. defaultnormal_vertex: [
  10871. "vec3 objectNormal;",
  10872. "#ifdef USE_SKINNING",
  10873. "objectNormal = skinnedNormal.xyz;",
  10874. "#endif",
  10875. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  10876. "objectNormal = morphedNormal;",
  10877. "#endif",
  10878. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  10879. "objectNormal = normal;",
  10880. "#endif",
  10881. "#ifdef FLIP_SIDED",
  10882. "objectNormal = -objectNormal;",
  10883. "#endif",
  10884. "vec3 transformedNormal = normalMatrix * objectNormal;"
  10885. ].join("\n"),
  10886. // SHADOW MAP
  10887. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  10888. // http://spidergl.org/example.php?id=6
  10889. // http://fabiensanglard.net/shadowmapping
  10890. shadowmap_pars_fragment: [
  10891. "#ifdef USE_SHADOWMAP",
  10892. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  10893. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  10894. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  10895. "uniform float shadowBias[ MAX_SHADOWS ];",
  10896. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10897. "float unpackDepth( const in vec4 rgba_depth ) {",
  10898. "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 );",
  10899. "float depth = dot( rgba_depth, bit_shift );",
  10900. "return depth;",
  10901. "}",
  10902. "#endif"
  10903. ].join("\n"),
  10904. shadowmap_fragment: [
  10905. "#ifdef USE_SHADOWMAP",
  10906. "#ifdef SHADOWMAP_DEBUG",
  10907. "vec3 frustumColors[3];",
  10908. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  10909. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  10910. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  10911. "#endif",
  10912. "#ifdef SHADOWMAP_CASCADE",
  10913. "int inFrustumCount = 0;",
  10914. "#endif",
  10915. "float fDepth;",
  10916. "vec3 shadowColor = vec3( 1.0 );",
  10917. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10918. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  10919. // "if ( something && something )" breaks ATI OpenGL shader compiler
  10920. // "if ( all( something, something ) )" using this instead
  10921. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  10922. "bool inFrustum = all( inFrustumVec );",
  10923. // don't shadow pixels outside of light frustum
  10924. // use just first frustum (for cascades)
  10925. // don't shadow pixels behind far plane of light frustum
  10926. "#ifdef SHADOWMAP_CASCADE",
  10927. "inFrustumCount += int( inFrustum );",
  10928. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  10929. "#else",
  10930. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  10931. "#endif",
  10932. "bool frustumTest = all( frustumTestVec );",
  10933. "if ( frustumTest ) {",
  10934. "shadowCoord.z += shadowBias[ i ];",
  10935. "#if defined( SHADOWMAP_TYPE_PCF )",
  10936. // Percentage-close filtering
  10937. // (9 pixel kernel)
  10938. // http://fabiensanglard.net/shadowmappingPCF/
  10939. "float shadow = 0.0;",
  10940. /*
  10941. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  10942. // must enroll loop manually
  10943. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  10944. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  10945. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  10946. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  10947. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  10948. "float fDepth = unpackDepth( rgbaDepth );",
  10949. "if ( fDepth < shadowCoord.z )",
  10950. "shadow += 1.0;",
  10951. "}",
  10952. "shadow /= 9.0;",
  10953. */
  10954. "const float shadowDelta = 1.0 / 9.0;",
  10955. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10956. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10957. "float dx0 = -1.25 * xPixelOffset;",
  10958. "float dy0 = -1.25 * yPixelOffset;",
  10959. "float dx1 = 1.25 * xPixelOffset;",
  10960. "float dy1 = 1.25 * yPixelOffset;",
  10961. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10962. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10963. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10964. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10965. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10966. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10967. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10968. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10969. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10970. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10971. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10972. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10973. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10974. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10975. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10976. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10977. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10978. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10979. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10980. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  10981. // Percentage-close filtering
  10982. // (9 pixel kernel)
  10983. // http://fabiensanglard.net/shadowmappingPCF/
  10984. "float shadow = 0.0;",
  10985. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10986. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10987. "float dx0 = -1.0 * xPixelOffset;",
  10988. "float dy0 = -1.0 * yPixelOffset;",
  10989. "float dx1 = 1.0 * xPixelOffset;",
  10990. "float dy1 = 1.0 * yPixelOffset;",
  10991. "mat3 shadowKernel;",
  10992. "mat3 depthKernel;",
  10993. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10994. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10995. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10996. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10997. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10998. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10999. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  11000. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  11001. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  11002. "vec3 shadowZ = vec3( shadowCoord.z );",
  11003. "shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  11004. "shadowKernel[0] *= vec3(0.25);",
  11005. "shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  11006. "shadowKernel[1] *= vec3(0.25);",
  11007. "shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  11008. "shadowKernel[2] *= vec3(0.25);",
  11009. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  11010. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  11011. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  11012. "vec4 shadowValues;",
  11013. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  11014. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  11015. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  11016. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  11017. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  11018. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  11019. "#else",
  11020. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  11021. "float fDepth = unpackDepth( rgbaDepth );",
  11022. "if ( fDepth < shadowCoord.z )",
  11023. // spot with multiple shadows is darker
  11024. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  11025. // spot with multiple shadows has the same color as single shadow spot
  11026. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  11027. "#endif",
  11028. "}",
  11029. "#ifdef SHADOWMAP_DEBUG",
  11030. "#ifdef SHADOWMAP_CASCADE",
  11031. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  11032. "#else",
  11033. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  11034. "#endif",
  11035. "#endif",
  11036. "}",
  11037. "#ifdef GAMMA_OUTPUT",
  11038. "shadowColor *= shadowColor;",
  11039. "#endif",
  11040. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  11041. "#endif"
  11042. ].join("\n"),
  11043. shadowmap_pars_vertex: [
  11044. "#ifdef USE_SHADOWMAP",
  11045. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  11046. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  11047. "#endif"
  11048. ].join("\n"),
  11049. shadowmap_vertex: [
  11050. "#ifdef USE_SHADOWMAP",
  11051. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11052. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11053. "}",
  11054. "#endif"
  11055. ].join("\n"),
  11056. // ALPHATEST
  11057. alphatest_fragment: [
  11058. "#ifdef ALPHATEST",
  11059. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  11060. "#endif"
  11061. ].join("\n"),
  11062. // LINEAR SPACE
  11063. linear_to_gamma_fragment: [
  11064. "#ifdef GAMMA_OUTPUT",
  11065. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  11066. "#endif"
  11067. ].join("\n")
  11068. };
  11069. /**
  11070. * Uniform Utilities
  11071. */
  11072. THREE.UniformsUtils = {
  11073. merge: function ( uniforms ) {
  11074. var u, p, tmp, merged = {};
  11075. for ( u = 0; u < uniforms.length; u ++ ) {
  11076. tmp = this.clone( uniforms[ u ] );
  11077. for ( p in tmp ) {
  11078. merged[ p ] = tmp[ p ];
  11079. }
  11080. }
  11081. return merged;
  11082. },
  11083. clone: function ( uniforms_src ) {
  11084. var u, p, parameter, parameter_src, uniforms_dst = {};
  11085. for ( u in uniforms_src ) {
  11086. uniforms_dst[ u ] = {};
  11087. for ( p in uniforms_src[ u ] ) {
  11088. parameter_src = uniforms_src[ u ][ p ];
  11089. if ( parameter_src instanceof THREE.Color ||
  11090. parameter_src instanceof THREE.Vector2 ||
  11091. parameter_src instanceof THREE.Vector3 ||
  11092. parameter_src instanceof THREE.Vector4 ||
  11093. parameter_src instanceof THREE.Matrix4 ||
  11094. parameter_src instanceof THREE.Texture ) {
  11095. uniforms_dst[ u ][ p ] = parameter_src.clone();
  11096. } else if ( parameter_src instanceof Array ) {
  11097. uniforms_dst[ u ][ p ] = parameter_src.slice();
  11098. } else {
  11099. uniforms_dst[ u ][ p ] = parameter_src;
  11100. }
  11101. }
  11102. }
  11103. return uniforms_dst;
  11104. }
  11105. };
  11106. /**
  11107. * Uniforms library for shared webgl shaders
  11108. */
  11109. THREE.UniformsLib = {
  11110. common: {
  11111. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  11112. "opacity" : { type: "f", value: 1.0 },
  11113. "map" : { type: "t", value: null },
  11114. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  11115. "lightMap" : { type: "t", value: null },
  11116. "specularMap" : { type: "t", value: null },
  11117. "envMap" : { type: "t", value: null },
  11118. "flipEnvMap" : { type: "f", value: -1 },
  11119. "useRefract" : { type: "i", value: 0 },
  11120. "reflectivity" : { type: "f", value: 1.0 },
  11121. "refractionRatio" : { type: "f", value: 0.98 },
  11122. "combine" : { type: "i", value: 0 },
  11123. "morphTargetInfluences" : { type: "f", value: 0 }
  11124. },
  11125. bump: {
  11126. "bumpMap" : { type: "t", value: null },
  11127. "bumpScale" : { type: "f", value: 1 }
  11128. },
  11129. normalmap: {
  11130. "normalMap" : { type: "t", value: null },
  11131. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  11132. },
  11133. fog : {
  11134. "fogDensity" : { type: "f", value: 0.00025 },
  11135. "fogNear" : { type: "f", value: 1 },
  11136. "fogFar" : { type: "f", value: 2000 },
  11137. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  11138. },
  11139. lights: {
  11140. "ambientLightColor" : { type: "fv", value: [] },
  11141. "directionalLightDirection" : { type: "fv", value: [] },
  11142. "directionalLightColor" : { type: "fv", value: [] },
  11143. "hemisphereLightDirection" : { type: "fv", value: [] },
  11144. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  11145. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  11146. "pointLightColor" : { type: "fv", value: [] },
  11147. "pointLightPosition" : { type: "fv", value: [] },
  11148. "pointLightDistance" : { type: "fv1", value: [] },
  11149. "spotLightColor" : { type: "fv", value: [] },
  11150. "spotLightPosition" : { type: "fv", value: [] },
  11151. "spotLightDirection" : { type: "fv", value: [] },
  11152. "spotLightDistance" : { type: "fv1", value: [] },
  11153. "spotLightAngleCos" : { type: "fv1", value: [] },
  11154. "spotLightExponent" : { type: "fv1", value: [] }
  11155. },
  11156. particle: {
  11157. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  11158. "opacity" : { type: "f", value: 1.0 },
  11159. "size" : { type: "f", value: 1.0 },
  11160. "scale" : { type: "f", value: 1.0 },
  11161. "map" : { type: "t", value: null },
  11162. "fogDensity" : { type: "f", value: 0.00025 },
  11163. "fogNear" : { type: "f", value: 1 },
  11164. "fogFar" : { type: "f", value: 2000 },
  11165. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  11166. },
  11167. shadowmap: {
  11168. "shadowMap": { type: "tv", value: [] },
  11169. "shadowMapSize": { type: "v2v", value: [] },
  11170. "shadowBias" : { type: "fv1", value: [] },
  11171. "shadowDarkness": { type: "fv1", value: [] },
  11172. "shadowMatrix" : { type: "m4v", value: [] }
  11173. }
  11174. };
  11175. /**
  11176. * Webgl Shader Library for three.js
  11177. *
  11178. * @author alteredq / http://alteredqualia.com/
  11179. * @author mrdoob / http://mrdoob.com/
  11180. * @author mikael emtinger / http://gomo.se/
  11181. */
  11182. THREE.ShaderLib = {
  11183. 'basic': {
  11184. uniforms: THREE.UniformsUtils.merge( [
  11185. THREE.UniformsLib[ "common" ],
  11186. THREE.UniformsLib[ "fog" ],
  11187. THREE.UniformsLib[ "shadowmap" ]
  11188. ] ),
  11189. vertexShader: [
  11190. THREE.ShaderChunk[ "map_pars_vertex" ],
  11191. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11192. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11193. THREE.ShaderChunk[ "color_pars_vertex" ],
  11194. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11195. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11196. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11197. "void main() {",
  11198. THREE.ShaderChunk[ "map_vertex" ],
  11199. THREE.ShaderChunk[ "lightmap_vertex" ],
  11200. THREE.ShaderChunk[ "color_vertex" ],
  11201. THREE.ShaderChunk[ "skinbase_vertex" ],
  11202. "#ifdef USE_ENVMAP",
  11203. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11204. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11205. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11206. "#endif",
  11207. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11208. THREE.ShaderChunk[ "skinning_vertex" ],
  11209. THREE.ShaderChunk[ "default_vertex" ],
  11210. THREE.ShaderChunk[ "worldpos_vertex" ],
  11211. THREE.ShaderChunk[ "envmap_vertex" ],
  11212. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11213. "}"
  11214. ].join("\n"),
  11215. fragmentShader: [
  11216. "uniform vec3 diffuse;",
  11217. "uniform float opacity;",
  11218. THREE.ShaderChunk[ "color_pars_fragment" ],
  11219. THREE.ShaderChunk[ "map_pars_fragment" ],
  11220. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11221. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11222. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11223. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11224. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11225. "void main() {",
  11226. "gl_FragColor = vec4( diffuse, opacity );",
  11227. THREE.ShaderChunk[ "map_fragment" ],
  11228. THREE.ShaderChunk[ "alphatest_fragment" ],
  11229. THREE.ShaderChunk[ "specularmap_fragment" ],
  11230. THREE.ShaderChunk[ "lightmap_fragment" ],
  11231. THREE.ShaderChunk[ "color_fragment" ],
  11232. THREE.ShaderChunk[ "envmap_fragment" ],
  11233. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11234. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11235. THREE.ShaderChunk[ "fog_fragment" ],
  11236. "}"
  11237. ].join("\n")
  11238. },
  11239. 'lambert': {
  11240. uniforms: THREE.UniformsUtils.merge( [
  11241. THREE.UniformsLib[ "common" ],
  11242. THREE.UniformsLib[ "fog" ],
  11243. THREE.UniformsLib[ "lights" ],
  11244. THREE.UniformsLib[ "shadowmap" ],
  11245. {
  11246. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  11247. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  11248. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11249. }
  11250. ] ),
  11251. vertexShader: [
  11252. "#define LAMBERT",
  11253. "varying vec3 vLightFront;",
  11254. "#ifdef DOUBLE_SIDED",
  11255. "varying vec3 vLightBack;",
  11256. "#endif",
  11257. THREE.ShaderChunk[ "map_pars_vertex" ],
  11258. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11259. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11260. THREE.ShaderChunk[ "lights_lambert_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[ "morphnormal_vertex" ],
  11270. THREE.ShaderChunk[ "skinbase_vertex" ],
  11271. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11272. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11273. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11274. THREE.ShaderChunk[ "skinning_vertex" ],
  11275. THREE.ShaderChunk[ "default_vertex" ],
  11276. THREE.ShaderChunk[ "worldpos_vertex" ],
  11277. THREE.ShaderChunk[ "envmap_vertex" ],
  11278. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  11279. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11280. "}"
  11281. ].join("\n"),
  11282. fragmentShader: [
  11283. "uniform float opacity;",
  11284. "varying vec3 vLightFront;",
  11285. "#ifdef DOUBLE_SIDED",
  11286. "varying vec3 vLightBack;",
  11287. "#endif",
  11288. THREE.ShaderChunk[ "color_pars_fragment" ],
  11289. THREE.ShaderChunk[ "map_pars_fragment" ],
  11290. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11291. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11292. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11293. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11294. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11295. "void main() {",
  11296. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  11297. THREE.ShaderChunk[ "map_fragment" ],
  11298. THREE.ShaderChunk[ "alphatest_fragment" ],
  11299. THREE.ShaderChunk[ "specularmap_fragment" ],
  11300. "#ifdef DOUBLE_SIDED",
  11301. //"float isFront = float( gl_FrontFacing );",
  11302. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  11303. "if ( gl_FrontFacing )",
  11304. "gl_FragColor.xyz *= vLightFront;",
  11305. "else",
  11306. "gl_FragColor.xyz *= vLightBack;",
  11307. "#else",
  11308. "gl_FragColor.xyz *= vLightFront;",
  11309. "#endif",
  11310. THREE.ShaderChunk[ "lightmap_fragment" ],
  11311. THREE.ShaderChunk[ "color_fragment" ],
  11312. THREE.ShaderChunk[ "envmap_fragment" ],
  11313. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11314. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11315. THREE.ShaderChunk[ "fog_fragment" ],
  11316. "}"
  11317. ].join("\n")
  11318. },
  11319. 'phong': {
  11320. uniforms: THREE.UniformsUtils.merge( [
  11321. THREE.UniformsLib[ "common" ],
  11322. THREE.UniformsLib[ "bump" ],
  11323. THREE.UniformsLib[ "normalmap" ],
  11324. THREE.UniformsLib[ "fog" ],
  11325. THREE.UniformsLib[ "lights" ],
  11326. THREE.UniformsLib[ "shadowmap" ],
  11327. {
  11328. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  11329. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  11330. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  11331. "shininess": { type: "f", value: 30 },
  11332. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11333. }
  11334. ] ),
  11335. vertexShader: [
  11336. "#define PHONG",
  11337. "varying vec3 vViewPosition;",
  11338. "varying vec3 vNormal;",
  11339. THREE.ShaderChunk[ "map_pars_vertex" ],
  11340. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11341. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11342. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  11343. THREE.ShaderChunk[ "color_pars_vertex" ],
  11344. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11345. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11346. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11347. "void main() {",
  11348. THREE.ShaderChunk[ "map_vertex" ],
  11349. THREE.ShaderChunk[ "lightmap_vertex" ],
  11350. THREE.ShaderChunk[ "color_vertex" ],
  11351. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11352. THREE.ShaderChunk[ "skinbase_vertex" ],
  11353. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11354. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11355. "vNormal = normalize( transformedNormal );",
  11356. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11357. THREE.ShaderChunk[ "skinning_vertex" ],
  11358. THREE.ShaderChunk[ "default_vertex" ],
  11359. "vViewPosition = -mvPosition.xyz;",
  11360. THREE.ShaderChunk[ "worldpos_vertex" ],
  11361. THREE.ShaderChunk[ "envmap_vertex" ],
  11362. THREE.ShaderChunk[ "lights_phong_vertex" ],
  11363. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11364. "}"
  11365. ].join("\n"),
  11366. fragmentShader: [
  11367. "uniform vec3 diffuse;",
  11368. "uniform float opacity;",
  11369. "uniform vec3 ambient;",
  11370. "uniform vec3 emissive;",
  11371. "uniform vec3 specular;",
  11372. "uniform float shininess;",
  11373. THREE.ShaderChunk[ "color_pars_fragment" ],
  11374. THREE.ShaderChunk[ "map_pars_fragment" ],
  11375. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11376. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11377. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11378. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  11379. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11380. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  11381. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  11382. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11383. "void main() {",
  11384. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  11385. THREE.ShaderChunk[ "map_fragment" ],
  11386. THREE.ShaderChunk[ "alphatest_fragment" ],
  11387. THREE.ShaderChunk[ "specularmap_fragment" ],
  11388. THREE.ShaderChunk[ "lights_phong_fragment" ],
  11389. THREE.ShaderChunk[ "lightmap_fragment" ],
  11390. THREE.ShaderChunk[ "color_fragment" ],
  11391. THREE.ShaderChunk[ "envmap_fragment" ],
  11392. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11393. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11394. THREE.ShaderChunk[ "fog_fragment" ],
  11395. "}"
  11396. ].join("\n")
  11397. },
  11398. 'particle_basic': {
  11399. uniforms: THREE.UniformsUtils.merge( [
  11400. THREE.UniformsLib[ "particle" ],
  11401. THREE.UniformsLib[ "shadowmap" ]
  11402. ] ),
  11403. vertexShader: [
  11404. "uniform float size;",
  11405. "uniform float scale;",
  11406. THREE.ShaderChunk[ "color_pars_vertex" ],
  11407. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11408. "void main() {",
  11409. THREE.ShaderChunk[ "color_vertex" ],
  11410. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11411. "#ifdef USE_SIZEATTENUATION",
  11412. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  11413. "#else",
  11414. "gl_PointSize = size;",
  11415. "#endif",
  11416. "gl_Position = projectionMatrix * mvPosition;",
  11417. THREE.ShaderChunk[ "worldpos_vertex" ],
  11418. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11419. "}"
  11420. ].join("\n"),
  11421. fragmentShader: [
  11422. "uniform vec3 psColor;",
  11423. "uniform float opacity;",
  11424. THREE.ShaderChunk[ "color_pars_fragment" ],
  11425. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  11426. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11427. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11428. "void main() {",
  11429. "gl_FragColor = vec4( psColor, opacity );",
  11430. THREE.ShaderChunk[ "map_particle_fragment" ],
  11431. THREE.ShaderChunk[ "alphatest_fragment" ],
  11432. THREE.ShaderChunk[ "color_fragment" ],
  11433. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11434. THREE.ShaderChunk[ "fog_fragment" ],
  11435. "}"
  11436. ].join("\n")
  11437. },
  11438. 'dashed': {
  11439. uniforms: THREE.UniformsUtils.merge( [
  11440. THREE.UniformsLib[ "common" ],
  11441. THREE.UniformsLib[ "fog" ],
  11442. {
  11443. "scale": { type: "f", value: 1 },
  11444. "dashSize": { type: "f", value: 1 },
  11445. "totalSize": { type: "f", value: 2 }
  11446. }
  11447. ] ),
  11448. vertexShader: [
  11449. "uniform float scale;",
  11450. "attribute float lineDistance;",
  11451. "varying float vLineDistance;",
  11452. THREE.ShaderChunk[ "color_pars_vertex" ],
  11453. "void main() {",
  11454. THREE.ShaderChunk[ "color_vertex" ],
  11455. "vLineDistance = scale * lineDistance;",
  11456. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11457. "gl_Position = projectionMatrix * mvPosition;",
  11458. "}"
  11459. ].join("\n"),
  11460. fragmentShader: [
  11461. "uniform vec3 diffuse;",
  11462. "uniform float opacity;",
  11463. "uniform float dashSize;",
  11464. "uniform float totalSize;",
  11465. "varying float vLineDistance;",
  11466. THREE.ShaderChunk[ "color_pars_fragment" ],
  11467. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11468. "void main() {",
  11469. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  11470. "discard;",
  11471. "}",
  11472. "gl_FragColor = vec4( diffuse, opacity );",
  11473. THREE.ShaderChunk[ "color_fragment" ],
  11474. THREE.ShaderChunk[ "fog_fragment" ],
  11475. "}"
  11476. ].join("\n")
  11477. },
  11478. 'depth': {
  11479. uniforms: {
  11480. "mNear": { type: "f", value: 1.0 },
  11481. "mFar" : { type: "f", value: 2000.0 },
  11482. "opacity" : { type: "f", value: 1.0 }
  11483. },
  11484. vertexShader: [
  11485. "void main() {",
  11486. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11487. "}"
  11488. ].join("\n"),
  11489. fragmentShader: [
  11490. "uniform float mNear;",
  11491. "uniform float mFar;",
  11492. "uniform float opacity;",
  11493. "void main() {",
  11494. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  11495. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  11496. "gl_FragColor = vec4( vec3( color ), opacity );",
  11497. "}"
  11498. ].join("\n")
  11499. },
  11500. 'normal': {
  11501. uniforms: {
  11502. "opacity" : { type: "f", value: 1.0 }
  11503. },
  11504. vertexShader: [
  11505. "varying vec3 vNormal;",
  11506. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11507. "void main() {",
  11508. "vNormal = normalize( normalMatrix * normal );",
  11509. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11510. THREE.ShaderChunk[ "default_vertex" ],
  11511. "}"
  11512. ].join("\n"),
  11513. fragmentShader: [
  11514. "uniform float opacity;",
  11515. "varying vec3 vNormal;",
  11516. "void main() {",
  11517. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  11518. "}"
  11519. ].join("\n")
  11520. },
  11521. /* -------------------------------------------------------------------------
  11522. // Normal map shader
  11523. // - Blinn-Phong
  11524. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  11525. // - point and directional lights (use with "lights: true" material option)
  11526. ------------------------------------------------------------------------- */
  11527. 'normalmap' : {
  11528. uniforms: THREE.UniformsUtils.merge( [
  11529. THREE.UniformsLib[ "fog" ],
  11530. THREE.UniformsLib[ "lights" ],
  11531. THREE.UniformsLib[ "shadowmap" ],
  11532. {
  11533. "enableAO" : { type: "i", value: 0 },
  11534. "enableDiffuse" : { type: "i", value: 0 },
  11535. "enableSpecular" : { type: "i", value: 0 },
  11536. "enableReflection": { type: "i", value: 0 },
  11537. "enableDisplacement": { type: "i", value: 0 },
  11538. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  11539. "tDiffuse" : { type: "t", value: null },
  11540. "tCube" : { type: "t", value: null },
  11541. "tNormal" : { type: "t", value: null },
  11542. "tSpecular" : { type: "t", value: null },
  11543. "tAO" : { type: "t", value: null },
  11544. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11545. "uDisplacementBias": { type: "f", value: 0.0 },
  11546. "uDisplacementScale": { type: "f", value: 1.0 },
  11547. "diffuse": { type: "c", value: new THREE.Color( 0xffffff ) },
  11548. "specular": { type: "c", value: new THREE.Color( 0x111111 ) },
  11549. "ambient": { type: "c", value: new THREE.Color( 0xffffff ) },
  11550. "shininess": { type: "f", value: 30 },
  11551. "opacity": { type: "f", value: 1 },
  11552. "useRefract": { type: "i", value: 0 },
  11553. "refractionRatio": { type: "f", value: 0.98 },
  11554. "reflectivity": { type: "f", value: 0.5 },
  11555. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  11556. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11557. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11558. }
  11559. ] ),
  11560. fragmentShader: [
  11561. "uniform vec3 ambient;",
  11562. "uniform vec3 diffuse;",
  11563. "uniform vec3 specular;",
  11564. "uniform float shininess;",
  11565. "uniform float opacity;",
  11566. "uniform bool enableDiffuse;",
  11567. "uniform bool enableSpecular;",
  11568. "uniform bool enableAO;",
  11569. "uniform bool enableReflection;",
  11570. "uniform sampler2D tDiffuse;",
  11571. "uniform sampler2D tNormal;",
  11572. "uniform sampler2D tSpecular;",
  11573. "uniform sampler2D tAO;",
  11574. "uniform samplerCube tCube;",
  11575. "uniform vec2 uNormalScale;",
  11576. "uniform bool useRefract;",
  11577. "uniform float refractionRatio;",
  11578. "uniform float reflectivity;",
  11579. "varying vec3 vTangent;",
  11580. "varying vec3 vBinormal;",
  11581. "varying vec3 vNormal;",
  11582. "varying vec2 vUv;",
  11583. "uniform vec3 ambientLightColor;",
  11584. "#if MAX_DIR_LIGHTS > 0",
  11585. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11586. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11587. "#endif",
  11588. "#if MAX_HEMI_LIGHTS > 0",
  11589. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  11590. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  11591. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  11592. "#endif",
  11593. "#if MAX_POINT_LIGHTS > 0",
  11594. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11595. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11596. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11597. "#endif",
  11598. "#if MAX_SPOT_LIGHTS > 0",
  11599. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  11600. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  11601. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  11602. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  11603. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  11604. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  11605. "#endif",
  11606. "#ifdef WRAP_AROUND",
  11607. "uniform vec3 wrapRGB;",
  11608. "#endif",
  11609. "varying vec3 vWorldPosition;",
  11610. "varying vec3 vViewPosition;",
  11611. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11612. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11613. "void main() {",
  11614. "gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  11615. "vec3 specularTex = vec3( 1.0 );",
  11616. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  11617. "normalTex.xy *= uNormalScale;",
  11618. "normalTex = normalize( normalTex );",
  11619. "if( enableDiffuse ) {",
  11620. "#ifdef GAMMA_INPUT",
  11621. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  11622. "texelColor.xyz *= texelColor.xyz;",
  11623. "gl_FragColor = gl_FragColor * texelColor;",
  11624. "#else",
  11625. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  11626. "#endif",
  11627. "}",
  11628. "if( enableAO ) {",
  11629. "#ifdef GAMMA_INPUT",
  11630. "vec4 aoColor = texture2D( tAO, vUv );",
  11631. "aoColor.xyz *= aoColor.xyz;",
  11632. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  11633. "#else",
  11634. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  11635. "#endif",
  11636. "}",
  11637. "if( enableSpecular )",
  11638. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  11639. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  11640. "vec3 finalNormal = tsb * normalTex;",
  11641. "#ifdef FLIP_SIDED",
  11642. "finalNormal = -finalNormal;",
  11643. "#endif",
  11644. "vec3 normal = normalize( finalNormal );",
  11645. "vec3 viewPosition = normalize( vViewPosition );",
  11646. // point lights
  11647. "#if MAX_POINT_LIGHTS > 0",
  11648. "vec3 pointDiffuse = vec3( 0.0 );",
  11649. "vec3 pointSpecular = vec3( 0.0 );",
  11650. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11651. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11652. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  11653. "float pointDistance = 1.0;",
  11654. "if ( pointLightDistance[ i ] > 0.0 )",
  11655. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  11656. "pointVector = normalize( pointVector );",
  11657. // diffuse
  11658. "#ifdef WRAP_AROUND",
  11659. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  11660. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  11661. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11662. "#else",
  11663. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  11664. "#endif",
  11665. "pointDiffuse += pointDistance * pointLightColor[ i ] * diffuse * pointDiffuseWeight;",
  11666. // specular
  11667. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  11668. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11669. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  11670. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11671. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11672. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  11673. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  11674. "}",
  11675. "#endif",
  11676. // spot lights
  11677. "#if MAX_SPOT_LIGHTS > 0",
  11678. "vec3 spotDiffuse = vec3( 0.0 );",
  11679. "vec3 spotSpecular = vec3( 0.0 );",
  11680. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  11681. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  11682. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  11683. "float spotDistance = 1.0;",
  11684. "if ( spotLightDistance[ i ] > 0.0 )",
  11685. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  11686. "spotVector = normalize( spotVector );",
  11687. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  11688. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  11689. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  11690. // diffuse
  11691. "#ifdef WRAP_AROUND",
  11692. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  11693. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  11694. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  11695. "#else",
  11696. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  11697. "#endif",
  11698. "spotDiffuse += spotDistance * spotLightColor[ i ] * diffuse * spotDiffuseWeight * spotEffect;",
  11699. // specular
  11700. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  11701. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  11702. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  11703. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11704. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11705. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  11706. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  11707. "}",
  11708. "}",
  11709. "#endif",
  11710. // directional lights
  11711. "#if MAX_DIR_LIGHTS > 0",
  11712. "vec3 dirDiffuse = vec3( 0.0 );",
  11713. "vec3 dirSpecular = vec3( 0.0 );",
  11714. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  11715. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11716. "vec3 dirVector = normalize( lDirection.xyz );",
  11717. // diffuse
  11718. "#ifdef WRAP_AROUND",
  11719. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  11720. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  11721. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  11722. "#else",
  11723. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  11724. "#endif",
  11725. "dirDiffuse += directionalLightColor[ i ] * diffuse * dirDiffuseWeight;",
  11726. // specular
  11727. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11728. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11729. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  11730. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11731. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11732. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  11733. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11734. "}",
  11735. "#endif",
  11736. // hemisphere lights
  11737. "#if MAX_HEMI_LIGHTS > 0",
  11738. "vec3 hemiDiffuse = vec3( 0.0 );",
  11739. "vec3 hemiSpecular = vec3( 0.0 );" ,
  11740. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  11741. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  11742. "vec3 lVector = normalize( lDirection.xyz );",
  11743. // diffuse
  11744. "float dotProduct = dot( normal, lVector );",
  11745. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  11746. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  11747. "hemiDiffuse += diffuse * hemiColor;",
  11748. // specular (sky light)
  11749. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  11750. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  11751. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  11752. // specular (ground light)
  11753. "vec3 lVectorGround = -lVector;",
  11754. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  11755. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  11756. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  11757. "float dotProductGround = dot( normal, lVectorGround );",
  11758. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11759. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11760. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  11761. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  11762. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  11763. "}",
  11764. "#endif",
  11765. // all lights contribution summation
  11766. "vec3 totalDiffuse = vec3( 0.0 );",
  11767. "vec3 totalSpecular = vec3( 0.0 );",
  11768. "#if MAX_DIR_LIGHTS > 0",
  11769. "totalDiffuse += dirDiffuse;",
  11770. "totalSpecular += dirSpecular;",
  11771. "#endif",
  11772. "#if MAX_HEMI_LIGHTS > 0",
  11773. "totalDiffuse += hemiDiffuse;",
  11774. "totalSpecular += hemiSpecular;",
  11775. "#endif",
  11776. "#if MAX_POINT_LIGHTS > 0",
  11777. "totalDiffuse += pointDiffuse;",
  11778. "totalSpecular += pointSpecular;",
  11779. "#endif",
  11780. "#if MAX_SPOT_LIGHTS > 0",
  11781. "totalDiffuse += spotDiffuse;",
  11782. "totalSpecular += spotSpecular;",
  11783. "#endif",
  11784. "#ifdef METAL",
  11785. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  11786. "#else",
  11787. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  11788. "#endif",
  11789. "if ( enableReflection ) {",
  11790. "vec3 vReflect;",
  11791. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  11792. "if ( useRefract ) {",
  11793. "vReflect = refract( cameraToVertex, normal, refractionRatio );",
  11794. "} else {",
  11795. "vReflect = reflect( cameraToVertex, normal );",
  11796. "}",
  11797. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  11798. "#ifdef GAMMA_INPUT",
  11799. "cubeColor.xyz *= cubeColor.xyz;",
  11800. "#endif",
  11801. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * reflectivity );",
  11802. "}",
  11803. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11804. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11805. THREE.ShaderChunk[ "fog_fragment" ],
  11806. "}"
  11807. ].join("\n"),
  11808. vertexShader: [
  11809. "attribute vec4 tangent;",
  11810. "uniform vec2 uOffset;",
  11811. "uniform vec2 uRepeat;",
  11812. "uniform bool enableDisplacement;",
  11813. "#ifdef VERTEX_TEXTURES",
  11814. "uniform sampler2D tDisplacement;",
  11815. "uniform float uDisplacementScale;",
  11816. "uniform float uDisplacementBias;",
  11817. "#endif",
  11818. "varying vec3 vTangent;",
  11819. "varying vec3 vBinormal;",
  11820. "varying vec3 vNormal;",
  11821. "varying vec2 vUv;",
  11822. "varying vec3 vWorldPosition;",
  11823. "varying vec3 vViewPosition;",
  11824. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11825. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11826. "void main() {",
  11827. THREE.ShaderChunk[ "skinbase_vertex" ],
  11828. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11829. // normal, tangent and binormal vectors
  11830. "#ifdef USE_SKINNING",
  11831. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  11832. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  11833. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  11834. "#else",
  11835. "vNormal = normalize( normalMatrix * normal );",
  11836. "vTangent = normalize( normalMatrix * tangent.xyz );",
  11837. "#endif",
  11838. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  11839. "vUv = uv * uRepeat + uOffset;",
  11840. // displacement mapping
  11841. "vec3 displacedPosition;",
  11842. "#ifdef VERTEX_TEXTURES",
  11843. "if ( enableDisplacement ) {",
  11844. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  11845. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  11846. "displacedPosition = position + normalize( normal ) * df;",
  11847. "} else {",
  11848. "#ifdef USE_SKINNING",
  11849. "vec4 skinVertex = vec4( position, 1.0 );",
  11850. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11851. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11852. "displacedPosition = skinned.xyz;",
  11853. "#else",
  11854. "displacedPosition = position;",
  11855. "#endif",
  11856. "}",
  11857. "#else",
  11858. "#ifdef USE_SKINNING",
  11859. "vec4 skinVertex = vec4( position, 1.0 );",
  11860. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11861. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11862. "displacedPosition = skinned.xyz;",
  11863. "#else",
  11864. "displacedPosition = position;",
  11865. "#endif",
  11866. "#endif",
  11867. //
  11868. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  11869. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  11870. "gl_Position = projectionMatrix * mvPosition;",
  11871. //
  11872. "vWorldPosition = worldPosition.xyz;",
  11873. "vViewPosition = -mvPosition.xyz;",
  11874. // shadows
  11875. "#ifdef USE_SHADOWMAP",
  11876. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11877. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11878. "}",
  11879. "#endif",
  11880. "}"
  11881. ].join("\n")
  11882. },
  11883. /* -------------------------------------------------------------------------
  11884. // Cube map shader
  11885. ------------------------------------------------------------------------- */
  11886. 'cube': {
  11887. uniforms: { "tCube": { type: "t", value: null },
  11888. "tFlip": { type: "f", value: -1 } },
  11889. vertexShader: [
  11890. "varying vec3 vWorldPosition;",
  11891. "void main() {",
  11892. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  11893. "vWorldPosition = worldPosition.xyz;",
  11894. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11895. "}"
  11896. ].join("\n"),
  11897. fragmentShader: [
  11898. "uniform samplerCube tCube;",
  11899. "uniform float tFlip;",
  11900. "varying vec3 vWorldPosition;",
  11901. "void main() {",
  11902. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  11903. "}"
  11904. ].join("\n")
  11905. },
  11906. // Depth encoding into RGBA texture
  11907. // based on SpiderGL shadow map example
  11908. // http://spidergl.org/example.php?id=6
  11909. // originally from
  11910. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  11911. // see also here:
  11912. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  11913. 'depthRGBA': {
  11914. uniforms: {},
  11915. vertexShader: [
  11916. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11917. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11918. "void main() {",
  11919. THREE.ShaderChunk[ "skinbase_vertex" ],
  11920. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11921. THREE.ShaderChunk[ "skinning_vertex" ],
  11922. THREE.ShaderChunk[ "default_vertex" ],
  11923. "}"
  11924. ].join("\n"),
  11925. fragmentShader: [
  11926. "vec4 pack_depth( const in float depth ) {",
  11927. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  11928. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  11929. "vec4 res = fract( depth * bit_shift );",
  11930. "res -= res.xxyz * bit_mask;",
  11931. "return res;",
  11932. "}",
  11933. "void main() {",
  11934. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  11935. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  11936. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  11937. //"gl_FragData[ 0 ] = pack_depth( z );",
  11938. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  11939. "}"
  11940. ].join("\n")
  11941. }
  11942. };
  11943. /**
  11944. * @author supereggbert / http://www.paulbrunt.co.uk/
  11945. * @author mrdoob / http://mrdoob.com/
  11946. * @author alteredq / http://alteredqualia.com/
  11947. * @author szimek / https://github.com/szimek/
  11948. */
  11949. THREE.WebGLRenderer = function ( parameters ) {
  11950. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  11951. parameters = parameters || {};
  11952. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  11953. _context = parameters.context !== undefined ? parameters.context : null,
  11954. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  11955. _buffers = {},
  11956. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  11957. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11958. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11959. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11960. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  11961. _clearColor = new THREE.Color( 0x000000 ),
  11962. _clearAlpha = 0;
  11963. // public properties
  11964. this.domElement = _canvas;
  11965. this.context = null;
  11966. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  11967. ? parameters.devicePixelRatio
  11968. : self.devicePixelRatio !== undefined
  11969. ? self.devicePixelRatio
  11970. : 1;
  11971. // clearing
  11972. this.autoClear = true;
  11973. this.autoClearColor = true;
  11974. this.autoClearDepth = true;
  11975. this.autoClearStencil = true;
  11976. // scene graph
  11977. this.sortObjects = true;
  11978. this.autoUpdateObjects = true;
  11979. // physically based shading
  11980. this.gammaInput = false;
  11981. this.gammaOutput = false;
  11982. // shadow map
  11983. this.shadowMapEnabled = false;
  11984. this.shadowMapAutoUpdate = true;
  11985. this.shadowMapType = THREE.PCFShadowMap;
  11986. this.shadowMapCullFace = THREE.CullFaceFront;
  11987. this.shadowMapDebug = false;
  11988. this.shadowMapCascade = false;
  11989. // morphs
  11990. this.maxMorphTargets = 8;
  11991. this.maxMorphNormals = 4;
  11992. // flags
  11993. this.autoScaleCubemaps = true;
  11994. // custom render plugins
  11995. this.renderPluginsPre = [];
  11996. this.renderPluginsPost = [];
  11997. // info
  11998. this.info = {
  11999. memory: {
  12000. programs: 0,
  12001. geometries: 0,
  12002. textures: 0
  12003. },
  12004. render: {
  12005. calls: 0,
  12006. vertices: 0,
  12007. faces: 0,
  12008. points: 0
  12009. }
  12010. };
  12011. // internal properties
  12012. var _this = this,
  12013. _programs = [],
  12014. _programs_counter = 0,
  12015. // internal state cache
  12016. _currentProgram = null,
  12017. _currentFramebuffer = null,
  12018. _currentMaterialId = -1,
  12019. _currentGeometryGroupHash = null,
  12020. _currentCamera = null,
  12021. _geometryGroupCounter = 0,
  12022. _usedTextureUnits = 0,
  12023. // GL state cache
  12024. _oldDoubleSided = -1,
  12025. _oldFlipSided = -1,
  12026. _oldBlending = -1,
  12027. _oldBlendEquation = -1,
  12028. _oldBlendSrc = -1,
  12029. _oldBlendDst = -1,
  12030. _oldDepthTest = -1,
  12031. _oldDepthWrite = -1,
  12032. _oldPolygonOffset = null,
  12033. _oldPolygonOffsetFactor = null,
  12034. _oldPolygonOffsetUnits = null,
  12035. _oldLineWidth = null,
  12036. _viewportX = 0,
  12037. _viewportY = 0,
  12038. _viewportWidth = _canvas.width,
  12039. _viewportHeight = _canvas.height,
  12040. _currentWidth = 0,
  12041. _currentHeight = 0,
  12042. _enabledAttributes = new Uint8Array( 16 ),
  12043. // frustum
  12044. _frustum = new THREE.Frustum(),
  12045. // camera matrices cache
  12046. _projScreenMatrix = new THREE.Matrix4(),
  12047. _projScreenMatrixPS = new THREE.Matrix4(),
  12048. _vector3 = new THREE.Vector3(),
  12049. // light arrays cache
  12050. _direction = new THREE.Vector3(),
  12051. _lightsNeedUpdate = true,
  12052. _lights = {
  12053. ambient: [ 0, 0, 0 ],
  12054. directional: { length: 0, colors: new Array(), positions: new Array() },
  12055. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  12056. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  12057. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  12058. };
  12059. // initialize
  12060. var _gl;
  12061. var _glExtensionTextureFloat;
  12062. var _glExtensionTextureFloatLinear;
  12063. var _glExtensionStandardDerivatives;
  12064. var _glExtensionTextureFilterAnisotropic;
  12065. var _glExtensionCompressedTextureS3TC;
  12066. initGL();
  12067. setDefaultGLState();
  12068. this.context = _gl;
  12069. // GPU capabilities
  12070. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  12071. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  12072. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  12073. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  12074. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  12075. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  12076. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  12077. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  12078. //
  12079. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  12080. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  12081. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  12082. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  12083. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  12084. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  12085. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  12086. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  12087. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  12088. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  12089. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  12090. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  12091. // clamp precision to maximum available
  12092. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  12093. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  12094. if ( _precision === "highp" && ! highpAvailable ) {
  12095. if ( mediumpAvailable ) {
  12096. _precision = "mediump";
  12097. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  12098. } else {
  12099. _precision = "lowp";
  12100. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  12101. }
  12102. }
  12103. if ( _precision === "mediump" && ! mediumpAvailable ) {
  12104. _precision = "lowp";
  12105. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  12106. }
  12107. // API
  12108. this.getContext = function () {
  12109. return _gl;
  12110. };
  12111. this.supportsVertexTextures = function () {
  12112. return _supportsVertexTextures;
  12113. };
  12114. this.supportsFloatTextures = function () {
  12115. return _glExtensionTextureFloat;
  12116. };
  12117. this.supportsStandardDerivatives = function () {
  12118. return _glExtensionStandardDerivatives;
  12119. };
  12120. this.supportsCompressedTextureS3TC = function () {
  12121. return _glExtensionCompressedTextureS3TC;
  12122. };
  12123. this.getMaxAnisotropy = function () {
  12124. return _maxAnisotropy;
  12125. };
  12126. this.getPrecision = function () {
  12127. return _precision;
  12128. };
  12129. this.setSize = function ( width, height, updateStyle ) {
  12130. _canvas.width = width * this.devicePixelRatio;
  12131. _canvas.height = height * this.devicePixelRatio;
  12132. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  12133. _canvas.style.width = width + 'px';
  12134. _canvas.style.height = height + 'px';
  12135. }
  12136. this.setViewport( 0, 0, width, height );
  12137. };
  12138. this.setViewport = function ( x, y, width, height ) {
  12139. _viewportX = x * this.devicePixelRatio;
  12140. _viewportY = y * this.devicePixelRatio;
  12141. _viewportWidth = width * this.devicePixelRatio;
  12142. _viewportHeight = height * this.devicePixelRatio;
  12143. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  12144. };
  12145. this.setScissor = function ( x, y, width, height ) {
  12146. _gl.scissor(
  12147. x * this.devicePixelRatio,
  12148. y * this.devicePixelRatio,
  12149. width * this.devicePixelRatio,
  12150. height * this.devicePixelRatio
  12151. );
  12152. };
  12153. this.enableScissorTest = function ( enable ) {
  12154. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  12155. };
  12156. // Clearing
  12157. this.setClearColor = function ( color, alpha ) {
  12158. _clearColor.set( color );
  12159. _clearAlpha = alpha !== undefined ? alpha : 1;
  12160. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  12161. };
  12162. this.setClearColorHex = function ( hex, alpha ) {
  12163. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  12164. this.setClearColor( hex, alpha );
  12165. };
  12166. this.getClearColor = function () {
  12167. return _clearColor;
  12168. };
  12169. this.getClearAlpha = function () {
  12170. return _clearAlpha;
  12171. };
  12172. this.clear = function ( color, depth, stencil ) {
  12173. var bits = 0;
  12174. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  12175. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  12176. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  12177. _gl.clear( bits );
  12178. };
  12179. this.clearColor = function () {
  12180. _gl.clear( _gl.COLOR_BUFFER_BIT );
  12181. };
  12182. this.clearDepth = function () {
  12183. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  12184. };
  12185. this.clearStencil = function () {
  12186. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  12187. };
  12188. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  12189. this.setRenderTarget( renderTarget );
  12190. this.clear( color, depth, stencil );
  12191. };
  12192. // Plugins
  12193. this.addPostPlugin = function ( plugin ) {
  12194. plugin.init( this );
  12195. this.renderPluginsPost.push( plugin );
  12196. };
  12197. this.addPrePlugin = function ( plugin ) {
  12198. plugin.init( this );
  12199. this.renderPluginsPre.push( plugin );
  12200. };
  12201. // Rendering
  12202. this.updateShadowMap = function ( scene, camera ) {
  12203. _currentProgram = null;
  12204. _oldBlending = -1;
  12205. _oldDepthTest = -1;
  12206. _oldDepthWrite = -1;
  12207. _currentGeometryGroupHash = -1;
  12208. _currentMaterialId = -1;
  12209. _lightsNeedUpdate = true;
  12210. _oldDoubleSided = -1;
  12211. _oldFlipSided = -1;
  12212. this.shadowMapPlugin.update( scene, camera );
  12213. };
  12214. // Internal functions
  12215. // Buffer allocation
  12216. function createParticleBuffers ( geometry ) {
  12217. geometry.__webglVertexBuffer = _gl.createBuffer();
  12218. geometry.__webglColorBuffer = _gl.createBuffer();
  12219. _this.info.memory.geometries ++;
  12220. };
  12221. function createLineBuffers ( geometry ) {
  12222. geometry.__webglVertexBuffer = _gl.createBuffer();
  12223. geometry.__webglColorBuffer = _gl.createBuffer();
  12224. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  12225. _this.info.memory.geometries ++;
  12226. };
  12227. function createMeshBuffers ( geometryGroup ) {
  12228. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  12229. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  12230. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  12231. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  12232. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  12233. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  12234. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  12235. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  12236. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  12237. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  12238. var m, ml;
  12239. if ( geometryGroup.numMorphTargets ) {
  12240. geometryGroup.__webglMorphTargetsBuffers = [];
  12241. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12242. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  12243. }
  12244. }
  12245. if ( geometryGroup.numMorphNormals ) {
  12246. geometryGroup.__webglMorphNormalsBuffers = [];
  12247. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12248. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  12249. }
  12250. }
  12251. _this.info.memory.geometries ++;
  12252. };
  12253. // Events
  12254. var onGeometryDispose = function ( event ) {
  12255. var geometry = event.target;
  12256. geometry.removeEventListener( 'dispose', onGeometryDispose );
  12257. deallocateGeometry( geometry );
  12258. };
  12259. var onTextureDispose = function ( event ) {
  12260. var texture = event.target;
  12261. texture.removeEventListener( 'dispose', onTextureDispose );
  12262. deallocateTexture( texture );
  12263. _this.info.memory.textures --;
  12264. };
  12265. var onRenderTargetDispose = function ( event ) {
  12266. var renderTarget = event.target;
  12267. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  12268. deallocateRenderTarget( renderTarget );
  12269. _this.info.memory.textures --;
  12270. };
  12271. var onMaterialDispose = function ( event ) {
  12272. var material = event.target;
  12273. material.removeEventListener( 'dispose', onMaterialDispose );
  12274. deallocateMaterial( material );
  12275. };
  12276. // Buffer deallocation
  12277. var deleteBuffers = function ( geometry ) {
  12278. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  12279. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  12280. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  12281. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  12282. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  12283. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  12284. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  12285. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  12286. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  12287. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  12288. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  12289. // custom attributes
  12290. if ( geometry.__webglCustomAttributesList !== undefined ) {
  12291. for ( var id in geometry.__webglCustomAttributesList ) {
  12292. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  12293. }
  12294. }
  12295. _this.info.memory.geometries --;
  12296. };
  12297. var deallocateGeometry = function ( geometry ) {
  12298. geometry.__webglInit = undefined;
  12299. if ( geometry instanceof THREE.BufferGeometry ) {
  12300. var attributes = geometry.attributes;
  12301. for ( var key in attributes ) {
  12302. if ( attributes[ key ].buffer !== undefined ) {
  12303. _gl.deleteBuffer( attributes[ key ].buffer );
  12304. }
  12305. }
  12306. _this.info.memory.geometries --;
  12307. } else {
  12308. if ( geometry.geometryGroups !== undefined ) {
  12309. for ( var g in geometry.geometryGroups ) {
  12310. var geometryGroup = geometry.geometryGroups[ g ];
  12311. if ( geometryGroup.numMorphTargets !== undefined ) {
  12312. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12313. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  12314. }
  12315. }
  12316. if ( geometryGroup.numMorphNormals !== undefined ) {
  12317. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12318. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  12319. }
  12320. }
  12321. deleteBuffers( geometryGroup );
  12322. }
  12323. } else {
  12324. deleteBuffers( geometry );
  12325. }
  12326. }
  12327. };
  12328. var deallocateTexture = function ( texture ) {
  12329. if ( texture.image && texture.image.__webglTextureCube ) {
  12330. // cube texture
  12331. _gl.deleteTexture( texture.image.__webglTextureCube );
  12332. } else {
  12333. // 2D texture
  12334. if ( ! texture.__webglInit ) return;
  12335. texture.__webglInit = false;
  12336. _gl.deleteTexture( texture.__webglTexture );
  12337. }
  12338. };
  12339. var deallocateRenderTarget = function ( renderTarget ) {
  12340. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  12341. _gl.deleteTexture( renderTarget.__webglTexture );
  12342. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  12343. for ( var i = 0; i < 6; i ++ ) {
  12344. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  12345. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  12346. }
  12347. } else {
  12348. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  12349. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  12350. }
  12351. };
  12352. var deallocateMaterial = function ( material ) {
  12353. var program = material.program;
  12354. if ( program === undefined ) return;
  12355. material.program = undefined;
  12356. // only deallocate GL program if this was the last use of shared program
  12357. // assumed there is only single copy of any program in the _programs list
  12358. // (that's how it's constructed)
  12359. var i, il, programInfo;
  12360. var deleteProgram = false;
  12361. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12362. programInfo = _programs[ i ];
  12363. if ( programInfo.program === program ) {
  12364. programInfo.usedTimes --;
  12365. if ( programInfo.usedTimes === 0 ) {
  12366. deleteProgram = true;
  12367. }
  12368. break;
  12369. }
  12370. }
  12371. if ( deleteProgram === true ) {
  12372. // avoid using array.splice, this is costlier than creating new array from scratch
  12373. var newPrograms = [];
  12374. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12375. programInfo = _programs[ i ];
  12376. if ( programInfo.program !== program ) {
  12377. newPrograms.push( programInfo );
  12378. }
  12379. }
  12380. _programs = newPrograms;
  12381. _gl.deleteProgram( program );
  12382. _this.info.memory.programs --;
  12383. }
  12384. };
  12385. // Buffer initialization
  12386. function initCustomAttributes ( geometry, object ) {
  12387. var nvertices = geometry.vertices.length;
  12388. var material = object.material;
  12389. if ( material.attributes ) {
  12390. if ( geometry.__webglCustomAttributesList === undefined ) {
  12391. geometry.__webglCustomAttributesList = [];
  12392. }
  12393. for ( var a in material.attributes ) {
  12394. var attribute = material.attributes[ a ];
  12395. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12396. attribute.__webglInitialized = true;
  12397. var size = 1; // "f" and "i"
  12398. if ( attribute.type === "v2" ) size = 2;
  12399. else if ( attribute.type === "v3" ) size = 3;
  12400. else if ( attribute.type === "v4" ) size = 4;
  12401. else if ( attribute.type === "c" ) size = 3;
  12402. attribute.size = size;
  12403. attribute.array = new Float32Array( nvertices * size );
  12404. attribute.buffer = _gl.createBuffer();
  12405. attribute.buffer.belongsToAttribute = a;
  12406. attribute.needsUpdate = true;
  12407. }
  12408. geometry.__webglCustomAttributesList.push( attribute );
  12409. }
  12410. }
  12411. };
  12412. function initParticleBuffers ( geometry, object ) {
  12413. var nvertices = geometry.vertices.length;
  12414. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12415. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12416. geometry.__sortArray = [];
  12417. geometry.__webglParticleCount = nvertices;
  12418. initCustomAttributes ( geometry, object );
  12419. };
  12420. function initLineBuffers ( geometry, object ) {
  12421. var nvertices = geometry.vertices.length;
  12422. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12423. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12424. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  12425. geometry.__webglLineCount = nvertices;
  12426. initCustomAttributes ( geometry, object );
  12427. };
  12428. function initMeshBuffers ( geometryGroup, object ) {
  12429. var geometry = object.geometry,
  12430. faces3 = geometryGroup.faces3,
  12431. nvertices = faces3.length * 3,
  12432. ntris = faces3.length * 1,
  12433. nlines = faces3.length * 3,
  12434. material = getBufferMaterial( object, geometryGroup ),
  12435. uvType = bufferGuessUVType( material ),
  12436. normalType = bufferGuessNormalType( material ),
  12437. vertexColorType = bufferGuessVertexColorType( material );
  12438. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  12439. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  12440. if ( normalType ) {
  12441. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  12442. }
  12443. if ( geometry.hasTangents ) {
  12444. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  12445. }
  12446. if ( vertexColorType ) {
  12447. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  12448. }
  12449. if ( uvType ) {
  12450. if ( geometry.faceVertexUvs.length > 0 ) {
  12451. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  12452. }
  12453. if ( geometry.faceVertexUvs.length > 1 ) {
  12454. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  12455. }
  12456. }
  12457. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  12458. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  12459. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  12460. }
  12461. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  12462. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  12463. var m, ml;
  12464. if ( geometryGroup.numMorphTargets ) {
  12465. geometryGroup.__morphTargetsArrays = [];
  12466. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12467. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  12468. }
  12469. }
  12470. if ( geometryGroup.numMorphNormals ) {
  12471. geometryGroup.__morphNormalsArrays = [];
  12472. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12473. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  12474. }
  12475. }
  12476. geometryGroup.__webglFaceCount = ntris * 3;
  12477. geometryGroup.__webglLineCount = nlines * 2;
  12478. // custom attributes
  12479. if ( material.attributes ) {
  12480. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  12481. geometryGroup.__webglCustomAttributesList = [];
  12482. }
  12483. for ( var a in material.attributes ) {
  12484. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  12485. // attribute buffers which are correctly indexed in the setMeshBuffers function
  12486. var originalAttribute = material.attributes[ a ];
  12487. var attribute = {};
  12488. for ( var property in originalAttribute ) {
  12489. attribute[ property ] = originalAttribute[ property ];
  12490. }
  12491. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12492. attribute.__webglInitialized = true;
  12493. var size = 1; // "f" and "i"
  12494. if( attribute.type === "v2" ) size = 2;
  12495. else if( attribute.type === "v3" ) size = 3;
  12496. else if( attribute.type === "v4" ) size = 4;
  12497. else if( attribute.type === "c" ) size = 3;
  12498. attribute.size = size;
  12499. attribute.array = new Float32Array( nvertices * size );
  12500. attribute.buffer = _gl.createBuffer();
  12501. attribute.buffer.belongsToAttribute = a;
  12502. originalAttribute.needsUpdate = true;
  12503. attribute.__original = originalAttribute;
  12504. }
  12505. geometryGroup.__webglCustomAttributesList.push( attribute );
  12506. }
  12507. }
  12508. geometryGroup.__inittedArrays = true;
  12509. };
  12510. function getBufferMaterial( object, geometryGroup ) {
  12511. return object.material instanceof THREE.MeshFaceMaterial
  12512. ? object.material.materials[ geometryGroup.materialIndex ]
  12513. : object.material;
  12514. };
  12515. function materialNeedsSmoothNormals ( material ) {
  12516. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  12517. };
  12518. function bufferGuessNormalType ( material ) {
  12519. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  12520. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  12521. return false;
  12522. }
  12523. if ( materialNeedsSmoothNormals( material ) ) {
  12524. return THREE.SmoothShading;
  12525. } else {
  12526. return THREE.FlatShading;
  12527. }
  12528. };
  12529. function bufferGuessVertexColorType( material ) {
  12530. if ( material.vertexColors ) {
  12531. return material.vertexColors;
  12532. }
  12533. return false;
  12534. };
  12535. function bufferGuessUVType( material ) {
  12536. // material must use some texture to require uvs
  12537. if ( material.map ||
  12538. material.lightMap ||
  12539. material.bumpMap ||
  12540. material.normalMap ||
  12541. material.specularMap ||
  12542. material instanceof THREE.ShaderMaterial ) {
  12543. return true;
  12544. }
  12545. return false;
  12546. };
  12547. //
  12548. function initDirectBuffers( geometry ) {
  12549. var a, attribute, type;
  12550. for ( a in geometry.attributes ) {
  12551. if ( a === "index" ) {
  12552. type = _gl.ELEMENT_ARRAY_BUFFER;
  12553. } else {
  12554. type = _gl.ARRAY_BUFFER;
  12555. }
  12556. attribute = geometry.attributes[ a ];
  12557. attribute.buffer = _gl.createBuffer();
  12558. _gl.bindBuffer( type, attribute.buffer );
  12559. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  12560. }
  12561. };
  12562. function initGeometry2Buffers( geometry ) {
  12563. var buffers = {};
  12564. var attributes = [ 'vertices', 'normals', 'uvs' ];
  12565. for ( var key in attributes ) {
  12566. var array = geometry[ attributes[ key ] ];
  12567. var buffer = _gl.createBuffer();
  12568. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12569. _gl.bufferData( _gl.ARRAY_BUFFER, array, _gl.STATIC_DRAW );
  12570. buffers[ attributes[ key ] ] = buffer;
  12571. }
  12572. _buffers[ geometry.id ] = buffers;
  12573. };
  12574. // Buffer setting
  12575. function setParticleBuffers ( geometry, hint, object ) {
  12576. var v, c, vertex, offset, index, color,
  12577. vertices = geometry.vertices,
  12578. vl = vertices.length,
  12579. colors = geometry.colors,
  12580. cl = colors.length,
  12581. vertexArray = geometry.__vertexArray,
  12582. colorArray = geometry.__colorArray,
  12583. sortArray = geometry.__sortArray,
  12584. dirtyVertices = geometry.verticesNeedUpdate,
  12585. dirtyElements = geometry.elementsNeedUpdate,
  12586. dirtyColors = geometry.colorsNeedUpdate,
  12587. customAttributes = geometry.__webglCustomAttributesList,
  12588. i, il,
  12589. a, ca, cal, value,
  12590. customAttribute;
  12591. if ( object.sortParticles ) {
  12592. _projScreenMatrixPS.copy( _projScreenMatrix );
  12593. _projScreenMatrixPS.multiply( object.matrixWorld );
  12594. for ( v = 0; v < vl; v ++ ) {
  12595. vertex = vertices[ v ];
  12596. _vector3.copy( vertex );
  12597. _vector3.applyProjection( _projScreenMatrixPS );
  12598. sortArray[ v ] = [ _vector3.z, v ];
  12599. }
  12600. sortArray.sort( numericalSort );
  12601. for ( v = 0; v < vl; v ++ ) {
  12602. vertex = vertices[ sortArray[v][1] ];
  12603. offset = v * 3;
  12604. vertexArray[ offset ] = vertex.x;
  12605. vertexArray[ offset + 1 ] = vertex.y;
  12606. vertexArray[ offset + 2 ] = vertex.z;
  12607. }
  12608. for ( c = 0; c < cl; c ++ ) {
  12609. offset = c * 3;
  12610. color = colors[ sortArray[c][1] ];
  12611. colorArray[ offset ] = color.r;
  12612. colorArray[ offset + 1 ] = color.g;
  12613. colorArray[ offset + 2 ] = color.b;
  12614. }
  12615. if ( customAttributes ) {
  12616. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12617. customAttribute = customAttributes[ i ];
  12618. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  12619. offset = 0;
  12620. cal = customAttribute.value.length;
  12621. if ( customAttribute.size === 1 ) {
  12622. for ( ca = 0; ca < cal; ca ++ ) {
  12623. index = sortArray[ ca ][ 1 ];
  12624. customAttribute.array[ ca ] = customAttribute.value[ index ];
  12625. }
  12626. } else if ( customAttribute.size === 2 ) {
  12627. for ( ca = 0; ca < cal; ca ++ ) {
  12628. index = sortArray[ ca ][ 1 ];
  12629. value = customAttribute.value[ index ];
  12630. customAttribute.array[ offset ] = value.x;
  12631. customAttribute.array[ offset + 1 ] = value.y;
  12632. offset += 2;
  12633. }
  12634. } else if ( customAttribute.size === 3 ) {
  12635. if ( customAttribute.type === "c" ) {
  12636. for ( ca = 0; ca < cal; ca ++ ) {
  12637. index = sortArray[ ca ][ 1 ];
  12638. value = customAttribute.value[ index ];
  12639. customAttribute.array[ offset ] = value.r;
  12640. customAttribute.array[ offset + 1 ] = value.g;
  12641. customAttribute.array[ offset + 2 ] = value.b;
  12642. offset += 3;
  12643. }
  12644. } else {
  12645. for ( ca = 0; ca < cal; ca ++ ) {
  12646. index = sortArray[ ca ][ 1 ];
  12647. value = customAttribute.value[ index ];
  12648. customAttribute.array[ offset ] = value.x;
  12649. customAttribute.array[ offset + 1 ] = value.y;
  12650. customAttribute.array[ offset + 2 ] = value.z;
  12651. offset += 3;
  12652. }
  12653. }
  12654. } else if ( customAttribute.size === 4 ) {
  12655. for ( ca = 0; ca < cal; ca ++ ) {
  12656. index = sortArray[ ca ][ 1 ];
  12657. value = customAttribute.value[ index ];
  12658. customAttribute.array[ offset ] = value.x;
  12659. customAttribute.array[ offset + 1 ] = value.y;
  12660. customAttribute.array[ offset + 2 ] = value.z;
  12661. customAttribute.array[ offset + 3 ] = value.w;
  12662. offset += 4;
  12663. }
  12664. }
  12665. }
  12666. }
  12667. } else {
  12668. if ( dirtyVertices ) {
  12669. for ( v = 0; v < vl; v ++ ) {
  12670. vertex = vertices[ v ];
  12671. offset = v * 3;
  12672. vertexArray[ offset ] = vertex.x;
  12673. vertexArray[ offset + 1 ] = vertex.y;
  12674. vertexArray[ offset + 2 ] = vertex.z;
  12675. }
  12676. }
  12677. if ( dirtyColors ) {
  12678. for ( c = 0; c < cl; c ++ ) {
  12679. color = colors[ c ];
  12680. offset = c * 3;
  12681. colorArray[ offset ] = color.r;
  12682. colorArray[ offset + 1 ] = color.g;
  12683. colorArray[ offset + 2 ] = color.b;
  12684. }
  12685. }
  12686. if ( customAttributes ) {
  12687. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12688. customAttribute = customAttributes[ i ];
  12689. if ( customAttribute.needsUpdate &&
  12690. ( customAttribute.boundTo === undefined ||
  12691. customAttribute.boundTo === "vertices") ) {
  12692. cal = customAttribute.value.length;
  12693. offset = 0;
  12694. if ( customAttribute.size === 1 ) {
  12695. for ( ca = 0; ca < cal; ca ++ ) {
  12696. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12697. }
  12698. } else if ( customAttribute.size === 2 ) {
  12699. for ( ca = 0; ca < cal; ca ++ ) {
  12700. value = customAttribute.value[ ca ];
  12701. customAttribute.array[ offset ] = value.x;
  12702. customAttribute.array[ offset + 1 ] = value.y;
  12703. offset += 2;
  12704. }
  12705. } else if ( customAttribute.size === 3 ) {
  12706. if ( customAttribute.type === "c" ) {
  12707. for ( ca = 0; ca < cal; ca ++ ) {
  12708. value = customAttribute.value[ ca ];
  12709. customAttribute.array[ offset ] = value.r;
  12710. customAttribute.array[ offset + 1 ] = value.g;
  12711. customAttribute.array[ offset + 2 ] = value.b;
  12712. offset += 3;
  12713. }
  12714. } else {
  12715. for ( ca = 0; ca < cal; ca ++ ) {
  12716. value = customAttribute.value[ ca ];
  12717. customAttribute.array[ offset ] = value.x;
  12718. customAttribute.array[ offset + 1 ] = value.y;
  12719. customAttribute.array[ offset + 2 ] = value.z;
  12720. offset += 3;
  12721. }
  12722. }
  12723. } else if ( customAttribute.size === 4 ) {
  12724. for ( ca = 0; ca < cal; ca ++ ) {
  12725. value = customAttribute.value[ ca ];
  12726. customAttribute.array[ offset ] = value.x;
  12727. customAttribute.array[ offset + 1 ] = value.y;
  12728. customAttribute.array[ offset + 2 ] = value.z;
  12729. customAttribute.array[ offset + 3 ] = value.w;
  12730. offset += 4;
  12731. }
  12732. }
  12733. }
  12734. }
  12735. }
  12736. }
  12737. if ( dirtyVertices || object.sortParticles ) {
  12738. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12739. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12740. }
  12741. if ( dirtyColors || object.sortParticles ) {
  12742. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12743. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12744. }
  12745. if ( customAttributes ) {
  12746. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12747. customAttribute = customAttributes[ i ];
  12748. if ( customAttribute.needsUpdate || object.sortParticles ) {
  12749. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12750. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12751. }
  12752. }
  12753. }
  12754. };
  12755. function setLineBuffers ( geometry, hint ) {
  12756. var v, c, d, vertex, offset, color,
  12757. vertices = geometry.vertices,
  12758. colors = geometry.colors,
  12759. lineDistances = geometry.lineDistances,
  12760. vl = vertices.length,
  12761. cl = colors.length,
  12762. dl = lineDistances.length,
  12763. vertexArray = geometry.__vertexArray,
  12764. colorArray = geometry.__colorArray,
  12765. lineDistanceArray = geometry.__lineDistanceArray,
  12766. dirtyVertices = geometry.verticesNeedUpdate,
  12767. dirtyColors = geometry.colorsNeedUpdate,
  12768. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  12769. customAttributes = geometry.__webglCustomAttributesList,
  12770. i, il,
  12771. a, ca, cal, value,
  12772. customAttribute;
  12773. if ( dirtyVertices ) {
  12774. for ( v = 0; v < vl; v ++ ) {
  12775. vertex = vertices[ v ];
  12776. offset = v * 3;
  12777. vertexArray[ offset ] = vertex.x;
  12778. vertexArray[ offset + 1 ] = vertex.y;
  12779. vertexArray[ offset + 2 ] = vertex.z;
  12780. }
  12781. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12782. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12783. }
  12784. if ( dirtyColors ) {
  12785. for ( c = 0; c < cl; c ++ ) {
  12786. color = colors[ c ];
  12787. offset = c * 3;
  12788. colorArray[ offset ] = color.r;
  12789. colorArray[ offset + 1 ] = color.g;
  12790. colorArray[ offset + 2 ] = color.b;
  12791. }
  12792. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12793. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12794. }
  12795. if ( dirtyLineDistances ) {
  12796. for ( d = 0; d < dl; d ++ ) {
  12797. lineDistanceArray[ d ] = lineDistances[ d ];
  12798. }
  12799. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  12800. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  12801. }
  12802. if ( customAttributes ) {
  12803. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12804. customAttribute = customAttributes[ i ];
  12805. if ( customAttribute.needsUpdate &&
  12806. ( customAttribute.boundTo === undefined ||
  12807. customAttribute.boundTo === "vertices" ) ) {
  12808. offset = 0;
  12809. cal = customAttribute.value.length;
  12810. if ( customAttribute.size === 1 ) {
  12811. for ( ca = 0; ca < cal; ca ++ ) {
  12812. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12813. }
  12814. } else if ( customAttribute.size === 2 ) {
  12815. for ( ca = 0; ca < cal; ca ++ ) {
  12816. value = customAttribute.value[ ca ];
  12817. customAttribute.array[ offset ] = value.x;
  12818. customAttribute.array[ offset + 1 ] = value.y;
  12819. offset += 2;
  12820. }
  12821. } else if ( customAttribute.size === 3 ) {
  12822. if ( customAttribute.type === "c" ) {
  12823. for ( ca = 0; ca < cal; ca ++ ) {
  12824. value = customAttribute.value[ ca ];
  12825. customAttribute.array[ offset ] = value.r;
  12826. customAttribute.array[ offset + 1 ] = value.g;
  12827. customAttribute.array[ offset + 2 ] = value.b;
  12828. offset += 3;
  12829. }
  12830. } else {
  12831. for ( ca = 0; ca < cal; ca ++ ) {
  12832. value = customAttribute.value[ ca ];
  12833. customAttribute.array[ offset ] = value.x;
  12834. customAttribute.array[ offset + 1 ] = value.y;
  12835. customAttribute.array[ offset + 2 ] = value.z;
  12836. offset += 3;
  12837. }
  12838. }
  12839. } else if ( customAttribute.size === 4 ) {
  12840. for ( ca = 0; ca < cal; ca ++ ) {
  12841. value = customAttribute.value[ ca ];
  12842. customAttribute.array[ offset ] = value.x;
  12843. customAttribute.array[ offset + 1 ] = value.y;
  12844. customAttribute.array[ offset + 2 ] = value.z;
  12845. customAttribute.array[ offset + 3 ] = value.w;
  12846. offset += 4;
  12847. }
  12848. }
  12849. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12850. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12851. }
  12852. }
  12853. }
  12854. };
  12855. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  12856. if ( ! geometryGroup.__inittedArrays ) {
  12857. return;
  12858. }
  12859. var normalType = bufferGuessNormalType( material ),
  12860. vertexColorType = bufferGuessVertexColorType( material ),
  12861. uvType = bufferGuessUVType( material ),
  12862. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  12863. var f, fl, fi, face,
  12864. vertexNormals, faceNormal, normal,
  12865. vertexColors, faceColor,
  12866. vertexTangents,
  12867. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  12868. c1, c2, c3, c4,
  12869. sw1, sw2, sw3, sw4,
  12870. si1, si2, si3, si4,
  12871. sa1, sa2, sa3, sa4,
  12872. sb1, sb2, sb3, sb4,
  12873. m, ml, i, il,
  12874. vn, uvi, uv2i,
  12875. vk, vkl, vka,
  12876. nka, chf, faceVertexNormals,
  12877. a,
  12878. vertexIndex = 0,
  12879. offset = 0,
  12880. offset_uv = 0,
  12881. offset_uv2 = 0,
  12882. offset_face = 0,
  12883. offset_normal = 0,
  12884. offset_tangent = 0,
  12885. offset_line = 0,
  12886. offset_color = 0,
  12887. offset_skin = 0,
  12888. offset_morphTarget = 0,
  12889. offset_custom = 0,
  12890. offset_customSrc = 0,
  12891. value,
  12892. vertexArray = geometryGroup.__vertexArray,
  12893. uvArray = geometryGroup.__uvArray,
  12894. uv2Array = geometryGroup.__uv2Array,
  12895. normalArray = geometryGroup.__normalArray,
  12896. tangentArray = geometryGroup.__tangentArray,
  12897. colorArray = geometryGroup.__colorArray,
  12898. skinIndexArray = geometryGroup.__skinIndexArray,
  12899. skinWeightArray = geometryGroup.__skinWeightArray,
  12900. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  12901. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  12902. customAttributes = geometryGroup.__webglCustomAttributesList,
  12903. customAttribute,
  12904. faceArray = geometryGroup.__faceArray,
  12905. lineArray = geometryGroup.__lineArray,
  12906. geometry = object.geometry, // this is shared for all chunks
  12907. dirtyVertices = geometry.verticesNeedUpdate,
  12908. dirtyElements = geometry.elementsNeedUpdate,
  12909. dirtyUvs = geometry.uvsNeedUpdate,
  12910. dirtyNormals = geometry.normalsNeedUpdate,
  12911. dirtyTangents = geometry.tangentsNeedUpdate,
  12912. dirtyColors = geometry.colorsNeedUpdate,
  12913. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  12914. vertices = geometry.vertices,
  12915. chunk_faces3 = geometryGroup.faces3,
  12916. obj_faces = geometry.faces,
  12917. obj_uvs = geometry.faceVertexUvs[ 0 ],
  12918. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  12919. obj_colors = geometry.colors,
  12920. obj_skinIndices = geometry.skinIndices,
  12921. obj_skinWeights = geometry.skinWeights,
  12922. morphTargets = geometry.morphTargets,
  12923. morphNormals = geometry.morphNormals;
  12924. if ( dirtyVertices ) {
  12925. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12926. face = obj_faces[ chunk_faces3[ f ] ];
  12927. v1 = vertices[ face.a ];
  12928. v2 = vertices[ face.b ];
  12929. v3 = vertices[ face.c ];
  12930. vertexArray[ offset ] = v1.x;
  12931. vertexArray[ offset + 1 ] = v1.y;
  12932. vertexArray[ offset + 2 ] = v1.z;
  12933. vertexArray[ offset + 3 ] = v2.x;
  12934. vertexArray[ offset + 4 ] = v2.y;
  12935. vertexArray[ offset + 5 ] = v2.z;
  12936. vertexArray[ offset + 6 ] = v3.x;
  12937. vertexArray[ offset + 7 ] = v3.y;
  12938. vertexArray[ offset + 8 ] = v3.z;
  12939. offset += 9;
  12940. }
  12941. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12942. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12943. }
  12944. if ( dirtyMorphTargets ) {
  12945. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  12946. offset_morphTarget = 0;
  12947. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12948. chf = chunk_faces3[ f ];
  12949. face = obj_faces[ chf ];
  12950. // morph positions
  12951. v1 = morphTargets[ vk ].vertices[ face.a ];
  12952. v2 = morphTargets[ vk ].vertices[ face.b ];
  12953. v3 = morphTargets[ vk ].vertices[ face.c ];
  12954. vka = morphTargetsArrays[ vk ];
  12955. vka[ offset_morphTarget ] = v1.x;
  12956. vka[ offset_morphTarget + 1 ] = v1.y;
  12957. vka[ offset_morphTarget + 2 ] = v1.z;
  12958. vka[ offset_morphTarget + 3 ] = v2.x;
  12959. vka[ offset_morphTarget + 4 ] = v2.y;
  12960. vka[ offset_morphTarget + 5 ] = v2.z;
  12961. vka[ offset_morphTarget + 6 ] = v3.x;
  12962. vka[ offset_morphTarget + 7 ] = v3.y;
  12963. vka[ offset_morphTarget + 8 ] = v3.z;
  12964. // morph normals
  12965. if ( material.morphNormals ) {
  12966. if ( needsSmoothNormals ) {
  12967. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12968. n1 = faceVertexNormals.a;
  12969. n2 = faceVertexNormals.b;
  12970. n3 = faceVertexNormals.c;
  12971. } else {
  12972. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12973. n2 = n1;
  12974. n3 = n1;
  12975. }
  12976. nka = morphNormalsArrays[ vk ];
  12977. nka[ offset_morphTarget ] = n1.x;
  12978. nka[ offset_morphTarget + 1 ] = n1.y;
  12979. nka[ offset_morphTarget + 2 ] = n1.z;
  12980. nka[ offset_morphTarget + 3 ] = n2.x;
  12981. nka[ offset_morphTarget + 4 ] = n2.y;
  12982. nka[ offset_morphTarget + 5 ] = n2.z;
  12983. nka[ offset_morphTarget + 6 ] = n3.x;
  12984. nka[ offset_morphTarget + 7 ] = n3.y;
  12985. nka[ offset_morphTarget + 8 ] = n3.z;
  12986. }
  12987. //
  12988. offset_morphTarget += 9;
  12989. }
  12990. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  12991. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  12992. if ( material.morphNormals ) {
  12993. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  12994. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  12995. }
  12996. }
  12997. }
  12998. if ( obj_skinWeights.length ) {
  12999. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13000. face = obj_faces[ chunk_faces3[ f ] ];
  13001. // weights
  13002. sw1 = obj_skinWeights[ face.a ];
  13003. sw2 = obj_skinWeights[ face.b ];
  13004. sw3 = obj_skinWeights[ face.c ];
  13005. skinWeightArray[ offset_skin ] = sw1.x;
  13006. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  13007. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  13008. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  13009. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  13010. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  13011. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  13012. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  13013. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  13014. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  13015. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  13016. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  13017. // indices
  13018. si1 = obj_skinIndices[ face.a ];
  13019. si2 = obj_skinIndices[ face.b ];
  13020. si3 = obj_skinIndices[ face.c ];
  13021. skinIndexArray[ offset_skin ] = si1.x;
  13022. skinIndexArray[ offset_skin + 1 ] = si1.y;
  13023. skinIndexArray[ offset_skin + 2 ] = si1.z;
  13024. skinIndexArray[ offset_skin + 3 ] = si1.w;
  13025. skinIndexArray[ offset_skin + 4 ] = si2.x;
  13026. skinIndexArray[ offset_skin + 5 ] = si2.y;
  13027. skinIndexArray[ offset_skin + 6 ] = si2.z;
  13028. skinIndexArray[ offset_skin + 7 ] = si2.w;
  13029. skinIndexArray[ offset_skin + 8 ] = si3.x;
  13030. skinIndexArray[ offset_skin + 9 ] = si3.y;
  13031. skinIndexArray[ offset_skin + 10 ] = si3.z;
  13032. skinIndexArray[ offset_skin + 11 ] = si3.w;
  13033. offset_skin += 12;
  13034. }
  13035. if ( offset_skin > 0 ) {
  13036. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13037. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  13038. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13039. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  13040. }
  13041. }
  13042. if ( dirtyColors && vertexColorType ) {
  13043. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13044. face = obj_faces[ chunk_faces3[ f ] ];
  13045. vertexColors = face.vertexColors;
  13046. faceColor = face.color;
  13047. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  13048. c1 = vertexColors[ 0 ];
  13049. c2 = vertexColors[ 1 ];
  13050. c3 = vertexColors[ 2 ];
  13051. } else {
  13052. c1 = faceColor;
  13053. c2 = faceColor;
  13054. c3 = faceColor;
  13055. }
  13056. colorArray[ offset_color ] = c1.r;
  13057. colorArray[ offset_color + 1 ] = c1.g;
  13058. colorArray[ offset_color + 2 ] = c1.b;
  13059. colorArray[ offset_color + 3 ] = c2.r;
  13060. colorArray[ offset_color + 4 ] = c2.g;
  13061. colorArray[ offset_color + 5 ] = c2.b;
  13062. colorArray[ offset_color + 6 ] = c3.r;
  13063. colorArray[ offset_color + 7 ] = c3.g;
  13064. colorArray[ offset_color + 8 ] = c3.b;
  13065. offset_color += 9;
  13066. }
  13067. if ( offset_color > 0 ) {
  13068. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13069. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  13070. }
  13071. }
  13072. if ( dirtyTangents && geometry.hasTangents ) {
  13073. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13074. face = obj_faces[ chunk_faces3[ f ] ];
  13075. vertexTangents = face.vertexTangents;
  13076. t1 = vertexTangents[ 0 ];
  13077. t2 = vertexTangents[ 1 ];
  13078. t3 = vertexTangents[ 2 ];
  13079. tangentArray[ offset_tangent ] = t1.x;
  13080. tangentArray[ offset_tangent + 1 ] = t1.y;
  13081. tangentArray[ offset_tangent + 2 ] = t1.z;
  13082. tangentArray[ offset_tangent + 3 ] = t1.w;
  13083. tangentArray[ offset_tangent + 4 ] = t2.x;
  13084. tangentArray[ offset_tangent + 5 ] = t2.y;
  13085. tangentArray[ offset_tangent + 6 ] = t2.z;
  13086. tangentArray[ offset_tangent + 7 ] = t2.w;
  13087. tangentArray[ offset_tangent + 8 ] = t3.x;
  13088. tangentArray[ offset_tangent + 9 ] = t3.y;
  13089. tangentArray[ offset_tangent + 10 ] = t3.z;
  13090. tangentArray[ offset_tangent + 11 ] = t3.w;
  13091. offset_tangent += 12;
  13092. }
  13093. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13094. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  13095. }
  13096. if ( dirtyNormals && normalType ) {
  13097. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13098. face = obj_faces[ chunk_faces3[ f ] ];
  13099. vertexNormals = face.vertexNormals;
  13100. faceNormal = face.normal;
  13101. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  13102. for ( i = 0; i < 3; i ++ ) {
  13103. vn = vertexNormals[ i ];
  13104. normalArray[ offset_normal ] = vn.x;
  13105. normalArray[ offset_normal + 1 ] = vn.y;
  13106. normalArray[ offset_normal + 2 ] = vn.z;
  13107. offset_normal += 3;
  13108. }
  13109. } else {
  13110. for ( i = 0; i < 3; i ++ ) {
  13111. normalArray[ offset_normal ] = faceNormal.x;
  13112. normalArray[ offset_normal + 1 ] = faceNormal.y;
  13113. normalArray[ offset_normal + 2 ] = faceNormal.z;
  13114. offset_normal += 3;
  13115. }
  13116. }
  13117. }
  13118. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13119. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  13120. }
  13121. if ( dirtyUvs && obj_uvs && uvType ) {
  13122. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13123. fi = chunk_faces3[ f ];
  13124. uv = obj_uvs[ fi ];
  13125. if ( uv === undefined ) continue;
  13126. for ( i = 0; i < 3; i ++ ) {
  13127. uvi = uv[ i ];
  13128. uvArray[ offset_uv ] = uvi.x;
  13129. uvArray[ offset_uv + 1 ] = uvi.y;
  13130. offset_uv += 2;
  13131. }
  13132. }
  13133. if ( offset_uv > 0 ) {
  13134. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13135. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  13136. }
  13137. }
  13138. if ( dirtyUvs && obj_uvs2 && uvType ) {
  13139. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13140. fi = chunk_faces3[ f ];
  13141. uv2 = obj_uvs2[ fi ];
  13142. if ( uv2 === undefined ) continue;
  13143. for ( i = 0; i < 3; i ++ ) {
  13144. uv2i = uv2[ i ];
  13145. uv2Array[ offset_uv2 ] = uv2i.x;
  13146. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  13147. offset_uv2 += 2;
  13148. }
  13149. }
  13150. if ( offset_uv2 > 0 ) {
  13151. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13152. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  13153. }
  13154. }
  13155. if ( dirtyElements ) {
  13156. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13157. faceArray[ offset_face ] = vertexIndex;
  13158. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  13159. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  13160. offset_face += 3;
  13161. lineArray[ offset_line ] = vertexIndex;
  13162. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  13163. lineArray[ offset_line + 2 ] = vertexIndex;
  13164. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  13165. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  13166. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  13167. offset_line += 6;
  13168. vertexIndex += 3;
  13169. }
  13170. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13171. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  13172. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13173. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  13174. }
  13175. if ( customAttributes ) {
  13176. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13177. customAttribute = customAttributes[ i ];
  13178. if ( ! customAttribute.__original.needsUpdate ) continue;
  13179. offset_custom = 0;
  13180. offset_customSrc = 0;
  13181. if ( customAttribute.size === 1 ) {
  13182. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13183. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13184. face = obj_faces[ chunk_faces3[ f ] ];
  13185. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  13186. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  13187. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  13188. offset_custom += 3;
  13189. }
  13190. } else if ( customAttribute.boundTo === "faces" ) {
  13191. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13192. value = customAttribute.value[ chunk_faces3[ f ] ];
  13193. customAttribute.array[ offset_custom ] = value;
  13194. customAttribute.array[ offset_custom + 1 ] = value;
  13195. customAttribute.array[ offset_custom + 2 ] = value;
  13196. offset_custom += 3;
  13197. }
  13198. }
  13199. } else if ( customAttribute.size === 2 ) {
  13200. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13201. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13202. face = obj_faces[ chunk_faces3[ f ] ];
  13203. v1 = customAttribute.value[ face.a ];
  13204. v2 = customAttribute.value[ face.b ];
  13205. v3 = customAttribute.value[ face.c ];
  13206. customAttribute.array[ offset_custom ] = v1.x;
  13207. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13208. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13209. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13210. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13211. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13212. offset_custom += 6;
  13213. }
  13214. } else if ( customAttribute.boundTo === "faces" ) {
  13215. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13216. value = customAttribute.value[ chunk_faces3[ f ] ];
  13217. v1 = value;
  13218. v2 = value;
  13219. v3 = value;
  13220. customAttribute.array[ offset_custom ] = v1.x;
  13221. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13222. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13223. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13224. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13225. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13226. offset_custom += 6;
  13227. }
  13228. }
  13229. } else if ( customAttribute.size === 3 ) {
  13230. var pp;
  13231. if ( customAttribute.type === "c" ) {
  13232. pp = [ "r", "g", "b" ];
  13233. } else {
  13234. pp = [ "x", "y", "z" ];
  13235. }
  13236. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13237. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13238. face = obj_faces[ chunk_faces3[ f ] ];
  13239. v1 = customAttribute.value[ face.a ];
  13240. v2 = customAttribute.value[ face.b ];
  13241. v3 = customAttribute.value[ face.c ];
  13242. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13243. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13244. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13245. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13246. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13247. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13248. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13249. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13250. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13251. offset_custom += 9;
  13252. }
  13253. } else if ( customAttribute.boundTo === "faces" ) {
  13254. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13255. value = customAttribute.value[ chunk_faces3[ f ] ];
  13256. v1 = value;
  13257. v2 = value;
  13258. v3 = value;
  13259. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13260. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13261. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13262. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13263. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13264. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13265. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13266. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13267. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13268. offset_custom += 9;
  13269. }
  13270. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13271. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13272. value = customAttribute.value[ chunk_faces3[ f ] ];
  13273. v1 = value[ 0 ];
  13274. v2 = value[ 1 ];
  13275. v3 = value[ 2 ];
  13276. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13277. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13278. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13279. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13280. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13281. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13282. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13283. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13284. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13285. offset_custom += 9;
  13286. }
  13287. }
  13288. } else if ( customAttribute.size === 4 ) {
  13289. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13290. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13291. face = obj_faces[ chunk_faces3[ f ] ];
  13292. v1 = customAttribute.value[ face.a ];
  13293. v2 = customAttribute.value[ face.b ];
  13294. v3 = customAttribute.value[ face.c ];
  13295. customAttribute.array[ offset_custom ] = v1.x;
  13296. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13297. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13298. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13299. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13300. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13301. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13302. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13303. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13304. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13305. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13306. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13307. offset_custom += 12;
  13308. }
  13309. } else if ( customAttribute.boundTo === "faces" ) {
  13310. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13311. value = customAttribute.value[ chunk_faces3[ f ] ];
  13312. v1 = value;
  13313. v2 = value;
  13314. v3 = value;
  13315. customAttribute.array[ offset_custom ] = v1.x;
  13316. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13317. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13318. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13319. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13320. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13321. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13322. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13323. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13324. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13325. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13326. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13327. offset_custom += 12;
  13328. }
  13329. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13330. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13331. value = customAttribute.value[ chunk_faces3[ f ] ];
  13332. v1 = value[ 0 ];
  13333. v2 = value[ 1 ];
  13334. v3 = value[ 2 ];
  13335. customAttribute.array[ offset_custom ] = v1.x;
  13336. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13337. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13338. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13339. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13340. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13341. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13342. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13343. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13344. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13345. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13346. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13347. offset_custom += 12;
  13348. }
  13349. }
  13350. }
  13351. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  13352. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  13353. }
  13354. }
  13355. if ( dispose ) {
  13356. delete geometryGroup.__inittedArrays;
  13357. delete geometryGroup.__colorArray;
  13358. delete geometryGroup.__normalArray;
  13359. delete geometryGroup.__tangentArray;
  13360. delete geometryGroup.__uvArray;
  13361. delete geometryGroup.__uv2Array;
  13362. delete geometryGroup.__faceArray;
  13363. delete geometryGroup.__vertexArray;
  13364. delete geometryGroup.__lineArray;
  13365. delete geometryGroup.__skinIndexArray;
  13366. delete geometryGroup.__skinWeightArray;
  13367. }
  13368. };
  13369. // used by renderBufferDirect for THREE.Line
  13370. function setupLinesVertexAttributes( material, programAttributes, geometryAttributes, startIndex ) {
  13371. var attributeItem, attributeName, attributePointer, attributeSize;
  13372. for ( attributeName in programAttributes ) {
  13373. attributePointer = programAttributes[ attributeName ];
  13374. attributeItem = geometryAttributes[ attributeName ];
  13375. if ( attributePointer >= 0 ) {
  13376. if ( attributeItem ) {
  13377. attributeSize = attributeItem.itemSize;
  13378. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13379. enableAttribute( attributePointer );
  13380. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13381. } else if ( material.defaultAttributeValues ) {
  13382. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13383. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13384. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13385. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13386. }
  13387. }
  13388. }
  13389. }
  13390. }
  13391. function setDirectBuffers( geometry, hint ) {
  13392. var attributes = geometry.attributes;
  13393. var attributeName, attributeItem;
  13394. for ( attributeName in attributes ) {
  13395. attributeItem = attributes[ attributeName ];
  13396. if ( attributeItem.needsUpdate ) {
  13397. if ( attributeName === 'index' ) {
  13398. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  13399. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  13400. } else {
  13401. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13402. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  13403. }
  13404. attributeItem.needsUpdate = false;
  13405. }
  13406. }
  13407. }
  13408. function setGeometry2Buffers( geometry, hint ) {
  13409. if ( geometry.needsUpdate === false ) return;
  13410. var attributes = [ 'vertices', 'normals', 'uvs' ];
  13411. var buffers = _buffers[ geometry.id ];
  13412. for ( var key in attributes ) {
  13413. var array = geometry[ attributes[ key ] ];
  13414. var buffer = buffers[ attributes[ key ] ];
  13415. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  13416. _gl.bufferData( _gl.ARRAY_BUFFER, array, hint );
  13417. }
  13418. geometry.needsUpdate = false;
  13419. };
  13420. // Buffer rendering
  13421. this.renderBufferImmediate = function ( object, program, material ) {
  13422. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  13423. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  13424. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  13425. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  13426. if ( object.hasPositions ) {
  13427. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  13428. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  13429. _gl.enableVertexAttribArray( program.attributes.position );
  13430. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13431. }
  13432. if ( object.hasNormals ) {
  13433. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  13434. if ( material.shading === THREE.FlatShading ) {
  13435. var nx, ny, nz,
  13436. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  13437. normalArray,
  13438. i, il = object.count * 3;
  13439. for( i = 0; i < il; i += 9 ) {
  13440. normalArray = object.normalArray;
  13441. nax = normalArray[ i ];
  13442. nay = normalArray[ i + 1 ];
  13443. naz = normalArray[ i + 2 ];
  13444. nbx = normalArray[ i + 3 ];
  13445. nby = normalArray[ i + 4 ];
  13446. nbz = normalArray[ i + 5 ];
  13447. ncx = normalArray[ i + 6 ];
  13448. ncy = normalArray[ i + 7 ];
  13449. ncz = normalArray[ i + 8 ];
  13450. nx = ( nax + nbx + ncx ) / 3;
  13451. ny = ( nay + nby + ncy ) / 3;
  13452. nz = ( naz + nbz + ncz ) / 3;
  13453. normalArray[ i ] = nx;
  13454. normalArray[ i + 1 ] = ny;
  13455. normalArray[ i + 2 ] = nz;
  13456. normalArray[ i + 3 ] = nx;
  13457. normalArray[ i + 4 ] = ny;
  13458. normalArray[ i + 5 ] = nz;
  13459. normalArray[ i + 6 ] = nx;
  13460. normalArray[ i + 7 ] = ny;
  13461. normalArray[ i + 8 ] = nz;
  13462. }
  13463. }
  13464. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13465. _gl.enableVertexAttribArray( program.attributes.normal );
  13466. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13467. }
  13468. if ( object.hasUvs && material.map ) {
  13469. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13470. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13471. _gl.enableVertexAttribArray( program.attributes.uv );
  13472. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13473. }
  13474. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13475. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13476. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13477. _gl.enableVertexAttribArray( program.attributes.color );
  13478. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13479. }
  13480. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13481. object.count = 0;
  13482. };
  13483. this.renderBufferGeometry2 = function ( camera, lights, fog, material, geometry, object ) {
  13484. var program = setProgram( camera, lights, fog, material, object );
  13485. var programAttributes = program.attributes;
  13486. var attributes = { 'position': 'vertices', 'normal': 'normals', 'uv': 'uvs' };
  13487. var itemSizes = { 'position': 3, 'normal': 3, 'uv': 2 };
  13488. var buffers = _buffers[ geometry.id ];
  13489. disableAttributes();
  13490. for ( var name in programAttributes ) {
  13491. var attributePointer = programAttributes[ name ];
  13492. if ( attributePointer >= 0 ) {
  13493. var array = geometry[ attributes[ name ] ];
  13494. if ( array !== undefined && array.length > 0 ) {
  13495. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers[ attributes[ name ] ] );
  13496. enableAttribute( attributePointer );
  13497. _gl.vertexAttribPointer( attributePointer, itemSizes[ name ], _gl.FLOAT, false, 0, 0 );
  13498. } else {
  13499. if ( itemSizes[ name ] === 3 ) {
  13500. _gl.vertexAttrib3fv( attributePointer, [ 0, 0, 0 ] );
  13501. } else if ( itemSizes[ name ] === 2 ) {
  13502. _gl.vertexAttrib2fv( attributePointer, [ 0, 0 ] );
  13503. }
  13504. }
  13505. }
  13506. }
  13507. _gl.drawArrays( _gl.TRIANGLES, 0, geometry.vertices.length / 3 );
  13508. };
  13509. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  13510. if ( material.visible === false ) return;
  13511. var linewidth, a, attribute;
  13512. var attributeItem, attributeName, attributePointer, attributeSize;
  13513. var program = setProgram( camera, lights, fog, material, object );
  13514. var programAttributes = program.attributes;
  13515. var geometryAttributes = geometry.attributes;
  13516. var updateBuffers = false,
  13517. wireframeBit = material.wireframe ? 1 : 0,
  13518. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13519. if ( geometryHash !== _currentGeometryGroupHash ) {
  13520. _currentGeometryGroupHash = geometryHash;
  13521. updateBuffers = true;
  13522. }
  13523. if ( updateBuffers ) {
  13524. disableAttributes();
  13525. }
  13526. // render mesh
  13527. if ( object instanceof THREE.Mesh ) {
  13528. var index = geometryAttributes[ "index" ];
  13529. // indexed triangles
  13530. if ( index ) {
  13531. var offsets = geometry.offsets;
  13532. // if there is more than 1 chunk
  13533. // must set attribute pointers to use new offsets for each chunk
  13534. // even if geometry and materials didn't change
  13535. if ( offsets.length > 1 ) updateBuffers = true;
  13536. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13537. var startIndex = offsets[ i ].index;
  13538. if ( updateBuffers ) {
  13539. for ( attributeName in programAttributes ) {
  13540. attributePointer = programAttributes[ attributeName ];
  13541. attributeItem = geometryAttributes[ attributeName ];
  13542. if ( attributePointer >= 0 ) {
  13543. if ( attributeItem ) {
  13544. attributeSize = attributeItem.itemSize;
  13545. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13546. enableAttribute( attributePointer );
  13547. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13548. } else if ( material.defaultAttributeValues ) {
  13549. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13550. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13551. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13552. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13553. }
  13554. }
  13555. }
  13556. }
  13557. // indices
  13558. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13559. }
  13560. // render indexed triangles
  13561. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  13562. _this.info.render.calls ++;
  13563. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13564. _this.info.render.faces += offsets[ i ].count / 3;
  13565. }
  13566. // non-indexed triangles
  13567. } else {
  13568. if ( updateBuffers ) {
  13569. for ( attributeName in programAttributes ) {
  13570. if ( attributeName === 'index') continue;
  13571. attributePointer = programAttributes[ attributeName ];
  13572. attributeItem = geometryAttributes[ attributeName ];
  13573. if ( attributePointer >= 0 ) {
  13574. if ( attributeItem ) {
  13575. attributeSize = attributeItem.itemSize;
  13576. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13577. enableAttribute( attributePointer );
  13578. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13579. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  13580. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13581. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13582. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13583. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13584. }
  13585. }
  13586. }
  13587. }
  13588. }
  13589. var position = geometry.attributes[ "position" ];
  13590. // render non-indexed triangles
  13591. _gl.drawArrays( _gl.TRIANGLES, 0, position.array.length / 3 );
  13592. _this.info.render.calls ++;
  13593. _this.info.render.vertices += position.array.length / 3;
  13594. _this.info.render.faces += position.array.length / 3 / 3;
  13595. }
  13596. // render particles
  13597. } else if ( object instanceof THREE.ParticleSystem ) {
  13598. if ( updateBuffers ) {
  13599. for ( attributeName in programAttributes ) {
  13600. attributePointer = programAttributes[ attributeName ];
  13601. attributeItem = geometryAttributes[ attributeName ];
  13602. if ( attributePointer >= 0 ) {
  13603. if ( attributeItem ) {
  13604. attributeSize = attributeItem.itemSize;
  13605. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13606. enableAttribute( attributePointer );
  13607. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13608. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  13609. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13610. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13611. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13612. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13613. }
  13614. }
  13615. }
  13616. }
  13617. }
  13618. var position = geometryAttributes[ "position" ];
  13619. // render particles
  13620. _gl.drawArrays( _gl.POINTS, 0, position.array.length / 3 );
  13621. _this.info.render.calls ++;
  13622. _this.info.render.points += position.array.length / 3;
  13623. } else if ( object instanceof THREE.Line ) {
  13624. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13625. setLineWidth( material.linewidth );
  13626. var index = geometryAttributes[ "index" ];
  13627. // indexed lines
  13628. if ( index ) {
  13629. var offsets = geometry.offsets;
  13630. // if there is more than 1 chunk
  13631. // must set attribute pointers to use new offsets for each chunk
  13632. // even if geometry and materials didn't change
  13633. if ( offsets.length > 1 ) updateBuffers = true;
  13634. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13635. var startIndex = offsets[ i ].index;
  13636. if ( updateBuffers ) {
  13637. setupLinesVertexAttributes(material, programAttributes, geometryAttributes, startIndex);
  13638. // indices
  13639. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13640. }
  13641. // render indexed lines
  13642. _gl.drawElements( _gl.LINES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16Array
  13643. _this.info.render.calls ++;
  13644. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13645. }
  13646. }
  13647. // non-indexed lines
  13648. else {
  13649. if ( updateBuffers ) {
  13650. setupLinesVertexAttributes(material, programAttributes, geometryAttributes, 0);
  13651. }
  13652. var position = geometryAttributes[ "position" ];
  13653. _gl.drawArrays( primitives, 0, position.array.length / 3 );
  13654. _this.info.render.calls ++;
  13655. _this.info.render.points += position.array.length;
  13656. }
  13657. }
  13658. };
  13659. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  13660. if ( material.visible === false ) return;
  13661. var linewidth, a, attribute, i, il;
  13662. var program = setProgram( camera, lights, fog, material, object );
  13663. var attributes = program.attributes;
  13664. var updateBuffers = false,
  13665. wireframeBit = material.wireframe ? 1 : 0,
  13666. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13667. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  13668. _currentGeometryGroupHash = geometryGroupHash;
  13669. updateBuffers = true;
  13670. }
  13671. if ( updateBuffers ) {
  13672. disableAttributes();
  13673. }
  13674. // vertices
  13675. if ( !material.morphTargets && attributes.position >= 0 ) {
  13676. if ( updateBuffers ) {
  13677. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13678. enableAttribute( attributes.position );
  13679. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13680. }
  13681. } else {
  13682. if ( object.morphTargetBase ) {
  13683. setupMorphTargets( material, geometryGroup, object );
  13684. }
  13685. }
  13686. if ( updateBuffers ) {
  13687. // custom attributes
  13688. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  13689. if ( geometryGroup.__webglCustomAttributesList ) {
  13690. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  13691. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  13692. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  13693. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  13694. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  13695. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  13696. }
  13697. }
  13698. }
  13699. // colors
  13700. if ( attributes.color >= 0 ) {
  13701. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  13702. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13703. enableAttribute( attributes.color );
  13704. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13705. } else if ( material.defaultAttributeValues ) {
  13706. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  13707. }
  13708. }
  13709. // normals
  13710. if ( attributes.normal >= 0 ) {
  13711. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13712. enableAttribute( attributes.normal );
  13713. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13714. }
  13715. // tangents
  13716. if ( attributes.tangent >= 0 ) {
  13717. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13718. enableAttribute( attributes.tangent );
  13719. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  13720. }
  13721. // uvs
  13722. if ( attributes.uv >= 0 ) {
  13723. if ( object.geometry.faceVertexUvs[0] ) {
  13724. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13725. enableAttribute( attributes.uv );
  13726. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13727. } else if ( material.defaultAttributeValues ) {
  13728. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  13729. }
  13730. }
  13731. if ( attributes.uv2 >= 0 ) {
  13732. if ( object.geometry.faceVertexUvs[1] ) {
  13733. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13734. enableAttribute( attributes.uv2 );
  13735. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  13736. } else if ( material.defaultAttributeValues ) {
  13737. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  13738. }
  13739. }
  13740. if ( material.skinning &&
  13741. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  13742. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13743. enableAttribute( attributes.skinIndex );
  13744. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  13745. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13746. enableAttribute( attributes.skinWeight );
  13747. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  13748. }
  13749. // line distances
  13750. if ( attributes.lineDistance >= 0 ) {
  13751. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  13752. enableAttribute( attributes.lineDistance );
  13753. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  13754. }
  13755. }
  13756. // render mesh
  13757. if ( object instanceof THREE.Mesh ) {
  13758. // wireframe
  13759. if ( material.wireframe ) {
  13760. setLineWidth( material.wireframeLinewidth );
  13761. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13762. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  13763. // triangles
  13764. } else {
  13765. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13766. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  13767. }
  13768. _this.info.render.calls ++;
  13769. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  13770. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  13771. // render lines
  13772. } else if ( object instanceof THREE.Line ) {
  13773. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13774. setLineWidth( material.linewidth );
  13775. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  13776. _this.info.render.calls ++;
  13777. // render particles
  13778. } else if ( object instanceof THREE.ParticleSystem ) {
  13779. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  13780. _this.info.render.calls ++;
  13781. _this.info.render.points += geometryGroup.__webglParticleCount;
  13782. }
  13783. };
  13784. function enableAttribute( attribute ) {
  13785. if ( _enabledAttributes[ attribute ] === 0 ) {
  13786. _gl.enableVertexAttribArray( attribute );
  13787. _enabledAttributes[ attribute ] = 1;
  13788. }
  13789. };
  13790. function disableAttributes() {
  13791. for ( var attribute in _enabledAttributes ) {
  13792. if ( _enabledAttributes[ attribute ] === 1 ) {
  13793. _gl.disableVertexAttribArray( attribute );
  13794. _enabledAttributes[ attribute ] = 0;
  13795. }
  13796. }
  13797. };
  13798. function setupMorphTargets ( material, geometryGroup, object ) {
  13799. // set base
  13800. var attributes = material.program.attributes;
  13801. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  13802. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13803. enableAttribute( attributes.position );
  13804. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13805. } else if ( attributes.position >= 0 ) {
  13806. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13807. enableAttribute( attributes.position );
  13808. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13809. }
  13810. if ( object.morphTargetForcedOrder.length ) {
  13811. // set forced order
  13812. var m = 0;
  13813. var order = object.morphTargetForcedOrder;
  13814. var influences = object.morphTargetInfluences;
  13815. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13816. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13817. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13818. enableAttribute( attributes[ "morphTarget" + m ] );
  13819. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13820. }
  13821. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13822. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13823. enableAttribute( attributes[ "morphNormal" + m ] );
  13824. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13825. }
  13826. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13827. m ++;
  13828. }
  13829. } else {
  13830. // find the most influencing
  13831. var influence, activeInfluenceIndices = [];
  13832. var influences = object.morphTargetInfluences;
  13833. var i, il = influences.length;
  13834. for ( i = 0; i < il; i ++ ) {
  13835. influence = influences[ i ];
  13836. if ( influence > 0 ) {
  13837. activeInfluenceIndices.push( [ influence, i ] );
  13838. }
  13839. }
  13840. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13841. activeInfluenceIndices.sort( numericalSort );
  13842. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13843. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13844. activeInfluenceIndices.sort( numericalSort );
  13845. } else if ( activeInfluenceIndices.length === 0 ) {
  13846. activeInfluenceIndices.push( [ 0, 0 ] );
  13847. };
  13848. var influenceIndex, m = 0;
  13849. while ( m < material.numSupportedMorphTargets ) {
  13850. if ( activeInfluenceIndices[ m ] ) {
  13851. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13852. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13853. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13854. enableAttribute( attributes[ "morphTarget" + m ] );
  13855. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13856. }
  13857. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13858. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13859. enableAttribute( attributes[ "morphNormal" + m ] );
  13860. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13861. }
  13862. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13863. } else {
  13864. /*
  13865. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13866. if ( material.morphNormals ) {
  13867. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13868. }
  13869. */
  13870. object.__webglMorphTargetInfluences[ m ] = 0;
  13871. }
  13872. m ++;
  13873. }
  13874. }
  13875. // load updated influences uniform
  13876. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13877. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13878. }
  13879. };
  13880. // Sorting
  13881. function painterSortStable ( a, b ) {
  13882. if ( a.z !== b.z ) {
  13883. return b.z - a.z;
  13884. } else {
  13885. return a.id - b.id;
  13886. }
  13887. };
  13888. function numericalSort ( a, b ) {
  13889. return b[ 0 ] - a[ 0 ];
  13890. };
  13891. // Rendering
  13892. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13893. if ( camera instanceof THREE.Camera === false ) {
  13894. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13895. return;
  13896. }
  13897. var i, il,
  13898. webglObject, object,
  13899. renderList,
  13900. lights = scene.__lights,
  13901. fog = scene.fog;
  13902. // reset caching for this frame
  13903. _currentMaterialId = -1;
  13904. _lightsNeedUpdate = true;
  13905. // update scene graph
  13906. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  13907. // update camera matrices and frustum
  13908. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  13909. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13910. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13911. _frustum.setFromMatrix( _projScreenMatrix );
  13912. // update WebGL objects
  13913. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  13914. // custom render plugins (pre pass)
  13915. renderPlugins( this.renderPluginsPre, scene, camera );
  13916. //
  13917. _this.info.render.calls = 0;
  13918. _this.info.render.vertices = 0;
  13919. _this.info.render.faces = 0;
  13920. _this.info.render.points = 0;
  13921. this.setRenderTarget( renderTarget );
  13922. if ( this.autoClear || forceClear ) {
  13923. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13924. }
  13925. // set matrices for regular objects (frustum culled)
  13926. renderList = scene.__webglObjects;
  13927. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13928. webglObject = renderList[ i ];
  13929. object = webglObject.object;
  13930. webglObject.id = i;
  13931. webglObject.render = false;
  13932. if ( object.visible ) {
  13933. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  13934. setupMatrices( object, camera );
  13935. unrollBufferMaterial( webglObject );
  13936. webglObject.render = true;
  13937. if ( this.sortObjects === true ) {
  13938. if ( object.renderDepth !== null ) {
  13939. webglObject.z = object.renderDepth;
  13940. } else {
  13941. _vector3.setFromMatrixPosition( object.matrixWorld );
  13942. _vector3.applyProjection( _projScreenMatrix );
  13943. webglObject.z = _vector3.z;
  13944. }
  13945. }
  13946. }
  13947. }
  13948. }
  13949. if ( this.sortObjects ) {
  13950. renderList.sort( painterSortStable );
  13951. }
  13952. // set matrices for immediate objects
  13953. renderList = scene.__webglObjectsImmediate;
  13954. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13955. webglObject = renderList[ i ];
  13956. object = webglObject.object;
  13957. if ( object.visible ) {
  13958. setupMatrices( object, camera );
  13959. unrollImmediateBufferMaterial( webglObject );
  13960. }
  13961. }
  13962. if ( scene.overrideMaterial ) {
  13963. var material = scene.overrideMaterial;
  13964. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13965. this.setDepthTest( material.depthTest );
  13966. this.setDepthWrite( material.depthWrite );
  13967. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13968. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  13969. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  13970. } else {
  13971. var material = null;
  13972. // opaque pass (front-to-back order)
  13973. this.setBlending( THREE.NoBlending );
  13974. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  13975. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  13976. // transparent pass (back-to-front order)
  13977. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  13978. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  13979. }
  13980. // custom render plugins (post pass)
  13981. renderPlugins( this.renderPluginsPost, scene, camera );
  13982. // Generate mipmap if we're using any kind of mipmap filtering
  13983. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  13984. updateRenderTargetMipmap( renderTarget );
  13985. }
  13986. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13987. this.setDepthTest( true );
  13988. this.setDepthWrite( true );
  13989. // _gl.finish();
  13990. };
  13991. function renderPlugins( plugins, scene, camera ) {
  13992. if ( ! plugins.length ) return;
  13993. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  13994. // reset state for plugin (to start from clean slate)
  13995. _currentProgram = null;
  13996. _currentCamera = null;
  13997. _oldBlending = -1;
  13998. _oldDepthTest = -1;
  13999. _oldDepthWrite = -1;
  14000. _oldDoubleSided = -1;
  14001. _oldFlipSided = -1;
  14002. _currentGeometryGroupHash = -1;
  14003. _currentMaterialId = -1;
  14004. _lightsNeedUpdate = true;
  14005. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  14006. // reset state after plugin (anything could have changed)
  14007. _currentProgram = null;
  14008. _currentCamera = null;
  14009. _oldBlending = -1;
  14010. _oldDepthTest = -1;
  14011. _oldDepthWrite = -1;
  14012. _oldDoubleSided = -1;
  14013. _oldFlipSided = -1;
  14014. _currentGeometryGroupHash = -1;
  14015. _currentMaterialId = -1;
  14016. _lightsNeedUpdate = true;
  14017. }
  14018. };
  14019. function renderObjects( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  14020. var webglObject, object, buffer, material, start, end, delta;
  14021. if ( reverse ) {
  14022. start = renderList.length - 1;
  14023. end = -1;
  14024. delta = -1;
  14025. } else {
  14026. start = 0;
  14027. end = renderList.length;
  14028. delta = 1;
  14029. }
  14030. for ( var i = start; i !== end; i += delta ) {
  14031. webglObject = renderList[ i ];
  14032. if ( webglObject.render ) {
  14033. object = webglObject.object;
  14034. buffer = webglObject.buffer;
  14035. if ( overrideMaterial ) {
  14036. material = overrideMaterial;
  14037. } else {
  14038. material = webglObject[ materialType ];
  14039. if ( ! material ) continue;
  14040. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  14041. _this.setDepthTest( material.depthTest );
  14042. _this.setDepthWrite( material.depthWrite );
  14043. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14044. }
  14045. _this.setMaterialFaces( material );
  14046. if ( buffer instanceof THREE.BufferGeometry ) {
  14047. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  14048. } else if ( buffer instanceof THREE.Geometry2 ) {
  14049. _this.renderBufferGeometry2( camera, lights, fog, material, buffer, object );
  14050. } else {
  14051. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  14052. }
  14053. }
  14054. }
  14055. };
  14056. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  14057. var webglObject, object, material, program;
  14058. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  14059. webglObject = renderList[ i ];
  14060. object = webglObject.object;
  14061. if ( object.visible ) {
  14062. if ( overrideMaterial ) {
  14063. material = overrideMaterial;
  14064. } else {
  14065. material = webglObject[ materialType ];
  14066. if ( ! material ) continue;
  14067. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  14068. _this.setDepthTest( material.depthTest );
  14069. _this.setDepthWrite( material.depthWrite );
  14070. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14071. }
  14072. _this.renderImmediateObject( camera, lights, fog, material, object );
  14073. }
  14074. }
  14075. };
  14076. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  14077. var program = setProgram( camera, lights, fog, material, object );
  14078. _currentGeometryGroupHash = -1;
  14079. _this.setMaterialFaces( material );
  14080. if ( object.immediateRenderCallback ) {
  14081. object.immediateRenderCallback( program, _gl, _frustum );
  14082. } else {
  14083. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  14084. }
  14085. };
  14086. function unrollImmediateBufferMaterial ( globject ) {
  14087. var object = globject.object,
  14088. material = object.material;
  14089. if ( material.transparent ) {
  14090. globject.transparent = material;
  14091. globject.opaque = null;
  14092. } else {
  14093. globject.opaque = material;
  14094. globject.transparent = null;
  14095. }
  14096. };
  14097. function unrollBufferMaterial ( globject ) {
  14098. var object = globject.object;
  14099. var buffer = globject.buffer;
  14100. var geometry = object.geometry;
  14101. var material = object.material;
  14102. if ( material instanceof THREE.MeshFaceMaterial ) {
  14103. var materialIndex = geometry instanceof THREE.BufferGeometry ? 0 : buffer.materialIndex;
  14104. material = material.materials[ materialIndex ];
  14105. if ( material.transparent ) {
  14106. globject.transparent = material;
  14107. globject.opaque = null;
  14108. } else {
  14109. globject.opaque = material;
  14110. globject.transparent = null;
  14111. }
  14112. } else {
  14113. if ( material ) {
  14114. if ( material.transparent ) {
  14115. globject.transparent = material;
  14116. globject.opaque = null;
  14117. } else {
  14118. globject.opaque = material;
  14119. globject.transparent = null;
  14120. }
  14121. }
  14122. }
  14123. };
  14124. // Geometry splitting
  14125. function sortFacesByMaterial ( geometry, material ) {
  14126. var f, fl, face, materialIndex, vertices,
  14127. groupHash, hash_map = {};
  14128. var numMorphTargets = geometry.morphTargets.length;
  14129. var numMorphNormals = geometry.morphNormals.length;
  14130. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  14131. geometry.geometryGroups = {};
  14132. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  14133. face = geometry.faces[ f ];
  14134. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  14135. if ( hash_map[ materialIndex ] === undefined ) {
  14136. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  14137. }
  14138. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  14139. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  14140. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  14141. }
  14142. vertices = 3;
  14143. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  14144. hash_map[ materialIndex ].counter += 1;
  14145. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  14146. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  14147. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  14148. }
  14149. }
  14150. geometry.geometryGroups[ groupHash ].faces3.push( f );
  14151. geometry.geometryGroups[ groupHash ].vertices += vertices;
  14152. }
  14153. geometry.geometryGroupsList = [];
  14154. for ( var g in geometry.geometryGroups ) {
  14155. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  14156. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  14157. }
  14158. };
  14159. // Objects refresh
  14160. this.initWebGLObjects = function ( scene ) {
  14161. if ( !scene.__webglObjects ) {
  14162. scene.__webglObjects = [];
  14163. scene.__webglObjectsImmediate = [];
  14164. scene.__webglSprites = [];
  14165. scene.__webglFlares = [];
  14166. }
  14167. while ( scene.__objectsAdded.length ) {
  14168. addObject( scene.__objectsAdded[ 0 ], scene );
  14169. scene.__objectsAdded.splice( 0, 1 );
  14170. }
  14171. while ( scene.__objectsRemoved.length ) {
  14172. removeObject( scene.__objectsRemoved[ 0 ], scene );
  14173. scene.__objectsRemoved.splice( 0, 1 );
  14174. }
  14175. // update must be called after objects adding / removal
  14176. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  14177. var object = scene.__webglObjects[ o ].object;
  14178. // TODO: Remove this hack (WebGLRenderer refactoring)
  14179. if ( object.__webglInit === undefined ) {
  14180. if ( object.__webglActive !== undefined ) {
  14181. removeObject( object, scene );
  14182. }
  14183. addObject( object, scene );
  14184. }
  14185. updateObject( object );
  14186. }
  14187. };
  14188. // Objects adding
  14189. function addObject( object, scene ) {
  14190. var g, geometry, material, geometryGroup;
  14191. if ( object.__webglInit === undefined ) {
  14192. object.__webglInit = true;
  14193. object._modelViewMatrix = new THREE.Matrix4();
  14194. object._normalMatrix = new THREE.Matrix3();
  14195. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  14196. object.geometry.__webglInit = true;
  14197. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  14198. }
  14199. geometry = object.geometry;
  14200. if ( geometry === undefined ) {
  14201. // fail silently for now
  14202. } else if ( geometry instanceof THREE.BufferGeometry ) {
  14203. initDirectBuffers( geometry );
  14204. } else if ( geometry instanceof THREE.Geometry2 ) {
  14205. initGeometry2Buffers( geometry );
  14206. } else if ( object instanceof THREE.Mesh ) {
  14207. material = object.material;
  14208. if ( geometry.geometryGroups === undefined ) {
  14209. sortFacesByMaterial( geometry, material );
  14210. }
  14211. // create separate VBOs per geometry chunk
  14212. for ( g in geometry.geometryGroups ) {
  14213. geometryGroup = geometry.geometryGroups[ g ];
  14214. // initialise VBO on the first access
  14215. if ( ! geometryGroup.__webglVertexBuffer ) {
  14216. createMeshBuffers( geometryGroup );
  14217. initMeshBuffers( geometryGroup, object );
  14218. geometry.verticesNeedUpdate = true;
  14219. geometry.morphTargetsNeedUpdate = true;
  14220. geometry.elementsNeedUpdate = true;
  14221. geometry.uvsNeedUpdate = true;
  14222. geometry.normalsNeedUpdate = true;
  14223. geometry.tangentsNeedUpdate = true;
  14224. geometry.colorsNeedUpdate = true;
  14225. }
  14226. }
  14227. } else if ( object instanceof THREE.Line ) {
  14228. if ( ! geometry.__webglVertexBuffer ) {
  14229. createLineBuffers( geometry );
  14230. initLineBuffers( geometry, object );
  14231. geometry.verticesNeedUpdate = true;
  14232. geometry.colorsNeedUpdate = true;
  14233. geometry.lineDistancesNeedUpdate = true;
  14234. }
  14235. } else if ( object instanceof THREE.ParticleSystem ) {
  14236. if ( ! geometry.__webglVertexBuffer ) {
  14237. createParticleBuffers( geometry );
  14238. initParticleBuffers( geometry, object );
  14239. geometry.verticesNeedUpdate = true;
  14240. geometry.colorsNeedUpdate = true;
  14241. }
  14242. }
  14243. }
  14244. if ( object.__webglActive === undefined ) {
  14245. if ( object instanceof THREE.Mesh ) {
  14246. geometry = object.geometry;
  14247. if ( geometry instanceof THREE.BufferGeometry ) {
  14248. addBuffer( scene.__webglObjects, geometry, object );
  14249. } else if ( geometry instanceof THREE.Geometry2 ) {
  14250. addBuffer( scene.__webglObjects, geometry, object );
  14251. } else if ( geometry instanceof THREE.Geometry ) {
  14252. for ( g in geometry.geometryGroups ) {
  14253. geometryGroup = geometry.geometryGroups[ g ];
  14254. addBuffer( scene.__webglObjects, geometryGroup, object );
  14255. }
  14256. }
  14257. } else if ( object instanceof THREE.Line ||
  14258. object instanceof THREE.ParticleSystem ) {
  14259. geometry = object.geometry;
  14260. addBuffer( scene.__webglObjects, geometry, object );
  14261. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14262. addBufferImmediate( scene.__webglObjectsImmediate, object );
  14263. } else if ( object instanceof THREE.Sprite ) {
  14264. scene.__webglSprites.push( object );
  14265. } else if ( object instanceof THREE.LensFlare ) {
  14266. scene.__webglFlares.push( object );
  14267. }
  14268. object.__webglActive = true;
  14269. }
  14270. };
  14271. function addBuffer( objlist, buffer, object ) {
  14272. objlist.push(
  14273. {
  14274. id: null,
  14275. buffer: buffer,
  14276. object: object,
  14277. opaque: null,
  14278. transparent: null,
  14279. z: 0
  14280. }
  14281. );
  14282. };
  14283. function addBufferImmediate( objlist, object ) {
  14284. objlist.push(
  14285. {
  14286. id: null,
  14287. object: object,
  14288. opaque: null,
  14289. transparent: null,
  14290. z: 0
  14291. }
  14292. );
  14293. };
  14294. // Objects updates
  14295. function updateObject( object ) {
  14296. var geometry = object.geometry,
  14297. geometryGroup, customAttributesDirty, material;
  14298. if ( geometry instanceof THREE.BufferGeometry ) {
  14299. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW );
  14300. } else if ( geometry instanceof THREE.Geometry2 ) {
  14301. setGeometry2Buffers( geometry, _gl.DYNAMIC_DRAW );
  14302. } else if ( object instanceof THREE.Mesh ) {
  14303. // check all geometry groups
  14304. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  14305. geometryGroup = geometry.geometryGroupsList[ i ];
  14306. material = getBufferMaterial( object, geometryGroup );
  14307. if ( geometry.buffersNeedUpdate ) {
  14308. initMeshBuffers( geometryGroup, object );
  14309. }
  14310. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14311. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  14312. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  14313. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  14314. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  14315. }
  14316. }
  14317. geometry.verticesNeedUpdate = false;
  14318. geometry.morphTargetsNeedUpdate = false;
  14319. geometry.elementsNeedUpdate = false;
  14320. geometry.uvsNeedUpdate = false;
  14321. geometry.normalsNeedUpdate = false;
  14322. geometry.colorsNeedUpdate = false;
  14323. geometry.tangentsNeedUpdate = false;
  14324. geometry.buffersNeedUpdate = false;
  14325. material.attributes && clearCustomAttributes( material );
  14326. } else if ( object instanceof THREE.Line ) {
  14327. material = getBufferMaterial( object, geometry );
  14328. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14329. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  14330. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  14331. }
  14332. geometry.verticesNeedUpdate = false;
  14333. geometry.colorsNeedUpdate = false;
  14334. geometry.lineDistancesNeedUpdate = false;
  14335. material.attributes && clearCustomAttributes( material );
  14336. } else if ( object instanceof THREE.ParticleSystem ) {
  14337. material = getBufferMaterial( object, geometry );
  14338. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14339. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  14340. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  14341. }
  14342. geometry.verticesNeedUpdate = false;
  14343. geometry.colorsNeedUpdate = false;
  14344. material.attributes && clearCustomAttributes( material );
  14345. }
  14346. };
  14347. // Objects updates - custom attributes check
  14348. function areCustomAttributesDirty( material ) {
  14349. for ( var a in material.attributes ) {
  14350. if ( material.attributes[ a ].needsUpdate ) return true;
  14351. }
  14352. return false;
  14353. };
  14354. function clearCustomAttributes( material ) {
  14355. for ( var a in material.attributes ) {
  14356. material.attributes[ a ].needsUpdate = false;
  14357. }
  14358. };
  14359. // Objects removal
  14360. function removeObject( object, scene ) {
  14361. if ( object instanceof THREE.Mesh ||
  14362. object instanceof THREE.ParticleSystem ||
  14363. object instanceof THREE.Line ) {
  14364. removeInstances( scene.__webglObjects, object );
  14365. } else if ( object instanceof THREE.Sprite ) {
  14366. removeInstancesDirect( scene.__webglSprites, object );
  14367. } else if ( object instanceof THREE.LensFlare ) {
  14368. removeInstancesDirect( scene.__webglFlares, object );
  14369. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14370. removeInstances( scene.__webglObjectsImmediate, object );
  14371. }
  14372. delete object.__webglActive;
  14373. };
  14374. function removeInstances( objlist, object ) {
  14375. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14376. if ( objlist[ o ].object === object ) {
  14377. objlist.splice( o, 1 );
  14378. }
  14379. }
  14380. };
  14381. function removeInstancesDirect( objlist, object ) {
  14382. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14383. if ( objlist[ o ] === object ) {
  14384. objlist.splice( o, 1 );
  14385. }
  14386. }
  14387. };
  14388. // Materials
  14389. this.initMaterial = function ( material, lights, fog, object ) {
  14390. material.addEventListener( 'dispose', onMaterialDispose );
  14391. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  14392. if ( material instanceof THREE.MeshDepthMaterial ) {
  14393. shaderID = 'depth';
  14394. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14395. shaderID = 'normal';
  14396. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  14397. shaderID = 'basic';
  14398. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14399. shaderID = 'lambert';
  14400. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14401. shaderID = 'phong';
  14402. } else if ( material instanceof THREE.LineBasicMaterial ) {
  14403. shaderID = 'basic';
  14404. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14405. shaderID = 'dashed';
  14406. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  14407. shaderID = 'particle_basic';
  14408. }
  14409. if ( shaderID ) {
  14410. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  14411. }
  14412. // heuristics to create shader parameters according to lights in the scene
  14413. // (not to blow over maxLights budget)
  14414. maxLightCount = allocateLights( lights );
  14415. maxShadows = allocateShadows( lights );
  14416. maxBones = allocateBones( object );
  14417. parameters = {
  14418. map: !!material.map,
  14419. envMap: !!material.envMap,
  14420. lightMap: !!material.lightMap,
  14421. bumpMap: !!material.bumpMap,
  14422. normalMap: !!material.normalMap,
  14423. specularMap: !!material.specularMap,
  14424. vertexColors: material.vertexColors,
  14425. fog: fog,
  14426. useFog: material.fog,
  14427. fogExp: fog instanceof THREE.FogExp2,
  14428. sizeAttenuation: material.sizeAttenuation,
  14429. skinning: material.skinning,
  14430. maxBones: maxBones,
  14431. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  14432. morphTargets: material.morphTargets,
  14433. morphNormals: material.morphNormals,
  14434. maxMorphTargets: this.maxMorphTargets,
  14435. maxMorphNormals: this.maxMorphNormals,
  14436. maxDirLights: maxLightCount.directional,
  14437. maxPointLights: maxLightCount.point,
  14438. maxSpotLights: maxLightCount.spot,
  14439. maxHemiLights: maxLightCount.hemi,
  14440. maxShadows: maxShadows,
  14441. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  14442. shadowMapType: this.shadowMapType,
  14443. shadowMapDebug: this.shadowMapDebug,
  14444. shadowMapCascade: this.shadowMapCascade,
  14445. alphaTest: material.alphaTest,
  14446. metal: material.metal,
  14447. wrapAround: material.wrapAround,
  14448. doubleSided: material.side === THREE.DoubleSide,
  14449. flipSided: material.side === THREE.BackSide
  14450. };
  14451. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters, material.index0AttributeName );
  14452. var attributes = material.program.attributes;
  14453. if ( material.morphTargets ) {
  14454. material.numSupportedMorphTargets = 0;
  14455. var id, base = "morphTarget";
  14456. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  14457. id = base + i;
  14458. if ( attributes[ id ] >= 0 ) {
  14459. material.numSupportedMorphTargets ++;
  14460. }
  14461. }
  14462. }
  14463. if ( material.morphNormals ) {
  14464. material.numSupportedMorphNormals = 0;
  14465. var id, base = "morphNormal";
  14466. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  14467. id = base + i;
  14468. if ( attributes[ id ] >= 0 ) {
  14469. material.numSupportedMorphNormals ++;
  14470. }
  14471. }
  14472. }
  14473. material.uniformsList = [];
  14474. for ( u in material.uniforms ) {
  14475. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  14476. }
  14477. };
  14478. function setMaterialShaders( material, shaders ) {
  14479. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  14480. material.vertexShader = shaders.vertexShader;
  14481. material.fragmentShader = shaders.fragmentShader;
  14482. };
  14483. function setProgram( camera, lights, fog, material, object ) {
  14484. _usedTextureUnits = 0;
  14485. if ( material.needsUpdate ) {
  14486. if ( material.program ) deallocateMaterial( material );
  14487. _this.initMaterial( material, lights, fog, object );
  14488. material.needsUpdate = false;
  14489. }
  14490. if ( material.morphTargets ) {
  14491. if ( ! object.__webglMorphTargetInfluences ) {
  14492. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  14493. }
  14494. }
  14495. var refreshMaterial = false;
  14496. var program = material.program,
  14497. p_uniforms = program.uniforms,
  14498. m_uniforms = material.uniforms;
  14499. if ( program !== _currentProgram ) {
  14500. _gl.useProgram( program );
  14501. _currentProgram = program;
  14502. refreshMaterial = true;
  14503. }
  14504. if ( material.id !== _currentMaterialId ) {
  14505. _currentMaterialId = material.id;
  14506. refreshMaterial = true;
  14507. }
  14508. if ( refreshMaterial || camera !== _currentCamera ) {
  14509. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  14510. if ( camera !== _currentCamera ) _currentCamera = camera;
  14511. }
  14512. // skinning uniforms must be set even if material didn't change
  14513. // auto-setting of texture unit for bone texture must go before other textures
  14514. // not sure why, but otherwise weird things happen
  14515. if ( material.skinning ) {
  14516. if ( _supportsBoneTextures && object.useVertexTexture ) {
  14517. if ( p_uniforms.boneTexture !== null ) {
  14518. var textureUnit = getTextureUnit();
  14519. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  14520. _this.setTexture( object.boneTexture, textureUnit );
  14521. }
  14522. if ( p_uniforms.boneTextureWidth !== null ) {
  14523. _gl.uniform1i( p_uniforms.boneTextureWidth, object.boneTextureWidth );
  14524. }
  14525. if ( p_uniforms.boneTextureHeight !== null ) {
  14526. _gl.uniform1i( p_uniforms.boneTextureHeight, object.boneTextureHeight );
  14527. }
  14528. } else {
  14529. if ( p_uniforms.boneGlobalMatrices !== null ) {
  14530. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  14531. }
  14532. }
  14533. }
  14534. if ( refreshMaterial ) {
  14535. // refresh uniforms common to several materials
  14536. if ( fog && material.fog ) {
  14537. refreshUniformsFog( m_uniforms, fog );
  14538. }
  14539. if ( material instanceof THREE.MeshPhongMaterial ||
  14540. material instanceof THREE.MeshLambertMaterial ||
  14541. material.lights ) {
  14542. if ( _lightsNeedUpdate ) {
  14543. setupLights( program, lights );
  14544. _lightsNeedUpdate = false;
  14545. }
  14546. refreshUniformsLights( m_uniforms, _lights );
  14547. }
  14548. if ( material instanceof THREE.MeshBasicMaterial ||
  14549. material instanceof THREE.MeshLambertMaterial ||
  14550. material instanceof THREE.MeshPhongMaterial ) {
  14551. refreshUniformsCommon( m_uniforms, material );
  14552. }
  14553. // refresh single material specific uniforms
  14554. if ( material instanceof THREE.LineBasicMaterial ) {
  14555. refreshUniformsLine( m_uniforms, material );
  14556. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14557. refreshUniformsLine( m_uniforms, material );
  14558. refreshUniformsDash( m_uniforms, material );
  14559. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  14560. refreshUniformsParticle( m_uniforms, material );
  14561. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14562. refreshUniformsPhong( m_uniforms, material );
  14563. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14564. refreshUniformsLambert( m_uniforms, material );
  14565. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  14566. m_uniforms.mNear.value = camera.near;
  14567. m_uniforms.mFar.value = camera.far;
  14568. m_uniforms.opacity.value = material.opacity;
  14569. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14570. m_uniforms.opacity.value = material.opacity;
  14571. }
  14572. if ( object.receiveShadow && ! material._shadowPass ) {
  14573. refreshUniformsShadow( m_uniforms, lights );
  14574. }
  14575. // load common uniforms
  14576. loadUniformsGeneric( program, material.uniformsList );
  14577. // load material specific uniforms
  14578. // (shader material also gets them for the sake of genericity)
  14579. if ( material instanceof THREE.ShaderMaterial ||
  14580. material instanceof THREE.MeshPhongMaterial ||
  14581. material.envMap ) {
  14582. if ( p_uniforms.cameraPosition !== null ) {
  14583. _vector3.setFromMatrixPosition( camera.matrixWorld );
  14584. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  14585. }
  14586. }
  14587. if ( material instanceof THREE.MeshPhongMaterial ||
  14588. material instanceof THREE.MeshLambertMaterial ||
  14589. material instanceof THREE.ShaderMaterial ||
  14590. material.skinning ) {
  14591. if ( p_uniforms.viewMatrix !== null ) {
  14592. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  14593. }
  14594. }
  14595. }
  14596. loadUniformsMatrices( p_uniforms, object );
  14597. if ( p_uniforms.modelMatrix !== null ) {
  14598. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  14599. }
  14600. return program;
  14601. };
  14602. // Uniforms (refresh uniforms objects)
  14603. function refreshUniformsCommon ( uniforms, material ) {
  14604. uniforms.opacity.value = material.opacity;
  14605. if ( _this.gammaInput ) {
  14606. uniforms.diffuse.value.copyGammaToLinear( material.color );
  14607. } else {
  14608. uniforms.diffuse.value = material.color;
  14609. }
  14610. uniforms.map.value = material.map;
  14611. uniforms.lightMap.value = material.lightMap;
  14612. uniforms.specularMap.value = material.specularMap;
  14613. if ( material.bumpMap ) {
  14614. uniforms.bumpMap.value = material.bumpMap;
  14615. uniforms.bumpScale.value = material.bumpScale;
  14616. }
  14617. if ( material.normalMap ) {
  14618. uniforms.normalMap.value = material.normalMap;
  14619. uniforms.normalScale.value.copy( material.normalScale );
  14620. }
  14621. // uv repeat and offset setting priorities
  14622. // 1. color map
  14623. // 2. specular map
  14624. // 3. normal map
  14625. // 4. bump map
  14626. var uvScaleMap;
  14627. if ( material.map ) {
  14628. uvScaleMap = material.map;
  14629. } else if ( material.specularMap ) {
  14630. uvScaleMap = material.specularMap;
  14631. } else if ( material.normalMap ) {
  14632. uvScaleMap = material.normalMap;
  14633. } else if ( material.bumpMap ) {
  14634. uvScaleMap = material.bumpMap;
  14635. }
  14636. if ( uvScaleMap !== undefined ) {
  14637. var offset = uvScaleMap.offset;
  14638. var repeat = uvScaleMap.repeat;
  14639. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  14640. }
  14641. uniforms.envMap.value = material.envMap;
  14642. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  14643. if ( _this.gammaInput ) {
  14644. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  14645. uniforms.reflectivity.value = material.reflectivity;
  14646. } else {
  14647. uniforms.reflectivity.value = material.reflectivity;
  14648. }
  14649. uniforms.refractionRatio.value = material.refractionRatio;
  14650. uniforms.combine.value = material.combine;
  14651. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  14652. };
  14653. function refreshUniformsLine ( uniforms, material ) {
  14654. uniforms.diffuse.value = material.color;
  14655. uniforms.opacity.value = material.opacity;
  14656. };
  14657. function refreshUniformsDash ( uniforms, material ) {
  14658. uniforms.dashSize.value = material.dashSize;
  14659. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14660. uniforms.scale.value = material.scale;
  14661. };
  14662. function refreshUniformsParticle ( uniforms, material ) {
  14663. uniforms.psColor.value = material.color;
  14664. uniforms.opacity.value = material.opacity;
  14665. uniforms.size.value = material.size;
  14666. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  14667. uniforms.map.value = material.map;
  14668. };
  14669. function refreshUniformsFog ( uniforms, fog ) {
  14670. uniforms.fogColor.value = fog.color;
  14671. if ( fog instanceof THREE.Fog ) {
  14672. uniforms.fogNear.value = fog.near;
  14673. uniforms.fogFar.value = fog.far;
  14674. } else if ( fog instanceof THREE.FogExp2 ) {
  14675. uniforms.fogDensity.value = fog.density;
  14676. }
  14677. };
  14678. function refreshUniformsPhong ( uniforms, material ) {
  14679. uniforms.shininess.value = material.shininess;
  14680. if ( _this.gammaInput ) {
  14681. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14682. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14683. uniforms.specular.value.copyGammaToLinear( material.specular );
  14684. } else {
  14685. uniforms.ambient.value = material.ambient;
  14686. uniforms.emissive.value = material.emissive;
  14687. uniforms.specular.value = material.specular;
  14688. }
  14689. if ( material.wrapAround ) {
  14690. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14691. }
  14692. };
  14693. function refreshUniformsLambert ( uniforms, material ) {
  14694. if ( _this.gammaInput ) {
  14695. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14696. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14697. } else {
  14698. uniforms.ambient.value = material.ambient;
  14699. uniforms.emissive.value = material.emissive;
  14700. }
  14701. if ( material.wrapAround ) {
  14702. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14703. }
  14704. };
  14705. function refreshUniformsLights ( uniforms, lights ) {
  14706. uniforms.ambientLightColor.value = lights.ambient;
  14707. uniforms.directionalLightColor.value = lights.directional.colors;
  14708. uniforms.directionalLightDirection.value = lights.directional.positions;
  14709. uniforms.pointLightColor.value = lights.point.colors;
  14710. uniforms.pointLightPosition.value = lights.point.positions;
  14711. uniforms.pointLightDistance.value = lights.point.distances;
  14712. uniforms.spotLightColor.value = lights.spot.colors;
  14713. uniforms.spotLightPosition.value = lights.spot.positions;
  14714. uniforms.spotLightDistance.value = lights.spot.distances;
  14715. uniforms.spotLightDirection.value = lights.spot.directions;
  14716. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  14717. uniforms.spotLightExponent.value = lights.spot.exponents;
  14718. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  14719. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  14720. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  14721. };
  14722. function refreshUniformsShadow ( uniforms, lights ) {
  14723. if ( uniforms.shadowMatrix ) {
  14724. var j = 0;
  14725. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14726. var light = lights[ i ];
  14727. if ( ! light.castShadow ) continue;
  14728. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  14729. uniforms.shadowMap.value[ j ] = light.shadowMap;
  14730. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  14731. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  14732. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  14733. uniforms.shadowBias.value[ j ] = light.shadowBias;
  14734. j ++;
  14735. }
  14736. }
  14737. }
  14738. };
  14739. // Uniforms (load to GPU)
  14740. function loadUniformsMatrices ( uniforms, object ) {
  14741. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14742. if ( uniforms.normalMatrix ) {
  14743. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14744. }
  14745. };
  14746. function getTextureUnit() {
  14747. var textureUnit = _usedTextureUnits;
  14748. if ( textureUnit >= _maxTextures ) {
  14749. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  14750. }
  14751. _usedTextureUnits += 1;
  14752. return textureUnit;
  14753. };
  14754. function loadUniformsGeneric ( program, uniforms ) {
  14755. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  14756. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14757. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14758. if ( !location ) continue;
  14759. uniform = uniforms[ j ][ 0 ];
  14760. type = uniform.type;
  14761. value = uniform.value;
  14762. if ( type === "i" ) { // single integer
  14763. _gl.uniform1i( location, value );
  14764. } else if ( type === "f" ) { // single float
  14765. _gl.uniform1f( location, value );
  14766. } else if ( type === "v2" ) { // single THREE.Vector2
  14767. _gl.uniform2f( location, value.x, value.y );
  14768. } else if ( type === "v3" ) { // single THREE.Vector3
  14769. _gl.uniform3f( location, value.x, value.y, value.z );
  14770. } else if ( type === "v4" ) { // single THREE.Vector4
  14771. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14772. } else if ( type === "c" ) { // single THREE.Color
  14773. _gl.uniform3f( location, value.r, value.g, value.b );
  14774. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  14775. _gl.uniform1iv( location, value );
  14776. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  14777. _gl.uniform3iv( location, value );
  14778. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  14779. _gl.uniform1fv( location, value );
  14780. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  14781. _gl.uniform3fv( location, value );
  14782. } else if ( type === "v2v" ) { // array of THREE.Vector2
  14783. if ( uniform._array === undefined ) {
  14784. uniform._array = new Float32Array( 2 * value.length );
  14785. }
  14786. for ( i = 0, il = value.length; i < il; i ++ ) {
  14787. offset = i * 2;
  14788. uniform._array[ offset ] = value[ i ].x;
  14789. uniform._array[ offset + 1 ] = value[ i ].y;
  14790. }
  14791. _gl.uniform2fv( location, uniform._array );
  14792. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14793. if ( uniform._array === undefined ) {
  14794. uniform._array = new Float32Array( 3 * value.length );
  14795. }
  14796. for ( i = 0, il = value.length; i < il; i ++ ) {
  14797. offset = i * 3;
  14798. uniform._array[ offset ] = value[ i ].x;
  14799. uniform._array[ offset + 1 ] = value[ i ].y;
  14800. uniform._array[ offset + 2 ] = value[ i ].z;
  14801. }
  14802. _gl.uniform3fv( location, uniform._array );
  14803. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14804. if ( uniform._array === undefined ) {
  14805. uniform._array = new Float32Array( 4 * value.length );
  14806. }
  14807. for ( i = 0, il = value.length; i < il; i ++ ) {
  14808. offset = i * 4;
  14809. uniform._array[ offset ] = value[ i ].x;
  14810. uniform._array[ offset + 1 ] = value[ i ].y;
  14811. uniform._array[ offset + 2 ] = value[ i ].z;
  14812. uniform._array[ offset + 3 ] = value[ i ].w;
  14813. }
  14814. _gl.uniform4fv( location, uniform._array );
  14815. } else if ( type === "m4") { // single THREE.Matrix4
  14816. if ( uniform._array === undefined ) {
  14817. uniform._array = new Float32Array( 16 );
  14818. }
  14819. value.flattenToArray( uniform._array );
  14820. _gl.uniformMatrix4fv( location, false, uniform._array );
  14821. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14822. if ( uniform._array === undefined ) {
  14823. uniform._array = new Float32Array( 16 * value.length );
  14824. }
  14825. for ( i = 0, il = value.length; i < il; i ++ ) {
  14826. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14827. }
  14828. _gl.uniformMatrix4fv( location, false, uniform._array );
  14829. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14830. texture = value;
  14831. textureUnit = getTextureUnit();
  14832. _gl.uniform1i( location, textureUnit );
  14833. if ( !texture ) continue;
  14834. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  14835. setCubeTexture( texture, textureUnit );
  14836. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14837. setCubeTextureDynamic( texture, textureUnit );
  14838. } else {
  14839. _this.setTexture( texture, textureUnit );
  14840. }
  14841. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  14842. if ( uniform._array === undefined ) {
  14843. uniform._array = [];
  14844. }
  14845. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14846. uniform._array[ i ] = getTextureUnit();
  14847. }
  14848. _gl.uniform1iv( location, uniform._array );
  14849. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14850. texture = uniform.value[ i ];
  14851. textureUnit = uniform._array[ i ];
  14852. if ( !texture ) continue;
  14853. _this.setTexture( texture, textureUnit );
  14854. }
  14855. } else {
  14856. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  14857. }
  14858. }
  14859. };
  14860. function setupMatrices ( object, camera ) {
  14861. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14862. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  14863. };
  14864. //
  14865. function setColorGamma( array, offset, color, intensitySq ) {
  14866. array[ offset ] = color.r * color.r * intensitySq;
  14867. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14868. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14869. };
  14870. function setColorLinear( array, offset, color, intensity ) {
  14871. array[ offset ] = color.r * intensity;
  14872. array[ offset + 1 ] = color.g * intensity;
  14873. array[ offset + 2 ] = color.b * intensity;
  14874. };
  14875. function setupLights ( program, lights ) {
  14876. var l, ll, light, n,
  14877. r = 0, g = 0, b = 0,
  14878. color, skyColor, groundColor,
  14879. intensity, intensitySq,
  14880. position,
  14881. distance,
  14882. zlights = _lights,
  14883. dirColors = zlights.directional.colors,
  14884. dirPositions = zlights.directional.positions,
  14885. pointColors = zlights.point.colors,
  14886. pointPositions = zlights.point.positions,
  14887. pointDistances = zlights.point.distances,
  14888. spotColors = zlights.spot.colors,
  14889. spotPositions = zlights.spot.positions,
  14890. spotDistances = zlights.spot.distances,
  14891. spotDirections = zlights.spot.directions,
  14892. spotAnglesCos = zlights.spot.anglesCos,
  14893. spotExponents = zlights.spot.exponents,
  14894. hemiSkyColors = zlights.hemi.skyColors,
  14895. hemiGroundColors = zlights.hemi.groundColors,
  14896. hemiPositions = zlights.hemi.positions,
  14897. dirLength = 0,
  14898. pointLength = 0,
  14899. spotLength = 0,
  14900. hemiLength = 0,
  14901. dirCount = 0,
  14902. pointCount = 0,
  14903. spotCount = 0,
  14904. hemiCount = 0,
  14905. dirOffset = 0,
  14906. pointOffset = 0,
  14907. spotOffset = 0,
  14908. hemiOffset = 0;
  14909. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14910. light = lights[ l ];
  14911. if ( light.onlyShadow ) continue;
  14912. color = light.color;
  14913. intensity = light.intensity;
  14914. distance = light.distance;
  14915. if ( light instanceof THREE.AmbientLight ) {
  14916. if ( ! light.visible ) continue;
  14917. if ( _this.gammaInput ) {
  14918. r += color.r * color.r;
  14919. g += color.g * color.g;
  14920. b += color.b * color.b;
  14921. } else {
  14922. r += color.r;
  14923. g += color.g;
  14924. b += color.b;
  14925. }
  14926. } else if ( light instanceof THREE.DirectionalLight ) {
  14927. dirCount += 1;
  14928. if ( ! light.visible ) continue;
  14929. _direction.setFromMatrixPosition( light.matrixWorld );
  14930. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  14931. _direction.sub( _vector3 );
  14932. _direction.normalize();
  14933. // skip lights with undefined direction
  14934. // these create troubles in OpenGL (making pixel black)
  14935. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14936. dirOffset = dirLength * 3;
  14937. dirPositions[ dirOffset ] = _direction.x;
  14938. dirPositions[ dirOffset + 1 ] = _direction.y;
  14939. dirPositions[ dirOffset + 2 ] = _direction.z;
  14940. if ( _this.gammaInput ) {
  14941. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  14942. } else {
  14943. setColorLinear( dirColors, dirOffset, color, intensity );
  14944. }
  14945. dirLength += 1;
  14946. } else if ( light instanceof THREE.PointLight ) {
  14947. pointCount += 1;
  14948. if ( ! light.visible ) continue;
  14949. pointOffset = pointLength * 3;
  14950. if ( _this.gammaInput ) {
  14951. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  14952. } else {
  14953. setColorLinear( pointColors, pointOffset, color, intensity );
  14954. }
  14955. _vector3.setFromMatrixPosition( light.matrixWorld );
  14956. pointPositions[ pointOffset ] = _vector3.x;
  14957. pointPositions[ pointOffset + 1 ] = _vector3.y;
  14958. pointPositions[ pointOffset + 2 ] = _vector3.z;
  14959. pointDistances[ pointLength ] = distance;
  14960. pointLength += 1;
  14961. } else if ( light instanceof THREE.SpotLight ) {
  14962. spotCount += 1;
  14963. if ( ! light.visible ) continue;
  14964. spotOffset = spotLength * 3;
  14965. if ( _this.gammaInput ) {
  14966. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14967. } else {
  14968. setColorLinear( spotColors, spotOffset, color, intensity );
  14969. }
  14970. _vector3.setFromMatrixPosition( light.matrixWorld );
  14971. spotPositions[ spotOffset ] = _vector3.x;
  14972. spotPositions[ spotOffset + 1 ] = _vector3.y;
  14973. spotPositions[ spotOffset + 2 ] = _vector3.z;
  14974. spotDistances[ spotLength ] = distance;
  14975. _direction.copy( _vector3 );
  14976. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  14977. _direction.sub( _vector3 );
  14978. _direction.normalize();
  14979. spotDirections[ spotOffset ] = _direction.x;
  14980. spotDirections[ spotOffset + 1 ] = _direction.y;
  14981. spotDirections[ spotOffset + 2 ] = _direction.z;
  14982. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14983. spotExponents[ spotLength ] = light.exponent;
  14984. spotLength += 1;
  14985. } else if ( light instanceof THREE.HemisphereLight ) {
  14986. hemiCount += 1;
  14987. if ( ! light.visible ) continue;
  14988. _direction.setFromMatrixPosition( light.matrixWorld );
  14989. _direction.normalize();
  14990. // skip lights with undefined direction
  14991. // these create troubles in OpenGL (making pixel black)
  14992. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14993. hemiOffset = hemiLength * 3;
  14994. hemiPositions[ hemiOffset ] = _direction.x;
  14995. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14996. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14997. skyColor = light.color;
  14998. groundColor = light.groundColor;
  14999. if ( _this.gammaInput ) {
  15000. intensitySq = intensity * intensity;
  15001. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  15002. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  15003. } else {
  15004. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  15005. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  15006. }
  15007. hemiLength += 1;
  15008. }
  15009. }
  15010. // null eventual remains from removed lights
  15011. // (this is to avoid if in shader)
  15012. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  15013. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  15014. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  15015. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  15016. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  15017. zlights.directional.length = dirLength;
  15018. zlights.point.length = pointLength;
  15019. zlights.spot.length = spotLength;
  15020. zlights.hemi.length = hemiLength;
  15021. zlights.ambient[ 0 ] = r;
  15022. zlights.ambient[ 1 ] = g;
  15023. zlights.ambient[ 2 ] = b;
  15024. };
  15025. // GL state setting
  15026. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  15027. if ( cullFace === THREE.CullFaceNone ) {
  15028. _gl.disable( _gl.CULL_FACE );
  15029. } else {
  15030. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  15031. _gl.frontFace( _gl.CW );
  15032. } else {
  15033. _gl.frontFace( _gl.CCW );
  15034. }
  15035. if ( cullFace === THREE.CullFaceBack ) {
  15036. _gl.cullFace( _gl.BACK );
  15037. } else if ( cullFace === THREE.CullFaceFront ) {
  15038. _gl.cullFace( _gl.FRONT );
  15039. } else {
  15040. _gl.cullFace( _gl.FRONT_AND_BACK );
  15041. }
  15042. _gl.enable( _gl.CULL_FACE );
  15043. }
  15044. };
  15045. this.setMaterialFaces = function ( material ) {
  15046. var doubleSided = material.side === THREE.DoubleSide;
  15047. var flipSided = material.side === THREE.BackSide;
  15048. if ( _oldDoubleSided !== doubleSided ) {
  15049. if ( doubleSided ) {
  15050. _gl.disable( _gl.CULL_FACE );
  15051. } else {
  15052. _gl.enable( _gl.CULL_FACE );
  15053. }
  15054. _oldDoubleSided = doubleSided;
  15055. }
  15056. if ( _oldFlipSided !== flipSided ) {
  15057. if ( flipSided ) {
  15058. _gl.frontFace( _gl.CW );
  15059. } else {
  15060. _gl.frontFace( _gl.CCW );
  15061. }
  15062. _oldFlipSided = flipSided;
  15063. }
  15064. };
  15065. this.setDepthTest = function ( depthTest ) {
  15066. if ( _oldDepthTest !== depthTest ) {
  15067. if ( depthTest ) {
  15068. _gl.enable( _gl.DEPTH_TEST );
  15069. } else {
  15070. _gl.disable( _gl.DEPTH_TEST );
  15071. }
  15072. _oldDepthTest = depthTest;
  15073. }
  15074. };
  15075. this.setDepthWrite = function ( depthWrite ) {
  15076. if ( _oldDepthWrite !== depthWrite ) {
  15077. _gl.depthMask( depthWrite );
  15078. _oldDepthWrite = depthWrite;
  15079. }
  15080. };
  15081. function setLineWidth ( width ) {
  15082. if ( width !== _oldLineWidth ) {
  15083. _gl.lineWidth( width );
  15084. _oldLineWidth = width;
  15085. }
  15086. };
  15087. function setPolygonOffset ( polygonoffset, factor, units ) {
  15088. if ( _oldPolygonOffset !== polygonoffset ) {
  15089. if ( polygonoffset ) {
  15090. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  15091. } else {
  15092. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  15093. }
  15094. _oldPolygonOffset = polygonoffset;
  15095. }
  15096. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  15097. _gl.polygonOffset( factor, units );
  15098. _oldPolygonOffsetFactor = factor;
  15099. _oldPolygonOffsetUnits = units;
  15100. }
  15101. };
  15102. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  15103. if ( blending !== _oldBlending ) {
  15104. if ( blending === THREE.NoBlending ) {
  15105. _gl.disable( _gl.BLEND );
  15106. } else if ( blending === THREE.AdditiveBlending ) {
  15107. _gl.enable( _gl.BLEND );
  15108. _gl.blendEquation( _gl.FUNC_ADD );
  15109. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  15110. } else if ( blending === THREE.SubtractiveBlending ) {
  15111. // TODO: Find blendFuncSeparate() combination
  15112. _gl.enable( _gl.BLEND );
  15113. _gl.blendEquation( _gl.FUNC_ADD );
  15114. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  15115. } else if ( blending === THREE.MultiplyBlending ) {
  15116. // TODO: Find blendFuncSeparate() combination
  15117. _gl.enable( _gl.BLEND );
  15118. _gl.blendEquation( _gl.FUNC_ADD );
  15119. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  15120. } else if ( blending === THREE.CustomBlending ) {
  15121. _gl.enable( _gl.BLEND );
  15122. } else {
  15123. _gl.enable( _gl.BLEND );
  15124. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  15125. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  15126. }
  15127. _oldBlending = blending;
  15128. }
  15129. if ( blending === THREE.CustomBlending ) {
  15130. if ( blendEquation !== _oldBlendEquation ) {
  15131. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  15132. _oldBlendEquation = blendEquation;
  15133. }
  15134. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  15135. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  15136. _oldBlendSrc = blendSrc;
  15137. _oldBlendDst = blendDst;
  15138. }
  15139. } else {
  15140. _oldBlendEquation = null;
  15141. _oldBlendSrc = null;
  15142. _oldBlendDst = null;
  15143. }
  15144. };
  15145. // Defines
  15146. function generateDefines ( defines ) {
  15147. var value, chunk, chunks = [];
  15148. for ( var d in defines ) {
  15149. value = defines[ d ];
  15150. if ( value === false ) continue;
  15151. chunk = "#define " + d + " " + value;
  15152. chunks.push( chunk );
  15153. }
  15154. return chunks.join( "\n" );
  15155. };
  15156. // Shaders
  15157. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters, index0AttributeName ) {
  15158. var p, pl, d, program, code;
  15159. var chunks = [];
  15160. // Generate code
  15161. if ( shaderID ) {
  15162. chunks.push( shaderID );
  15163. } else {
  15164. chunks.push( fragmentShader );
  15165. chunks.push( vertexShader );
  15166. }
  15167. for ( d in defines ) {
  15168. chunks.push( d );
  15169. chunks.push( defines[ d ] );
  15170. }
  15171. for ( p in parameters ) {
  15172. chunks.push( p );
  15173. chunks.push( parameters[ p ] );
  15174. }
  15175. code = chunks.join();
  15176. // Check if code has been already compiled
  15177. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  15178. var programInfo = _programs[ p ];
  15179. if ( programInfo.code === code ) {
  15180. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  15181. programInfo.usedTimes ++;
  15182. return programInfo.program;
  15183. }
  15184. }
  15185. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  15186. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  15187. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  15188. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  15189. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  15190. }
  15191. // console.log( "building new program " );
  15192. //
  15193. var customDefines = generateDefines( defines );
  15194. //
  15195. program = _gl.createProgram();
  15196. var prefix_vertex = [
  15197. "precision " + _precision + " float;",
  15198. "precision " + _precision + " int;",
  15199. customDefines,
  15200. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  15201. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15202. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15203. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15204. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15205. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15206. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15207. "#define MAX_SHADOWS " + parameters.maxShadows,
  15208. "#define MAX_BONES " + parameters.maxBones,
  15209. parameters.map ? "#define USE_MAP" : "",
  15210. parameters.envMap ? "#define USE_ENVMAP" : "",
  15211. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15212. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15213. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15214. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15215. parameters.vertexColors ? "#define USE_COLOR" : "",
  15216. parameters.skinning ? "#define USE_SKINNING" : "",
  15217. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  15218. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  15219. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  15220. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15221. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15222. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15223. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15224. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15225. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15226. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15227. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  15228. "uniform mat4 modelMatrix;",
  15229. "uniform mat4 modelViewMatrix;",
  15230. "uniform mat4 projectionMatrix;",
  15231. "uniform mat4 viewMatrix;",
  15232. "uniform mat3 normalMatrix;",
  15233. "uniform vec3 cameraPosition;",
  15234. "attribute vec3 position;",
  15235. "attribute vec3 normal;",
  15236. "attribute vec2 uv;",
  15237. "attribute vec2 uv2;",
  15238. "#ifdef USE_COLOR",
  15239. "attribute vec3 color;",
  15240. "#endif",
  15241. "#ifdef USE_MORPHTARGETS",
  15242. "attribute vec3 morphTarget0;",
  15243. "attribute vec3 morphTarget1;",
  15244. "attribute vec3 morphTarget2;",
  15245. "attribute vec3 morphTarget3;",
  15246. "#ifdef USE_MORPHNORMALS",
  15247. "attribute vec3 morphNormal0;",
  15248. "attribute vec3 morphNormal1;",
  15249. "attribute vec3 morphNormal2;",
  15250. "attribute vec3 morphNormal3;",
  15251. "#else",
  15252. "attribute vec3 morphTarget4;",
  15253. "attribute vec3 morphTarget5;",
  15254. "attribute vec3 morphTarget6;",
  15255. "attribute vec3 morphTarget7;",
  15256. "#endif",
  15257. "#endif",
  15258. "#ifdef USE_SKINNING",
  15259. "attribute vec4 skinIndex;",
  15260. "attribute vec4 skinWeight;",
  15261. "#endif",
  15262. ""
  15263. ].join("\n");
  15264. var prefix_fragment = [
  15265. "precision " + _precision + " float;",
  15266. "precision " + _precision + " int;",
  15267. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  15268. customDefines,
  15269. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15270. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15271. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15272. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15273. "#define MAX_SHADOWS " + parameters.maxShadows,
  15274. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  15275. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15276. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15277. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  15278. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  15279. parameters.map ? "#define USE_MAP" : "",
  15280. parameters.envMap ? "#define USE_ENVMAP" : "",
  15281. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15282. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15283. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15284. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15285. parameters.vertexColors ? "#define USE_COLOR" : "",
  15286. parameters.metal ? "#define METAL" : "",
  15287. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15288. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15289. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15290. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15291. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15292. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15293. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15294. "uniform mat4 viewMatrix;",
  15295. "uniform vec3 cameraPosition;",
  15296. ""
  15297. ].join("\n");
  15298. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  15299. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  15300. _gl.attachShader( program, glVertexShader );
  15301. _gl.attachShader( program, glFragmentShader );
  15302. // Force a particular attribute to index 0.
  15303. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  15304. // And, color, for example is often automatically bound to index 0 so disabling it
  15305. if ( index0AttributeName !== undefined ) {
  15306. _gl.bindAttribLocation( program, 0, index0AttributeName );
  15307. } else {
  15308. _gl.bindAttribLocation( program, 0, 'position' );
  15309. }
  15310. _gl.linkProgram( program );
  15311. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  15312. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  15313. console.error( "Program Info Log: " + _gl.getProgramInfoLog( program ) );
  15314. }
  15315. // clean up
  15316. _gl.deleteShader( glFragmentShader );
  15317. _gl.deleteShader( glVertexShader );
  15318. // console.log( prefix_fragment + fragmentShader );
  15319. // console.log( prefix_vertex + vertexShader );
  15320. program.uniforms = {};
  15321. program.attributes = {};
  15322. var identifiers, u, a, i;
  15323. // cache uniform locations
  15324. identifiers = [
  15325. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  15326. 'morphTargetInfluences'
  15327. ];
  15328. if ( parameters.useVertexTexture ) {
  15329. identifiers.push( 'boneTexture' );
  15330. identifiers.push( 'boneTextureWidth' );
  15331. identifiers.push( 'boneTextureHeight' );
  15332. } else {
  15333. identifiers.push( 'boneGlobalMatrices' );
  15334. }
  15335. for ( u in uniforms ) {
  15336. identifiers.push( u );
  15337. }
  15338. cacheUniformLocations( program, identifiers );
  15339. // cache attributes locations
  15340. identifiers = [
  15341. "position", "normal", "uv", "uv2", "tangent", "color",
  15342. "skinIndex", "skinWeight", "lineDistance"
  15343. ];
  15344. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  15345. identifiers.push( "morphTarget" + i );
  15346. }
  15347. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  15348. identifiers.push( "morphNormal" + i );
  15349. }
  15350. for ( a in attributes ) {
  15351. identifiers.push( a );
  15352. }
  15353. cacheAttributeLocations( program, identifiers );
  15354. program.id = _programs_counter ++;
  15355. _programs.push( { program: program, code: code, usedTimes: 1 } );
  15356. _this.info.memory.programs = _programs.length;
  15357. return program;
  15358. };
  15359. // Shader parameters cache
  15360. function cacheUniformLocations ( program, identifiers ) {
  15361. var i, l, id;
  15362. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  15363. id = identifiers[ i ];
  15364. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  15365. }
  15366. };
  15367. function cacheAttributeLocations ( program, identifiers ) {
  15368. var i, l, id;
  15369. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  15370. id = identifiers[ i ];
  15371. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  15372. }
  15373. };
  15374. function addLineNumbers ( string ) {
  15375. var chunks = string.split( "\n" );
  15376. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  15377. // Chrome reports shader errors on lines
  15378. // starting counting from 1
  15379. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  15380. }
  15381. return chunks.join( "\n" );
  15382. };
  15383. function getShader ( type, string ) {
  15384. var shader;
  15385. if ( type === "fragment" ) {
  15386. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  15387. } else if ( type === "vertex" ) {
  15388. shader = _gl.createShader( _gl.VERTEX_SHADER );
  15389. }
  15390. _gl.shaderSource( shader, string );
  15391. _gl.compileShader( shader );
  15392. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  15393. console.error( _gl.getShaderInfoLog( shader ) );
  15394. console.error( addLineNumbers( string ) );
  15395. return null;
  15396. }
  15397. return shader;
  15398. };
  15399. // Textures
  15400. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  15401. if ( isImagePowerOfTwo ) {
  15402. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  15403. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  15404. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  15405. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  15406. } else {
  15407. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  15408. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  15409. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  15410. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  15411. }
  15412. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  15413. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  15414. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  15415. texture.__oldAnisotropy = texture.anisotropy;
  15416. }
  15417. }
  15418. };
  15419. this.setTexture = function ( texture, slot ) {
  15420. if ( texture.needsUpdate ) {
  15421. if ( ! texture.__webglInit ) {
  15422. texture.__webglInit = true;
  15423. texture.addEventListener( 'dispose', onTextureDispose );
  15424. texture.__webglTexture = _gl.createTexture();
  15425. _this.info.memory.textures ++;
  15426. }
  15427. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15428. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15429. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15430. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  15431. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  15432. var image = texture.image,
  15433. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  15434. glFormat = paramThreeToGL( texture.format ),
  15435. glType = paramThreeToGL( texture.type );
  15436. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  15437. var mipmap, mipmaps = texture.mipmaps;
  15438. if ( texture instanceof THREE.DataTexture ) {
  15439. // use manually created mipmaps if available
  15440. // if there are no manual mipmaps
  15441. // set 0 level mipmap and then use GL to generate other mipmap levels
  15442. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15443. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15444. mipmap = mipmaps[ i ];
  15445. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15446. }
  15447. texture.generateMipmaps = false;
  15448. } else {
  15449. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  15450. }
  15451. } else if ( texture instanceof THREE.CompressedTexture ) {
  15452. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15453. mipmap = mipmaps[ i ];
  15454. if ( texture.format!==THREE.RGBAFormat ) {
  15455. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15456. } else {
  15457. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15458. }
  15459. }
  15460. } else { // regular Texture (image, video, canvas)
  15461. // use manually created mipmaps if available
  15462. // if there are no manual mipmaps
  15463. // set 0 level mipmap and then use GL to generate other mipmap levels
  15464. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15465. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15466. mipmap = mipmaps[ i ];
  15467. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  15468. }
  15469. texture.generateMipmaps = false;
  15470. } else {
  15471. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  15472. }
  15473. }
  15474. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15475. texture.needsUpdate = false;
  15476. if ( texture.onUpdate ) texture.onUpdate();
  15477. } else {
  15478. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15479. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15480. }
  15481. };
  15482. function clampToMaxSize ( image, maxSize ) {
  15483. if ( image.width <= maxSize && image.height <= maxSize ) {
  15484. return image;
  15485. }
  15486. // Warning: Scaling through the canvas will only work with images that use
  15487. // premultiplied alpha.
  15488. var maxDimension = Math.max( image.width, image.height );
  15489. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  15490. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  15491. var canvas = document.createElement( 'canvas' );
  15492. canvas.width = newWidth;
  15493. canvas.height = newHeight;
  15494. var ctx = canvas.getContext( "2d" );
  15495. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  15496. return canvas;
  15497. }
  15498. function setCubeTexture ( texture, slot ) {
  15499. if ( texture.image.length === 6 ) {
  15500. if ( texture.needsUpdate ) {
  15501. if ( ! texture.image.__webglTextureCube ) {
  15502. texture.addEventListener( 'dispose', onTextureDispose );
  15503. texture.image.__webglTextureCube = _gl.createTexture();
  15504. _this.info.memory.textures ++;
  15505. }
  15506. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15507. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15508. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15509. var isCompressed = texture instanceof THREE.CompressedTexture;
  15510. var cubeImage = [];
  15511. for ( var i = 0; i < 6; i ++ ) {
  15512. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  15513. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  15514. } else {
  15515. cubeImage[ i ] = texture.image[ i ];
  15516. }
  15517. }
  15518. var image = cubeImage[ 0 ],
  15519. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  15520. glFormat = paramThreeToGL( texture.format ),
  15521. glType = paramThreeToGL( texture.type );
  15522. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  15523. for ( var i = 0; i < 6; i ++ ) {
  15524. if( !isCompressed ) {
  15525. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15526. } else {
  15527. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15528. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15529. mipmap = mipmaps[ j ];
  15530. if ( texture.format!==THREE.RGBAFormat ) {
  15531. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15532. } else {
  15533. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15534. }
  15535. }
  15536. }
  15537. }
  15538. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  15539. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15540. }
  15541. texture.needsUpdate = false;
  15542. if ( texture.onUpdate ) texture.onUpdate();
  15543. } else {
  15544. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15545. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15546. }
  15547. }
  15548. };
  15549. function setCubeTextureDynamic ( texture, slot ) {
  15550. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15551. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  15552. };
  15553. // Render targets
  15554. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  15555. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15556. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  15557. };
  15558. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  15559. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15560. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15561. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15562. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15563. /* For some reason this is not working. Defaulting to RGBA4.
  15564. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15565. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  15566. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15567. */
  15568. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15569. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15570. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15571. } else {
  15572. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15573. }
  15574. };
  15575. this.setRenderTarget = function ( renderTarget ) {
  15576. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  15577. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  15578. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  15579. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  15580. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15581. renderTarget.__webglTexture = _gl.createTexture();
  15582. _this.info.memory.textures ++;
  15583. // Setup texture, create render and frame buffers
  15584. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ),
  15585. glFormat = paramThreeToGL( renderTarget.format ),
  15586. glType = paramThreeToGL( renderTarget.type );
  15587. if ( isCube ) {
  15588. renderTarget.__webglFramebuffer = [];
  15589. renderTarget.__webglRenderbuffer = [];
  15590. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15591. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  15592. for ( var i = 0; i < 6; i ++ ) {
  15593. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15594. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  15595. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15596. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15597. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  15598. }
  15599. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15600. } else {
  15601. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  15602. if ( renderTarget.shareDepthFrom ) {
  15603. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  15604. } else {
  15605. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  15606. }
  15607. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15608. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  15609. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15610. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  15611. if ( renderTarget.shareDepthFrom ) {
  15612. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15613. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15614. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15615. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15616. }
  15617. } else {
  15618. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15619. }
  15620. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15621. }
  15622. // Release everything
  15623. if ( isCube ) {
  15624. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15625. } else {
  15626. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15627. }
  15628. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15629. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15630. }
  15631. var framebuffer, width, height, vx, vy;
  15632. if ( renderTarget ) {
  15633. if ( isCube ) {
  15634. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15635. } else {
  15636. framebuffer = renderTarget.__webglFramebuffer;
  15637. }
  15638. width = renderTarget.width;
  15639. height = renderTarget.height;
  15640. vx = 0;
  15641. vy = 0;
  15642. } else {
  15643. framebuffer = null;
  15644. width = _viewportWidth;
  15645. height = _viewportHeight;
  15646. vx = _viewportX;
  15647. vy = _viewportY;
  15648. }
  15649. if ( framebuffer !== _currentFramebuffer ) {
  15650. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15651. _gl.viewport( vx, vy, width, height );
  15652. _currentFramebuffer = framebuffer;
  15653. }
  15654. _currentWidth = width;
  15655. _currentHeight = height;
  15656. };
  15657. function updateRenderTargetMipmap ( renderTarget ) {
  15658. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15659. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15660. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15661. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15662. } else {
  15663. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15664. _gl.generateMipmap( _gl.TEXTURE_2D );
  15665. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15666. }
  15667. };
  15668. // Fallback filters for non-power-of-2 textures
  15669. function filterFallback ( f ) {
  15670. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15671. return _gl.NEAREST;
  15672. }
  15673. return _gl.LINEAR;
  15674. };
  15675. // Map three.js constants to WebGL constants
  15676. function paramThreeToGL ( p ) {
  15677. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15678. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15679. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15680. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15681. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15682. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15683. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15684. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15685. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15686. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15687. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15688. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15689. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15690. if ( p === THREE.ByteType ) return _gl.BYTE;
  15691. if ( p === THREE.ShortType ) return _gl.SHORT;
  15692. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15693. if ( p === THREE.IntType ) return _gl.INT;
  15694. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15695. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15696. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15697. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15698. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15699. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15700. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15701. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15702. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15703. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15704. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15705. if ( p === THREE.OneFactor ) return _gl.ONE;
  15706. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15707. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15708. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15709. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15710. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15711. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15712. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15713. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15714. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15715. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15716. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15717. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15718. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15719. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15720. }
  15721. return 0;
  15722. };
  15723. // Allocations
  15724. function allocateBones ( object ) {
  15725. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  15726. return 1024;
  15727. } else {
  15728. // default for when object is not specified
  15729. // ( for example when prebuilding shader
  15730. // to be used with multiple objects )
  15731. //
  15732. // - leave some extra space for other uniforms
  15733. // - limit here is ANGLE's 254 max uniform vectors
  15734. // (up to 54 should be safe)
  15735. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15736. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15737. var maxBones = nVertexMatrices;
  15738. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15739. maxBones = Math.min( object.bones.length, maxBones );
  15740. if ( maxBones < object.bones.length ) {
  15741. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  15742. }
  15743. }
  15744. return maxBones;
  15745. }
  15746. };
  15747. function allocateLights( lights ) {
  15748. var dirLights = 0;
  15749. var pointLights = 0;
  15750. var spotLights = 0;
  15751. var hemiLights = 0;
  15752. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15753. var light = lights[ l ];
  15754. if ( light.onlyShadow ) continue;
  15755. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15756. if ( light instanceof THREE.PointLight ) pointLights ++;
  15757. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15758. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15759. }
  15760. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15761. };
  15762. function allocateShadows( lights ) {
  15763. var maxShadows = 0;
  15764. for ( var l = 0, ll = lights.length; l < ll; l++ ) {
  15765. var light = lights[ l ];
  15766. if ( ! light.castShadow ) continue;
  15767. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15768. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15769. }
  15770. return maxShadows;
  15771. };
  15772. // Initialization
  15773. function initGL() {
  15774. try {
  15775. var attributes = {
  15776. alpha: _alpha,
  15777. premultipliedAlpha: _premultipliedAlpha,
  15778. antialias: _antialias,
  15779. stencil: _stencil,
  15780. preserveDrawingBuffer: _preserveDrawingBuffer
  15781. };
  15782. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  15783. if ( _gl === null ) {
  15784. throw 'Error creating WebGL context.';
  15785. }
  15786. } catch ( error ) {
  15787. console.error( error );
  15788. }
  15789. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15790. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  15791. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15792. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15793. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15794. if ( ! _glExtensionTextureFloat ) {
  15795. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15796. }
  15797. if ( ! _glExtensionStandardDerivatives ) {
  15798. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15799. }
  15800. if ( ! _glExtensionTextureFilterAnisotropic ) {
  15801. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15802. }
  15803. if ( ! _glExtensionCompressedTextureS3TC ) {
  15804. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15805. }
  15806. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15807. _gl.getShaderPrecisionFormat = function() {
  15808. return {
  15809. "rangeMin" : 1,
  15810. "rangeMax" : 1,
  15811. "precision" : 1
  15812. };
  15813. }
  15814. }
  15815. };
  15816. function setDefaultGLState () {
  15817. _gl.clearColor( 0, 0, 0, 1 );
  15818. _gl.clearDepth( 1 );
  15819. _gl.clearStencil( 0 );
  15820. _gl.enable( _gl.DEPTH_TEST );
  15821. _gl.depthFunc( _gl.LEQUAL );
  15822. _gl.frontFace( _gl.CCW );
  15823. _gl.cullFace( _gl.BACK );
  15824. _gl.enable( _gl.CULL_FACE );
  15825. _gl.enable( _gl.BLEND );
  15826. _gl.blendEquation( _gl.FUNC_ADD );
  15827. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15828. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  15829. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15830. };
  15831. // default plugins (order is important)
  15832. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15833. this.addPrePlugin( this.shadowMapPlugin );
  15834. this.addPostPlugin( new THREE.SpritePlugin() );
  15835. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15836. };
  15837. /**
  15838. * @author szimek / https://github.com/szimek/
  15839. * @author alteredq / http://alteredqualia.com/
  15840. */
  15841. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15842. this.width = width;
  15843. this.height = height;
  15844. options = options || {};
  15845. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15846. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15847. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15848. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15849. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15850. this.offset = new THREE.Vector2( 0, 0 );
  15851. this.repeat = new THREE.Vector2( 1, 1 );
  15852. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15853. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15854. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15855. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15856. this.generateMipmaps = true;
  15857. this.shareDepthFrom = null;
  15858. };
  15859. THREE.WebGLRenderTarget.prototype = {
  15860. constructor: THREE.WebGLRenderTarget,
  15861. clone: function () {
  15862. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15863. tmp.wrapS = this.wrapS;
  15864. tmp.wrapT = this.wrapT;
  15865. tmp.magFilter = this.magFilter;
  15866. tmp.minFilter = this.minFilter;
  15867. tmp.anisotropy = this.anisotropy;
  15868. tmp.offset.copy( this.offset );
  15869. tmp.repeat.copy( this.repeat );
  15870. tmp.format = this.format;
  15871. tmp.type = this.type;
  15872. tmp.depthBuffer = this.depthBuffer;
  15873. tmp.stencilBuffer = this.stencilBuffer;
  15874. tmp.generateMipmaps = this.generateMipmaps;
  15875. tmp.shareDepthFrom = this.shareDepthFrom;
  15876. return tmp;
  15877. },
  15878. dispose: function () {
  15879. this.dispatchEvent( { type: 'dispose' } );
  15880. }
  15881. };
  15882. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  15883. /**
  15884. * @author alteredq / http://alteredqualia.com
  15885. */
  15886. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15887. THREE.WebGLRenderTarget.call( this, width, height, options );
  15888. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15889. };
  15890. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15891. /**
  15892. * @author mrdoob / http://mrdoob.com/
  15893. */
  15894. THREE.RenderableVertex = function () {
  15895. this.position = new THREE.Vector3();
  15896. this.positionWorld = new THREE.Vector3();
  15897. this.positionScreen = new THREE.Vector4();
  15898. this.visible = true;
  15899. };
  15900. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15901. this.positionWorld.copy( vertex.positionWorld );
  15902. this.positionScreen.copy( vertex.positionScreen );
  15903. };
  15904. /**
  15905. * @author mrdoob / http://mrdoob.com/
  15906. */
  15907. THREE.RenderableFace = function () {
  15908. this.id = 0;
  15909. this.v1 = new THREE.RenderableVertex();
  15910. this.v2 = new THREE.RenderableVertex();
  15911. this.v3 = new THREE.RenderableVertex();
  15912. this.centroidModel = new THREE.Vector3();
  15913. this.normalModel = new THREE.Vector3();
  15914. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15915. this.vertexNormalsLength = 0;
  15916. this.color = null;
  15917. this.material = null;
  15918. this.uvs = [[]];
  15919. this.z = 0;
  15920. };
  15921. /**
  15922. * @author mrdoob / http://mrdoob.com/
  15923. */
  15924. THREE.RenderableObject = function () {
  15925. this.id = 0;
  15926. this.object = null;
  15927. this.z = 0;
  15928. };
  15929. /**
  15930. * @author mrdoob / http://mrdoob.com/
  15931. */
  15932. THREE.RenderableSprite = function () {
  15933. this.id = 0;
  15934. this.object = null;
  15935. this.x = 0;
  15936. this.y = 0;
  15937. this.z = 0;
  15938. this.rotation = 0;
  15939. this.scale = new THREE.Vector2();
  15940. this.material = null;
  15941. };
  15942. /**
  15943. * @author mrdoob / http://mrdoob.com/
  15944. */
  15945. THREE.RenderableLine = function () {
  15946. this.id = 0;
  15947. this.v1 = new THREE.RenderableVertex();
  15948. this.v2 = new THREE.RenderableVertex();
  15949. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  15950. this.material = null;
  15951. this.z = 0;
  15952. };
  15953. /**
  15954. * @author mrdoob / http://mrdoob.com/
  15955. * @author alteredq / http://alteredqualia.com/
  15956. */
  15957. THREE.GeometryUtils = {
  15958. // Merge two geometries or geometry and geometry from object (using object's transform)
  15959. merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) {
  15960. var matrix, normalMatrix,
  15961. vertexOffset = geometry1.vertices.length,
  15962. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  15963. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  15964. vertices1 = geometry1.vertices,
  15965. vertices2 = geometry2.vertices,
  15966. faces1 = geometry1.faces,
  15967. faces2 = geometry2.faces,
  15968. uvs1 = geometry1.faceVertexUvs[ 0 ],
  15969. uvs2 = geometry2.faceVertexUvs[ 0 ];
  15970. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  15971. if ( object2 instanceof THREE.Mesh ) {
  15972. object2.matrixAutoUpdate && object2.updateMatrix();
  15973. matrix = object2.matrix;
  15974. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  15975. }
  15976. // vertices
  15977. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  15978. var vertex = vertices2[ i ];
  15979. var vertexCopy = vertex.clone();
  15980. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  15981. vertices1.push( vertexCopy );
  15982. }
  15983. // faces
  15984. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  15985. var face = faces2[ i ], faceCopy, normal, color,
  15986. faceVertexNormals = face.vertexNormals,
  15987. faceVertexColors = face.vertexColors;
  15988. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  15989. faceCopy.normal.copy( face.normal );
  15990. if ( normalMatrix ) {
  15991. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  15992. }
  15993. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  15994. normal = faceVertexNormals[ j ].clone();
  15995. if ( normalMatrix ) {
  15996. normal.applyMatrix3( normalMatrix ).normalize();
  15997. }
  15998. faceCopy.vertexNormals.push( normal );
  15999. }
  16000. faceCopy.color.copy( face.color );
  16001. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  16002. color = faceVertexColors[ j ];
  16003. faceCopy.vertexColors.push( color.clone() );
  16004. }
  16005. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  16006. faceCopy.centroid.copy( face.centroid );
  16007. if ( matrix ) {
  16008. faceCopy.centroid.applyMatrix4( matrix );
  16009. }
  16010. faces1.push( faceCopy );
  16011. }
  16012. // uvs
  16013. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  16014. var uv = uvs2[ i ], uvCopy = [];
  16015. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  16016. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  16017. }
  16018. uvs1.push( uvCopy );
  16019. }
  16020. },
  16021. // Get random point in triangle (via barycentric coordinates)
  16022. // (uniform distribution)
  16023. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  16024. randomPointInTriangle: function () {
  16025. var vector = new THREE.Vector3();
  16026. return function ( vectorA, vectorB, vectorC ) {
  16027. var point = new THREE.Vector3();
  16028. var a = THREE.Math.random16();
  16029. var b = THREE.Math.random16();
  16030. if ( ( a + b ) > 1 ) {
  16031. a = 1 - a;
  16032. b = 1 - b;
  16033. }
  16034. var c = 1 - a - b;
  16035. point.copy( vectorA );
  16036. point.multiplyScalar( a );
  16037. vector.copy( vectorB );
  16038. vector.multiplyScalar( b );
  16039. point.add( vector );
  16040. vector.copy( vectorC );
  16041. vector.multiplyScalar( c );
  16042. point.add( vector );
  16043. return point;
  16044. };
  16045. }(),
  16046. // Get random point in face (triangle / quad)
  16047. // (uniform distribution)
  16048. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  16049. var vA, vB, vC, vD;
  16050. vA = geometry.vertices[ face.a ];
  16051. vB = geometry.vertices[ face.b ];
  16052. vC = geometry.vertices[ face.c ];
  16053. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  16054. },
  16055. // Get uniformly distributed random points in mesh
  16056. // - create array with cumulative sums of face areas
  16057. // - pick random number from 0 to total area
  16058. // - find corresponding place in area array by binary search
  16059. // - get random point in face
  16060. randomPointsInGeometry: function ( geometry, n ) {
  16061. var face, i,
  16062. faces = geometry.faces,
  16063. vertices = geometry.vertices,
  16064. il = faces.length,
  16065. totalArea = 0,
  16066. cumulativeAreas = [],
  16067. vA, vB, vC, vD;
  16068. // precompute face areas
  16069. for ( i = 0; i < il; i ++ ) {
  16070. face = faces[ i ];
  16071. vA = vertices[ face.a ];
  16072. vB = vertices[ face.b ];
  16073. vC = vertices[ face.c ];
  16074. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  16075. totalArea += face._area;
  16076. cumulativeAreas[ i ] = totalArea;
  16077. }
  16078. // binary search cumulative areas array
  16079. function binarySearchIndices( value ) {
  16080. function binarySearch( start, end ) {
  16081. // return closest larger index
  16082. // if exact number is not found
  16083. if ( end < start )
  16084. return start;
  16085. var mid = start + Math.floor( ( end - start ) / 2 );
  16086. if ( cumulativeAreas[ mid ] > value ) {
  16087. return binarySearch( start, mid - 1 );
  16088. } else if ( cumulativeAreas[ mid ] < value ) {
  16089. return binarySearch( mid + 1, end );
  16090. } else {
  16091. return mid;
  16092. }
  16093. }
  16094. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  16095. return result;
  16096. }
  16097. // pick random face weighted by face area
  16098. var r, index,
  16099. result = [];
  16100. var stats = {};
  16101. for ( i = 0; i < n; i ++ ) {
  16102. r = THREE.Math.random16() * totalArea;
  16103. index = binarySearchIndices( r );
  16104. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  16105. if ( ! stats[ index ] ) {
  16106. stats[ index ] = 1;
  16107. } else {
  16108. stats[ index ] += 1;
  16109. }
  16110. }
  16111. return result;
  16112. },
  16113. // Get triangle area (half of parallelogram)
  16114. // http://mathworld.wolfram.com/TriangleArea.html
  16115. triangleArea: function () {
  16116. var vector1 = new THREE.Vector3();
  16117. var vector2 = new THREE.Vector3();
  16118. return function ( vectorA, vectorB, vectorC ) {
  16119. vector1.subVectors( vectorB, vectorA );
  16120. vector2.subVectors( vectorC, vectorA );
  16121. vector1.cross( vector2 );
  16122. return 0.5 * vector1.length();
  16123. };
  16124. }(),
  16125. // Center geometry so that 0,0,0 is in center of bounding box
  16126. center: function ( geometry ) {
  16127. geometry.computeBoundingBox();
  16128. var bb = geometry.boundingBox;
  16129. var offset = new THREE.Vector3();
  16130. offset.addVectors( bb.min, bb.max );
  16131. offset.multiplyScalar( -0.5 );
  16132. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  16133. geometry.computeBoundingBox();
  16134. return offset;
  16135. },
  16136. triangulateQuads: function ( geometry ) {
  16137. var i, il, j, jl;
  16138. var faces = [];
  16139. var faceVertexUvs = [];
  16140. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  16141. faceVertexUvs[ i ] = [];
  16142. }
  16143. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  16144. var face = geometry.faces[ i ];
  16145. faces.push( face );
  16146. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  16147. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  16148. }
  16149. }
  16150. geometry.faces = faces;
  16151. geometry.faceVertexUvs = faceVertexUvs;
  16152. geometry.computeCentroids();
  16153. geometry.computeFaceNormals();
  16154. geometry.computeVertexNormals();
  16155. if ( geometry.hasTangents ) geometry.computeTangents();
  16156. }
  16157. };
  16158. /**
  16159. * @author alteredq / http://alteredqualia.com/
  16160. * @author mrdoob / http://mrdoob.com/
  16161. */
  16162. THREE.ImageUtils = {
  16163. crossOrigin: undefined,
  16164. loadTexture: function ( url, mapping, onLoad, onError ) {
  16165. var loader = new THREE.ImageLoader();
  16166. loader.crossOrigin = this.crossOrigin;
  16167. var texture = new THREE.Texture( undefined, mapping );
  16168. var image = loader.load( url, function () {
  16169. texture.needsUpdate = true;
  16170. if ( onLoad ) onLoad( texture );
  16171. } );
  16172. texture.image = image;
  16173. texture.sourceFile = url;
  16174. return texture;
  16175. },
  16176. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  16177. var texture = new THREE.CompressedTexture();
  16178. texture.mapping = mapping;
  16179. var request = new XMLHttpRequest();
  16180. request.onload = function () {
  16181. var buffer = request.response;
  16182. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16183. texture.format = dds.format;
  16184. texture.mipmaps = dds.mipmaps;
  16185. texture.image.width = dds.width;
  16186. texture.image.height = dds.height;
  16187. // gl.generateMipmap fails for compressed textures
  16188. // mipmaps must be embedded in the DDS file
  16189. // or texture filters must not use mipmapping
  16190. texture.generateMipmaps = false;
  16191. texture.needsUpdate = true;
  16192. if ( onLoad ) onLoad( texture );
  16193. }
  16194. request.onerror = onError;
  16195. request.open( 'GET', url, true );
  16196. request.responseType = "arraybuffer";
  16197. request.send( null );
  16198. return texture;
  16199. },
  16200. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  16201. var images = [];
  16202. images.loadCount = 0;
  16203. var texture = new THREE.Texture();
  16204. texture.image = images;
  16205. if ( mapping !== undefined ) texture.mapping = mapping;
  16206. // no flipping needed for cube textures
  16207. texture.flipY = false;
  16208. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16209. var cubeImage = new Image();
  16210. images[ i ] = cubeImage;
  16211. cubeImage.onload = function () {
  16212. images.loadCount += 1;
  16213. if ( images.loadCount === 6 ) {
  16214. texture.needsUpdate = true;
  16215. if ( onLoad ) onLoad( texture );
  16216. }
  16217. };
  16218. cubeImage.onerror = onError;
  16219. cubeImage.crossOrigin = this.crossOrigin;
  16220. cubeImage.src = array[ i ];
  16221. }
  16222. return texture;
  16223. },
  16224. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  16225. var images = [];
  16226. images.loadCount = 0;
  16227. var texture = new THREE.CompressedTexture();
  16228. texture.image = images;
  16229. if ( mapping !== undefined ) texture.mapping = mapping;
  16230. // no flipping for cube textures
  16231. // (also flipping doesn't work for compressed textures )
  16232. texture.flipY = false;
  16233. // can't generate mipmaps for compressed textures
  16234. // mips must be embedded in DDS files
  16235. texture.generateMipmaps = false;
  16236. var generateCubeFaceCallback = function ( rq, img ) {
  16237. return function () {
  16238. var buffer = rq.response;
  16239. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16240. img.format = dds.format;
  16241. img.mipmaps = dds.mipmaps;
  16242. img.width = dds.width;
  16243. img.height = dds.height;
  16244. images.loadCount += 1;
  16245. if ( images.loadCount === 6 ) {
  16246. texture.format = dds.format;
  16247. texture.needsUpdate = true;
  16248. if ( onLoad ) onLoad( texture );
  16249. }
  16250. }
  16251. }
  16252. // compressed cubemap textures as 6 separate DDS files
  16253. if ( array instanceof Array ) {
  16254. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16255. var cubeImage = {};
  16256. images[ i ] = cubeImage;
  16257. var request = new XMLHttpRequest();
  16258. request.onload = generateCubeFaceCallback( request, cubeImage );
  16259. request.onerror = onError;
  16260. var url = array[ i ];
  16261. request.open( 'GET', url, true );
  16262. request.responseType = "arraybuffer";
  16263. request.send( null );
  16264. }
  16265. // compressed cubemap texture stored in a single DDS file
  16266. } else {
  16267. var url = array;
  16268. var request = new XMLHttpRequest();
  16269. request.onload = function( ) {
  16270. var buffer = request.response;
  16271. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16272. if ( dds.isCubemap ) {
  16273. var faces = dds.mipmaps.length / dds.mipmapCount;
  16274. for ( var f = 0; f < faces; f ++ ) {
  16275. images[ f ] = { mipmaps : [] };
  16276. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16277. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  16278. images[ f ].format = dds.format;
  16279. images[ f ].width = dds.width;
  16280. images[ f ].height = dds.height;
  16281. }
  16282. }
  16283. texture.format = dds.format;
  16284. texture.needsUpdate = true;
  16285. if ( onLoad ) onLoad( texture );
  16286. }
  16287. }
  16288. request.onerror = onError;
  16289. request.open( 'GET', url, true );
  16290. request.responseType = "arraybuffer";
  16291. request.send( null );
  16292. }
  16293. return texture;
  16294. },
  16295. loadDDSTexture: function ( url, mapping, onLoad, onError ) {
  16296. var images = [];
  16297. images.loadCount = 0;
  16298. var texture = new THREE.CompressedTexture();
  16299. texture.image = images;
  16300. if ( mapping !== undefined ) texture.mapping = mapping;
  16301. // no flipping for cube textures
  16302. // (also flipping doesn't work for compressed textures )
  16303. texture.flipY = false;
  16304. // can't generate mipmaps for compressed textures
  16305. // mips must be embedded in DDS files
  16306. texture.generateMipmaps = false;
  16307. {
  16308. var request = new XMLHttpRequest();
  16309. request.onload = function( ) {
  16310. var buffer = request.response;
  16311. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16312. if ( dds.isCubemap ) {
  16313. var faces = dds.mipmaps.length / dds.mipmapCount;
  16314. for ( var f = 0; f < faces; f ++ ) {
  16315. images[ f ] = { mipmaps : [] };
  16316. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16317. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  16318. images[ f ].format = dds.format;
  16319. images[ f ].width = dds.width;
  16320. images[ f ].height = dds.height;
  16321. }
  16322. }
  16323. } else {
  16324. texture.image.width = dds.width;
  16325. texture.image.height = dds.height;
  16326. texture.mipmaps = dds.mipmaps;
  16327. }
  16328. texture.format = dds.format;
  16329. texture.needsUpdate = true;
  16330. if ( onLoad ) onLoad( texture );
  16331. }
  16332. request.onerror = onError;
  16333. request.open( 'GET', url, true );
  16334. request.responseType = "arraybuffer";
  16335. request.send( null );
  16336. }
  16337. return texture;
  16338. },
  16339. parseDDS: function ( buffer, loadMipmaps ) {
  16340. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  16341. // Adapted from @toji's DDS utils
  16342. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  16343. // All values and structures referenced from:
  16344. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  16345. var DDS_MAGIC = 0x20534444;
  16346. var DDSD_CAPS = 0x1,
  16347. DDSD_HEIGHT = 0x2,
  16348. DDSD_WIDTH = 0x4,
  16349. DDSD_PITCH = 0x8,
  16350. DDSD_PIXELFORMAT = 0x1000,
  16351. DDSD_MIPMAPCOUNT = 0x20000,
  16352. DDSD_LINEARSIZE = 0x80000,
  16353. DDSD_DEPTH = 0x800000;
  16354. var DDSCAPS_COMPLEX = 0x8,
  16355. DDSCAPS_MIPMAP = 0x400000,
  16356. DDSCAPS_TEXTURE = 0x1000;
  16357. var DDSCAPS2_CUBEMAP = 0x200,
  16358. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  16359. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  16360. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  16361. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  16362. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  16363. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  16364. DDSCAPS2_VOLUME = 0x200000;
  16365. var DDPF_ALPHAPIXELS = 0x1,
  16366. DDPF_ALPHA = 0x2,
  16367. DDPF_FOURCC = 0x4,
  16368. DDPF_RGB = 0x40,
  16369. DDPF_YUV = 0x200,
  16370. DDPF_LUMINANCE = 0x20000;
  16371. function fourCCToInt32( value ) {
  16372. return value.charCodeAt(0) +
  16373. (value.charCodeAt(1) << 8) +
  16374. (value.charCodeAt(2) << 16) +
  16375. (value.charCodeAt(3) << 24);
  16376. }
  16377. function int32ToFourCC( value ) {
  16378. return String.fromCharCode(
  16379. value & 0xff,
  16380. (value >> 8) & 0xff,
  16381. (value >> 16) & 0xff,
  16382. (value >> 24) & 0xff
  16383. );
  16384. }
  16385. function loadARGBMip( buffer, dataOffset, width, height ) {
  16386. var dataLength = width*height*4;
  16387. var srcBuffer = new Uint8Array( buffer, dataOffset, dataLength );
  16388. var byteArray = new Uint8Array( dataLength );
  16389. var dst = 0;
  16390. var src = 0;
  16391. for ( var y = 0; y < height; y++ ) {
  16392. for ( var x = 0; x < width; x++ ) {
  16393. var b = srcBuffer[src]; src++;
  16394. var g = srcBuffer[src]; src++;
  16395. var r = srcBuffer[src]; src++;
  16396. var a = srcBuffer[src]; src++;
  16397. byteArray[dst] = r; dst++; //r
  16398. byteArray[dst] = g; dst++; //g
  16399. byteArray[dst] = b; dst++; //b
  16400. byteArray[dst] = a; dst++; //a
  16401. }
  16402. }
  16403. return byteArray;
  16404. }
  16405. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  16406. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  16407. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  16408. var headerLengthInt = 31; // The header length in 32 bit ints
  16409. // Offsets into the header array
  16410. var off_magic = 0;
  16411. var off_size = 1;
  16412. var off_flags = 2;
  16413. var off_height = 3;
  16414. var off_width = 4;
  16415. var off_mipmapCount = 7;
  16416. var off_pfFlags = 20;
  16417. var off_pfFourCC = 21;
  16418. var off_RGBBitCount = 22;
  16419. var off_RBitMask = 23;
  16420. var off_GBitMask = 24;
  16421. var off_BBitMask = 25;
  16422. var off_ABitMask = 26;
  16423. var off_caps = 27;
  16424. var off_caps2 = 28;
  16425. var off_caps3 = 29;
  16426. var off_caps4 = 30;
  16427. // Parse header
  16428. var header = new Int32Array( buffer, 0, headerLengthInt );
  16429. if ( header[ off_magic ] !== DDS_MAGIC ) {
  16430. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  16431. return dds;
  16432. }
  16433. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  16434. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  16435. return dds;
  16436. }
  16437. var blockBytes;
  16438. var fourCC = header[ off_pfFourCC ];
  16439. var isRGBAUncompressed = false;
  16440. switch ( fourCC ) {
  16441. case FOURCC_DXT1:
  16442. blockBytes = 8;
  16443. dds.format = THREE.RGB_S3TC_DXT1_Format;
  16444. break;
  16445. case FOURCC_DXT3:
  16446. blockBytes = 16;
  16447. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  16448. break;
  16449. case FOURCC_DXT5:
  16450. blockBytes = 16;
  16451. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  16452. break;
  16453. default:
  16454. if( header[off_RGBBitCount] ==32
  16455. && header[off_RBitMask]&0xff0000
  16456. && header[off_GBitMask]&0xff00
  16457. && header[off_BBitMask]&0xff
  16458. && header[off_ABitMask]&0xff000000 ) {
  16459. isRGBAUncompressed = true;
  16460. blockBytes = 64;
  16461. dds.format = THREE.RGBAFormat;
  16462. } else {
  16463. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  16464. return dds;
  16465. }
  16466. }
  16467. dds.mipmapCount = 1;
  16468. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  16469. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  16470. }
  16471. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  16472. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  16473. dds.width = header[ off_width ];
  16474. dds.height = header[ off_height ];
  16475. var dataOffset = header[ off_size ] + 4;
  16476. // Extract mipmaps buffers
  16477. var width = dds.width;
  16478. var height = dds.height;
  16479. var faces = dds.isCubemap ? 6 : 1;
  16480. for ( var face = 0; face < faces; face ++ ) {
  16481. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16482. if( isRGBAUncompressed ) {
  16483. var byteArray = loadARGBMip( buffer, dataOffset, width, height );
  16484. var dataLength = byteArray.length;
  16485. } else {
  16486. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  16487. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  16488. }
  16489. var mipmap = { "data": byteArray, "width": width, "height": height };
  16490. dds.mipmaps.push( mipmap );
  16491. dataOffset += dataLength;
  16492. width = Math.max( width * 0.5, 1 );
  16493. height = Math.max( height * 0.5, 1 );
  16494. }
  16495. width = dds.width;
  16496. height = dds.height;
  16497. }
  16498. return dds;
  16499. },
  16500. getNormalMap: function ( image, depth ) {
  16501. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  16502. var cross = function ( a, b ) {
  16503. 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 ] ];
  16504. }
  16505. var subtract = function ( a, b ) {
  16506. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  16507. }
  16508. var normalize = function ( a ) {
  16509. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  16510. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  16511. }
  16512. depth = depth | 1;
  16513. var width = image.width;
  16514. var height = image.height;
  16515. var canvas = document.createElement( 'canvas' );
  16516. canvas.width = width;
  16517. canvas.height = height;
  16518. var context = canvas.getContext( '2d' );
  16519. context.drawImage( image, 0, 0 );
  16520. var data = context.getImageData( 0, 0, width, height ).data;
  16521. var imageData = context.createImageData( width, height );
  16522. var output = imageData.data;
  16523. for ( var x = 0; x < width; x ++ ) {
  16524. for ( var y = 0; y < height; y ++ ) {
  16525. var ly = y - 1 < 0 ? 0 : y - 1;
  16526. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  16527. var lx = x - 1 < 0 ? 0 : x - 1;
  16528. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  16529. var points = [];
  16530. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  16531. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  16532. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  16533. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  16534. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  16535. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  16536. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  16537. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  16538. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  16539. var normals = [];
  16540. var num_points = points.length;
  16541. for ( var i = 0; i < num_points; i ++ ) {
  16542. var v1 = points[ i ];
  16543. var v2 = points[ ( i + 1 ) % num_points ];
  16544. v1 = subtract( v1, origin );
  16545. v2 = subtract( v2, origin );
  16546. normals.push( normalize( cross( v1, v2 ) ) );
  16547. }
  16548. var normal = [ 0, 0, 0 ];
  16549. for ( var i = 0; i < normals.length; i ++ ) {
  16550. normal[ 0 ] += normals[ i ][ 0 ];
  16551. normal[ 1 ] += normals[ i ][ 1 ];
  16552. normal[ 2 ] += normals[ i ][ 2 ];
  16553. }
  16554. normal[ 0 ] /= normals.length;
  16555. normal[ 1 ] /= normals.length;
  16556. normal[ 2 ] /= normals.length;
  16557. var idx = ( y * width + x ) * 4;
  16558. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16559. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16560. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  16561. output[ idx + 3 ] = 255;
  16562. }
  16563. }
  16564. context.putImageData( imageData, 0, 0 );
  16565. return canvas;
  16566. },
  16567. generateDataTexture: function ( width, height, color ) {
  16568. var size = width * height;
  16569. var data = new Uint8Array( 3 * size );
  16570. var r = Math.floor( color.r * 255 );
  16571. var g = Math.floor( color.g * 255 );
  16572. var b = Math.floor( color.b * 255 );
  16573. for ( var i = 0; i < size; i ++ ) {
  16574. data[ i * 3 ] = r;
  16575. data[ i * 3 + 1 ] = g;
  16576. data[ i * 3 + 2 ] = b;
  16577. }
  16578. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16579. texture.needsUpdate = true;
  16580. return texture;
  16581. }
  16582. };
  16583. /**
  16584. * @author alteredq / http://alteredqualia.com/
  16585. */
  16586. THREE.SceneUtils = {
  16587. createMultiMaterialObject: function ( geometry, materials ) {
  16588. var group = new THREE.Object3D();
  16589. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16590. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16591. }
  16592. return group;
  16593. },
  16594. detach : function ( child, parent, scene ) {
  16595. child.applyMatrix( parent.matrixWorld );
  16596. parent.remove( child );
  16597. scene.add( child );
  16598. },
  16599. attach: function ( child, scene, parent ) {
  16600. var matrixWorldInverse = new THREE.Matrix4();
  16601. matrixWorldInverse.getInverse( parent.matrixWorld );
  16602. child.applyMatrix( matrixWorldInverse );
  16603. scene.remove( child );
  16604. parent.add( child );
  16605. }
  16606. };
  16607. /**
  16608. * @author zz85 / http://www.lab4games.net/zz85/blog
  16609. * @author alteredq / http://alteredqualia.com/
  16610. *
  16611. * For Text operations in three.js (See TextGeometry)
  16612. *
  16613. * It uses techniques used in:
  16614. *
  16615. * typeface.js and canvastext
  16616. * For converting fonts and rendering with javascript
  16617. * http://typeface.neocracy.org
  16618. *
  16619. * Triangulation ported from AS3
  16620. * Simple Polygon Triangulation
  16621. * http://actionsnippet.com/?p=1462
  16622. *
  16623. * A Method to triangulate shapes with holes
  16624. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16625. *
  16626. */
  16627. THREE.FontUtils = {
  16628. faces : {},
  16629. // Just for now. face[weight][style]
  16630. face : "helvetiker",
  16631. weight: "normal",
  16632. style : "normal",
  16633. size : 150,
  16634. divisions : 10,
  16635. getFace : function() {
  16636. return this.faces[ this.face ][ this.weight ][ this.style ];
  16637. },
  16638. loadFace : function( data ) {
  16639. var family = data.familyName.toLowerCase();
  16640. var ThreeFont = this;
  16641. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16642. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16643. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16644. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16645. return data;
  16646. },
  16647. drawText : function( text ) {
  16648. var characterPts = [], allPts = [];
  16649. // RenderText
  16650. var i, p,
  16651. face = this.getFace(),
  16652. scale = this.size / face.resolution,
  16653. offset = 0,
  16654. chars = String( text ).split( '' ),
  16655. length = chars.length;
  16656. var fontPaths = [];
  16657. for ( i = 0; i < length; i ++ ) {
  16658. var path = new THREE.Path();
  16659. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16660. offset += ret.offset;
  16661. fontPaths.push( ret.path );
  16662. }
  16663. // get the width
  16664. var width = offset / 2;
  16665. //
  16666. // for ( p = 0; p < allPts.length; p++ ) {
  16667. //
  16668. // allPts[ p ].x -= width;
  16669. //
  16670. // }
  16671. //var extract = this.extractPoints( allPts, characterPts );
  16672. //extract.contour = allPts;
  16673. //extract.paths = fontPaths;
  16674. //extract.offset = width;
  16675. return { paths : fontPaths, offset : width };
  16676. },
  16677. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16678. var pts = [];
  16679. var i, i2, divisions,
  16680. outline, action, length,
  16681. scaleX, scaleY,
  16682. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16683. laste,
  16684. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16685. if ( !glyph ) return;
  16686. if ( glyph.o ) {
  16687. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16688. length = outline.length;
  16689. scaleX = scale;
  16690. scaleY = scale;
  16691. for ( i = 0; i < length; ) {
  16692. action = outline[ i ++ ];
  16693. //console.log( action );
  16694. switch( action ) {
  16695. case 'm':
  16696. // Move To
  16697. x = outline[ i++ ] * scaleX + offset;
  16698. y = outline[ i++ ] * scaleY;
  16699. path.moveTo( x, y );
  16700. break;
  16701. case 'l':
  16702. // Line To
  16703. x = outline[ i++ ] * scaleX + offset;
  16704. y = outline[ i++ ] * scaleY;
  16705. path.lineTo(x,y);
  16706. break;
  16707. case 'q':
  16708. // QuadraticCurveTo
  16709. cpx = outline[ i++ ] * scaleX + offset;
  16710. cpy = outline[ i++ ] * scaleY;
  16711. cpx1 = outline[ i++ ] * scaleX + offset;
  16712. cpy1 = outline[ i++ ] * scaleY;
  16713. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16714. laste = pts[ pts.length - 1 ];
  16715. if ( laste ) {
  16716. cpx0 = laste.x;
  16717. cpy0 = laste.y;
  16718. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16719. var t = i2 / divisions;
  16720. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16721. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16722. }
  16723. }
  16724. break;
  16725. case 'b':
  16726. // Cubic Bezier Curve
  16727. cpx = outline[ i++ ] * scaleX + offset;
  16728. cpy = outline[ i++ ] * scaleY;
  16729. cpx1 = outline[ i++ ] * scaleX + offset;
  16730. cpy1 = outline[ i++ ] * -scaleY;
  16731. cpx2 = outline[ i++ ] * scaleX + offset;
  16732. cpy2 = outline[ i++ ] * -scaleY;
  16733. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16734. laste = pts[ pts.length - 1 ];
  16735. if ( laste ) {
  16736. cpx0 = laste.x;
  16737. cpy0 = laste.y;
  16738. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16739. var t = i2 / divisions;
  16740. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16741. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16742. }
  16743. }
  16744. break;
  16745. }
  16746. }
  16747. }
  16748. return { offset: glyph.ha*scale, path:path};
  16749. }
  16750. };
  16751. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16752. // Parameters
  16753. parameters = parameters || {};
  16754. var size = parameters.size !== undefined ? parameters.size : 100;
  16755. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16756. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16757. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16758. var style = parameters.style !== undefined ? parameters.style : "normal";
  16759. THREE.FontUtils.size = size;
  16760. THREE.FontUtils.divisions = curveSegments;
  16761. THREE.FontUtils.face = font;
  16762. THREE.FontUtils.weight = weight;
  16763. THREE.FontUtils.style = style;
  16764. // Get a Font data json object
  16765. var data = THREE.FontUtils.drawText( text );
  16766. var paths = data.paths;
  16767. var shapes = [];
  16768. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16769. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16770. }
  16771. return shapes;
  16772. };
  16773. /**
  16774. * This code is a quick port of code written in C++ which was submitted to
  16775. * flipcode.com by John W. Ratcliff // July 22, 2000
  16776. * See original code and more information here:
  16777. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16778. *
  16779. * ported to actionscript by Zevan Rosser
  16780. * www.actionsnippet.com
  16781. *
  16782. * ported to javascript by Joshua Koo
  16783. * http://www.lab4games.net/zz85/blog
  16784. *
  16785. */
  16786. ( function( namespace ) {
  16787. var EPSILON = 0.0000000001;
  16788. // takes in an contour array and returns
  16789. var process = function( contour, indices ) {
  16790. var n = contour.length;
  16791. if ( n < 3 ) return null;
  16792. var result = [],
  16793. verts = [],
  16794. vertIndices = [];
  16795. /* we want a counter-clockwise polygon in verts */
  16796. var u, v, w;
  16797. if ( area( contour ) > 0.0 ) {
  16798. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16799. } else {
  16800. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16801. }
  16802. var nv = n;
  16803. /* remove nv - 2 vertices, creating 1 triangle every time */
  16804. var count = 2 * nv; /* error detection */
  16805. for( v = nv - 1; nv > 2; ) {
  16806. /* if we loop, it is probably a non-simple polygon */
  16807. if ( ( count-- ) <= 0 ) {
  16808. //** Triangulate: ERROR - probable bad polygon!
  16809. //throw ( "Warning, unable to triangulate polygon!" );
  16810. //return null;
  16811. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16812. console.log( "Warning, unable to triangulate polygon!" );
  16813. if ( indices ) return vertIndices;
  16814. return result;
  16815. }
  16816. /* three consecutive vertices in current polygon, <u,v,w> */
  16817. u = v; if ( nv <= u ) u = 0; /* previous */
  16818. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16819. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16820. if ( snip( contour, u, v, w, nv, verts ) ) {
  16821. var a, b, c, s, t;
  16822. /* true names of the vertices */
  16823. a = verts[ u ];
  16824. b = verts[ v ];
  16825. c = verts[ w ];
  16826. /* output Triangle */
  16827. result.push( [ contour[ a ],
  16828. contour[ b ],
  16829. contour[ c ] ] );
  16830. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16831. /* remove v from the remaining polygon */
  16832. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16833. verts[ s ] = verts[ t ];
  16834. }
  16835. nv--;
  16836. /* reset error detection counter */
  16837. count = 2 * nv;
  16838. }
  16839. }
  16840. if ( indices ) return vertIndices;
  16841. return result;
  16842. };
  16843. // calculate area of the contour polygon
  16844. var area = function ( contour ) {
  16845. var n = contour.length;
  16846. var a = 0.0;
  16847. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16848. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16849. }
  16850. return a * 0.5;
  16851. };
  16852. var snip = function ( contour, u, v, w, n, verts ) {
  16853. var p;
  16854. var ax, ay, bx, by;
  16855. var cx, cy, px, py;
  16856. ax = contour[ verts[ u ] ].x;
  16857. ay = contour[ verts[ u ] ].y;
  16858. bx = contour[ verts[ v ] ].x;
  16859. by = contour[ verts[ v ] ].y;
  16860. cx = contour[ verts[ w ] ].x;
  16861. cy = contour[ verts[ w ] ].y;
  16862. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16863. var aX, aY, bX, bY, cX, cY;
  16864. var apx, apy, bpx, bpy, cpx, cpy;
  16865. var cCROSSap, bCROSScp, aCROSSbp;
  16866. aX = cx - bx; aY = cy - by;
  16867. bX = ax - cx; bY = ay - cy;
  16868. cX = bx - ax; cY = by - ay;
  16869. for ( p = 0; p < n; p++ ) {
  16870. px = contour[ verts[ p ] ].x
  16871. py = contour[ verts[ p ] ].y
  16872. if ( ( (px === ax) && (py === ay) ) ||
  16873. ( (px === bx) && (py === by) ) ||
  16874. ( (px === cx) && (py === cy) ) ) continue;
  16875. apx = px - ax; apy = py - ay;
  16876. bpx = px - bx; bpy = py - by;
  16877. cpx = px - cx; cpy = py - cy;
  16878. // see if p is inside triangle abc
  16879. aCROSSbp = aX*bpy - aY*bpx;
  16880. cCROSSap = cX*apy - cY*apx;
  16881. bCROSScp = bX*cpy - bY*cpx;
  16882. if ( (aCROSSbp >= -EPSILON) && (bCROSScp >= -EPSILON) && (cCROSSap >= -EPSILON) ) return false;
  16883. }
  16884. return true;
  16885. };
  16886. namespace.Triangulate = process;
  16887. namespace.Triangulate.area = area;
  16888. return namespace;
  16889. })(THREE.FontUtils);
  16890. // To use the typeface.js face files, hook up the API
  16891. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  16892. THREE.typeface_js = self._typeface_js;
  16893. /**
  16894. * @author zz85 / http://www.lab4games.net/zz85/blog
  16895. * Extensible curve object
  16896. *
  16897. * Some common of Curve methods
  16898. * .getPoint(t), getTangent(t)
  16899. * .getPointAt(u), getTagentAt(u)
  16900. * .getPoints(), .getSpacedPoints()
  16901. * .getLength()
  16902. * .updateArcLengths()
  16903. *
  16904. * This following classes subclasses THREE.Curve:
  16905. *
  16906. * -- 2d classes --
  16907. * THREE.LineCurve
  16908. * THREE.QuadraticBezierCurve
  16909. * THREE.CubicBezierCurve
  16910. * THREE.SplineCurve
  16911. * THREE.ArcCurve
  16912. * THREE.EllipseCurve
  16913. *
  16914. * -- 3d classes --
  16915. * THREE.LineCurve3
  16916. * THREE.QuadraticBezierCurve3
  16917. * THREE.CubicBezierCurve3
  16918. * THREE.SplineCurve3
  16919. * THREE.ClosedSplineCurve3
  16920. *
  16921. * A series of curves can be represented as a THREE.CurvePath
  16922. *
  16923. **/
  16924. /**************************************************************
  16925. * Abstract Curve base class
  16926. **************************************************************/
  16927. THREE.Curve = function () {
  16928. };
  16929. // Virtual base class method to overwrite and implement in subclasses
  16930. // - t [0 .. 1]
  16931. THREE.Curve.prototype.getPoint = function ( t ) {
  16932. console.log( "Warning, getPoint() not implemented!" );
  16933. return null;
  16934. };
  16935. // Get point at relative position in curve according to arc length
  16936. // - u [0 .. 1]
  16937. THREE.Curve.prototype.getPointAt = function ( u ) {
  16938. var t = this.getUtoTmapping( u );
  16939. return this.getPoint( t );
  16940. };
  16941. // Get sequence of points using getPoint( t )
  16942. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16943. if ( !divisions ) divisions = 5;
  16944. var d, pts = [];
  16945. for ( d = 0; d <= divisions; d ++ ) {
  16946. pts.push( this.getPoint( d / divisions ) );
  16947. }
  16948. return pts;
  16949. };
  16950. // Get sequence of points using getPointAt( u )
  16951. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16952. if ( !divisions ) divisions = 5;
  16953. var d, pts = [];
  16954. for ( d = 0; d <= divisions; d ++ ) {
  16955. pts.push( this.getPointAt( d / divisions ) );
  16956. }
  16957. return pts;
  16958. };
  16959. // Get total curve arc length
  16960. THREE.Curve.prototype.getLength = function () {
  16961. var lengths = this.getLengths();
  16962. return lengths[ lengths.length - 1 ];
  16963. };
  16964. // Get list of cumulative segment lengths
  16965. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16966. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16967. if ( this.cacheArcLengths
  16968. && ( this.cacheArcLengths.length == divisions + 1 )
  16969. && !this.needsUpdate) {
  16970. //console.log( "cached", this.cacheArcLengths );
  16971. return this.cacheArcLengths;
  16972. }
  16973. this.needsUpdate = false;
  16974. var cache = [];
  16975. var current, last = this.getPoint( 0 );
  16976. var p, sum = 0;
  16977. cache.push( 0 );
  16978. for ( p = 1; p <= divisions; p ++ ) {
  16979. current = this.getPoint ( p / divisions );
  16980. sum += current.distanceTo( last );
  16981. cache.push( sum );
  16982. last = current;
  16983. }
  16984. this.cacheArcLengths = cache;
  16985. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16986. };
  16987. THREE.Curve.prototype.updateArcLengths = function() {
  16988. this.needsUpdate = true;
  16989. this.getLengths();
  16990. };
  16991. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16992. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16993. var arcLengths = this.getLengths();
  16994. var i = 0, il = arcLengths.length;
  16995. var targetArcLength; // The targeted u distance value to get
  16996. if ( distance ) {
  16997. targetArcLength = distance;
  16998. } else {
  16999. targetArcLength = u * arcLengths[ il - 1 ];
  17000. }
  17001. //var time = Date.now();
  17002. // binary search for the index with largest value smaller than target u distance
  17003. var low = 0, high = il - 1, comparison;
  17004. while ( low <= high ) {
  17005. 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
  17006. comparison = arcLengths[ i ] - targetArcLength;
  17007. if ( comparison < 0 ) {
  17008. low = i + 1;
  17009. continue;
  17010. } else if ( comparison > 0 ) {
  17011. high = i - 1;
  17012. continue;
  17013. } else {
  17014. high = i;
  17015. break;
  17016. // DONE
  17017. }
  17018. }
  17019. i = high;
  17020. //console.log('b' , i, low, high, Date.now()- time);
  17021. if ( arcLengths[ i ] == targetArcLength ) {
  17022. var t = i / ( il - 1 );
  17023. return t;
  17024. }
  17025. // we could get finer grain at lengths, or use simple interpolatation between two points
  17026. var lengthBefore = arcLengths[ i ];
  17027. var lengthAfter = arcLengths[ i + 1 ];
  17028. var segmentLength = lengthAfter - lengthBefore;
  17029. // determine where we are between the 'before' and 'after' points
  17030. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  17031. // add that fractional amount to t
  17032. var t = ( i + segmentFraction ) / ( il -1 );
  17033. return t;
  17034. };
  17035. // Returns a unit vector tangent at t
  17036. // In case any sub curve does not implement its tangent derivation,
  17037. // 2 points a small delta apart will be used to find its gradient
  17038. // which seems to give a reasonable approximation
  17039. THREE.Curve.prototype.getTangent = function( t ) {
  17040. var delta = 0.0001;
  17041. var t1 = t - delta;
  17042. var t2 = t + delta;
  17043. // Capping in case of danger
  17044. if ( t1 < 0 ) t1 = 0;
  17045. if ( t2 > 1 ) t2 = 1;
  17046. var pt1 = this.getPoint( t1 );
  17047. var pt2 = this.getPoint( t2 );
  17048. var vec = pt2.clone().sub(pt1);
  17049. return vec.normalize();
  17050. };
  17051. THREE.Curve.prototype.getTangentAt = function ( u ) {
  17052. var t = this.getUtoTmapping( u );
  17053. return this.getTangent( t );
  17054. };
  17055. /**************************************************************
  17056. * Utils
  17057. **************************************************************/
  17058. THREE.Curve.Utils = {
  17059. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  17060. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  17061. },
  17062. // Puay Bing, thanks for helping with this derivative!
  17063. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  17064. return -3 * p0 * (1 - t) * (1 - t) +
  17065. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  17066. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  17067. 3 * t * t * p3;
  17068. },
  17069. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  17070. // To check if my formulas are correct
  17071. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  17072. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  17073. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  17074. var h11 = 3 * t * t - 2 * t; // t3 − t2
  17075. return h00 + h10 + h01 + h11;
  17076. },
  17077. // Catmull-Rom
  17078. interpolate: function( p0, p1, p2, p3, t ) {
  17079. var v0 = ( p2 - p0 ) * 0.5;
  17080. var v1 = ( p3 - p1 ) * 0.5;
  17081. var t2 = t * t;
  17082. var t3 = t * t2;
  17083. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17084. }
  17085. };
  17086. // TODO: Transformation for Curves?
  17087. /**************************************************************
  17088. * 3D Curves
  17089. **************************************************************/
  17090. // A Factory method for creating new curve subclasses
  17091. THREE.Curve.create = function ( constructor, getPointFunc ) {
  17092. constructor.prototype = Object.create( THREE.Curve.prototype );
  17093. constructor.prototype.getPoint = getPointFunc;
  17094. return constructor;
  17095. };
  17096. /**
  17097. * @author zz85 / http://www.lab4games.net/zz85/blog
  17098. *
  17099. **/
  17100. /**************************************************************
  17101. * Curved Path - a curve path is simply a array of connected
  17102. * curves, but retains the api of a curve
  17103. **************************************************************/
  17104. THREE.CurvePath = function () {
  17105. this.curves = [];
  17106. this.bends = [];
  17107. this.autoClose = false; // Automatically closes the path
  17108. };
  17109. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  17110. THREE.CurvePath.prototype.add = function ( curve ) {
  17111. this.curves.push( curve );
  17112. };
  17113. THREE.CurvePath.prototype.checkConnection = function() {
  17114. // TODO
  17115. // If the ending of curve is not connected to the starting
  17116. // or the next curve, then, this is not a real path
  17117. };
  17118. THREE.CurvePath.prototype.closePath = function() {
  17119. // TODO Test
  17120. // and verify for vector3 (needs to implement equals)
  17121. // Add a line curve if start and end of lines are not connected
  17122. var startPoint = this.curves[0].getPoint(0);
  17123. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  17124. if (!startPoint.equals(endPoint)) {
  17125. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  17126. }
  17127. };
  17128. // To get accurate point with reference to
  17129. // entire path distance at time t,
  17130. // following has to be done:
  17131. // 1. Length of each sub path have to be known
  17132. // 2. Locate and identify type of curve
  17133. // 3. Get t for the curve
  17134. // 4. Return curve.getPointAt(t')
  17135. THREE.CurvePath.prototype.getPoint = function( t ) {
  17136. var d = t * this.getLength();
  17137. var curveLengths = this.getCurveLengths();
  17138. var i = 0, diff, curve;
  17139. // To think about boundaries points.
  17140. while ( i < curveLengths.length ) {
  17141. if ( curveLengths[ i ] >= d ) {
  17142. diff = curveLengths[ i ] - d;
  17143. curve = this.curves[ i ];
  17144. var u = 1 - diff / curve.getLength();
  17145. return curve.getPointAt( u );
  17146. break;
  17147. }
  17148. i ++;
  17149. }
  17150. return null;
  17151. // loop where sum != 0, sum > d , sum+1 <d
  17152. };
  17153. /*
  17154. THREE.CurvePath.prototype.getTangent = function( t ) {
  17155. };*/
  17156. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  17157. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  17158. // getPoint() depends on getLength
  17159. THREE.CurvePath.prototype.getLength = function() {
  17160. var lens = this.getCurveLengths();
  17161. return lens[ lens.length - 1 ];
  17162. };
  17163. // Compute lengths and cache them
  17164. // We cannot overwrite getLengths() because UtoT mapping uses it.
  17165. THREE.CurvePath.prototype.getCurveLengths = function() {
  17166. // We use cache values if curves and cache array are same length
  17167. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  17168. return this.cacheLengths;
  17169. };
  17170. // Get length of subsurve
  17171. // Push sums into cached array
  17172. var lengths = [], sums = 0;
  17173. var i, il = this.curves.length;
  17174. for ( i = 0; i < il; i ++ ) {
  17175. sums += this.curves[ i ].getLength();
  17176. lengths.push( sums );
  17177. }
  17178. this.cacheLengths = lengths;
  17179. return lengths;
  17180. };
  17181. // Returns min and max coordinates, as well as centroid
  17182. THREE.CurvePath.prototype.getBoundingBox = function () {
  17183. var points = this.getPoints();
  17184. var maxX, maxY, maxZ;
  17185. var minX, minY, minZ;
  17186. maxX = maxY = Number.NEGATIVE_INFINITY;
  17187. minX = minY = Number.POSITIVE_INFINITY;
  17188. var p, i, il, sum;
  17189. var v3 = points[0] instanceof THREE.Vector3;
  17190. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  17191. for ( i = 0, il = points.length; i < il; i ++ ) {
  17192. p = points[ i ];
  17193. if ( p.x > maxX ) maxX = p.x;
  17194. else if ( p.x < minX ) minX = p.x;
  17195. if ( p.y > maxY ) maxY = p.y;
  17196. else if ( p.y < minY ) minY = p.y;
  17197. if ( v3 ) {
  17198. if ( p.z > maxZ ) maxZ = p.z;
  17199. else if ( p.z < minZ ) minZ = p.z;
  17200. }
  17201. sum.add( p );
  17202. }
  17203. var ret = {
  17204. minX: minX,
  17205. minY: minY,
  17206. maxX: maxX,
  17207. maxY: maxY,
  17208. centroid: sum.divideScalar( il )
  17209. };
  17210. if ( v3 ) {
  17211. ret.maxZ = maxZ;
  17212. ret.minZ = minZ;
  17213. }
  17214. return ret;
  17215. };
  17216. /**************************************************************
  17217. * Create Geometries Helpers
  17218. **************************************************************/
  17219. /// Generate geometry from path points (for Line or ParticleSystem objects)
  17220. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  17221. var pts = this.getPoints( divisions, true );
  17222. return this.createGeometry( pts );
  17223. };
  17224. // Generate geometry from equidistance sampling along the path
  17225. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  17226. var pts = this.getSpacedPoints( divisions, true );
  17227. return this.createGeometry( pts );
  17228. };
  17229. THREE.CurvePath.prototype.createGeometry = function( points ) {
  17230. var geometry = new THREE.Geometry();
  17231. for ( var i = 0; i < points.length; i ++ ) {
  17232. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  17233. }
  17234. return geometry;
  17235. };
  17236. /**************************************************************
  17237. * Bend / Wrap Helper Methods
  17238. **************************************************************/
  17239. // Wrap path / Bend modifiers?
  17240. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  17241. this.bends.push( bendpath );
  17242. };
  17243. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  17244. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  17245. var i, il;
  17246. if ( !bends ) {
  17247. bends = this.bends;
  17248. }
  17249. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17250. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17251. }
  17252. return oldPts;
  17253. };
  17254. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  17255. var oldPts = this.getSpacedPoints( segments );
  17256. var i, il;
  17257. if ( !bends ) {
  17258. bends = this.bends;
  17259. }
  17260. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17261. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17262. }
  17263. return oldPts;
  17264. };
  17265. // This returns getPoints() bend/wrapped around the contour of a path.
  17266. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  17267. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  17268. var bounds = this.getBoundingBox();
  17269. var i, il, p, oldX, oldY, xNorm;
  17270. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  17271. p = oldPts[ i ];
  17272. oldX = p.x;
  17273. oldY = p.y;
  17274. xNorm = oldX / bounds.maxX;
  17275. // If using actual distance, for length > path, requires line extrusions
  17276. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  17277. xNorm = path.getUtoTmapping( xNorm, oldX );
  17278. // check for out of bounds?
  17279. var pathPt = path.getPoint( xNorm );
  17280. var normal = path.getTangent( xNorm );
  17281. normal.set( -normal.y, normal.x ).multiplyScalar( oldY );
  17282. p.x = pathPt.x + normal.x;
  17283. p.y = pathPt.y + normal.y;
  17284. }
  17285. return oldPts;
  17286. };
  17287. /**
  17288. * @author alteredq / http://alteredqualia.com/
  17289. */
  17290. THREE.Gyroscope = function () {
  17291. THREE.Object3D.call( this );
  17292. };
  17293. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  17294. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  17295. this.matrixAutoUpdate && this.updateMatrix();
  17296. // update matrixWorld
  17297. if ( this.matrixWorldNeedsUpdate || force ) {
  17298. if ( this.parent ) {
  17299. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  17300. this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld );
  17301. this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject );
  17302. this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld );
  17303. } else {
  17304. this.matrixWorld.copy( this.matrix );
  17305. }
  17306. this.matrixWorldNeedsUpdate = false;
  17307. force = true;
  17308. }
  17309. // update children
  17310. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  17311. this.children[ i ].updateMatrixWorld( force );
  17312. }
  17313. };
  17314. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  17315. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  17316. THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion();
  17317. THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion();
  17318. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  17319. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  17320. /**
  17321. * @author zz85 / http://www.lab4games.net/zz85/blog
  17322. * Creates free form 2d path using series of points, lines or curves.
  17323. *
  17324. **/
  17325. THREE.Path = function ( points ) {
  17326. THREE.CurvePath.call(this);
  17327. this.actions = [];
  17328. if ( points ) {
  17329. this.fromPoints( points );
  17330. }
  17331. };
  17332. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  17333. THREE.PathActions = {
  17334. MOVE_TO: 'moveTo',
  17335. LINE_TO: 'lineTo',
  17336. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  17337. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  17338. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  17339. ARC: 'arc', // Circle
  17340. ELLIPSE: 'ellipse'
  17341. };
  17342. // TODO Clean up PATH API
  17343. // Create path using straight lines to connect all points
  17344. // - vectors: array of Vector2
  17345. THREE.Path.prototype.fromPoints = function ( vectors ) {
  17346. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  17347. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  17348. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  17349. };
  17350. };
  17351. // startPath() endPath()?
  17352. THREE.Path.prototype.moveTo = function ( x, y ) {
  17353. var args = Array.prototype.slice.call( arguments );
  17354. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  17355. };
  17356. THREE.Path.prototype.lineTo = function ( x, y ) {
  17357. var args = Array.prototype.slice.call( arguments );
  17358. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17359. var x0 = lastargs[ lastargs.length - 2 ];
  17360. var y0 = lastargs[ lastargs.length - 1 ];
  17361. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  17362. this.curves.push( curve );
  17363. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  17364. };
  17365. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  17366. var args = Array.prototype.slice.call( arguments );
  17367. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17368. var x0 = lastargs[ lastargs.length - 2 ];
  17369. var y0 = lastargs[ lastargs.length - 1 ];
  17370. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  17371. new THREE.Vector2( aCPx, aCPy ),
  17372. new THREE.Vector2( aX, aY ) );
  17373. this.curves.push( curve );
  17374. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  17375. };
  17376. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  17377. aCP2x, aCP2y,
  17378. aX, aY ) {
  17379. var args = Array.prototype.slice.call( arguments );
  17380. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17381. var x0 = lastargs[ lastargs.length - 2 ];
  17382. var y0 = lastargs[ lastargs.length - 1 ];
  17383. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  17384. new THREE.Vector2( aCP1x, aCP1y ),
  17385. new THREE.Vector2( aCP2x, aCP2y ),
  17386. new THREE.Vector2( aX, aY ) );
  17387. this.curves.push( curve );
  17388. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  17389. };
  17390. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  17391. var args = Array.prototype.slice.call( arguments );
  17392. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17393. var x0 = lastargs[ lastargs.length - 2 ];
  17394. var y0 = lastargs[ lastargs.length - 1 ];
  17395. //---
  17396. var npts = [ new THREE.Vector2( x0, y0 ) ];
  17397. Array.prototype.push.apply( npts, pts );
  17398. var curve = new THREE.SplineCurve( npts );
  17399. this.curves.push( curve );
  17400. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  17401. };
  17402. // FUTURE: Change the API or follow canvas API?
  17403. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  17404. aStartAngle, aEndAngle, aClockwise ) {
  17405. var lastargs = this.actions[ this.actions.length - 1].args;
  17406. var x0 = lastargs[ lastargs.length - 2 ];
  17407. var y0 = lastargs[ lastargs.length - 1 ];
  17408. this.absarc(aX + x0, aY + y0, aRadius,
  17409. aStartAngle, aEndAngle, aClockwise );
  17410. };
  17411. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  17412. aStartAngle, aEndAngle, aClockwise ) {
  17413. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17414. };
  17415. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  17416. aStartAngle, aEndAngle, aClockwise ) {
  17417. var lastargs = this.actions[ this.actions.length - 1].args;
  17418. var x0 = lastargs[ lastargs.length - 2 ];
  17419. var y0 = lastargs[ lastargs.length - 1 ];
  17420. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  17421. aStartAngle, aEndAngle, aClockwise );
  17422. };
  17423. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  17424. aStartAngle, aEndAngle, aClockwise ) {
  17425. var args = Array.prototype.slice.call( arguments );
  17426. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  17427. aStartAngle, aEndAngle, aClockwise );
  17428. this.curves.push( curve );
  17429. var lastPoint = curve.getPoint(1);
  17430. args.push(lastPoint.x);
  17431. args.push(lastPoint.y);
  17432. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17433. };
  17434. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17435. if ( ! divisions ) divisions = 40;
  17436. var points = [];
  17437. for ( var i = 0; i < divisions; i ++ ) {
  17438. points.push( this.getPoint( i / divisions ) );
  17439. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17440. }
  17441. // if ( closedPath ) {
  17442. //
  17443. // points.push( points[ 0 ] );
  17444. //
  17445. // }
  17446. return points;
  17447. };
  17448. /* Return an array of vectors based on contour of the path */
  17449. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17450. if (this.useSpacedPoints) {
  17451. console.log('tata');
  17452. return this.getSpacedPoints( divisions, closedPath );
  17453. }
  17454. divisions = divisions || 12;
  17455. var points = [];
  17456. var i, il, item, action, args;
  17457. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17458. laste, j,
  17459. t, tx, ty;
  17460. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17461. item = this.actions[ i ];
  17462. action = item.action;
  17463. args = item.args;
  17464. switch( action ) {
  17465. case THREE.PathActions.MOVE_TO:
  17466. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17467. break;
  17468. case THREE.PathActions.LINE_TO:
  17469. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17470. break;
  17471. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17472. cpx = args[ 2 ];
  17473. cpy = args[ 3 ];
  17474. cpx1 = args[ 0 ];
  17475. cpy1 = args[ 1 ];
  17476. if ( points.length > 0 ) {
  17477. laste = points[ points.length - 1 ];
  17478. cpx0 = laste.x;
  17479. cpy0 = laste.y;
  17480. } else {
  17481. laste = this.actions[ i - 1 ].args;
  17482. cpx0 = laste[ laste.length - 2 ];
  17483. cpy0 = laste[ laste.length - 1 ];
  17484. }
  17485. for ( j = 1; j <= divisions; j ++ ) {
  17486. t = j / divisions;
  17487. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17488. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17489. points.push( new THREE.Vector2( tx, ty ) );
  17490. }
  17491. break;
  17492. case THREE.PathActions.BEZIER_CURVE_TO:
  17493. cpx = args[ 4 ];
  17494. cpy = args[ 5 ];
  17495. cpx1 = args[ 0 ];
  17496. cpy1 = args[ 1 ];
  17497. cpx2 = args[ 2 ];
  17498. cpy2 = args[ 3 ];
  17499. if ( points.length > 0 ) {
  17500. laste = points[ points.length - 1 ];
  17501. cpx0 = laste.x;
  17502. cpy0 = laste.y;
  17503. } else {
  17504. laste = this.actions[ i - 1 ].args;
  17505. cpx0 = laste[ laste.length - 2 ];
  17506. cpy0 = laste[ laste.length - 1 ];
  17507. }
  17508. for ( j = 1; j <= divisions; j ++ ) {
  17509. t = j / divisions;
  17510. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17511. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17512. points.push( new THREE.Vector2( tx, ty ) );
  17513. }
  17514. break;
  17515. case THREE.PathActions.CSPLINE_THRU:
  17516. laste = this.actions[ i - 1 ].args;
  17517. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17518. var spts = [ last ];
  17519. var n = divisions * args[ 0 ].length;
  17520. spts = spts.concat( args[ 0 ] );
  17521. var spline = new THREE.SplineCurve( spts );
  17522. for ( j = 1; j <= n; j ++ ) {
  17523. points.push( spline.getPointAt( j / n ) ) ;
  17524. }
  17525. break;
  17526. case THREE.PathActions.ARC:
  17527. var aX = args[ 0 ], aY = args[ 1 ],
  17528. aRadius = args[ 2 ],
  17529. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17530. aClockwise = !!args[ 5 ];
  17531. var deltaAngle = aEndAngle - aStartAngle;
  17532. var angle;
  17533. var tdivisions = divisions * 2;
  17534. for ( j = 1; j <= tdivisions; j ++ ) {
  17535. t = j / tdivisions;
  17536. if ( ! aClockwise ) {
  17537. t = 1 - t;
  17538. }
  17539. angle = aStartAngle + t * deltaAngle;
  17540. tx = aX + aRadius * Math.cos( angle );
  17541. ty = aY + aRadius * Math.sin( angle );
  17542. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17543. points.push( new THREE.Vector2( tx, ty ) );
  17544. }
  17545. //console.log(points);
  17546. break;
  17547. case THREE.PathActions.ELLIPSE:
  17548. var aX = args[ 0 ], aY = args[ 1 ],
  17549. xRadius = args[ 2 ],
  17550. yRadius = args[ 3 ],
  17551. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17552. aClockwise = !!args[ 6 ];
  17553. var deltaAngle = aEndAngle - aStartAngle;
  17554. var angle;
  17555. var tdivisions = divisions * 2;
  17556. for ( j = 1; j <= tdivisions; j ++ ) {
  17557. t = j / tdivisions;
  17558. if ( ! aClockwise ) {
  17559. t = 1 - t;
  17560. }
  17561. angle = aStartAngle + t * deltaAngle;
  17562. tx = aX + xRadius * Math.cos( angle );
  17563. ty = aY + yRadius * Math.sin( angle );
  17564. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17565. points.push( new THREE.Vector2( tx, ty ) );
  17566. }
  17567. //console.log(points);
  17568. break;
  17569. } // end switch
  17570. }
  17571. // Normalize to remove the closing point by default.
  17572. var lastPoint = points[ points.length - 1];
  17573. var EPSILON = 0.0000000001;
  17574. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17575. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17576. points.splice( points.length - 1, 1);
  17577. if ( closedPath ) {
  17578. points.push( points[ 0 ] );
  17579. }
  17580. return points;
  17581. };
  17582. // Breaks path into shapes
  17583. THREE.Path.prototype.toShapes = function( isCCW ) {
  17584. function isPointInsidePolygon( inPt, inPolygon ) {
  17585. var EPSILON = 0.0000000001;
  17586. var polyLen = inPolygon.length;
  17587. // inPt on polygon contour => immediate success or
  17588. // toggling of inside/outside at every single! intersection point of an edge
  17589. // with the horizontal line through inPt, left of inPt
  17590. // not counting lowerY endpoints of edges and whole edges on that line
  17591. var inside = false;
  17592. for( var p = polyLen - 1, q = 0; q < polyLen; p = q++ ) {
  17593. var edgeLowPt = inPolygon[ p ];
  17594. var edgeHighPt = inPolygon[ q ];
  17595. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  17596. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  17597. if ( Math.abs(edgeDy) > EPSILON ) { // not parallel
  17598. if ( edgeDy < 0 ) {
  17599. edgeLowPt = inPolygon[ q ]; edgeDx = -edgeDx;
  17600. edgeHighPt = inPolygon[ p ]; edgeDy = -edgeDy;
  17601. }
  17602. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  17603. if ( inPt.y == edgeLowPt.y ) {
  17604. if ( inPt.x == edgeLowPt.x ) return true; // inPt is on contour ?
  17605. // continue; // no intersection or edgeLowPt => doesn't count !!!
  17606. } else {
  17607. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  17608. if ( perpEdge == 0 ) return true; // inPt is on contour ?
  17609. if ( perpEdge < 0 ) continue;
  17610. inside = !inside; // true intersection left of inPt
  17611. }
  17612. } else { // parallel or colinear
  17613. if ( inPt.y != edgeLowPt.y ) continue; // parallel
  17614. // egde lies on the same horizontal line as inPt
  17615. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  17616. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  17617. // continue;
  17618. }
  17619. }
  17620. return inside;
  17621. }
  17622. var i, il, item, action, args;
  17623. var subPaths = [], lastPath = new THREE.Path();
  17624. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17625. item = this.actions[ i ];
  17626. args = item.args;
  17627. action = item.action;
  17628. if ( action == THREE.PathActions.MOVE_TO ) {
  17629. if ( lastPath.actions.length != 0 ) {
  17630. subPaths.push( lastPath );
  17631. lastPath = new THREE.Path();
  17632. }
  17633. }
  17634. lastPath[ action ].apply( lastPath, args );
  17635. }
  17636. if ( lastPath.actions.length != 0 ) {
  17637. subPaths.push( lastPath );
  17638. }
  17639. // console.log(subPaths);
  17640. if ( subPaths.length == 0 ) return [];
  17641. var solid, tmpPath, tmpShape, shapes = [];
  17642. if ( subPaths.length == 1) {
  17643. tmpPath = subPaths[0];
  17644. tmpShape = new THREE.Shape();
  17645. tmpShape.actions = tmpPath.actions;
  17646. tmpShape.curves = tmpPath.curves;
  17647. shapes.push( tmpShape );
  17648. return shapes;
  17649. }
  17650. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17651. holesFirst = isCCW ? !holesFirst : holesFirst;
  17652. // console.log("Holes first", holesFirst);
  17653. var betterShapeHoles = [];
  17654. var newShapes = [];
  17655. var newShapeHoles = [];
  17656. var mainIdx = 0;
  17657. var tmpPoints;
  17658. newShapes[mainIdx] = undefined;
  17659. newShapeHoles[mainIdx] = [];
  17660. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17661. tmpPath = subPaths[ i ];
  17662. tmpPoints = tmpPath.getPoints();
  17663. solid = THREE.Shape.Utils.isClockWise( tmpPoints );
  17664. solid = isCCW ? !solid : solid;
  17665. if ( solid ) {
  17666. if ( (! holesFirst ) && ( newShapes[mainIdx] ) ) mainIdx++;
  17667. newShapes[mainIdx] = { s: new THREE.Shape(), p: tmpPoints };
  17668. newShapes[mainIdx].s.actions = tmpPath.actions;
  17669. newShapes[mainIdx].s.curves = tmpPath.curves;
  17670. if ( holesFirst ) mainIdx++;
  17671. newShapeHoles[mainIdx] = [];
  17672. //console.log('cw', i);
  17673. } else {
  17674. newShapeHoles[mainIdx].push( { h: tmpPath, p: tmpPoints[0] } );
  17675. //console.log('ccw', i);
  17676. }
  17677. }
  17678. if ( newShapes.length > 1 ) {
  17679. var ambigious = false;
  17680. var toChange = [];
  17681. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) {
  17682. betterShapeHoles[sIdx] = [];
  17683. }
  17684. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) {
  17685. var sh = newShapes[sIdx];
  17686. var sho = newShapeHoles[sIdx];
  17687. for (var hIdx = 0; hIdx < sho.length; hIdx++ ) {
  17688. var ho = sho[hIdx];
  17689. var hole_unassigned = true;
  17690. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++ ) {
  17691. if ( isPointInsidePolygon( ho.p, newShapes[s2Idx].p ) ) {
  17692. if ( sIdx != s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  17693. if ( hole_unassigned ) {
  17694. hole_unassigned = false;
  17695. betterShapeHoles[s2Idx].push( ho );
  17696. } else {
  17697. ambigious = true;
  17698. }
  17699. }
  17700. }
  17701. if ( hole_unassigned ) { betterShapeHoles[sIdx].push( ho ); }
  17702. }
  17703. }
  17704. // console.log("ambigious: ", ambigious);
  17705. if ( toChange.length > 0 ) {
  17706. // console.log("to change: ", toChange);
  17707. if (! ambigious) newShapeHoles = betterShapeHoles;
  17708. }
  17709. }
  17710. var tmpHoles, j, jl;
  17711. for ( i = 0, il = newShapes.length; i < il; i ++ ) {
  17712. tmpShape = newShapes[i].s;
  17713. shapes.push( tmpShape );
  17714. tmpHoles = newShapeHoles[i];
  17715. for ( j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  17716. tmpShape.holes.push( tmpHoles[j].h );
  17717. }
  17718. }
  17719. //console.log("shape", shapes);
  17720. return shapes;
  17721. };
  17722. /**
  17723. * @author zz85 / http://www.lab4games.net/zz85/blog
  17724. * Defines a 2d shape plane using paths.
  17725. **/
  17726. // STEP 1 Create a path.
  17727. // STEP 2 Turn path into shape.
  17728. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17729. // STEP 3a - Extract points from each shape, turn to vertices
  17730. // STEP 3b - Triangulate each shape, add faces.
  17731. THREE.Shape = function () {
  17732. THREE.Path.apply( this, arguments );
  17733. this.holes = [];
  17734. };
  17735. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17736. // Convenience method to return ExtrudeGeometry
  17737. THREE.Shape.prototype.extrude = function ( options ) {
  17738. var extruded = new THREE.ExtrudeGeometry( this, options );
  17739. return extruded;
  17740. };
  17741. // Convenience method to return ShapeGeometry
  17742. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17743. var geometry = new THREE.ShapeGeometry( this, options );
  17744. return geometry;
  17745. };
  17746. // Get points of holes
  17747. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17748. var i, il = this.holes.length, holesPts = [];
  17749. for ( i = 0; i < il; i ++ ) {
  17750. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17751. }
  17752. return holesPts;
  17753. };
  17754. // Get points of holes (spaced by regular distance)
  17755. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17756. var i, il = this.holes.length, holesPts = [];
  17757. for ( i = 0; i < il; i ++ ) {
  17758. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17759. }
  17760. return holesPts;
  17761. };
  17762. // Get points of shape and holes (keypoints based on segments parameter)
  17763. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17764. return {
  17765. shape: this.getTransformedPoints( divisions ),
  17766. holes: this.getPointsHoles( divisions )
  17767. };
  17768. };
  17769. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17770. if (this.useSpacedPoints) {
  17771. return this.extractAllSpacedPoints(divisions);
  17772. }
  17773. return this.extractAllPoints(divisions);
  17774. };
  17775. //
  17776. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17777. //
  17778. // return {
  17779. //
  17780. // shape: this.transform( bend, divisions ),
  17781. // holes: this.getPointsHoles( divisions, bend )
  17782. //
  17783. // };
  17784. //
  17785. // };
  17786. // Get points of shape and holes (spaced by regular distance)
  17787. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17788. return {
  17789. shape: this.getTransformedSpacedPoints( divisions ),
  17790. holes: this.getSpacedPointsHoles( divisions )
  17791. };
  17792. };
  17793. /**************************************************************
  17794. * Utils
  17795. **************************************************************/
  17796. THREE.Shape.Utils = {
  17797. triangulateShape: function ( contour, holes ) {
  17798. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  17799. // inOtherPt needs to be colinear to the inSegment
  17800. if ( inSegPt1.x != inSegPt2.x ) {
  17801. if ( inSegPt1.x < inSegPt2.x ) {
  17802. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  17803. } else {
  17804. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  17805. }
  17806. } else {
  17807. if ( inSegPt1.y < inSegPt2.y ) {
  17808. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  17809. } else {
  17810. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  17811. }
  17812. }
  17813. }
  17814. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  17815. var EPSILON = 0.0000000001;
  17816. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  17817. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  17818. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  17819. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  17820. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  17821. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  17822. if ( Math.abs(limit) > EPSILON ) { // not parallel
  17823. var perpSeg2;
  17824. if ( limit > 0 ) {
  17825. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  17826. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17827. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  17828. } else {
  17829. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  17830. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17831. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  17832. }
  17833. // i.e. to reduce rounding errors
  17834. // intersection at endpoint of segment#1?
  17835. if ( perpSeg2 == 0 ) {
  17836. if ( ( inExcludeAdjacentSegs ) &&
  17837. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17838. return [ inSeg1Pt1 ];
  17839. }
  17840. if ( perpSeg2 == limit ) {
  17841. if ( ( inExcludeAdjacentSegs ) &&
  17842. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17843. return [ inSeg1Pt2 ];
  17844. }
  17845. // intersection at endpoint of segment#2?
  17846. if ( perpSeg1 == 0 ) return [ inSeg2Pt1 ];
  17847. if ( perpSeg1 == limit ) return [ inSeg2Pt2 ];
  17848. // return real intersection point
  17849. var factorSeg1 = perpSeg2 / limit;
  17850. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  17851. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  17852. } else { // parallel or colinear
  17853. if ( ( perpSeg1 != 0 ) ||
  17854. ( seg2dy * seg1seg2dx != seg2dx * seg1seg2dy ) ) return [];
  17855. // they are collinear or degenerate
  17856. var seg1Pt = ( (seg1dx == 0) && (seg1dy == 0) ); // segment1 ist just a point?
  17857. var seg2Pt = ( (seg2dx == 0) && (seg2dy == 0) ); // segment2 ist just a point?
  17858. // both segments are points
  17859. if ( seg1Pt && seg2Pt ) {
  17860. if ( (inSeg1Pt1.x != inSeg2Pt1.x) ||
  17861. (inSeg1Pt1.y != inSeg2Pt1.y) ) return []; // they are distinct points
  17862. return [ inSeg1Pt1 ]; // they are the same point
  17863. }
  17864. // segment#1 is a single point
  17865. if ( seg1Pt ) {
  17866. if (! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  17867. return [ inSeg1Pt1 ];
  17868. }
  17869. // segment#2 is a single point
  17870. if ( seg2Pt ) {
  17871. if (! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  17872. return [ inSeg2Pt1 ];
  17873. }
  17874. // they are collinear segments, which might overlap
  17875. var seg1min, seg1max, seg1minVal, seg1maxVal;
  17876. var seg2min, seg2max, seg2minVal, seg2maxVal;
  17877. if (seg1dx != 0) { // the segments are NOT on a vertical line
  17878. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  17879. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  17880. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  17881. } else {
  17882. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  17883. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  17884. }
  17885. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  17886. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  17887. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  17888. } else {
  17889. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  17890. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  17891. }
  17892. } else { // the segments are on a vertical line
  17893. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  17894. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  17895. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  17896. } else {
  17897. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  17898. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  17899. }
  17900. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  17901. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  17902. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  17903. } else {
  17904. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  17905. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  17906. }
  17907. }
  17908. if ( seg1minVal <= seg2minVal ) {
  17909. if ( seg1maxVal < seg2minVal ) return [];
  17910. if ( seg1maxVal == seg2minVal ) {
  17911. if ( inExcludeAdjacentSegs ) return [];
  17912. return [ seg2min ];
  17913. }
  17914. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  17915. return [ seg2min, seg2max ];
  17916. } else {
  17917. if ( seg1minVal > seg2maxVal ) return [];
  17918. if ( seg1minVal == seg2maxVal ) {
  17919. if ( inExcludeAdjacentSegs ) return [];
  17920. return [ seg1min ];
  17921. }
  17922. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  17923. return [ seg1min, seg2max ];
  17924. }
  17925. }
  17926. }
  17927. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  17928. // The order of legs is important
  17929. var EPSILON = 0.0000000001;
  17930. // translation of all points, so that Vertex is at (0,0)
  17931. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  17932. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  17933. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  17934. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  17935. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  17936. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  17937. if ( Math.abs(from2toAngle) > EPSILON ) { // angle != 180 deg.
  17938. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  17939. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  17940. if ( from2toAngle > 0 ) { // main angle < 180 deg.
  17941. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  17942. } else { // main angle > 180 deg.
  17943. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  17944. }
  17945. } else { // angle == 180 deg.
  17946. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  17947. return ( from2otherAngle > 0 );
  17948. }
  17949. }
  17950. function removeHoles( contour, holes ) {
  17951. var shape = contour.concat(); // work on this shape
  17952. var hole;
  17953. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  17954. // Check if hole point lies within angle around shape point
  17955. var lastShapeIdx = shape.length - 1;
  17956. var prevShapeIdx = inShapeIdx - 1;
  17957. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  17958. var nextShapeIdx = inShapeIdx + 1;
  17959. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  17960. var insideAngle = isPointInsideAngle( shape[inShapeIdx], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[inHoleIdx] );
  17961. if (! insideAngle ) {
  17962. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  17963. return false;
  17964. }
  17965. // Check if shape point lies within angle around hole point
  17966. var lastHoleIdx = hole.length - 1;
  17967. var prevHoleIdx = inHoleIdx - 1;
  17968. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  17969. var nextHoleIdx = inHoleIdx + 1;
  17970. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  17971. insideAngle = isPointInsideAngle( hole[inHoleIdx], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[inShapeIdx] );
  17972. if (! insideAngle ) {
  17973. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  17974. return false;
  17975. }
  17976. return true;
  17977. }
  17978. function intersectsShapeEdge( inShapePt, inHolePt ) {
  17979. // checks for intersections with shape edges
  17980. var sIdx, nextIdx, intersection;
  17981. for ( sIdx = 0; sIdx < shape.length; sIdx++ ) {
  17982. nextIdx = sIdx+1; nextIdx %= shape.length;
  17983. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[sIdx], shape[nextIdx], true );
  17984. if ( intersection.length > 0 ) return true;
  17985. }
  17986. return false;
  17987. }
  17988. var indepHoles = [];
  17989. function intersectsHoleEdge( inShapePt, inHolePt ) {
  17990. // checks for intersections with hole edges
  17991. var ihIdx, chkHole,
  17992. hIdx, nextIdx, intersection;
  17993. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx++ ) {
  17994. chkHole = holes[indepHoles[ihIdx]];
  17995. for ( hIdx = 0; hIdx < chkHole.length; hIdx++ ) {
  17996. nextIdx = hIdx+1; nextIdx %= chkHole.length;
  17997. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[hIdx], chkHole[nextIdx], true );
  17998. if ( intersection.length > 0 ) return true;
  17999. }
  18000. }
  18001. return false;
  18002. }
  18003. var holeIndex, shapeIndex,
  18004. shapePt, h, h2, holePt,
  18005. holeIdx, cutKey, failedCuts = [],
  18006. tmpShape1, tmpShape2,
  18007. tmpHole1, tmpHole2;
  18008. for (h in holes) { indepHoles.push( h ); }
  18009. var counter = indepHoles.length * 2;
  18010. while ( indepHoles.length > 0 ) {
  18011. counter --;
  18012. if ( counter < 0 ) {
  18013. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  18014. break;
  18015. }
  18016. // search for shape-vertex and hole-vertex,
  18017. // which can be connected without intersections
  18018. for ( shapeIndex = 0; shapeIndex < shape.length; shapeIndex++ ) {
  18019. shapePt = shape[ shapeIndex ];
  18020. holeIndex = -1;
  18021. // search for hole which can be reached without intersections
  18022. for ( h = 0; h < indepHoles.length; h++ ) {
  18023. holeIdx = indepHoles[h];
  18024. // prevent multiple checks
  18025. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  18026. if ( failedCuts[cutKey] !== undefined ) continue;
  18027. hole = holes[holeIdx];
  18028. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  18029. holePt = hole[ h2 ];
  18030. if (! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  18031. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  18032. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  18033. holeIndex = h2;
  18034. indepHoles.splice(h,1);
  18035. tmpShape1 = shape.slice( 0, shapeIndex+1 );
  18036. tmpShape2 = shape.slice( shapeIndex );
  18037. tmpHole1 = hole.slice( holeIndex );
  18038. tmpHole2 = hole.slice( 0, holeIndex+1 );
  18039. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  18040. // Debug only, to show the selected cuts
  18041. // glob_CutLines.push( [ shapePt, holePt ] );
  18042. break;
  18043. }
  18044. if ( holeIndex >= 0 ) break; // hole-vertex found
  18045. failedCuts[cutKey] = true; // remember failure
  18046. }
  18047. if ( holeIndex >= 0 ) break; // hole-vertex found
  18048. }
  18049. }
  18050. return shape; /* shape with no holes */
  18051. }
  18052. var i, il, f, face,
  18053. key, index,
  18054. allPointsMap = {};
  18055. // 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.
  18056. var allpoints = contour.concat();
  18057. for (var h in holes) { Array.prototype.push.apply( allpoints, holes[h] ); }
  18058. //console.log( "allpoints",allpoints, allpoints.length );
  18059. // prepare all points map
  18060. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  18061. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  18062. if ( allPointsMap[ key ] !== undefined ) {
  18063. console.log( "Duplicate point", key );
  18064. }
  18065. allPointsMap[ key ] = i;
  18066. }
  18067. // remove holes by cutting paths to holes and adding them to the shape
  18068. var shapeWithoutHoles = removeHoles( contour, holes );
  18069. var triangles = THREE.FontUtils.Triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  18070. //console.log( "triangles",triangles, triangles.length );
  18071. // check all face vertices against all points map
  18072. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  18073. face = triangles[ i ];
  18074. for ( f = 0; f < 3; f ++ ) {
  18075. key = face[ f ].x + ":" + face[ f ].y;
  18076. index = allPointsMap[ key ];
  18077. if ( index !== undefined ) {
  18078. face[ f ] = index;
  18079. }
  18080. }
  18081. }
  18082. return triangles.concat();
  18083. },
  18084. isClockWise: function ( pts ) {
  18085. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  18086. },
  18087. // Bezier Curves formulas obtained from
  18088. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  18089. // Quad Bezier Functions
  18090. b2p0: function ( t, p ) {
  18091. var k = 1 - t;
  18092. return k * k * p;
  18093. },
  18094. b2p1: function ( t, p ) {
  18095. return 2 * ( 1 - t ) * t * p;
  18096. },
  18097. b2p2: function ( t, p ) {
  18098. return t * t * p;
  18099. },
  18100. b2: function ( t, p0, p1, p2 ) {
  18101. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  18102. },
  18103. // Cubic Bezier Functions
  18104. b3p0: function ( t, p ) {
  18105. var k = 1 - t;
  18106. return k * k * k * p;
  18107. },
  18108. b3p1: function ( t, p ) {
  18109. var k = 1 - t;
  18110. return 3 * k * k * t * p;
  18111. },
  18112. b3p2: function ( t, p ) {
  18113. var k = 1 - t;
  18114. return 3 * k * t * t * p;
  18115. },
  18116. b3p3: function ( t, p ) {
  18117. return t * t * t * p;
  18118. },
  18119. b3: function ( t, p0, p1, p2, p3 ) {
  18120. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  18121. }
  18122. };
  18123. /**************************************************************
  18124. * Line
  18125. **************************************************************/
  18126. THREE.LineCurve = function ( v1, v2 ) {
  18127. this.v1 = v1;
  18128. this.v2 = v2;
  18129. };
  18130. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  18131. THREE.LineCurve.prototype.getPoint = function ( t ) {
  18132. var point = this.v2.clone().sub(this.v1);
  18133. point.multiplyScalar( t ).add( this.v1 );
  18134. return point;
  18135. };
  18136. // Line curve is linear, so we can overwrite default getPointAt
  18137. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  18138. return this.getPoint( u );
  18139. };
  18140. THREE.LineCurve.prototype.getTangent = function( t ) {
  18141. var tangent = this.v2.clone().sub(this.v1);
  18142. return tangent.normalize();
  18143. };
  18144. /**************************************************************
  18145. * Quadratic Bezier curve
  18146. **************************************************************/
  18147. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  18148. this.v0 = v0;
  18149. this.v1 = v1;
  18150. this.v2 = v2;
  18151. };
  18152. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  18153. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  18154. var tx, ty;
  18155. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  18156. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  18157. return new THREE.Vector2( tx, ty );
  18158. };
  18159. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  18160. var tx, ty;
  18161. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  18162. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  18163. // returns unit vector
  18164. var tangent = new THREE.Vector2( tx, ty );
  18165. tangent.normalize();
  18166. return tangent;
  18167. };
  18168. /**************************************************************
  18169. * Cubic Bezier curve
  18170. **************************************************************/
  18171. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  18172. this.v0 = v0;
  18173. this.v1 = v1;
  18174. this.v2 = v2;
  18175. this.v3 = v3;
  18176. };
  18177. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  18178. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  18179. var tx, ty;
  18180. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18181. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18182. return new THREE.Vector2( tx, ty );
  18183. };
  18184. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  18185. var tx, ty;
  18186. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18187. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18188. var tangent = new THREE.Vector2( tx, ty );
  18189. tangent.normalize();
  18190. return tangent;
  18191. };
  18192. /**************************************************************
  18193. * Spline curve
  18194. **************************************************************/
  18195. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  18196. this.points = (points == undefined) ? [] : points;
  18197. };
  18198. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  18199. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  18200. var v = new THREE.Vector2();
  18201. var c = [];
  18202. var points = this.points, point, intPoint, weight;
  18203. point = ( points.length - 1 ) * t;
  18204. intPoint = Math.floor( point );
  18205. weight = point - intPoint;
  18206. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18207. c[ 1 ] = intPoint;
  18208. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  18209. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  18210. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  18211. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  18212. return v;
  18213. };
  18214. /**************************************************************
  18215. * Ellipse curve
  18216. **************************************************************/
  18217. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) {
  18218. this.aX = aX;
  18219. this.aY = aY;
  18220. this.xRadius = xRadius;
  18221. this.yRadius = yRadius;
  18222. this.aStartAngle = aStartAngle;
  18223. this.aEndAngle = aEndAngle;
  18224. this.aClockwise = aClockwise;
  18225. };
  18226. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  18227. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  18228. var angle;
  18229. var deltaAngle = this.aEndAngle - this.aStartAngle;
  18230. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  18231. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  18232. if ( this.aClockwise === true ) {
  18233. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  18234. } else {
  18235. angle = this.aStartAngle + t * deltaAngle;
  18236. }
  18237. var tx = this.aX + this.xRadius * Math.cos( angle );
  18238. var ty = this.aY + this.yRadius * Math.sin( angle );
  18239. return new THREE.Vector2( tx, ty );
  18240. };
  18241. /**************************************************************
  18242. * Arc curve
  18243. **************************************************************/
  18244. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18245. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18246. };
  18247. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  18248. /**************************************************************
  18249. * Line3D
  18250. **************************************************************/
  18251. THREE.LineCurve3 = THREE.Curve.create(
  18252. function ( v1, v2 ) {
  18253. this.v1 = v1;
  18254. this.v2 = v2;
  18255. },
  18256. function ( t ) {
  18257. var r = new THREE.Vector3();
  18258. r.subVectors( this.v2, this.v1 ); // diff
  18259. r.multiplyScalar( t );
  18260. r.add( this.v1 );
  18261. return r;
  18262. }
  18263. );
  18264. /**************************************************************
  18265. * Quadratic Bezier 3D curve
  18266. **************************************************************/
  18267. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  18268. function ( v0, v1, v2 ) {
  18269. this.v0 = v0;
  18270. this.v1 = v1;
  18271. this.v2 = v2;
  18272. },
  18273. function ( t ) {
  18274. var tx, ty, tz;
  18275. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  18276. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  18277. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  18278. return new THREE.Vector3( tx, ty, tz );
  18279. }
  18280. );
  18281. /**************************************************************
  18282. * Cubic Bezier 3D curve
  18283. **************************************************************/
  18284. THREE.CubicBezierCurve3 = THREE.Curve.create(
  18285. function ( v0, v1, v2, v3 ) {
  18286. this.v0 = v0;
  18287. this.v1 = v1;
  18288. this.v2 = v2;
  18289. this.v3 = v3;
  18290. },
  18291. function ( t ) {
  18292. var tx, ty, tz;
  18293. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18294. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18295. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  18296. return new THREE.Vector3( tx, ty, tz );
  18297. }
  18298. );
  18299. /**************************************************************
  18300. * Spline 3D curve
  18301. **************************************************************/
  18302. THREE.SplineCurve3 = THREE.Curve.create(
  18303. function ( points /* array of Vector3 */) {
  18304. this.points = (points == undefined) ? [] : points;
  18305. },
  18306. function ( t ) {
  18307. var v = new THREE.Vector3();
  18308. var c = [];
  18309. var points = this.points, point, intPoint, weight;
  18310. point = ( points.length - 1 ) * t;
  18311. intPoint = Math.floor( point );
  18312. weight = point - intPoint;
  18313. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18314. c[ 1 ] = intPoint;
  18315. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18316. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18317. var pt0 = points[ c[0] ],
  18318. pt1 = points[ c[1] ],
  18319. pt2 = points[ c[2] ],
  18320. pt3 = points[ c[3] ];
  18321. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  18322. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  18323. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  18324. return v;
  18325. }
  18326. );
  18327. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  18328. // var v = new THREE.Vector3();
  18329. // var c = [];
  18330. // var points = this.points, point, intPoint, weight;
  18331. // point = ( points.length - 1 ) * t;
  18332. // intPoint = Math.floor( point );
  18333. // weight = point - intPoint;
  18334. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18335. // c[ 1 ] = intPoint;
  18336. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18337. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18338. // var pt0 = points[ c[0] ],
  18339. // pt1 = points[ c[1] ],
  18340. // pt2 = points[ c[2] ],
  18341. // pt3 = points[ c[3] ];
  18342. // // t = weight;
  18343. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  18344. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  18345. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  18346. // return v;
  18347. // }
  18348. /**************************************************************
  18349. * Closed Spline 3D curve
  18350. **************************************************************/
  18351. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  18352. function ( points /* array of Vector3 */) {
  18353. this.points = (points == undefined) ? [] : points;
  18354. },
  18355. function ( t ) {
  18356. var v = new THREE.Vector3();
  18357. var c = [];
  18358. var points = this.points, point, intPoint, weight;
  18359. point = ( points.length - 0 ) * t;
  18360. // This needs to be from 0-length +1
  18361. intPoint = Math.floor( point );
  18362. weight = point - intPoint;
  18363. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  18364. c[ 0 ] = ( intPoint - 1 ) % points.length;
  18365. c[ 1 ] = ( intPoint ) % points.length;
  18366. c[ 2 ] = ( intPoint + 1 ) % points.length;
  18367. c[ 3 ] = ( intPoint + 2 ) % points.length;
  18368. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  18369. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  18370. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  18371. return v;
  18372. }
  18373. );
  18374. /**
  18375. * @author mikael emtinger / http://gomo.se/
  18376. */
  18377. THREE.AnimationHandler = (function() {
  18378. var playing = [];
  18379. var library = {};
  18380. var that = {};
  18381. //--- update ---
  18382. that.update = function( deltaTimeMS ) {
  18383. for( var i = 0; i < playing.length; i ++ )
  18384. playing[ i ].update( deltaTimeMS );
  18385. };
  18386. //--- add ---
  18387. that.addToUpdate = function( animation ) {
  18388. if ( playing.indexOf( animation ) === -1 )
  18389. playing.push( animation );
  18390. };
  18391. //--- remove ---
  18392. that.removeFromUpdate = function( animation ) {
  18393. var index = playing.indexOf( animation );
  18394. if( index !== -1 )
  18395. playing.splice( index, 1 );
  18396. };
  18397. //--- add ---
  18398. that.add = function( data ) {
  18399. if ( library[ data.name ] !== undefined )
  18400. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  18401. library[ data.name ] = data;
  18402. initData( data );
  18403. };
  18404. //--- get ---
  18405. that.get = function( name ) {
  18406. if ( typeof name === "string" ) {
  18407. if ( library[ name ] ) {
  18408. return library[ name ];
  18409. } else {
  18410. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  18411. return null;
  18412. }
  18413. } else {
  18414. // todo: add simple tween library
  18415. }
  18416. };
  18417. //--- parse ---
  18418. that.parse = function( root ) {
  18419. // setup hierarchy
  18420. var hierarchy = [];
  18421. if ( root instanceof THREE.SkinnedMesh ) {
  18422. for( var b = 0; b < root.bones.length; b++ ) {
  18423. hierarchy.push( root.bones[ b ] );
  18424. }
  18425. } else {
  18426. parseRecurseHierarchy( root, hierarchy );
  18427. }
  18428. return hierarchy;
  18429. };
  18430. var parseRecurseHierarchy = function( root, hierarchy ) {
  18431. hierarchy.push( root );
  18432. for( var c = 0; c < root.children.length; c++ )
  18433. parseRecurseHierarchy( root.children[ c ], hierarchy );
  18434. }
  18435. //--- init data ---
  18436. var initData = function( data ) {
  18437. if( data.initialized === true )
  18438. return;
  18439. // loop through all keys
  18440. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  18441. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18442. // remove minus times
  18443. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  18444. data.hierarchy[ h ].keys[ k ].time = 0;
  18445. // create quaternions
  18446. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  18447. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  18448. var quat = data.hierarchy[ h ].keys[ k ].rot;
  18449. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  18450. }
  18451. }
  18452. // prepare morph target keys
  18453. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  18454. // get all used
  18455. var usedMorphTargets = {};
  18456. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18457. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18458. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  18459. usedMorphTargets[ morphTargetName ] = -1;
  18460. }
  18461. }
  18462. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  18463. // set all used on all frames
  18464. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18465. var influences = {};
  18466. for ( var morphTargetName in usedMorphTargets ) {
  18467. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18468. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  18469. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  18470. break;
  18471. }
  18472. }
  18473. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  18474. influences[ morphTargetName ] = 0;
  18475. }
  18476. }
  18477. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  18478. }
  18479. }
  18480. // remove all keys that are on the same time
  18481. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18482. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  18483. data.hierarchy[ h ].keys.splice( k, 1 );
  18484. k --;
  18485. }
  18486. }
  18487. // set index
  18488. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18489. data.hierarchy[ h ].keys[ k ].index = k;
  18490. }
  18491. }
  18492. // done
  18493. data.initialized = true;
  18494. };
  18495. // interpolation types
  18496. that.LINEAR = 0;
  18497. that.CATMULLROM = 1;
  18498. that.CATMULLROM_FORWARD = 2;
  18499. return that;
  18500. }());
  18501. /**
  18502. * @author mikael emtinger / http://gomo.se/
  18503. * @author mrdoob / http://mrdoob.com/
  18504. * @author alteredq / http://alteredqualia.com/
  18505. */
  18506. THREE.Animation = function ( root, name ) {
  18507. this.root = root;
  18508. this.data = THREE.AnimationHandler.get( name );
  18509. this.hierarchy = THREE.AnimationHandler.parse( root );
  18510. this.currentTime = 0;
  18511. this.timeScale = 1;
  18512. this.isPlaying = false;
  18513. this.isPaused = true;
  18514. this.loop = true;
  18515. this.interpolationType = THREE.AnimationHandler.LINEAR;
  18516. this.points = [];
  18517. this.target = new THREE.Vector3();
  18518. };
  18519. THREE.Animation.prototype.play = function ( startTime ) {
  18520. this.currentTime = startTime !== undefined ? startTime : 0;
  18521. if ( this.isPlaying === false ) {
  18522. this.isPlaying = true;
  18523. this.reset();
  18524. this.update( 0 );
  18525. }
  18526. this.isPaused = false;
  18527. THREE.AnimationHandler.addToUpdate( this );
  18528. };
  18529. THREE.Animation.prototype.pause = function() {
  18530. if ( this.isPaused === true ) {
  18531. THREE.AnimationHandler.addToUpdate( this );
  18532. } else {
  18533. THREE.AnimationHandler.removeFromUpdate( this );
  18534. }
  18535. this.isPaused = !this.isPaused;
  18536. };
  18537. THREE.Animation.prototype.stop = function() {
  18538. this.isPlaying = false;
  18539. this.isPaused = false;
  18540. THREE.AnimationHandler.removeFromUpdate( this );
  18541. };
  18542. THREE.Animation.prototype.reset = function () {
  18543. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18544. var object = this.hierarchy[ h ];
  18545. object.matrixAutoUpdate = true;
  18546. if ( object.animationCache === undefined ) {
  18547. object.animationCache = {};
  18548. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  18549. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  18550. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18551. }
  18552. var prevKey = object.animationCache.prevKey;
  18553. var nextKey = object.animationCache.nextKey;
  18554. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  18555. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  18556. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  18557. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  18558. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  18559. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  18560. }
  18561. };
  18562. THREE.Animation.prototype.update = function ( delta ) {
  18563. if ( this.isPlaying === false ) return;
  18564. this.currentTime += delta * this.timeScale;
  18565. //
  18566. var vector;
  18567. var types = [ "pos", "rot", "scl" ];
  18568. var duration = this.data.length;
  18569. if ( this.loop === true && this.currentTime > duration ) {
  18570. this.currentTime %= duration;
  18571. this.reset();
  18572. }
  18573. this.currentTime = Math.min( this.currentTime, duration );
  18574. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18575. var object = this.hierarchy[ h ];
  18576. var animationCache = object.animationCache;
  18577. // loop through pos/rot/scl
  18578. for ( var t = 0; t < 3; t ++ ) {
  18579. // get keys
  18580. var type = types[ t ];
  18581. var prevKey = animationCache.prevKey[ type ];
  18582. var nextKey = animationCache.nextKey[ type ];
  18583. if ( nextKey.time <= this.currentTime ) {
  18584. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18585. nextKey = this.getNextKeyWith( type, h, 1 );
  18586. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18587. prevKey = nextKey;
  18588. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18589. }
  18590. animationCache.prevKey[ type ] = prevKey;
  18591. animationCache.nextKey[ type ] = nextKey;
  18592. }
  18593. object.matrixAutoUpdate = true;
  18594. object.matrixWorldNeedsUpdate = true;
  18595. var scale = ( this.currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18596. var prevXYZ = prevKey[ type ];
  18597. var nextXYZ = nextKey[ type ];
  18598. if ( scale < 0 ) scale = 0;
  18599. if ( scale > 1 ) scale = 1;
  18600. // interpolate
  18601. if ( type === "pos" ) {
  18602. vector = object.position;
  18603. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18604. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18605. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18606. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18607. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18608. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18609. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18610. this.points[ 1 ] = prevXYZ;
  18611. this.points[ 2 ] = nextXYZ;
  18612. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18613. scale = scale * 0.33 + 0.33;
  18614. var currentPoint = this.interpolateCatmullRom( this.points, scale );
  18615. vector.x = currentPoint[ 0 ];
  18616. vector.y = currentPoint[ 1 ];
  18617. vector.z = currentPoint[ 2 ];
  18618. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18619. var forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  18620. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18621. this.target.sub( vector );
  18622. this.target.y = 0;
  18623. this.target.normalize();
  18624. var angle = Math.atan2( this.target.x, this.target.z );
  18625. object.rotation.set( 0, angle, 0 );
  18626. }
  18627. }
  18628. } else if ( type === "rot" ) {
  18629. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  18630. } else if ( type === "scl" ) {
  18631. vector = object.scale;
  18632. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18633. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18634. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18635. }
  18636. }
  18637. }
  18638. if ( this.loop === false && this.currentTime > duration ) {
  18639. this.stop();
  18640. }
  18641. };
  18642. // Catmull-Rom spline
  18643. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  18644. var c = [], v3 = [],
  18645. point, intPoint, weight, w2, w3,
  18646. pa, pb, pc, pd;
  18647. point = ( points.length - 1 ) * scale;
  18648. intPoint = Math.floor( point );
  18649. weight = point - intPoint;
  18650. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18651. c[ 1 ] = intPoint;
  18652. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18653. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18654. pa = points[ c[ 0 ] ];
  18655. pb = points[ c[ 1 ] ];
  18656. pc = points[ c[ 2 ] ];
  18657. pd = points[ c[ 3 ] ];
  18658. w2 = weight * weight;
  18659. w3 = weight * w2;
  18660. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18661. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18662. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18663. return v3;
  18664. };
  18665. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18666. var v0 = ( p2 - p0 ) * 0.5,
  18667. v1 = ( p3 - p1 ) * 0.5;
  18668. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18669. };
  18670. // Get next key with
  18671. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18672. var keys = this.data.hierarchy[ h ].keys;
  18673. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18674. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18675. key = key < keys.length - 1 ? key : keys.length - 1;
  18676. } else {
  18677. key = key % keys.length;
  18678. }
  18679. for ( ; key < keys.length; key++ ) {
  18680. if ( keys[ key ][ type ] !== undefined ) {
  18681. return keys[ key ];
  18682. }
  18683. }
  18684. return this.data.hierarchy[ h ].keys[ 0 ];
  18685. };
  18686. // Get previous key with
  18687. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18688. var keys = this.data.hierarchy[ h ].keys;
  18689. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18690. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18691. key = key > 0 ? key : 0;
  18692. } else {
  18693. key = key >= 0 ? key : key + keys.length;
  18694. }
  18695. for ( ; key >= 0; key -- ) {
  18696. if ( keys[ key ][ type ] !== undefined ) {
  18697. return keys[ key ];
  18698. }
  18699. }
  18700. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18701. };
  18702. /**
  18703. * @author mikael emtinger / http://gomo.se/
  18704. * @author mrdoob / http://mrdoob.com/
  18705. * @author alteredq / http://alteredqualia.com/
  18706. * @author khang duong
  18707. * @author erik kitson
  18708. */
  18709. THREE.KeyFrameAnimation = function ( root, data ) {
  18710. this.root = root;
  18711. this.data = THREE.AnimationHandler.get( data );
  18712. this.hierarchy = THREE.AnimationHandler.parse( root );
  18713. this.currentTime = 0;
  18714. this.timeScale = 0.001;
  18715. this.isPlaying = false;
  18716. this.isPaused = true;
  18717. this.loop = true;
  18718. // initialize to first keyframes
  18719. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18720. var keys = this.data.hierarchy[h].keys,
  18721. sids = this.data.hierarchy[h].sids,
  18722. obj = this.hierarchy[h];
  18723. if ( keys.length && sids ) {
  18724. for ( var s = 0; s < sids.length; s++ ) {
  18725. var sid = sids[ s ],
  18726. next = this.getNextKeyWith( sid, h, 0 );
  18727. if ( next ) {
  18728. next.apply( sid );
  18729. }
  18730. }
  18731. obj.matrixAutoUpdate = false;
  18732. this.data.hierarchy[h].node.updateMatrix();
  18733. obj.matrixWorldNeedsUpdate = true;
  18734. }
  18735. }
  18736. };
  18737. // Play
  18738. THREE.KeyFrameAnimation.prototype.play = function ( startTime ) {
  18739. this.currentTime = startTime !== undefined ? startTime : 0;
  18740. if ( this.isPlaying === false ) {
  18741. this.isPlaying = true;
  18742. // reset key cache
  18743. var h, hl = this.hierarchy.length,
  18744. object,
  18745. node;
  18746. for ( h = 0; h < hl; h++ ) {
  18747. object = this.hierarchy[ h ];
  18748. node = this.data.hierarchy[ h ];
  18749. if ( node.animationCache === undefined ) {
  18750. node.animationCache = {};
  18751. node.animationCache.prevKey = null;
  18752. node.animationCache.nextKey = null;
  18753. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18754. }
  18755. var keys = this.data.hierarchy[h].keys;
  18756. if (keys.length) {
  18757. node.animationCache.prevKey = keys[ 0 ];
  18758. node.animationCache.nextKey = keys[ 1 ];
  18759. this.startTime = Math.min( keys[0].time, this.startTime );
  18760. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18761. }
  18762. }
  18763. this.update( 0 );
  18764. }
  18765. this.isPaused = false;
  18766. THREE.AnimationHandler.addToUpdate( this );
  18767. };
  18768. // Pause
  18769. THREE.KeyFrameAnimation.prototype.pause = function() {
  18770. if( this.isPaused ) {
  18771. THREE.AnimationHandler.addToUpdate( this );
  18772. } else {
  18773. THREE.AnimationHandler.removeFromUpdate( this );
  18774. }
  18775. this.isPaused = !this.isPaused;
  18776. };
  18777. // Stop
  18778. THREE.KeyFrameAnimation.prototype.stop = function() {
  18779. this.isPlaying = false;
  18780. this.isPaused = false;
  18781. THREE.AnimationHandler.removeFromUpdate( this );
  18782. // reset JIT matrix and remove cache
  18783. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18784. var obj = this.hierarchy[ h ];
  18785. var node = this.data.hierarchy[ h ];
  18786. if ( node.animationCache !== undefined ) {
  18787. var original = node.animationCache.originalMatrix;
  18788. if( obj instanceof THREE.Bone ) {
  18789. original.copy( obj.skinMatrix );
  18790. obj.skinMatrix = original;
  18791. } else {
  18792. original.copy( obj.matrix );
  18793. obj.matrix = original;
  18794. }
  18795. delete node.animationCache;
  18796. }
  18797. }
  18798. };
  18799. // Update
  18800. THREE.KeyFrameAnimation.prototype.update = function ( delta ) {
  18801. if ( this.isPlaying === false ) return;
  18802. this.currentTime += delta * this.timeScale;
  18803. //
  18804. var duration = this.data.length;
  18805. if ( this.loop === true && this.currentTime > duration ) {
  18806. this.currentTime %= duration;
  18807. }
  18808. this.currentTime = Math.min( this.currentTime, duration );
  18809. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18810. var object = this.hierarchy[ h ];
  18811. var node = this.data.hierarchy[ h ];
  18812. var keys = node.keys,
  18813. animationCache = node.animationCache;
  18814. if ( keys.length ) {
  18815. var prevKey = animationCache.prevKey;
  18816. var nextKey = animationCache.nextKey;
  18817. if ( nextKey.time <= this.currentTime ) {
  18818. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18819. prevKey = nextKey;
  18820. nextKey = keys[ prevKey.index + 1 ];
  18821. }
  18822. animationCache.prevKey = prevKey;
  18823. animationCache.nextKey = nextKey;
  18824. }
  18825. if ( nextKey.time >= this.currentTime ) {
  18826. prevKey.interpolate( nextKey, this.currentTime );
  18827. } else {
  18828. prevKey.interpolate( nextKey, nextKey.time );
  18829. }
  18830. this.data.hierarchy[ h ].node.updateMatrix();
  18831. object.matrixWorldNeedsUpdate = true;
  18832. }
  18833. }
  18834. };
  18835. // Get next key with
  18836. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18837. var keys = this.data.hierarchy[ h ].keys;
  18838. key = key % keys.length;
  18839. for ( ; key < keys.length; key++ ) {
  18840. if ( keys[ key ].hasTarget( sid ) ) {
  18841. return keys[ key ];
  18842. }
  18843. }
  18844. return keys[ 0 ];
  18845. };
  18846. // Get previous key with
  18847. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18848. var keys = this.data.hierarchy[ h ].keys;
  18849. key = key >= 0 ? key : key + keys.length;
  18850. for ( ; key >= 0; key-- ) {
  18851. if ( keys[ key ].hasTarget( sid ) ) {
  18852. return keys[ key ];
  18853. }
  18854. }
  18855. return keys[ keys.length - 1 ];
  18856. };
  18857. /**
  18858. * @author mrdoob / http://mrdoob.com
  18859. */
  18860. THREE.MorphAnimation = function ( mesh ) {
  18861. this.mesh = mesh;
  18862. this.frames = mesh.morphTargetInfluences.length;
  18863. this.currentTime = 0;
  18864. this.duration = 1000;
  18865. this.loop = true;
  18866. this.isPlaying = false;
  18867. };
  18868. THREE.MorphAnimation.prototype = {
  18869. play: function () {
  18870. this.isPlaying = true;
  18871. },
  18872. pause: function () {
  18873. this.isPlaying = false;
  18874. },
  18875. update: ( function () {
  18876. var lastFrame = 0;
  18877. var currentFrame = 0;
  18878. return function ( delta ) {
  18879. if ( this.isPlaying === false ) return;
  18880. this.currentTime += delta;
  18881. if ( this.loop === true && this.currentTime > this.duration ) {
  18882. this.currentTime %= this.duration;
  18883. }
  18884. this.currentTime = Math.min( this.currentTime, this.duration );
  18885. var interpolation = this.duration / this.frames;
  18886. var frame = Math.floor( this.currentTime / interpolation );
  18887. if ( frame != currentFrame ) {
  18888. this.mesh.morphTargetInfluences[ lastFrame ] = 0;
  18889. this.mesh.morphTargetInfluences[ currentFrame ] = 1;
  18890. this.mesh.morphTargetInfluences[ frame ] = 0;
  18891. lastFrame = currentFrame;
  18892. currentFrame = frame;
  18893. }
  18894. this.mesh.morphTargetInfluences[ frame ] = ( this.currentTime % interpolation ) / interpolation;
  18895. this.mesh.morphTargetInfluences[ lastFrame ] = 1 - this.mesh.morphTargetInfluences[ frame ];
  18896. }
  18897. } )()
  18898. };
  18899. /**
  18900. * Camera for rendering cube maps
  18901. * - renders scene into axis-aligned cube
  18902. *
  18903. * @author alteredq / http://alteredqualia.com/
  18904. */
  18905. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18906. THREE.Object3D.call( this );
  18907. var fov = 90, aspect = 1;
  18908. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18909. cameraPX.up.set( 0, -1, 0 );
  18910. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18911. this.add( cameraPX );
  18912. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18913. cameraNX.up.set( 0, -1, 0 );
  18914. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18915. this.add( cameraNX );
  18916. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18917. cameraPY.up.set( 0, 0, 1 );
  18918. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18919. this.add( cameraPY );
  18920. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18921. cameraNY.up.set( 0, 0, -1 );
  18922. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18923. this.add( cameraNY );
  18924. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18925. cameraPZ.up.set( 0, -1, 0 );
  18926. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18927. this.add( cameraPZ );
  18928. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18929. cameraNZ.up.set( 0, -1, 0 );
  18930. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18931. this.add( cameraNZ );
  18932. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18933. this.updateCubeMap = function ( renderer, scene ) {
  18934. var renderTarget = this.renderTarget;
  18935. var generateMipmaps = renderTarget.generateMipmaps;
  18936. renderTarget.generateMipmaps = false;
  18937. renderTarget.activeCubeFace = 0;
  18938. renderer.render( scene, cameraPX, renderTarget );
  18939. renderTarget.activeCubeFace = 1;
  18940. renderer.render( scene, cameraNX, renderTarget );
  18941. renderTarget.activeCubeFace = 2;
  18942. renderer.render( scene, cameraPY, renderTarget );
  18943. renderTarget.activeCubeFace = 3;
  18944. renderer.render( scene, cameraNY, renderTarget );
  18945. renderTarget.activeCubeFace = 4;
  18946. renderer.render( scene, cameraPZ, renderTarget );
  18947. renderTarget.generateMipmaps = generateMipmaps;
  18948. renderTarget.activeCubeFace = 5;
  18949. renderer.render( scene, cameraNZ, renderTarget );
  18950. };
  18951. };
  18952. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18953. /**
  18954. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18955. *
  18956. * A general perpose camera, for setting FOV, Lens Focal Length,
  18957. * and switching between perspective and orthographic views easily.
  18958. * Use this only if you do not wish to manage
  18959. * both a Orthographic and Perspective Camera
  18960. *
  18961. */
  18962. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18963. THREE.Camera.call( this );
  18964. this.fov = fov;
  18965. this.left = -width / 2;
  18966. this.right = width / 2
  18967. this.top = height / 2;
  18968. this.bottom = -height / 2;
  18969. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18970. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18971. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18972. this.zoom = 1;
  18973. this.toPerspective();
  18974. var aspect = width/height;
  18975. };
  18976. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18977. THREE.CombinedCamera.prototype.toPerspective = function () {
  18978. // Switches to the Perspective Camera
  18979. this.near = this.cameraP.near;
  18980. this.far = this.cameraP.far;
  18981. this.cameraP.fov = this.fov / this.zoom ;
  18982. this.cameraP.updateProjectionMatrix();
  18983. this.projectionMatrix = this.cameraP.projectionMatrix;
  18984. this.inPerspectiveMode = true;
  18985. this.inOrthographicMode = false;
  18986. };
  18987. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18988. // Switches to the Orthographic camera estimating viewport from Perspective
  18989. var fov = this.fov;
  18990. var aspect = this.cameraP.aspect;
  18991. var near = this.cameraP.near;
  18992. var far = this.cameraP.far;
  18993. // The size that we set is the mid plane of the viewing frustum
  18994. var hyperfocus = ( near + far ) / 2;
  18995. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18996. var planeHeight = 2 * halfHeight;
  18997. var planeWidth = planeHeight * aspect;
  18998. var halfWidth = planeWidth / 2;
  18999. halfHeight /= this.zoom;
  19000. halfWidth /= this.zoom;
  19001. this.cameraO.left = -halfWidth;
  19002. this.cameraO.right = halfWidth;
  19003. this.cameraO.top = halfHeight;
  19004. this.cameraO.bottom = -halfHeight;
  19005. // this.cameraO.left = -farHalfWidth;
  19006. // this.cameraO.right = farHalfWidth;
  19007. // this.cameraO.top = farHalfHeight;
  19008. // this.cameraO.bottom = -farHalfHeight;
  19009. // this.cameraO.left = this.left / this.zoom;
  19010. // this.cameraO.right = this.right / this.zoom;
  19011. // this.cameraO.top = this.top / this.zoom;
  19012. // this.cameraO.bottom = this.bottom / this.zoom;
  19013. this.cameraO.updateProjectionMatrix();
  19014. this.near = this.cameraO.near;
  19015. this.far = this.cameraO.far;
  19016. this.projectionMatrix = this.cameraO.projectionMatrix;
  19017. this.inPerspectiveMode = false;
  19018. this.inOrthographicMode = true;
  19019. };
  19020. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  19021. this.cameraP.aspect = width / height;
  19022. this.left = -width / 2;
  19023. this.right = width / 2
  19024. this.top = height / 2;
  19025. this.bottom = -height / 2;
  19026. };
  19027. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  19028. this.fov = fov;
  19029. if ( this.inPerspectiveMode ) {
  19030. this.toPerspective();
  19031. } else {
  19032. this.toOrthographic();
  19033. }
  19034. };
  19035. // For mantaining similar API with PerspectiveCamera
  19036. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  19037. if ( this.inPerspectiveMode ) {
  19038. this.toPerspective();
  19039. } else {
  19040. this.toPerspective();
  19041. this.toOrthographic();
  19042. }
  19043. };
  19044. /*
  19045. * Uses Focal Length (in mm) to estimate and set FOV
  19046. * 35mm (fullframe) camera is used if frame size is not specified;
  19047. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  19048. */
  19049. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  19050. if ( frameHeight === undefined ) frameHeight = 24;
  19051. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  19052. this.setFov( fov );
  19053. return fov;
  19054. };
  19055. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  19056. this.zoom = zoom;
  19057. if ( this.inPerspectiveMode ) {
  19058. this.toPerspective();
  19059. } else {
  19060. this.toOrthographic();
  19061. }
  19062. };
  19063. THREE.CombinedCamera.prototype.toFrontView = function() {
  19064. this.rotation.x = 0;
  19065. this.rotation.y = 0;
  19066. this.rotation.z = 0;
  19067. // should we be modifing the matrix instead?
  19068. this.rotationAutoUpdate = false;
  19069. };
  19070. THREE.CombinedCamera.prototype.toBackView = function() {
  19071. this.rotation.x = 0;
  19072. this.rotation.y = Math.PI;
  19073. this.rotation.z = 0;
  19074. this.rotationAutoUpdate = false;
  19075. };
  19076. THREE.CombinedCamera.prototype.toLeftView = function() {
  19077. this.rotation.x = 0;
  19078. this.rotation.y = - Math.PI / 2;
  19079. this.rotation.z = 0;
  19080. this.rotationAutoUpdate = false;
  19081. };
  19082. THREE.CombinedCamera.prototype.toRightView = function() {
  19083. this.rotation.x = 0;
  19084. this.rotation.y = Math.PI / 2;
  19085. this.rotation.z = 0;
  19086. this.rotationAutoUpdate = false;
  19087. };
  19088. THREE.CombinedCamera.prototype.toTopView = function() {
  19089. this.rotation.x = - Math.PI / 2;
  19090. this.rotation.y = 0;
  19091. this.rotation.z = 0;
  19092. this.rotationAutoUpdate = false;
  19093. };
  19094. THREE.CombinedCamera.prototype.toBottomView = function() {
  19095. this.rotation.x = Math.PI / 2;
  19096. this.rotation.y = 0;
  19097. this.rotation.z = 0;
  19098. this.rotationAutoUpdate = false;
  19099. };
  19100. /**
  19101. * @author mrdoob / http://mrdoob.com/
  19102. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  19103. */
  19104. THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  19105. THREE.Geometry.call( this );
  19106. var scope = this;
  19107. this.width = width;
  19108. this.height = height;
  19109. this.depth = depth;
  19110. this.widthSegments = widthSegments || 1;
  19111. this.heightSegments = heightSegments || 1;
  19112. this.depthSegments = depthSegments || 1;
  19113. var width_half = this.width / 2;
  19114. var height_half = this.height / 2;
  19115. var depth_half = this.depth / 2;
  19116. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  19117. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  19118. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  19119. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  19120. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  19121. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  19122. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  19123. var w, ix, iy,
  19124. gridX = scope.widthSegments,
  19125. gridY = scope.heightSegments,
  19126. width_half = width / 2,
  19127. height_half = height / 2,
  19128. offset = scope.vertices.length;
  19129. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  19130. w = 'z';
  19131. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  19132. w = 'y';
  19133. gridY = scope.depthSegments;
  19134. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  19135. w = 'x';
  19136. gridX = scope.depthSegments;
  19137. }
  19138. var gridX1 = gridX + 1,
  19139. gridY1 = gridY + 1,
  19140. segment_width = width / gridX,
  19141. segment_height = height / gridY,
  19142. normal = new THREE.Vector3();
  19143. normal[ w ] = depth > 0 ? 1 : - 1;
  19144. for ( iy = 0; iy < gridY1; iy ++ ) {
  19145. for ( ix = 0; ix < gridX1; ix ++ ) {
  19146. var vector = new THREE.Vector3();
  19147. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  19148. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  19149. vector[ w ] = depth;
  19150. scope.vertices.push( vector );
  19151. }
  19152. }
  19153. for ( iy = 0; iy < gridY; iy++ ) {
  19154. for ( ix = 0; ix < gridX; ix++ ) {
  19155. var a = ix + gridX1 * iy;
  19156. var b = ix + gridX1 * ( iy + 1 );
  19157. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  19158. var d = ( ix + 1 ) + gridX1 * iy;
  19159. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  19160. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  19161. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  19162. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  19163. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  19164. face.normal.copy( normal );
  19165. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19166. face.materialIndex = materialIndex;
  19167. scope.faces.push( face );
  19168. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19169. face = new THREE.Face3( b + offset, c + offset, d + offset );
  19170. face.normal.copy( normal );
  19171. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19172. face.materialIndex = materialIndex;
  19173. scope.faces.push( face );
  19174. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19175. }
  19176. }
  19177. }
  19178. this.computeCentroids();
  19179. this.mergeVertices();
  19180. };
  19181. THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19182. /**
  19183. * @author hughes
  19184. */
  19185. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  19186. THREE.Geometry.call( this );
  19187. this.radius = radius = radius || 50;
  19188. this.segments = segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  19189. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19190. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19191. var i, uvs = [],
  19192. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  19193. this.vertices.push(center);
  19194. uvs.push( centerUV );
  19195. for ( i = 0; i <= segments; i ++ ) {
  19196. var vertex = new THREE.Vector3();
  19197. var segment = thetaStart + i / segments * thetaLength;
  19198. vertex.x = radius * Math.cos( segment );
  19199. vertex.y = radius * Math.sin( segment );
  19200. this.vertices.push( vertex );
  19201. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  19202. }
  19203. var n = new THREE.Vector3( 0, 0, 1 );
  19204. for ( i = 1; i <= segments; i ++ ) {
  19205. var v1 = i;
  19206. var v2 = i + 1 ;
  19207. var v3 = 0;
  19208. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19209. this.faceVertexUvs[ 0 ].push( [ uvs[ i ].clone(), uvs[ i + 1 ].clone(), centerUV.clone() ] );
  19210. }
  19211. this.computeCentroids();
  19212. this.computeFaceNormals();
  19213. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19214. };
  19215. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19216. // DEPRECATED
  19217. THREE.CubeGeometry = THREE.BoxGeometry;
  19218. /**
  19219. * @author mrdoob / http://mrdoob.com/
  19220. */
  19221. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
  19222. THREE.Geometry.call( this );
  19223. this.radiusTop = radiusTop = radiusTop !== undefined ? radiusTop : 20;
  19224. this.radiusBottom = radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  19225. this.height = height = height !== undefined ? height : 100;
  19226. this.radialSegments = radialSegments = radialSegments || 8;
  19227. this.heightSegments = heightSegments = heightSegments || 1;
  19228. this.openEnded = openEnded = openEnded !== undefined ? openEnded : false;
  19229. var heightHalf = height / 2;
  19230. var x, y, vertices = [], uvs = [];
  19231. for ( y = 0; y <= heightSegments; y ++ ) {
  19232. var verticesRow = [];
  19233. var uvsRow = [];
  19234. var v = y / heightSegments;
  19235. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  19236. for ( x = 0; x <= radialSegments; x ++ ) {
  19237. var u = x / radialSegments;
  19238. var vertex = new THREE.Vector3();
  19239. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  19240. vertex.y = - v * height + heightHalf;
  19241. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  19242. this.vertices.push( vertex );
  19243. verticesRow.push( this.vertices.length - 1 );
  19244. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19245. }
  19246. vertices.push( verticesRow );
  19247. uvs.push( uvsRow );
  19248. }
  19249. var tanTheta = ( radiusBottom - radiusTop ) / height;
  19250. var na, nb;
  19251. for ( x = 0; x < radialSegments; x ++ ) {
  19252. if ( radiusTop !== 0 ) {
  19253. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  19254. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  19255. } else {
  19256. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  19257. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  19258. }
  19259. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  19260. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  19261. for ( y = 0; y < heightSegments; y ++ ) {
  19262. var v1 = vertices[ y ][ x ];
  19263. var v2 = vertices[ y + 1 ][ x ];
  19264. var v3 = vertices[ y + 1 ][ x + 1 ];
  19265. var v4 = vertices[ y ][ x + 1 ];
  19266. var n1 = na.clone();
  19267. var n2 = na.clone();
  19268. var n3 = nb.clone();
  19269. var n4 = nb.clone();
  19270. var uv1 = uvs[ y ][ x ].clone();
  19271. var uv2 = uvs[ y + 1 ][ x ].clone();
  19272. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  19273. var uv4 = uvs[ y ][ x + 1 ].clone();
  19274. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19275. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19276. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  19277. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  19278. }
  19279. }
  19280. // top cap
  19281. if ( openEnded === false && radiusTop > 0 ) {
  19282. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  19283. for ( x = 0; x < radialSegments; x ++ ) {
  19284. var v1 = vertices[ 0 ][ x ];
  19285. var v2 = vertices[ 0 ][ x + 1 ];
  19286. var v3 = this.vertices.length - 1;
  19287. var n1 = new THREE.Vector3( 0, 1, 0 );
  19288. var n2 = new THREE.Vector3( 0, 1, 0 );
  19289. var n3 = new THREE.Vector3( 0, 1, 0 );
  19290. var uv1 = uvs[ 0 ][ x ].clone();
  19291. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  19292. var uv3 = new THREE.Vector2( uv2.x, 0 );
  19293. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19294. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19295. }
  19296. }
  19297. // bottom cap
  19298. if ( openEnded === false && radiusBottom > 0 ) {
  19299. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  19300. for ( x = 0; x < radialSegments; x ++ ) {
  19301. var v1 = vertices[ y ][ x + 1 ];
  19302. var v2 = vertices[ y ][ x ];
  19303. var v3 = this.vertices.length - 1;
  19304. var n1 = new THREE.Vector3( 0, - 1, 0 );
  19305. var n2 = new THREE.Vector3( 0, - 1, 0 );
  19306. var n3 = new THREE.Vector3( 0, - 1, 0 );
  19307. var uv1 = uvs[ y ][ x + 1 ].clone();
  19308. var uv2 = uvs[ y ][ x ].clone();
  19309. var uv3 = new THREE.Vector2( uv2.x, 1 );
  19310. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19311. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19312. }
  19313. }
  19314. this.computeCentroids();
  19315. this.computeFaceNormals();
  19316. }
  19317. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19318. /**
  19319. * @author zz85 / http://www.lab4games.net/zz85/blog
  19320. *
  19321. * Creates extruded geometry from a path shape.
  19322. *
  19323. * parameters = {
  19324. *
  19325. * curveSegments: <int>, // number of points on the curves
  19326. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  19327. * amount: <int>, // Depth to extrude the shape
  19328. *
  19329. * bevelEnabled: <bool>, // turn on bevel
  19330. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19331. * bevelSize: <float>, // how far from shape outline is bevel
  19332. * bevelSegments: <int>, // number of bevel layers
  19333. *
  19334. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  19335. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  19336. *
  19337. * material: <int> // material index for front and back faces
  19338. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  19339. * uvGenerator: <Object> // object that provides UV generator functions
  19340. *
  19341. * }
  19342. **/
  19343. THREE.ExtrudeGeometry = function ( shapes, options ) {
  19344. if ( typeof( shapes ) === "undefined" ) {
  19345. shapes = [];
  19346. return;
  19347. }
  19348. THREE.Geometry.call( this );
  19349. shapes = shapes instanceof Array ? shapes : [ shapes ];
  19350. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19351. this.addShapeList( shapes, options );
  19352. this.computeCentroids();
  19353. this.computeFaceNormals();
  19354. // can't really use automatic vertex normals
  19355. // as then front and back sides get smoothed too
  19356. // should do separate smoothing just for sides
  19357. //this.computeVertexNormals();
  19358. //console.log( "took", ( Date.now() - startTime ) );
  19359. };
  19360. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19361. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19362. var sl = shapes.length;
  19363. for ( var s = 0; s < sl; s ++ ) {
  19364. var shape = shapes[ s ];
  19365. this.addShape( shape, options );
  19366. }
  19367. };
  19368. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  19369. var amount = options.amount !== undefined ? options.amount : 100;
  19370. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  19371. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  19372. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19373. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  19374. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19375. var steps = options.steps !== undefined ? options.steps : 1;
  19376. var extrudePath = options.extrudePath;
  19377. var extrudePts, extrudeByPath = false;
  19378. var material = options.material;
  19379. var extrudeMaterial = options.extrudeMaterial;
  19380. // Use default WorldUVGenerator if no UV generators are specified.
  19381. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  19382. var shapebb = this.shapebb;
  19383. //shapebb = shape.getBoundingBox();
  19384. var splineTube, binormal, normal, position2;
  19385. if ( extrudePath ) {
  19386. extrudePts = extrudePath.getSpacedPoints( steps );
  19387. extrudeByPath = true;
  19388. bevelEnabled = false; // bevels not supported for path extrusion
  19389. // SETUP TNB variables
  19390. // Reuse TNB from TubeGeomtry for now.
  19391. // TODO1 - have a .isClosed in spline?
  19392. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  19393. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19394. binormal = new THREE.Vector3();
  19395. normal = new THREE.Vector3();
  19396. position2 = new THREE.Vector3();
  19397. }
  19398. // Safeguards if bevels are not enabled
  19399. if ( ! bevelEnabled ) {
  19400. bevelSegments = 0;
  19401. bevelThickness = 0;
  19402. bevelSize = 0;
  19403. }
  19404. // Variables initalization
  19405. var ahole, h, hl; // looping of holes
  19406. var scope = this;
  19407. var bevelPoints = [];
  19408. var shapesOffset = this.vertices.length;
  19409. var shapePoints = shape.extractPoints( curveSegments );
  19410. var vertices = shapePoints.shape;
  19411. var holes = shapePoints.holes;
  19412. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  19413. if ( reverse ) {
  19414. vertices = vertices.reverse();
  19415. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19416. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19417. ahole = holes[ h ];
  19418. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  19419. holes[ h ] = ahole.reverse();
  19420. }
  19421. }
  19422. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  19423. }
  19424. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  19425. /* Vertices */
  19426. var contour = vertices; // vertices has all points but contour has only points of circumference
  19427. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19428. ahole = holes[ h ];
  19429. vertices = vertices.concat( ahole );
  19430. }
  19431. function scalePt2 ( pt, vec, size ) {
  19432. if ( !vec ) console.log( "die" );
  19433. return vec.clone().multiplyScalar( size ).add( pt );
  19434. }
  19435. var b, bs, t, z,
  19436. vert, vlen = vertices.length,
  19437. face, flen = faces.length,
  19438. cont, clen = contour.length;
  19439. // Find directions for point movement
  19440. var RAD_TO_DEGREES = 180 / Math.PI;
  19441. function getBevelVec( inPt, inPrev, inNext ) {
  19442. var EPSILON = 0.0000000001;
  19443. var sign = THREE.Math.sign;
  19444. // computes for inPt the corresponding point inPt' on a new contour
  19445. // shiftet by 1 unit (length of normalized vector) to the left
  19446. // if we walk along contour clockwise, this new contour is outside the old one
  19447. //
  19448. // inPt' is the intersection of the two lines parallel to the two
  19449. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19450. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  19451. // good reading for geometry algorithms (here: line-line intersection)
  19452. // http://geomalgorithms.com/a05-_intersect-1.html
  19453. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  19454. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  19455. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  19456. // check for colinear edges
  19457. var colinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19458. if ( Math.abs( colinear0 ) > EPSILON ) { // not colinear
  19459. // length of vectors for normalizing
  19460. var v_prev_len = Math.sqrt( v_prev_lensq );
  19461. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  19462. // shift adjacent points by unit vectors to the left
  19463. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  19464. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  19465. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  19466. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  19467. // scaling factor for v_prev to intersection point
  19468. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  19469. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  19470. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19471. // vector from inPt to intersection point
  19472. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  19473. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  19474. // Don't normalize!, otherwise sharp corners become ugly
  19475. // but prevent crazy spikes
  19476. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y )
  19477. if ( v_trans_lensq <= 2 ) {
  19478. return new THREE.Vector2( v_trans_x, v_trans_y );
  19479. } else {
  19480. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  19481. }
  19482. } else { // handle special case of colinear edges
  19483. var direction_eq = false; // assumes: opposite
  19484. if ( v_prev_x > EPSILON ) {
  19485. if ( v_next_x > EPSILON ) { direction_eq = true; }
  19486. } else {
  19487. if ( v_prev_x < -EPSILON ) {
  19488. if ( v_next_x < -EPSILON ) { direction_eq = true; }
  19489. } else {
  19490. if ( sign(v_prev_y) == sign(v_next_y) ) { direction_eq = true; }
  19491. }
  19492. }
  19493. if ( direction_eq ) {
  19494. // console.log("Warning: lines are a straight sequence");
  19495. v_trans_x = -v_prev_y;
  19496. v_trans_y = v_prev_x;
  19497. shrink_by = Math.sqrt( v_prev_lensq );
  19498. } else {
  19499. // console.log("Warning: lines are a straight spike");
  19500. v_trans_x = v_prev_x;
  19501. v_trans_y = v_prev_y;
  19502. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  19503. }
  19504. }
  19505. return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  19506. }
  19507. var contourMovements = [];
  19508. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19509. if ( j === il ) j = 0;
  19510. if ( k === il ) k = 0;
  19511. // (j)---(i)---(k)
  19512. // console.log('i,j,k', i, j , k)
  19513. var pt_i = contour[ i ];
  19514. var pt_j = contour[ j ];
  19515. var pt_k = contour[ k ];
  19516. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19517. }
  19518. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  19519. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19520. ahole = holes[ h ];
  19521. oneHoleMovements = [];
  19522. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19523. if ( j === il ) j = 0;
  19524. if ( k === il ) k = 0;
  19525. // (j)---(i)---(k)
  19526. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19527. }
  19528. holesMovements.push( oneHoleMovements );
  19529. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19530. }
  19531. // Loop bevelSegments, 1 for the front, 1 for the back
  19532. for ( b = 0; b < bevelSegments; b ++ ) {
  19533. //for ( b = bevelSegments; b > 0; b -- ) {
  19534. t = b / bevelSegments;
  19535. z = bevelThickness * ( 1 - t );
  19536. //z = bevelThickness * t;
  19537. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  19538. //bs = bevelSize * t ; // linear
  19539. // contract shape
  19540. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19541. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19542. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  19543. v( vert.x, vert.y, - z );
  19544. }
  19545. // expand holes
  19546. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  19547. ahole = holes[ h ];
  19548. oneHoleMovements = holesMovements[ h ];
  19549. for ( i = 0, il = ahole.length; i < il; i++ ) {
  19550. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19551. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  19552. v( vert.x, vert.y, -z );
  19553. }
  19554. }
  19555. }
  19556. bs = bevelSize;
  19557. // Back facing vertices
  19558. for ( i = 0; i < vlen; i ++ ) {
  19559. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19560. if ( !extrudeByPath ) {
  19561. v( vert.x, vert.y, 0 );
  19562. } else {
  19563. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19564. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  19565. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  19566. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  19567. v( position2.x, position2.y, position2.z );
  19568. }
  19569. }
  19570. // Add stepped vertices...
  19571. // Including front facing vertices
  19572. var s;
  19573. for ( s = 1; s <= steps; s ++ ) {
  19574. for ( i = 0; i < vlen; i ++ ) {
  19575. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19576. if ( !extrudeByPath ) {
  19577. v( vert.x, vert.y, amount / steps * s );
  19578. } else {
  19579. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19580. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19581. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19582. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  19583. v( position2.x, position2.y, position2.z );
  19584. }
  19585. }
  19586. }
  19587. // Add bevel segments planes
  19588. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19589. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19590. t = b / bevelSegments;
  19591. z = bevelThickness * ( 1 - t );
  19592. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19593. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19594. // contract shape
  19595. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19596. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19597. v( vert.x, vert.y, amount + z );
  19598. }
  19599. // expand holes
  19600. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19601. ahole = holes[ h ];
  19602. oneHoleMovements = holesMovements[ h ];
  19603. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19604. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19605. if ( !extrudeByPath ) {
  19606. v( vert.x, vert.y, amount + z );
  19607. } else {
  19608. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19609. }
  19610. }
  19611. }
  19612. }
  19613. /* Faces */
  19614. // Top and bottom faces
  19615. buildLidFaces();
  19616. // Sides faces
  19617. buildSideFaces();
  19618. ///// Internal functions
  19619. function buildLidFaces() {
  19620. if ( bevelEnabled ) {
  19621. var layer = 0 ; // steps + 1
  19622. var offset = vlen * layer;
  19623. // Bottom faces
  19624. for ( i = 0; i < flen; i ++ ) {
  19625. face = faces[ i ];
  19626. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19627. }
  19628. layer = steps + bevelSegments * 2;
  19629. offset = vlen * layer;
  19630. // Top faces
  19631. for ( i = 0; i < flen; i ++ ) {
  19632. face = faces[ i ];
  19633. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19634. }
  19635. } else {
  19636. // Bottom faces
  19637. for ( i = 0; i < flen; i++ ) {
  19638. face = faces[ i ];
  19639. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19640. }
  19641. // Top faces
  19642. for ( i = 0; i < flen; i ++ ) {
  19643. face = faces[ i ];
  19644. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19645. }
  19646. }
  19647. }
  19648. // Create faces for the z-sides of the shape
  19649. function buildSideFaces() {
  19650. var layeroffset = 0;
  19651. sidewalls( contour, layeroffset );
  19652. layeroffset += contour.length;
  19653. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19654. ahole = holes[ h ];
  19655. sidewalls( ahole, layeroffset );
  19656. //, true
  19657. layeroffset += ahole.length;
  19658. }
  19659. }
  19660. function sidewalls( contour, layeroffset ) {
  19661. var j, k;
  19662. i = contour.length;
  19663. while ( --i >= 0 ) {
  19664. j = i;
  19665. k = i - 1;
  19666. if ( k < 0 ) k = contour.length - 1;
  19667. //console.log('b', i,j, i-1, k,vertices.length);
  19668. var s = 0, sl = steps + bevelSegments * 2;
  19669. for ( s = 0; s < sl; s ++ ) {
  19670. var slen1 = vlen * s;
  19671. var slen2 = vlen * ( s + 1 );
  19672. var a = layeroffset + j + slen1,
  19673. b = layeroffset + k + slen1,
  19674. c = layeroffset + k + slen2,
  19675. d = layeroffset + j + slen2;
  19676. f4( a, b, c, d, contour, s, sl, j, k );
  19677. }
  19678. }
  19679. }
  19680. function v( x, y, z ) {
  19681. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19682. }
  19683. function f3( a, b, c, isBottom ) {
  19684. a += shapesOffset;
  19685. b += shapesOffset;
  19686. c += shapesOffset;
  19687. // normal, color, material
  19688. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19689. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19690. scope.faceVertexUvs[ 0 ].push( uvs );
  19691. }
  19692. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19693. a += shapesOffset;
  19694. b += shapesOffset;
  19695. c += shapesOffset;
  19696. d += shapesOffset;
  19697. scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) );
  19698. scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) );
  19699. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19700. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19701. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  19702. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  19703. }
  19704. };
  19705. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19706. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19707. var ax = geometry.vertices[ indexA ].x,
  19708. ay = geometry.vertices[ indexA ].y,
  19709. bx = geometry.vertices[ indexB ].x,
  19710. by = geometry.vertices[ indexB ].y,
  19711. cx = geometry.vertices[ indexC ].x,
  19712. cy = geometry.vertices[ indexC ].y;
  19713. return [
  19714. new THREE.Vector2( ax, ay ),
  19715. new THREE.Vector2( bx, by ),
  19716. new THREE.Vector2( cx, cy )
  19717. ];
  19718. },
  19719. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19720. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19721. },
  19722. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19723. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19724. contourIndex1, contourIndex2 ) {
  19725. var ax = geometry.vertices[ indexA ].x,
  19726. ay = geometry.vertices[ indexA ].y,
  19727. az = geometry.vertices[ indexA ].z,
  19728. bx = geometry.vertices[ indexB ].x,
  19729. by = geometry.vertices[ indexB ].y,
  19730. bz = geometry.vertices[ indexB ].z,
  19731. cx = geometry.vertices[ indexC ].x,
  19732. cy = geometry.vertices[ indexC ].y,
  19733. cz = geometry.vertices[ indexC ].z,
  19734. dx = geometry.vertices[ indexD ].x,
  19735. dy = geometry.vertices[ indexD ].y,
  19736. dz = geometry.vertices[ indexD ].z;
  19737. if ( Math.abs( ay - by ) < 0.01 ) {
  19738. return [
  19739. new THREE.Vector2( ax, 1 - az ),
  19740. new THREE.Vector2( bx, 1 - bz ),
  19741. new THREE.Vector2( cx, 1 - cz ),
  19742. new THREE.Vector2( dx, 1 - dz )
  19743. ];
  19744. } else {
  19745. return [
  19746. new THREE.Vector2( ay, 1 - az ),
  19747. new THREE.Vector2( by, 1 - bz ),
  19748. new THREE.Vector2( cy, 1 - cz ),
  19749. new THREE.Vector2( dy, 1 - dz )
  19750. ];
  19751. }
  19752. }
  19753. };
  19754. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19755. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19756. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19757. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19758. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19759. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19760. /**
  19761. * @author jonobr1 / http://jonobr1.com
  19762. *
  19763. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19764. * ExtrudeGeometry.
  19765. *
  19766. * parameters = {
  19767. *
  19768. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19769. *
  19770. * material: <int> // material index for front and back faces
  19771. * uvGenerator: <Object> // object that provides UV generator functions
  19772. *
  19773. * }
  19774. **/
  19775. THREE.ShapeGeometry = function ( shapes, options ) {
  19776. THREE.Geometry.call( this );
  19777. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19778. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19779. this.addShapeList( shapes, options );
  19780. this.computeCentroids();
  19781. this.computeFaceNormals();
  19782. };
  19783. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19784. /**
  19785. * Add an array of shapes to THREE.ShapeGeometry.
  19786. */
  19787. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19788. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19789. this.addShape( shapes[ i ], options );
  19790. }
  19791. return this;
  19792. };
  19793. /**
  19794. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19795. */
  19796. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19797. if ( options === undefined ) options = {};
  19798. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19799. var material = options.material;
  19800. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19801. var shapebb = this.shapebb;
  19802. //
  19803. var i, l, hole, s;
  19804. var shapesOffset = this.vertices.length;
  19805. var shapePoints = shape.extractPoints( curveSegments );
  19806. var vertices = shapePoints.shape;
  19807. var holes = shapePoints.holes;
  19808. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19809. if ( reverse ) {
  19810. vertices = vertices.reverse();
  19811. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19812. for ( i = 0, l = holes.length; i < l; i++ ) {
  19813. hole = holes[ i ];
  19814. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19815. holes[ i ] = hole.reverse();
  19816. }
  19817. }
  19818. reverse = false;
  19819. }
  19820. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19821. // Vertices
  19822. var contour = vertices;
  19823. for ( i = 0, l = holes.length; i < l; i++ ) {
  19824. hole = holes[ i ];
  19825. vertices = vertices.concat( hole );
  19826. }
  19827. //
  19828. var vert, vlen = vertices.length;
  19829. var face, flen = faces.length;
  19830. var cont, clen = contour.length;
  19831. for ( i = 0; i < vlen; i++ ) {
  19832. vert = vertices[ i ];
  19833. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19834. }
  19835. for ( i = 0; i < flen; i++ ) {
  19836. face = faces[ i ];
  19837. var a = face[ 0 ] + shapesOffset;
  19838. var b = face[ 1 ] + shapesOffset;
  19839. var c = face[ 2 ] + shapesOffset;
  19840. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19841. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19842. }
  19843. };
  19844. /**
  19845. * @author astrodud / http://astrodud.isgreat.org/
  19846. * @author zz85 / https://github.com/zz85
  19847. * @author bhouston / http://exocortex.com
  19848. */
  19849. // points - to create a closed torus, one must use a set of points
  19850. // like so: [ a, b, c, d, a ], see first is the same as last.
  19851. // segments - the number of circumference segments to create
  19852. // phiStart - the starting radian
  19853. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19854. // 2*pi is a closed lathe, less than 2PI is a portion.
  19855. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19856. THREE.Geometry.call( this );
  19857. segments = segments || 12;
  19858. phiStart = phiStart || 0;
  19859. phiLength = phiLength || 2 * Math.PI;
  19860. var inversePointLength = 1.0 / ( points.length - 1 );
  19861. var inverseSegments = 1.0 / segments;
  19862. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19863. var phi = phiStart + i * inverseSegments * phiLength;
  19864. var c = Math.cos( phi ),
  19865. s = Math.sin( phi );
  19866. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19867. var pt = points[ j ];
  19868. var vertex = new THREE.Vector3();
  19869. vertex.x = c * pt.x - s * pt.y;
  19870. vertex.y = s * pt.x + c * pt.y;
  19871. vertex.z = pt.z;
  19872. this.vertices.push( vertex );
  19873. }
  19874. }
  19875. var np = points.length;
  19876. for ( var i = 0, il = segments; i < il; i ++ ) {
  19877. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19878. var base = j + np * i;
  19879. var a = base;
  19880. var b = base + np;
  19881. var c = base + 1 + np;
  19882. var d = base + 1;
  19883. var u0 = i * inverseSegments;
  19884. var v0 = j * inversePointLength;
  19885. var u1 = u0 + inverseSegments;
  19886. var v1 = v0 + inversePointLength;
  19887. this.faces.push( new THREE.Face3( a, b, d ) );
  19888. this.faceVertexUvs[ 0 ].push( [
  19889. new THREE.Vector2( u0, v0 ),
  19890. new THREE.Vector2( u1, v0 ),
  19891. new THREE.Vector2( u0, v1 )
  19892. ] );
  19893. this.faces.push( new THREE.Face3( b, c, d ) );
  19894. this.faceVertexUvs[ 0 ].push( [
  19895. new THREE.Vector2( u1, v0 ),
  19896. new THREE.Vector2( u1, v1 ),
  19897. new THREE.Vector2( u0, v1 )
  19898. ] );
  19899. }
  19900. }
  19901. this.mergeVertices();
  19902. this.computeCentroids();
  19903. this.computeFaceNormals();
  19904. this.computeVertexNormals();
  19905. };
  19906. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19907. /**
  19908. * @author mrdoob / http://mrdoob.com/
  19909. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19910. */
  19911. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19912. THREE.Geometry.call( this );
  19913. this.width = width;
  19914. this.height = height;
  19915. this.widthSegments = widthSegments || 1;
  19916. this.heightSegments = heightSegments || 1;
  19917. var ix, iz;
  19918. var width_half = width / 2;
  19919. var height_half = height / 2;
  19920. var gridX = this.widthSegments;
  19921. var gridZ = this.heightSegments;
  19922. var gridX1 = gridX + 1;
  19923. var gridZ1 = gridZ + 1;
  19924. var segment_width = this.width / gridX;
  19925. var segment_height = this.height / gridZ;
  19926. var normal = new THREE.Vector3( 0, 0, 1 );
  19927. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19928. for ( ix = 0; ix < gridX1; ix ++ ) {
  19929. var x = ix * segment_width - width_half;
  19930. var y = iz * segment_height - height_half;
  19931. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19932. }
  19933. }
  19934. for ( iz = 0; iz < gridZ; iz ++ ) {
  19935. for ( ix = 0; ix < gridX; ix ++ ) {
  19936. var a = ix + gridX1 * iz;
  19937. var b = ix + gridX1 * ( iz + 1 );
  19938. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19939. var d = ( ix + 1 ) + gridX1 * iz;
  19940. var uva = new THREE.Vector2( ix / gridX, 1 - iz / gridZ );
  19941. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ );
  19942. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ );
  19943. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ );
  19944. var face = new THREE.Face3( a, b, d );
  19945. face.normal.copy( normal );
  19946. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19947. this.faces.push( face );
  19948. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19949. face = new THREE.Face3( b, c, d );
  19950. face.normal.copy( normal );
  19951. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19952. this.faces.push( face );
  19953. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19954. }
  19955. }
  19956. this.computeCentroids();
  19957. };
  19958. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19959. /**
  19960. * @author Kaleb Murphy
  19961. */
  19962. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19963. THREE.Geometry.call( this );
  19964. innerRadius = innerRadius || 0;
  19965. outerRadius = outerRadius || 50;
  19966. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19967. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19968. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19969. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  19970. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19971. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  19972. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19973. var vertex = new THREE.Vector3();
  19974. var segment = thetaStart + o / thetaSegments * thetaLength;
  19975. vertex.x = radius * Math.cos( segment );
  19976. vertex.y = radius * Math.sin( segment );
  19977. this.vertices.push( vertex );
  19978. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  19979. }
  19980. radius += radiusStep;
  19981. }
  19982. var n = new THREE.Vector3( 0, 0, 1 );
  19983. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19984. var thetaSegment = i * thetaSegments;
  19985. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19986. var segment = o + thetaSegment;
  19987. var v1 = segment + i;
  19988. var v2 = segment + thetaSegments + i;
  19989. var v3 = segment + thetaSegments + 1 + i;
  19990. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19991. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19992. v1 = segment + i;
  19993. v2 = segment + thetaSegments + 1 + i;
  19994. v3 = segment + 1 + i;
  19995. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19996. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19997. }
  19998. }
  19999. this.computeCentroids();
  20000. this.computeFaceNormals();
  20001. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20002. };
  20003. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20004. /**
  20005. * @author mrdoob / http://mrdoob.com/
  20006. */
  20007. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  20008. THREE.Geometry.call( this );
  20009. this.radius = radius = radius || 50;
  20010. this.widthSegments = widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  20011. this.heightSegments = heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  20012. this.phiStart = phiStart = phiStart !== undefined ? phiStart : 0;
  20013. this.phiLength = phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  20014. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  20015. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  20016. var x, y, vertices = [], uvs = [];
  20017. for ( y = 0; y <= heightSegments; y ++ ) {
  20018. var verticesRow = [];
  20019. var uvsRow = [];
  20020. for ( x = 0; x <= widthSegments; x ++ ) {
  20021. var u = x / widthSegments;
  20022. var v = y / heightSegments;
  20023. var vertex = new THREE.Vector3();
  20024. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20025. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  20026. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20027. this.vertices.push( vertex );
  20028. verticesRow.push( this.vertices.length - 1 );
  20029. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  20030. }
  20031. vertices.push( verticesRow );
  20032. uvs.push( uvsRow );
  20033. }
  20034. for ( y = 0; y < this.heightSegments; y ++ ) {
  20035. for ( x = 0; x < this.widthSegments; x ++ ) {
  20036. var v1 = vertices[ y ][ x + 1 ];
  20037. var v2 = vertices[ y ][ x ];
  20038. var v3 = vertices[ y + 1 ][ x ];
  20039. var v4 = vertices[ y + 1 ][ x + 1 ];
  20040. var n1 = this.vertices[ v1 ].clone().normalize();
  20041. var n2 = this.vertices[ v2 ].clone().normalize();
  20042. var n3 = this.vertices[ v3 ].clone().normalize();
  20043. var n4 = this.vertices[ v4 ].clone().normalize();
  20044. var uv1 = uvs[ y ][ x + 1 ].clone();
  20045. var uv2 = uvs[ y ][ x ].clone();
  20046. var uv3 = uvs[ y + 1 ][ x ].clone();
  20047. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  20048. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  20049. uv1.x = ( uv1.x + uv2.x ) / 2;
  20050. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  20051. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  20052. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  20053. uv3.x = ( uv3.x + uv4.x ) / 2;
  20054. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  20055. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  20056. } else {
  20057. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  20058. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  20059. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  20060. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  20061. }
  20062. }
  20063. }
  20064. this.computeCentroids();
  20065. this.computeFaceNormals();
  20066. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20067. };
  20068. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20069. /**
  20070. * @author zz85 / http://www.lab4games.net/zz85/blog
  20071. * @author alteredq / http://alteredqualia.com/
  20072. *
  20073. * For creating 3D text geometry in three.js
  20074. *
  20075. * Text = 3D Text
  20076. *
  20077. * parameters = {
  20078. * size: <float>, // size of the text
  20079. * height: <float>, // thickness to extrude text
  20080. * curveSegments: <int>, // number of points on the curves
  20081. *
  20082. * font: <string>, // font name
  20083. * weight: <string>, // font weight (normal, bold)
  20084. * style: <string>, // font style (normal, italics)
  20085. *
  20086. * bevelEnabled: <bool>, // turn on bevel
  20087. * bevelThickness: <float>, // how deep into text bevel goes
  20088. * bevelSize: <float>, // how far from text outline is bevel
  20089. * }
  20090. *
  20091. */
  20092. /* Usage Examples
  20093. // TextGeometry wrapper
  20094. var text3d = new TextGeometry( text, options );
  20095. // Complete manner
  20096. var textShapes = THREE.FontUtils.generateShapes( text, options );
  20097. var text3d = new ExtrudeGeometry( textShapes, options );
  20098. */
  20099. THREE.TextGeometry = function ( text, parameters ) {
  20100. parameters = parameters || {};
  20101. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  20102. // translate parameters to ExtrudeGeometry API
  20103. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  20104. // defaults
  20105. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  20106. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  20107. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  20108. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  20109. };
  20110. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  20111. /**
  20112. * @author oosmoxiecode
  20113. * @author mrdoob / http://mrdoob.com/
  20114. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  20115. */
  20116. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  20117. THREE.Geometry.call( this );
  20118. var scope = this;
  20119. this.radius = radius || 100;
  20120. this.tube = tube || 40;
  20121. this.radialSegments = radialSegments || 8;
  20122. this.tubularSegments = tubularSegments || 6;
  20123. this.arc = arc || Math.PI * 2;
  20124. var center = new THREE.Vector3(), uvs = [], normals = [];
  20125. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  20126. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  20127. var u = i / this.tubularSegments * this.arc;
  20128. var v = j / this.radialSegments * Math.PI * 2;
  20129. center.x = this.radius * Math.cos( u );
  20130. center.y = this.radius * Math.sin( u );
  20131. var vertex = new THREE.Vector3();
  20132. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  20133. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  20134. vertex.z = this.tube * Math.sin( v );
  20135. this.vertices.push( vertex );
  20136. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  20137. normals.push( vertex.clone().sub( center ).normalize() );
  20138. }
  20139. }
  20140. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  20141. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  20142. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  20143. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  20144. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  20145. var d = ( this.tubularSegments + 1 ) * j + i;
  20146. var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
  20147. this.faces.push( face );
  20148. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  20149. face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
  20150. this.faces.push( face );
  20151. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  20152. }
  20153. }
  20154. this.computeCentroids();
  20155. this.computeFaceNormals();
  20156. };
  20157. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20158. /**
  20159. * @author oosmoxiecode
  20160. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  20161. */
  20162. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  20163. THREE.Geometry.call( this );
  20164. var scope = this;
  20165. this.radius = radius || 100;
  20166. this.tube = tube || 40;
  20167. this.radialSegments = radialSegments || 64;
  20168. this.tubularSegments = tubularSegments || 8;
  20169. this.p = p || 2;
  20170. this.q = q || 3;
  20171. this.heightScale = heightScale || 1;
  20172. this.grid = new Array( this.radialSegments );
  20173. var tang = new THREE.Vector3();
  20174. var n = new THREE.Vector3();
  20175. var bitan = new THREE.Vector3();
  20176. for ( var i = 0; i < this.radialSegments; ++ i ) {
  20177. this.grid[ i ] = new Array( this.tubularSegments );
  20178. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  20179. var p1 = getPos( u, this.q, this.p, this.radius, this.heightScale );
  20180. var p2 = getPos( u + 0.01, this.q, this.p, this.radius, this.heightScale );
  20181. tang.subVectors( p2, p1 );
  20182. n.addVectors( p2, p1 );
  20183. bitan.crossVectors( tang, n );
  20184. n.crossVectors( bitan, tang );
  20185. bitan.normalize();
  20186. n.normalize();
  20187. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  20188. var v = j / this.tubularSegments * 2 * Math.PI;
  20189. var cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20190. var cy = this.tube * Math.sin( v );
  20191. var pos = new THREE.Vector3();
  20192. pos.x = p1.x + cx * n.x + cy * bitan.x;
  20193. pos.y = p1.y + cx * n.y + cy * bitan.y;
  20194. pos.z = p1.z + cx * n.z + cy * bitan.z;
  20195. this.grid[ i ][ j ] = scope.vertices.push( pos ) - 1;
  20196. }
  20197. }
  20198. for ( var i = 0; i < this.radialSegments; ++ i ) {
  20199. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  20200. var ip = ( i + 1 ) % this.radialSegments;
  20201. var jp = ( j + 1 ) % this.tubularSegments;
  20202. var a = this.grid[ i ][ j ];
  20203. var b = this.grid[ ip ][ j ];
  20204. var c = this.grid[ ip ][ jp ];
  20205. var d = this.grid[ i ][ jp ];
  20206. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  20207. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  20208. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  20209. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  20210. this.faces.push( new THREE.Face3( a, b, d ) );
  20211. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  20212. this.faces.push( new THREE.Face3( b, c, d ) );
  20213. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  20214. }
  20215. }
  20216. this.computeCentroids();
  20217. this.computeFaceNormals();
  20218. this.computeVertexNormals();
  20219. function getPos( u, in_q, in_p, radius, heightScale ) {
  20220. var cu = Math.cos( u );
  20221. var su = Math.sin( u );
  20222. var quOverP = in_q / in_p * u;
  20223. var cs = Math.cos( quOverP );
  20224. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  20225. var ty = radius * ( 2 + cs ) * su * 0.5;
  20226. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  20227. return new THREE.Vector3( tx, ty, tz );
  20228. }
  20229. };
  20230. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20231. /**
  20232. * @author WestLangley / https://github.com/WestLangley
  20233. * @author zz85 / https://github.com/zz85
  20234. * @author miningold / https://github.com/miningold
  20235. *
  20236. * Modified from the TorusKnotGeometry by @oosmoxiecode
  20237. *
  20238. * Creates a tube which extrudes along a 3d spline
  20239. *
  20240. * Uses parallel transport frames as described in
  20241. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20242. */
  20243. THREE.TubeGeometry = function( path, segments, radius, radialSegments, closed ) {
  20244. THREE.Geometry.call( this );
  20245. this.path = path;
  20246. this.segments = segments || 64;
  20247. this.radius = radius || 1;
  20248. this.radialSegments = radialSegments || 8;
  20249. this.closed = closed || false;
  20250. this.grid = [];
  20251. var scope = this,
  20252. tangent,
  20253. normal,
  20254. binormal,
  20255. numpoints = this.segments + 1,
  20256. x, y, z,
  20257. tx, ty, tz,
  20258. u, v,
  20259. cx, cy,
  20260. pos, pos2 = new THREE.Vector3(),
  20261. i, j,
  20262. ip, jp,
  20263. a, b, c, d,
  20264. uva, uvb, uvc, uvd;
  20265. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  20266. tangents = frames.tangents,
  20267. normals = frames.normals,
  20268. binormals = frames.binormals;
  20269. // proxy internals
  20270. this.tangents = tangents;
  20271. this.normals = normals;
  20272. this.binormals = binormals;
  20273. function vert( x, y, z ) {
  20274. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  20275. }
  20276. // consruct the grid
  20277. for ( i = 0; i < numpoints; i++ ) {
  20278. this.grid[ i ] = [];
  20279. u = i / ( numpoints - 1 );
  20280. pos = path.getPointAt( u );
  20281. tangent = tangents[ i ];
  20282. normal = normals[ i ];
  20283. binormal = binormals[ i ];
  20284. for ( j = 0; j < this.radialSegments; j++ ) {
  20285. v = j / this.radialSegments * 2 * Math.PI;
  20286. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20287. cy = this.radius * Math.sin( v );
  20288. pos2.copy( pos );
  20289. pos2.x += cx * normal.x + cy * binormal.x;
  20290. pos2.y += cx * normal.y + cy * binormal.y;
  20291. pos2.z += cx * normal.z + cy * binormal.z;
  20292. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  20293. }
  20294. }
  20295. // construct the mesh
  20296. for ( i = 0; i < this.segments; i++ ) {
  20297. for ( j = 0; j < this.radialSegments; j++ ) {
  20298. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  20299. jp = (j + 1) % this.radialSegments;
  20300. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  20301. b = this.grid[ ip ][ j ];
  20302. c = this.grid[ ip ][ jp ];
  20303. d = this.grid[ i ][ jp ];
  20304. uva = new THREE.Vector2( i / this.segments, j / this.radialSegments );
  20305. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radialSegments );
  20306. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radialSegments );
  20307. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radialSegments );
  20308. this.faces.push( new THREE.Face3( a, b, d ) );
  20309. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  20310. this.faces.push( new THREE.Face3( b, c, d ) );
  20311. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  20312. }
  20313. }
  20314. this.computeCentroids();
  20315. this.computeFaceNormals();
  20316. this.computeVertexNormals();
  20317. };
  20318. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20319. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  20320. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  20321. var tangent = new THREE.Vector3(),
  20322. normal = new THREE.Vector3(),
  20323. binormal = new THREE.Vector3(),
  20324. tangents = [],
  20325. normals = [],
  20326. binormals = [],
  20327. vec = new THREE.Vector3(),
  20328. mat = new THREE.Matrix4(),
  20329. numpoints = segments + 1,
  20330. theta,
  20331. epsilon = 0.0001,
  20332. smallest,
  20333. tx, ty, tz,
  20334. i, u, v;
  20335. // expose internals
  20336. this.tangents = tangents;
  20337. this.normals = normals;
  20338. this.binormals = binormals;
  20339. // compute the tangent vectors for each segment on the path
  20340. for ( i = 0; i < numpoints; i++ ) {
  20341. u = i / ( numpoints - 1 );
  20342. tangents[ i ] = path.getTangentAt( u );
  20343. tangents[ i ].normalize();
  20344. }
  20345. initialNormal3();
  20346. function initialNormal1(lastBinormal) {
  20347. // fixed start binormal. Has dangers of 0 vectors
  20348. normals[ 0 ] = new THREE.Vector3();
  20349. binormals[ 0 ] = new THREE.Vector3();
  20350. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  20351. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  20352. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20353. }
  20354. function initialNormal2() {
  20355. // This uses the Frenet-Serret formula for deriving binormal
  20356. var t2 = path.getTangentAt( epsilon );
  20357. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  20358. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  20359. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  20360. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20361. }
  20362. function initialNormal3() {
  20363. // select an initial normal vector perpenicular to the first tangent vector,
  20364. // and in the direction of the smallest tangent xyz component
  20365. normals[ 0 ] = new THREE.Vector3();
  20366. binormals[ 0 ] = new THREE.Vector3();
  20367. smallest = Number.MAX_VALUE;
  20368. tx = Math.abs( tangents[ 0 ].x );
  20369. ty = Math.abs( tangents[ 0 ].y );
  20370. tz = Math.abs( tangents[ 0 ].z );
  20371. if ( tx <= smallest ) {
  20372. smallest = tx;
  20373. normal.set( 1, 0, 0 );
  20374. }
  20375. if ( ty <= smallest ) {
  20376. smallest = ty;
  20377. normal.set( 0, 1, 0 );
  20378. }
  20379. if ( tz <= smallest ) {
  20380. normal.set( 0, 0, 1 );
  20381. }
  20382. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20383. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20384. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20385. }
  20386. // compute the slowly-varying normal and binormal vectors for each segment on the path
  20387. for ( i = 1; i < numpoints; i++ ) {
  20388. normals[ i ] = normals[ i-1 ].clone();
  20389. binormals[ i ] = binormals[ i-1 ].clone();
  20390. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  20391. if ( vec.length() > epsilon ) {
  20392. vec.normalize();
  20393. theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  20394. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20395. }
  20396. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20397. }
  20398. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20399. if ( closed ) {
  20400. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), -1, 1 ) );
  20401. theta /= ( numpoints - 1 );
  20402. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  20403. theta = -theta;
  20404. }
  20405. for ( i = 1; i < numpoints; i++ ) {
  20406. // twist a little...
  20407. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20408. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20409. }
  20410. }
  20411. };
  20412. /**
  20413. * @author clockworkgeek / https://github.com/clockworkgeek
  20414. * @author timothypratley / https://github.com/timothypratley
  20415. * @author WestLangley / http://github.com/WestLangley
  20416. */
  20417. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  20418. THREE.Geometry.call( this );
  20419. radius = radius || 1;
  20420. detail = detail || 0;
  20421. var that = this;
  20422. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  20423. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  20424. }
  20425. var midpoints = [], p = this.vertices;
  20426. var f = [];
  20427. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20428. var v1 = p[ faces[ i ][ 0 ] ];
  20429. var v2 = p[ faces[ i ][ 1 ] ];
  20430. var v3 = p[ faces[ i ][ 2 ] ];
  20431. f[ i ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20432. }
  20433. for ( var i = 0, l = f.length; i < l; i ++ ) {
  20434. subdivide(f[ i ], detail);
  20435. }
  20436. // Handle case when face straddles the seam
  20437. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  20438. var uvs = this.faceVertexUvs[ 0 ][ i ];
  20439. var x0 = uvs[ 0 ].x;
  20440. var x1 = uvs[ 1 ].x;
  20441. var x2 = uvs[ 2 ].x;
  20442. var max = Math.max( x0, Math.max( x1, x2 ) );
  20443. var min = Math.min( x0, Math.min( x1, x2 ) );
  20444. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  20445. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  20446. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  20447. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  20448. }
  20449. }
  20450. // Apply radius
  20451. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  20452. this.vertices[ i ].multiplyScalar( radius );
  20453. }
  20454. // Merge vertices
  20455. this.mergeVertices();
  20456. this.computeCentroids();
  20457. this.computeFaceNormals();
  20458. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20459. // Project vector onto sphere's surface
  20460. function prepare( vector ) {
  20461. var vertex = vector.normalize().clone();
  20462. vertex.index = that.vertices.push( vertex ) - 1;
  20463. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  20464. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  20465. var v = inclination( vector ) / Math.PI + 0.5;
  20466. vertex.uv = new THREE.Vector2( u, 1 - v );
  20467. return vertex;
  20468. }
  20469. // Approximate a curved face with recursively sub-divided triangles.
  20470. function make( v1, v2, v3 ) {
  20471. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20472. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  20473. that.faces.push( face );
  20474. var azi = azimuth( face.centroid );
  20475. that.faceVertexUvs[ 0 ].push( [
  20476. correctUV( v1.uv, v1, azi ),
  20477. correctUV( v2.uv, v2, azi ),
  20478. correctUV( v3.uv, v3, azi )
  20479. ] );
  20480. }
  20481. // Analytically subdivide a face to the required detail level.
  20482. function subdivide(face, detail ) {
  20483. var cols = Math.pow(2, detail);
  20484. var cells = Math.pow(4, detail);
  20485. var a = prepare( that.vertices[ face.a ] );
  20486. var b = prepare( that.vertices[ face.b ] );
  20487. var c = prepare( that.vertices[ face.c ] );
  20488. var v = [];
  20489. // Construct all of the vertices for this subdivision.
  20490. for ( var i = 0 ; i <= cols; i ++ ) {
  20491. v[ i ] = [];
  20492. var aj = prepare( a.clone().lerp( c, i / cols ) );
  20493. var bj = prepare( b.clone().lerp( c, i / cols ) );
  20494. var rows = cols - i;
  20495. for ( var j = 0; j <= rows; j ++) {
  20496. if ( j == 0 && i == cols ) {
  20497. v[ i ][ j ] = aj;
  20498. } else {
  20499. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  20500. }
  20501. }
  20502. }
  20503. // Construct all of the faces.
  20504. for ( var i = 0; i < cols ; i ++ ) {
  20505. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  20506. var k = Math.floor( j / 2 );
  20507. if ( j % 2 == 0 ) {
  20508. make(
  20509. v[ i ][ k + 1],
  20510. v[ i + 1 ][ k ],
  20511. v[ i ][ k ]
  20512. );
  20513. } else {
  20514. make(
  20515. v[ i ][ k + 1 ],
  20516. v[ i + 1][ k + 1],
  20517. v[ i + 1 ][ k ]
  20518. );
  20519. }
  20520. }
  20521. }
  20522. }
  20523. // Angle around the Y axis, counter-clockwise when looking from above.
  20524. function azimuth( vector ) {
  20525. return Math.atan2( vector.z, -vector.x );
  20526. }
  20527. // Angle above the XZ plane.
  20528. function inclination( vector ) {
  20529. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20530. }
  20531. // Texture fixing helper. Spheres have some odd behaviours.
  20532. function correctUV( uv, vector, azimuth ) {
  20533. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  20534. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  20535. return uv.clone();
  20536. }
  20537. };
  20538. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20539. /**
  20540. * @author timothypratley / https://github.com/timothypratley
  20541. */
  20542. THREE.IcosahedronGeometry = function ( radius, detail ) {
  20543. this.radius = radius;
  20544. this.detail = detail;
  20545. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20546. var vertices = [
  20547. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  20548. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  20549. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  20550. ];
  20551. var faces = [
  20552. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  20553. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  20554. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  20555. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  20556. ];
  20557. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20558. };
  20559. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20560. /**
  20561. * @author timothypratley / https://github.com/timothypratley
  20562. */
  20563. THREE.OctahedronGeometry = function ( radius, detail ) {
  20564. var vertices = [
  20565. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  20566. ];
  20567. var faces = [
  20568. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  20569. ];
  20570. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20571. };
  20572. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20573. /**
  20574. * @author timothypratley / https://github.com/timothypratley
  20575. */
  20576. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20577. var vertices = [
  20578. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  20579. ];
  20580. var faces = [
  20581. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  20582. ];
  20583. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20584. };
  20585. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20586. /**
  20587. * @author zz85 / https://github.com/zz85
  20588. * Parametric Surfaces Geometry
  20589. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20590. *
  20591. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  20592. *
  20593. */
  20594. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  20595. THREE.Geometry.call( this );
  20596. var verts = this.vertices;
  20597. var faces = this.faces;
  20598. var uvs = this.faceVertexUvs[ 0 ];
  20599. var i, il, j, p;
  20600. var u, v;
  20601. var stackCount = stacks + 1;
  20602. var sliceCount = slices + 1;
  20603. for ( i = 0; i <= stacks; i ++ ) {
  20604. v = i / stacks;
  20605. for ( j = 0; j <= slices; j ++ ) {
  20606. u = j / slices;
  20607. p = func( u, v );
  20608. verts.push( p );
  20609. }
  20610. }
  20611. var a, b, c, d;
  20612. var uva, uvb, uvc, uvd;
  20613. for ( i = 0; i < stacks; i ++ ) {
  20614. for ( j = 0; j < slices; j ++ ) {
  20615. a = i * sliceCount + j;
  20616. b = i * sliceCount + j + 1;
  20617. c = (i + 1) * sliceCount + j + 1;
  20618. d = (i + 1) * sliceCount + j;
  20619. uva = new THREE.Vector2( j / slices, i / stacks );
  20620. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20621. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20622. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20623. faces.push( new THREE.Face3( a, b, d ) );
  20624. uvs.push( [ uva, uvb, uvd ] );
  20625. faces.push( new THREE.Face3( b, c, d ) );
  20626. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  20627. }
  20628. }
  20629. // console.log(this);
  20630. // magic bullet
  20631. // var diff = this.mergeVertices();
  20632. // console.log('removed ', diff, ' vertices by merging');
  20633. this.computeCentroids();
  20634. this.computeFaceNormals();
  20635. this.computeVertexNormals();
  20636. };
  20637. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20638. /**
  20639. * @author sroucheray / http://sroucheray.org/
  20640. * @author mrdoob / http://mrdoob.com/
  20641. */
  20642. THREE.AxisHelper = function ( size ) {
  20643. size = size || 1;
  20644. var geometry = new THREE.Geometry();
  20645. geometry.vertices.push(
  20646. new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ),
  20647. new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ),
  20648. new THREE.Vector3(), new THREE.Vector3( 0, 0, size )
  20649. );
  20650. geometry.colors.push(
  20651. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20652. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20653. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20654. );
  20655. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20656. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20657. };
  20658. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20659. /**
  20660. * @author WestLangley / http://github.com/WestLangley
  20661. * @author zz85 / http://github.com/zz85
  20662. * @author bhouston / http://exocortex.com
  20663. *
  20664. * Creates an arrow for visualizing directions
  20665. *
  20666. * Parameters:
  20667. * dir - Vector3
  20668. * origin - Vector3
  20669. * length - Number
  20670. * hex - color in hex value
  20671. * headLength - Number
  20672. * headWidth - Number
  20673. */
  20674. THREE.ArrowHelper = function ( dir, origin, length, hex, headLength, headWidth ) {
  20675. // dir is assumed to be normalized
  20676. THREE.Object3D.call( this );
  20677. if ( hex === undefined ) hex = 0xffff00;
  20678. if ( length === undefined ) length = 1;
  20679. if ( headLength === undefined ) headLength = 0.2 * length;
  20680. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20681. this.position = origin;
  20682. var lineGeometry = new THREE.Geometry();
  20683. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20684. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20685. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20686. this.line.matrixAutoUpdate = false;
  20687. this.add( this.line );
  20688. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  20689. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  20690. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20691. this.cone.matrixAutoUpdate = false;
  20692. this.add( this.cone );
  20693. this.setDirection( dir );
  20694. this.setLength( length, headLength, headWidth );
  20695. };
  20696. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20697. THREE.ArrowHelper.prototype.setDirection = function () {
  20698. var axis = new THREE.Vector3();
  20699. var radians;
  20700. return function ( dir ) {
  20701. // dir is assumed to be normalized
  20702. if ( dir.y > 0.99999 ) {
  20703. this.quaternion.set( 0, 0, 0, 1 );
  20704. } else if ( dir.y < - 0.99999 ) {
  20705. this.quaternion.set( 1, 0, 0, 0 );
  20706. } else {
  20707. axis.set( dir.z, 0, - dir.x ).normalize();
  20708. radians = Math.acos( dir.y );
  20709. this.quaternion.setFromAxisAngle( axis, radians );
  20710. }
  20711. };
  20712. }();
  20713. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  20714. if ( headLength === undefined ) headLength = 0.2 * length;
  20715. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20716. this.line.scale.set( 1, length, 1 );
  20717. this.line.updateMatrix();
  20718. this.cone.scale.set( headWidth, headLength, headWidth );
  20719. this.cone.position.y = length;
  20720. this.cone.updateMatrix();
  20721. };
  20722. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20723. this.line.material.color.setHex( hex );
  20724. this.cone.material.color.setHex( hex );
  20725. };
  20726. /**
  20727. * @author mrdoob / http://mrdoob.com/
  20728. */
  20729. THREE.BoxHelper = function ( object ) {
  20730. // 5____4
  20731. // 1/___0/|
  20732. // | 6__|_7
  20733. // 2/___3/
  20734. var vertices = [
  20735. new THREE.Vector3( 1, 1, 1 ),
  20736. new THREE.Vector3( - 1, 1, 1 ),
  20737. new THREE.Vector3( - 1, - 1, 1 ),
  20738. new THREE.Vector3( 1, - 1, 1 ),
  20739. new THREE.Vector3( 1, 1, - 1 ),
  20740. new THREE.Vector3( - 1, 1, - 1 ),
  20741. new THREE.Vector3( - 1, - 1, - 1 ),
  20742. new THREE.Vector3( 1, - 1, - 1 )
  20743. ];
  20744. this.vertices = vertices;
  20745. // TODO: Wouldn't be nice if Line had .segments?
  20746. var geometry = new THREE.Geometry();
  20747. geometry.vertices.push(
  20748. vertices[ 0 ], vertices[ 1 ],
  20749. vertices[ 1 ], vertices[ 2 ],
  20750. vertices[ 2 ], vertices[ 3 ],
  20751. vertices[ 3 ], vertices[ 0 ],
  20752. vertices[ 4 ], vertices[ 5 ],
  20753. vertices[ 5 ], vertices[ 6 ],
  20754. vertices[ 6 ], vertices[ 7 ],
  20755. vertices[ 7 ], vertices[ 4 ],
  20756. vertices[ 0 ], vertices[ 4 ],
  20757. vertices[ 1 ], vertices[ 5 ],
  20758. vertices[ 2 ], vertices[ 6 ],
  20759. vertices[ 3 ], vertices[ 7 ]
  20760. );
  20761. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  20762. if ( object !== undefined ) {
  20763. this.update( object );
  20764. }
  20765. };
  20766. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20767. THREE.BoxHelper.prototype.update = function ( object ) {
  20768. var geometry = object.geometry;
  20769. if ( geometry.boundingBox === null ) {
  20770. geometry.computeBoundingBox();
  20771. }
  20772. var min = geometry.boundingBox.min;
  20773. var max = geometry.boundingBox.max;
  20774. var vertices = this.vertices;
  20775. vertices[ 0 ].set( max.x, max.y, max.z );
  20776. vertices[ 1 ].set( min.x, max.y, max.z );
  20777. vertices[ 2 ].set( min.x, min.y, max.z );
  20778. vertices[ 3 ].set( max.x, min.y, max.z );
  20779. vertices[ 4 ].set( max.x, max.y, min.z );
  20780. vertices[ 5 ].set( min.x, max.y, min.z );
  20781. vertices[ 6 ].set( min.x, min.y, min.z );
  20782. vertices[ 7 ].set( max.x, min.y, min.z );
  20783. this.geometry.computeBoundingSphere();
  20784. this.geometry.verticesNeedUpdate = true;
  20785. this.matrixAutoUpdate = false;
  20786. this.matrixWorld = object.matrixWorld;
  20787. };
  20788. /**
  20789. * @author WestLangley / http://github.com/WestLangley
  20790. */
  20791. // a helper to show the world-axis-aligned bounding box for an object
  20792. THREE.BoundingBoxHelper = function ( object, hex ) {
  20793. var color = ( hex !== undefined ) ? hex : 0x888888;
  20794. this.object = object;
  20795. this.box = new THREE.Box3();
  20796. THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20797. };
  20798. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20799. THREE.BoundingBoxHelper.prototype.update = function () {
  20800. this.box.setFromObject( this.object );
  20801. this.box.size( this.scale );
  20802. this.box.center( this.position );
  20803. };
  20804. /**
  20805. * @author alteredq / http://alteredqualia.com/
  20806. *
  20807. * - shows frustum, line of sight and up of the camera
  20808. * - suitable for fast updates
  20809. * - based on frustum visualization in lightgl.js shadowmap example
  20810. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20811. */
  20812. THREE.CameraHelper = function ( camera ) {
  20813. var geometry = new THREE.Geometry();
  20814. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20815. var pointMap = {};
  20816. // colors
  20817. var hexFrustum = 0xffaa00;
  20818. var hexCone = 0xff0000;
  20819. var hexUp = 0x00aaff;
  20820. var hexTarget = 0xffffff;
  20821. var hexCross = 0x333333;
  20822. // near
  20823. addLine( "n1", "n2", hexFrustum );
  20824. addLine( "n2", "n4", hexFrustum );
  20825. addLine( "n4", "n3", hexFrustum );
  20826. addLine( "n3", "n1", hexFrustum );
  20827. // far
  20828. addLine( "f1", "f2", hexFrustum );
  20829. addLine( "f2", "f4", hexFrustum );
  20830. addLine( "f4", "f3", hexFrustum );
  20831. addLine( "f3", "f1", hexFrustum );
  20832. // sides
  20833. addLine( "n1", "f1", hexFrustum );
  20834. addLine( "n2", "f2", hexFrustum );
  20835. addLine( "n3", "f3", hexFrustum );
  20836. addLine( "n4", "f4", hexFrustum );
  20837. // cone
  20838. addLine( "p", "n1", hexCone );
  20839. addLine( "p", "n2", hexCone );
  20840. addLine( "p", "n3", hexCone );
  20841. addLine( "p", "n4", hexCone );
  20842. // up
  20843. addLine( "u1", "u2", hexUp );
  20844. addLine( "u2", "u3", hexUp );
  20845. addLine( "u3", "u1", hexUp );
  20846. // target
  20847. addLine( "c", "t", hexTarget );
  20848. addLine( "p", "c", hexCross );
  20849. // cross
  20850. addLine( "cn1", "cn2", hexCross );
  20851. addLine( "cn3", "cn4", hexCross );
  20852. addLine( "cf1", "cf2", hexCross );
  20853. addLine( "cf3", "cf4", hexCross );
  20854. function addLine( a, b, hex ) {
  20855. addPoint( a, hex );
  20856. addPoint( b, hex );
  20857. }
  20858. function addPoint( id, hex ) {
  20859. geometry.vertices.push( new THREE.Vector3() );
  20860. geometry.colors.push( new THREE.Color( hex ) );
  20861. if ( pointMap[ id ] === undefined ) {
  20862. pointMap[ id ] = [];
  20863. }
  20864. pointMap[ id ].push( geometry.vertices.length - 1 );
  20865. }
  20866. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20867. this.camera = camera;
  20868. this.matrixWorld = camera.matrixWorld;
  20869. this.matrixAutoUpdate = false;
  20870. this.pointMap = pointMap;
  20871. this.update();
  20872. };
  20873. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20874. THREE.CameraHelper.prototype.update = function () {
  20875. var vector = new THREE.Vector3();
  20876. var camera = new THREE.Camera();
  20877. var projector = new THREE.Projector();
  20878. return function () {
  20879. var scope = this;
  20880. var w = 1, h = 1;
  20881. // we need just camera projection matrix
  20882. // world matrix must be identity
  20883. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20884. // center / target
  20885. setPoint( "c", 0, 0, -1 );
  20886. setPoint( "t", 0, 0, 1 );
  20887. // near
  20888. setPoint( "n1", -w, -h, -1 );
  20889. setPoint( "n2", w, -h, -1 );
  20890. setPoint( "n3", -w, h, -1 );
  20891. setPoint( "n4", w, h, -1 );
  20892. // far
  20893. setPoint( "f1", -w, -h, 1 );
  20894. setPoint( "f2", w, -h, 1 );
  20895. setPoint( "f3", -w, h, 1 );
  20896. setPoint( "f4", w, h, 1 );
  20897. // up
  20898. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20899. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20900. setPoint( "u3", 0, h * 2, -1 );
  20901. // cross
  20902. setPoint( "cf1", -w, 0, 1 );
  20903. setPoint( "cf2", w, 0, 1 );
  20904. setPoint( "cf3", 0, -h, 1 );
  20905. setPoint( "cf4", 0, h, 1 );
  20906. setPoint( "cn1", -w, 0, -1 );
  20907. setPoint( "cn2", w, 0, -1 );
  20908. setPoint( "cn3", 0, -h, -1 );
  20909. setPoint( "cn4", 0, h, -1 );
  20910. function setPoint( point, x, y, z ) {
  20911. vector.set( x, y, z );
  20912. projector.unprojectVector( vector, camera );
  20913. var points = scope.pointMap[ point ];
  20914. if ( points !== undefined ) {
  20915. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20916. scope.geometry.vertices[ points[ i ] ].copy( vector );
  20917. }
  20918. }
  20919. }
  20920. this.geometry.verticesNeedUpdate = true;
  20921. };
  20922. }();
  20923. /**
  20924. * @author alteredq / http://alteredqualia.com/
  20925. * @author mrdoob / http://mrdoob.com/
  20926. * @author WestLangley / http://github.com/WestLangley
  20927. */
  20928. THREE.DirectionalLightHelper = function ( light, size ) {
  20929. THREE.Object3D.call( this );
  20930. this.light = light;
  20931. this.light.updateMatrixWorld();
  20932. this.matrixWorld = light.matrixWorld;
  20933. this.matrixAutoUpdate = false;
  20934. size = size || 1;
  20935. var geometry = new THREE.PlaneGeometry( size, size );
  20936. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20937. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20938. this.lightPlane = new THREE.Mesh( geometry, material );
  20939. this.add( this.lightPlane );
  20940. geometry = new THREE.Geometry();
  20941. geometry.vertices.push( new THREE.Vector3() );
  20942. geometry.vertices.push( new THREE.Vector3() );
  20943. material = new THREE.LineBasicMaterial( { fog: false } );
  20944. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20945. this.targetLine = new THREE.Line( geometry, material );
  20946. this.add( this.targetLine );
  20947. this.update();
  20948. };
  20949. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20950. THREE.DirectionalLightHelper.prototype.dispose = function () {
  20951. this.lightPlane.geometry.dispose();
  20952. this.lightPlane.material.dispose();
  20953. this.targetLine.geometry.dispose();
  20954. this.targetLine.material.dispose();
  20955. };
  20956. THREE.DirectionalLightHelper.prototype.update = function () {
  20957. var v1 = new THREE.Vector3();
  20958. var v2 = new THREE.Vector3();
  20959. var v3 = new THREE.Vector3();
  20960. return function () {
  20961. v1.setFromMatrixPosition( this.light.matrixWorld );
  20962. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20963. v3.subVectors( v2, v1 );
  20964. this.lightPlane.lookAt( v3 );
  20965. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20966. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  20967. this.targetLine.geometry.verticesNeedUpdate = true;
  20968. this.targetLine.material.color.copy( this.lightPlane.material.color );
  20969. }
  20970. }();
  20971. /**
  20972. * @author WestLangley / http://github.com/WestLangley
  20973. */
  20974. THREE.EdgesHelper = function ( object, hex ) {
  20975. var color = ( hex !== undefined ) ? hex : 0xffffff;
  20976. var edge = [ 0, 0 ], hash = {};
  20977. var sortFunction = function ( a, b ) { return a - b };
  20978. var keys = [ 'a', 'b', 'c' ];
  20979. var geometry = new THREE.BufferGeometry();
  20980. var geometry2 = object.geometry.clone();
  20981. geometry2.mergeVertices();
  20982. geometry2.computeFaceNormals();
  20983. var vertices = geometry2.vertices;
  20984. var faces = geometry2.faces;
  20985. var numEdges = 0;
  20986. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20987. var face = faces[ i ];
  20988. for ( var j = 0; j < 3; j ++ ) {
  20989. edge[ 0 ] = face[ keys[ j ] ];
  20990. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20991. edge.sort( sortFunction );
  20992. var key = edge.toString();
  20993. if ( hash[ key ] === undefined ) {
  20994. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  20995. numEdges ++;
  20996. } else {
  20997. hash[ key ].face2 = i;
  20998. }
  20999. }
  21000. }
  21001. geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 );
  21002. var coords = geometry.attributes.position.array;
  21003. var index = 0;
  21004. for ( var key in hash ) {
  21005. var h = hash[ key ];
  21006. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) < 0.9999 ) { // hardwired const OK
  21007. var vertex = vertices[ h.vert1 ];
  21008. coords[ index ++ ] = vertex.x;
  21009. coords[ index ++ ] = vertex.y;
  21010. coords[ index ++ ] = vertex.z;
  21011. vertex = vertices[ h.vert2 ];
  21012. coords[ index ++ ] = vertex.x;
  21013. coords[ index ++ ] = vertex.y;
  21014. coords[ index ++ ] = vertex.z;
  21015. }
  21016. }
  21017. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  21018. this.matrixAutoUpdate = false;
  21019. this.matrixWorld = object.matrixWorld;
  21020. };
  21021. THREE.EdgesHelper.prototype = Object.create( THREE.Line.prototype );
  21022. /**
  21023. * @author mrdoob / http://mrdoob.com/
  21024. * @author WestLangley / http://github.com/WestLangley
  21025. */
  21026. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  21027. this.object = object;
  21028. this.size = ( size !== undefined ) ? size : 1;
  21029. var color = ( hex !== undefined ) ? hex : 0xffff00;
  21030. var width = ( linewidth !== undefined ) ? linewidth : 1;
  21031. var geometry = new THREE.Geometry();
  21032. var faces = this.object.geometry.faces;
  21033. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21034. geometry.vertices.push( new THREE.Vector3() );
  21035. geometry.vertices.push( new THREE.Vector3() );
  21036. }
  21037. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21038. this.matrixAutoUpdate = false;
  21039. this.normalMatrix = new THREE.Matrix3();
  21040. this.update();
  21041. };
  21042. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  21043. THREE.FaceNormalsHelper.prototype.update = ( function ( object ) {
  21044. var v1 = new THREE.Vector3();
  21045. return function ( object ) {
  21046. this.object.updateMatrixWorld( true );
  21047. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  21048. var vertices = this.geometry.vertices;
  21049. var faces = this.object.geometry.faces;
  21050. var worldMatrix = this.object.matrixWorld;
  21051. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21052. var face = faces[ i ];
  21053. v1.copy( face.normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  21054. var idx = 2 * i;
  21055. vertices[ idx ].copy( face.centroid ).applyMatrix4( worldMatrix );
  21056. vertices[ idx + 1 ].addVectors( vertices[ idx ], v1 );
  21057. }
  21058. this.geometry.verticesNeedUpdate = true;
  21059. return this;
  21060. }
  21061. }());
  21062. /**
  21063. * @author mrdoob / http://mrdoob.com/
  21064. */
  21065. THREE.GridHelper = function ( size, step ) {
  21066. var geometry = new THREE.Geometry();
  21067. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  21068. this.color1 = new THREE.Color( 0x444444 );
  21069. this.color2 = new THREE.Color( 0x888888 );
  21070. for ( var i = - size; i <= size; i += step ) {
  21071. geometry.vertices.push(
  21072. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  21073. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  21074. );
  21075. var color = i === 0 ? this.color1 : this.color2;
  21076. geometry.colors.push( color, color, color, color );
  21077. }
  21078. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  21079. };
  21080. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  21081. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  21082. this.color1.set( colorCenterLine );
  21083. this.color2.set( colorGrid );
  21084. this.geometry.colorsNeedUpdate = true;
  21085. }
  21086. /**
  21087. * @author alteredq / http://alteredqualia.com/
  21088. * @author mrdoob / http://mrdoob.com/
  21089. */
  21090. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  21091. THREE.Object3D.call( this );
  21092. this.light = light;
  21093. this.light.updateMatrixWorld();
  21094. this.matrixWorld = light.matrixWorld;
  21095. this.matrixAutoUpdate = false;
  21096. this.colors = [ new THREE.Color(), new THREE.Color() ];
  21097. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21098. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  21099. for ( var i = 0, il = 8; i < il; i ++ ) {
  21100. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  21101. }
  21102. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  21103. this.lightSphere = new THREE.Mesh( geometry, material );
  21104. this.add( this.lightSphere );
  21105. this.update();
  21106. };
  21107. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21108. THREE.HemisphereLightHelper.prototype.dispose = function () {
  21109. this.lightSphere.geometry.dispose();
  21110. this.lightSphere.material.dispose();
  21111. };
  21112. THREE.HemisphereLightHelper.prototype.update = function () {
  21113. var vector = new THREE.Vector3();
  21114. return function () {
  21115. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  21116. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  21117. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  21118. this.lightSphere.geometry.colorsNeedUpdate = true;
  21119. }
  21120. }();
  21121. /**
  21122. * @author alteredq / http://alteredqualia.com/
  21123. * @author mrdoob / http://mrdoob.com/
  21124. */
  21125. THREE.PointLightHelper = function ( light, sphereSize ) {
  21126. this.light = light;
  21127. this.light.updateMatrixWorld();
  21128. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21129. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  21130. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21131. THREE.Mesh.call( this, geometry, material );
  21132. this.matrixWorld = this.light.matrixWorld;
  21133. this.matrixAutoUpdate = false;
  21134. /*
  21135. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  21136. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  21137. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  21138. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  21139. var d = light.distance;
  21140. if ( d === 0.0 ) {
  21141. this.lightDistance.visible = false;
  21142. } else {
  21143. this.lightDistance.scale.set( d, d, d );
  21144. }
  21145. this.add( this.lightDistance );
  21146. */
  21147. };
  21148. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  21149. THREE.PointLightHelper.prototype.dispose = function () {
  21150. this.geometry.dispose();
  21151. this.material.dispose();
  21152. };
  21153. THREE.PointLightHelper.prototype.update = function () {
  21154. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21155. /*
  21156. var d = this.light.distance;
  21157. if ( d === 0.0 ) {
  21158. this.lightDistance.visible = false;
  21159. } else {
  21160. this.lightDistance.visible = true;
  21161. this.lightDistance.scale.set( d, d, d );
  21162. }
  21163. */
  21164. };
  21165. /**
  21166. * @author alteredq / http://alteredqualia.com/
  21167. * @author mrdoob / http://mrdoob.com/
  21168. * @author WestLangley / http://github.com/WestLangley
  21169. */
  21170. THREE.SpotLightHelper = function ( light ) {
  21171. THREE.Object3D.call( this );
  21172. this.light = light;
  21173. this.light.updateMatrixWorld();
  21174. this.matrixWorld = light.matrixWorld;
  21175. this.matrixAutoUpdate = false;
  21176. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  21177. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
  21178. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  21179. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  21180. this.cone = new THREE.Mesh( geometry, material );
  21181. this.add( this.cone );
  21182. this.update();
  21183. };
  21184. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21185. THREE.SpotLightHelper.prototype.dispose = function () {
  21186. this.cone.geometry.dispose();
  21187. this.cone.material.dispose();
  21188. };
  21189. THREE.SpotLightHelper.prototype.update = function () {
  21190. var vector = new THREE.Vector3();
  21191. var vector2 = new THREE.Vector3();
  21192. return function () {
  21193. var coneLength = this.light.distance ? this.light.distance : 10000;
  21194. var coneWidth = coneLength * Math.tan( this.light.angle );
  21195. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  21196. vector.setFromMatrixPosition( this.light.matrixWorld );
  21197. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  21198. this.cone.lookAt( vector2.sub( vector ) );
  21199. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21200. };
  21201. }();
  21202. /**
  21203. * @author mrdoob / http://mrdoob.com/
  21204. * @author WestLangley / http://github.com/WestLangley
  21205. */
  21206. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  21207. this.object = object;
  21208. this.size = ( size !== undefined ) ? size : 1;
  21209. var color = ( hex !== undefined ) ? hex : 0xff0000;
  21210. var width = ( linewidth !== undefined ) ? linewidth : 1;
  21211. var geometry = new THREE.Geometry();
  21212. var vertices = object.geometry.vertices;
  21213. var faces = object.geometry.faces;
  21214. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21215. var face = faces[ i ];
  21216. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21217. geometry.vertices.push( new THREE.Vector3() );
  21218. geometry.vertices.push( new THREE.Vector3() );
  21219. }
  21220. }
  21221. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21222. this.matrixAutoUpdate = false;
  21223. this.normalMatrix = new THREE.Matrix3();
  21224. this.update();
  21225. };
  21226. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  21227. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  21228. var v1 = new THREE.Vector3();
  21229. return function( object ) {
  21230. var keys = [ 'a', 'b', 'c', 'd' ];
  21231. this.object.updateMatrixWorld( true );
  21232. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  21233. var vertices = this.geometry.vertices;
  21234. var verts = this.object.geometry.vertices;
  21235. var faces = this.object.geometry.faces;
  21236. var worldMatrix = this.object.matrixWorld;
  21237. var idx = 0;
  21238. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21239. var face = faces[ i ];
  21240. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21241. var vertexId = face[ keys[ j ] ];
  21242. var vertex = verts[ vertexId ];
  21243. var normal = face.vertexNormals[ j ];
  21244. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21245. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  21246. v1.add( vertices[ idx ] );
  21247. idx = idx + 1;
  21248. vertices[ idx ].copy( v1 );
  21249. idx = idx + 1;
  21250. }
  21251. }
  21252. this.geometry.verticesNeedUpdate = true;
  21253. return this;
  21254. }
  21255. }());
  21256. /**
  21257. * @author mrdoob / http://mrdoob.com/
  21258. * @author WestLangley / http://github.com/WestLangley
  21259. */
  21260. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  21261. this.object = object;
  21262. this.size = ( size !== undefined ) ? size : 1;
  21263. var color = ( hex !== undefined ) ? hex : 0x0000ff;
  21264. var width = ( linewidth !== undefined ) ? linewidth : 1;
  21265. var geometry = new THREE.Geometry();
  21266. var vertices = object.geometry.vertices;
  21267. var faces = object.geometry.faces;
  21268. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21269. var face = faces[ i ];
  21270. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21271. geometry.vertices.push( new THREE.Vector3() );
  21272. geometry.vertices.push( new THREE.Vector3() );
  21273. }
  21274. }
  21275. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21276. this.matrixAutoUpdate = false;
  21277. this.update();
  21278. };
  21279. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  21280. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  21281. var v1 = new THREE.Vector3();
  21282. return function( object ) {
  21283. var keys = [ 'a', 'b', 'c', 'd' ];
  21284. this.object.updateMatrixWorld( true );
  21285. var vertices = this.geometry.vertices;
  21286. var verts = this.object.geometry.vertices;
  21287. var faces = this.object.geometry.faces;
  21288. var worldMatrix = this.object.matrixWorld;
  21289. var idx = 0;
  21290. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21291. var face = faces[ i ];
  21292. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21293. var vertexId = face[ keys[ j ] ];
  21294. var vertex = verts[ vertexId ];
  21295. var tangent = face.vertexTangents[ j ];
  21296. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21297. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  21298. v1.add( vertices[ idx ] );
  21299. idx = idx + 1;
  21300. vertices[ idx ].copy( v1 );
  21301. idx = idx + 1;
  21302. }
  21303. }
  21304. this.geometry.verticesNeedUpdate = true;
  21305. return this;
  21306. }
  21307. }());
  21308. /**
  21309. * @author mrdoob / http://mrdoob.com/
  21310. */
  21311. THREE.WireframeHelper = function ( object, hex ) {
  21312. var color = ( hex !== undefined ) ? hex : 0xffffff;
  21313. var edge = [ 0, 0 ], hash = {};
  21314. var sortFunction = function ( a, b ) { return a - b };
  21315. var keys = [ 'a', 'b', 'c' ];
  21316. var geometry = new THREE.BufferGeometry();
  21317. if ( object.geometry instanceof THREE.Geometry ) {
  21318. var vertices = object.geometry.vertices;
  21319. var faces = object.geometry.faces;
  21320. var numEdges = 0;
  21321. // allocate maximal size
  21322. var edges = new Uint32Array( 6 * faces.length );
  21323. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21324. var face = faces[ i ];
  21325. for ( var j = 0; j < 3; j ++ ) {
  21326. edge[ 0 ] = face[ keys[ j ] ];
  21327. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  21328. edge.sort( sortFunction );
  21329. var key = edge.toString();
  21330. if ( hash[ key ] === undefined ) {
  21331. edges[ 2 * numEdges ] = edge[ 0 ];
  21332. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  21333. hash[ key ] = true;
  21334. numEdges ++;
  21335. }
  21336. }
  21337. }
  21338. geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 );
  21339. var coords = geometry.attributes.position.array;
  21340. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  21341. for ( var j = 0; j < 2; j ++ ) {
  21342. var vertex = vertices[ edges [ 2 * i + j] ];
  21343. var index = 6 * i + 3 * j;
  21344. coords[ index + 0 ] = vertex.x;
  21345. coords[ index + 1 ] = vertex.y;
  21346. coords[ index + 2 ] = vertex.z;
  21347. }
  21348. }
  21349. } else if ( object.geometry instanceof THREE.BufferGeometry && object.geometry.attributes.index !== undefined ) { // indexed BufferGeometry
  21350. var vertices = object.geometry.attributes.position.array;
  21351. var indices = object.geometry.attributes.index.array;
  21352. var offsets = object.geometry.offsets;
  21353. var numEdges = 0;
  21354. // allocate maximal size
  21355. var edges = new Uint32Array( 2 * indices.length );
  21356. for ( var o = 0, ol = offsets.length; o < ol; ++ o ) {
  21357. var start = offsets[ o ].start;
  21358. var count = offsets[ o ].count;
  21359. var index = offsets[ o ].index;
  21360. for ( var i = start, il = start + count; i < il; i += 3 ) {
  21361. for ( var j = 0; j < 3; j ++ ) {
  21362. edge[ 0 ] = index + indices[ i + j ];
  21363. edge[ 1 ] = index + indices[ i + ( j + 1 ) % 3 ];
  21364. edge.sort( sortFunction );
  21365. var key = edge.toString();
  21366. if ( hash[ key ] === undefined ) {
  21367. edges[ 2 * numEdges ] = edge[ 0 ];
  21368. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  21369. hash[ key ] = true;
  21370. numEdges ++;
  21371. }
  21372. }
  21373. }
  21374. }
  21375. geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 );
  21376. var coords = geometry.attributes.position.array;
  21377. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  21378. for ( var j = 0; j < 2; j ++ ) {
  21379. var index = 6 * i + 3 * j;
  21380. var index2 = 3 * edges[ 2 * i + j];
  21381. coords[ index + 0 ] = vertices[ index2 ];
  21382. coords[ index + 1 ] = vertices[ index2 + 1 ];
  21383. coords[ index + 2 ] = vertices[ index2 + 2 ];
  21384. }
  21385. }
  21386. } else if ( object.geometry instanceof THREE.BufferGeometry ) { // non-indexed BufferGeometry
  21387. var vertices = object.geometry.attributes.position.array;
  21388. var numEdges = vertices.length / 3;
  21389. var numTris = numEdges / 3;
  21390. geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 );
  21391. var coords = geometry.attributes.position.array;
  21392. for ( var i = 0, l = numTris; i < l; i ++ ) {
  21393. for ( var j = 0; j < 3; j ++ ) {
  21394. var index = 18 * i + 6 * j;
  21395. var index1 = 9 * i + 3 * j;
  21396. coords[ index + 0 ] = vertices[ index1 ];
  21397. coords[ index + 1 ] = vertices[ index1 + 1 ];
  21398. coords[ index + 2 ] = vertices[ index1 + 2 ];
  21399. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  21400. coords[ index + 3 ] = vertices[ index2 ];
  21401. coords[ index + 4 ] = vertices[ index2 + 1 ];
  21402. coords[ index + 5 ] = vertices[ index2 + 2 ];
  21403. }
  21404. }
  21405. }
  21406. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  21407. this.matrixAutoUpdate = false;
  21408. this.matrixWorld = object.matrixWorld;
  21409. };
  21410. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  21411. /**
  21412. * @author alteredq / http://alteredqualia.com/
  21413. */
  21414. THREE.ImmediateRenderObject = function () {
  21415. THREE.Object3D.call( this );
  21416. this.render = function ( renderCallback ) { };
  21417. };
  21418. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  21419. /**
  21420. * @author mikael emtinger / http://gomo.se/
  21421. * @author alteredq / http://alteredqualia.com/
  21422. */
  21423. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  21424. THREE.Object3D.call( this );
  21425. this.lensFlares = [];
  21426. this.positionScreen = new THREE.Vector3();
  21427. this.customUpdateCallback = undefined;
  21428. if( texture !== undefined ) {
  21429. this.add( texture, size, distance, blending, color );
  21430. }
  21431. };
  21432. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  21433. /*
  21434. * Add: adds another flare
  21435. */
  21436. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  21437. if( size === undefined ) size = -1;
  21438. if( distance === undefined ) distance = 0;
  21439. if( opacity === undefined ) opacity = 1;
  21440. if( color === undefined ) color = new THREE.Color( 0xffffff );
  21441. if( blending === undefined ) blending = THREE.NormalBlending;
  21442. distance = Math.min( distance, Math.max( 0, distance ) );
  21443. this.lensFlares.push( { texture: texture, // THREE.Texture
  21444. size: size, // size in pixels (-1 = use texture.width)
  21445. distance: distance, // distance (0-1) from light source (0=at light source)
  21446. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  21447. scale: 1, // scale
  21448. rotation: 1, // rotation
  21449. opacity: opacity, // opacity
  21450. color: color, // color
  21451. blending: blending } ); // blending
  21452. };
  21453. /*
  21454. * Update lens flares update positions on all flares based on the screen position
  21455. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  21456. */
  21457. THREE.LensFlare.prototype.updateLensFlares = function () {
  21458. var f, fl = this.lensFlares.length;
  21459. var flare;
  21460. var vecX = -this.positionScreen.x * 2;
  21461. var vecY = -this.positionScreen.y * 2;
  21462. for( f = 0; f < fl; f ++ ) {
  21463. flare = this.lensFlares[ f ];
  21464. flare.x = this.positionScreen.x + vecX * flare.distance;
  21465. flare.y = this.positionScreen.y + vecY * flare.distance;
  21466. flare.wantedRotation = flare.x * Math.PI * 0.25;
  21467. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  21468. }
  21469. };
  21470. /**
  21471. * @author alteredq / http://alteredqualia.com/
  21472. */
  21473. THREE.MorphBlendMesh = function( geometry, material ) {
  21474. THREE.Mesh.call( this, geometry, material );
  21475. this.animationsMap = {};
  21476. this.animationsList = [];
  21477. // prepare default animation
  21478. // (all frames played together in 1 second)
  21479. var numFrames = this.geometry.morphTargets.length;
  21480. var name = "__default";
  21481. var startFrame = 0;
  21482. var endFrame = numFrames - 1;
  21483. var fps = numFrames / 1;
  21484. this.createAnimation( name, startFrame, endFrame, fps );
  21485. this.setAnimationWeight( name, 1 );
  21486. };
  21487. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  21488. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  21489. var animation = {
  21490. startFrame: start,
  21491. endFrame: end,
  21492. length: end - start + 1,
  21493. fps: fps,
  21494. duration: ( end - start ) / fps,
  21495. lastFrame: 0,
  21496. currentFrame: 0,
  21497. active: false,
  21498. time: 0,
  21499. direction: 1,
  21500. weight: 1,
  21501. directionBackwards: false,
  21502. mirroredLoop: false
  21503. };
  21504. this.animationsMap[ name ] = animation;
  21505. this.animationsList.push( animation );
  21506. };
  21507. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21508. var pattern = /([a-z]+)(\d+)/;
  21509. var firstAnimation, frameRanges = {};
  21510. var geometry = this.geometry;
  21511. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21512. var morph = geometry.morphTargets[ i ];
  21513. var chunks = morph.name.match( pattern );
  21514. if ( chunks && chunks.length > 1 ) {
  21515. var name = chunks[ 1 ];
  21516. var num = chunks[ 2 ];
  21517. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  21518. var range = frameRanges[ name ];
  21519. if ( i < range.start ) range.start = i;
  21520. if ( i > range.end ) range.end = i;
  21521. if ( ! firstAnimation ) firstAnimation = name;
  21522. }
  21523. }
  21524. for ( var name in frameRanges ) {
  21525. var range = frameRanges[ name ];
  21526. this.createAnimation( name, range.start, range.end, fps );
  21527. }
  21528. this.firstAnimation = firstAnimation;
  21529. };
  21530. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  21531. var animation = this.animationsMap[ name ];
  21532. if ( animation ) {
  21533. animation.direction = 1;
  21534. animation.directionBackwards = false;
  21535. }
  21536. };
  21537. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  21538. var animation = this.animationsMap[ name ];
  21539. if ( animation ) {
  21540. animation.direction = -1;
  21541. animation.directionBackwards = true;
  21542. }
  21543. };
  21544. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  21545. var animation = this.animationsMap[ name ];
  21546. if ( animation ) {
  21547. animation.fps = fps;
  21548. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21549. }
  21550. };
  21551. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21552. var animation = this.animationsMap[ name ];
  21553. if ( animation ) {
  21554. animation.duration = duration;
  21555. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21556. }
  21557. };
  21558. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21559. var animation = this.animationsMap[ name ];
  21560. if ( animation ) {
  21561. animation.weight = weight;
  21562. }
  21563. };
  21564. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21565. var animation = this.animationsMap[ name ];
  21566. if ( animation ) {
  21567. animation.time = time;
  21568. }
  21569. };
  21570. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21571. var time = 0;
  21572. var animation = this.animationsMap[ name ];
  21573. if ( animation ) {
  21574. time = animation.time;
  21575. }
  21576. return time;
  21577. };
  21578. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21579. var duration = -1;
  21580. var animation = this.animationsMap[ name ];
  21581. if ( animation ) {
  21582. duration = animation.duration;
  21583. }
  21584. return duration;
  21585. };
  21586. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21587. var animation = this.animationsMap[ name ];
  21588. if ( animation ) {
  21589. animation.time = 0;
  21590. animation.active = true;
  21591. } else {
  21592. console.warn( "animation[" + name + "] undefined" );
  21593. }
  21594. };
  21595. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21596. var animation = this.animationsMap[ name ];
  21597. if ( animation ) {
  21598. animation.active = false;
  21599. }
  21600. };
  21601. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  21602. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21603. var animation = this.animationsList[ i ];
  21604. if ( ! animation.active ) continue;
  21605. var frameTime = animation.duration / animation.length;
  21606. animation.time += animation.direction * delta;
  21607. if ( animation.mirroredLoop ) {
  21608. if ( animation.time > animation.duration || animation.time < 0 ) {
  21609. animation.direction *= -1;
  21610. if ( animation.time > animation.duration ) {
  21611. animation.time = animation.duration;
  21612. animation.directionBackwards = true;
  21613. }
  21614. if ( animation.time < 0 ) {
  21615. animation.time = 0;
  21616. animation.directionBackwards = false;
  21617. }
  21618. }
  21619. } else {
  21620. animation.time = animation.time % animation.duration;
  21621. if ( animation.time < 0 ) animation.time += animation.duration;
  21622. }
  21623. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21624. var weight = animation.weight;
  21625. if ( keyframe !== animation.currentFrame ) {
  21626. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21627. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21628. this.morphTargetInfluences[ keyframe ] = 0;
  21629. animation.lastFrame = animation.currentFrame;
  21630. animation.currentFrame = keyframe;
  21631. }
  21632. var mix = ( animation.time % frameTime ) / frameTime;
  21633. if ( animation.directionBackwards ) mix = 1 - mix;
  21634. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21635. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21636. }
  21637. };
  21638. /**
  21639. * @author mikael emtinger / http://gomo.se/
  21640. * @author alteredq / http://alteredqualia.com/
  21641. */
  21642. THREE.LensFlarePlugin = function () {
  21643. var _gl, _renderer, _precision, _lensFlare = {};
  21644. this.init = function ( renderer ) {
  21645. _gl = renderer.context;
  21646. _renderer = renderer;
  21647. _precision = renderer.getPrecision();
  21648. _lensFlare.vertices = new Float32Array( 8 + 8 );
  21649. _lensFlare.faces = new Uint16Array( 6 );
  21650. var i = 0;
  21651. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  21652. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  21653. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  21654. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  21655. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21656. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21657. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  21658. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  21659. i = 0;
  21660. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  21661. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  21662. // buffers
  21663. _lensFlare.vertexBuffer = _gl.createBuffer();
  21664. _lensFlare.elementBuffer = _gl.createBuffer();
  21665. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21666. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  21667. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21668. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  21669. // textures
  21670. _lensFlare.tempTexture = _gl.createTexture();
  21671. _lensFlare.occlusionTexture = _gl.createTexture();
  21672. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21673. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21674. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21675. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21676. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21677. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21678. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21679. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21680. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21681. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21682. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21683. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21684. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21685. _lensFlare.hasVertexTexture = false;
  21686. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  21687. } else {
  21688. _lensFlare.hasVertexTexture = true;
  21689. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  21690. }
  21691. _lensFlare.attributes = {};
  21692. _lensFlare.uniforms = {};
  21693. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21694. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21695. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21696. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21697. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21698. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21699. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21700. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21701. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21702. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21703. };
  21704. /*
  21705. * Render lens flares
  21706. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21707. * reads these back and calculates occlusion.
  21708. * Then _lensFlare.update_lensFlares() is called to re-position and
  21709. * update transparency of flares. Then they are rendered.
  21710. *
  21711. */
  21712. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21713. var flares = scene.__webglFlares,
  21714. nFlares = flares.length;
  21715. if ( ! nFlares ) return;
  21716. var tempPosition = new THREE.Vector3();
  21717. var invAspect = viewportHeight / viewportWidth,
  21718. halfViewportWidth = viewportWidth * 0.5,
  21719. halfViewportHeight = viewportHeight * 0.5;
  21720. var size = 16 / viewportHeight,
  21721. scale = new THREE.Vector2( size * invAspect, size );
  21722. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21723. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21724. var uniforms = _lensFlare.uniforms,
  21725. attributes = _lensFlare.attributes;
  21726. // set _lensFlare program and reset blending
  21727. _gl.useProgram( _lensFlare.program );
  21728. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21729. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21730. // loop through all lens flares to update their occlusion and positions
  21731. // setup gl and common used attribs/unforms
  21732. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21733. _gl.uniform1i( uniforms.map, 1 );
  21734. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21735. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21736. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21737. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21738. _gl.disable( _gl.CULL_FACE );
  21739. _gl.depthMask( false );
  21740. var i, j, jl, flare, sprite;
  21741. for ( i = 0; i < nFlares; i ++ ) {
  21742. size = 16 / viewportHeight;
  21743. scale.set( size * invAspect, size );
  21744. // calc object screen position
  21745. flare = flares[ i ];
  21746. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21747. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  21748. tempPosition.applyProjection( camera.projectionMatrix );
  21749. // setup arrays for gl programs
  21750. screenPosition.copy( tempPosition )
  21751. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21752. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21753. // screen cull
  21754. if ( _lensFlare.hasVertexTexture || (
  21755. screenPositionPixels.x > 0 &&
  21756. screenPositionPixels.x < viewportWidth &&
  21757. screenPositionPixels.y > 0 &&
  21758. screenPositionPixels.y < viewportHeight ) ) {
  21759. // save current RGB to temp texture
  21760. _gl.activeTexture( _gl.TEXTURE1 );
  21761. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21762. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21763. // render pink quad
  21764. _gl.uniform1i( uniforms.renderType, 0 );
  21765. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21766. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21767. _gl.disable( _gl.BLEND );
  21768. _gl.enable( _gl.DEPTH_TEST );
  21769. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21770. // copy result to occlusionMap
  21771. _gl.activeTexture( _gl.TEXTURE0 );
  21772. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21773. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21774. // restore graphics
  21775. _gl.uniform1i( uniforms.renderType, 1 );
  21776. _gl.disable( _gl.DEPTH_TEST );
  21777. _gl.activeTexture( _gl.TEXTURE1 );
  21778. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21779. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21780. // update object positions
  21781. flare.positionScreen.copy( screenPosition )
  21782. if ( flare.customUpdateCallback ) {
  21783. flare.customUpdateCallback( flare );
  21784. } else {
  21785. flare.updateLensFlares();
  21786. }
  21787. // render flares
  21788. _gl.uniform1i( uniforms.renderType, 2 );
  21789. _gl.enable( _gl.BLEND );
  21790. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21791. sprite = flare.lensFlares[ j ];
  21792. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21793. screenPosition.x = sprite.x;
  21794. screenPosition.y = sprite.y;
  21795. screenPosition.z = sprite.z;
  21796. size = sprite.size * sprite.scale / viewportHeight;
  21797. scale.x = size * invAspect;
  21798. scale.y = size;
  21799. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21800. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21801. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21802. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21803. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21804. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21805. _renderer.setTexture( sprite.texture, 1 );
  21806. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21807. }
  21808. }
  21809. }
  21810. }
  21811. // restore gl
  21812. _gl.enable( _gl.CULL_FACE );
  21813. _gl.enable( _gl.DEPTH_TEST );
  21814. _gl.depthMask( true );
  21815. };
  21816. function createProgram ( shader, precision ) {
  21817. var program = _gl.createProgram();
  21818. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21819. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21820. var prefix = "precision " + precision + " float;\n";
  21821. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21822. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21823. _gl.compileShader( fragmentShader );
  21824. _gl.compileShader( vertexShader );
  21825. _gl.attachShader( program, fragmentShader );
  21826. _gl.attachShader( program, vertexShader );
  21827. _gl.linkProgram( program );
  21828. return program;
  21829. };
  21830. };
  21831. /**
  21832. * @author alteredq / http://alteredqualia.com/
  21833. */
  21834. THREE.ShadowMapPlugin = function () {
  21835. var _gl,
  21836. _renderer,
  21837. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21838. _frustum = new THREE.Frustum(),
  21839. _projScreenMatrix = new THREE.Matrix4(),
  21840. _min = new THREE.Vector3(),
  21841. _max = new THREE.Vector3(),
  21842. _matrixPosition = new THREE.Vector3();
  21843. this.init = function ( renderer ) {
  21844. _gl = renderer.context;
  21845. _renderer = renderer;
  21846. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21847. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21848. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21849. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21850. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21851. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21852. _depthMaterial._shadowPass = true;
  21853. _depthMaterialMorph._shadowPass = true;
  21854. _depthMaterialSkin._shadowPass = true;
  21855. _depthMaterialMorphSkin._shadowPass = true;
  21856. };
  21857. this.render = function ( scene, camera ) {
  21858. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21859. this.update( scene, camera );
  21860. };
  21861. this.update = function ( scene, camera ) {
  21862. var i, il, j, jl, n,
  21863. shadowMap, shadowMatrix, shadowCamera,
  21864. program, buffer, material,
  21865. webglObject, object, light,
  21866. renderList,
  21867. lights = [],
  21868. k = 0,
  21869. fog = null;
  21870. // set GL state for depth map
  21871. _gl.clearColor( 1, 1, 1, 1 );
  21872. _gl.disable( _gl.BLEND );
  21873. _gl.enable( _gl.CULL_FACE );
  21874. _gl.frontFace( _gl.CCW );
  21875. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21876. _gl.cullFace( _gl.FRONT );
  21877. } else {
  21878. _gl.cullFace( _gl.BACK );
  21879. }
  21880. _renderer.setDepthTest( true );
  21881. // preprocess lights
  21882. // - skip lights that are not casting shadows
  21883. // - create virtual lights for cascaded shadow maps
  21884. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21885. light = scene.__lights[ i ];
  21886. if ( ! light.castShadow ) continue;
  21887. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21888. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21889. var virtualLight;
  21890. if ( ! light.shadowCascadeArray[ n ] ) {
  21891. virtualLight = createVirtualLight( light, n );
  21892. virtualLight.originalCamera = camera;
  21893. var gyro = new THREE.Gyroscope();
  21894. gyro.position = light.shadowCascadeOffset;
  21895. gyro.add( virtualLight );
  21896. gyro.add( virtualLight.target );
  21897. camera.add( gyro );
  21898. light.shadowCascadeArray[ n ] = virtualLight;
  21899. console.log( "Created virtualLight", virtualLight );
  21900. } else {
  21901. virtualLight = light.shadowCascadeArray[ n ];
  21902. }
  21903. updateVirtualLight( light, n );
  21904. lights[ k ] = virtualLight;
  21905. k ++;
  21906. }
  21907. } else {
  21908. lights[ k ] = light;
  21909. k ++;
  21910. }
  21911. }
  21912. // render depth map
  21913. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21914. light = lights[ i ];
  21915. if ( ! light.shadowMap ) {
  21916. var shadowFilter = THREE.LinearFilter;
  21917. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21918. shadowFilter = THREE.NearestFilter;
  21919. }
  21920. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21921. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21922. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21923. light.shadowMatrix = new THREE.Matrix4();
  21924. }
  21925. if ( ! light.shadowCamera ) {
  21926. if ( light instanceof THREE.SpotLight ) {
  21927. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21928. } else if ( light instanceof THREE.DirectionalLight ) {
  21929. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21930. } else {
  21931. console.error( "Unsupported light type for shadow" );
  21932. continue;
  21933. }
  21934. scene.add( light.shadowCamera );
  21935. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21936. }
  21937. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21938. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21939. light.shadowCamera.add( light.cameraHelper );
  21940. }
  21941. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21942. updateShadowCamera( camera, light );
  21943. }
  21944. shadowMap = light.shadowMap;
  21945. shadowMatrix = light.shadowMatrix;
  21946. shadowCamera = light.shadowCamera;
  21947. shadowCamera.position.setFromMatrixPosition( light.matrixWorld );
  21948. _matrixPosition.setFromMatrixPosition( light.target.matrixWorld );
  21949. shadowCamera.lookAt( _matrixPosition );
  21950. shadowCamera.updateMatrixWorld();
  21951. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21952. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21953. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21954. // compute shadow matrix
  21955. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21956. 0.0, 0.5, 0.0, 0.5,
  21957. 0.0, 0.0, 0.5, 0.5,
  21958. 0.0, 0.0, 0.0, 1.0 );
  21959. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  21960. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  21961. // update camera matrices and frustum
  21962. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21963. _frustum.setFromMatrix( _projScreenMatrix );
  21964. // render shadow map
  21965. _renderer.setRenderTarget( shadowMap );
  21966. _renderer.clear();
  21967. // set object matrices & frustum culling
  21968. renderList = scene.__webglObjects;
  21969. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21970. webglObject = renderList[ j ];
  21971. object = webglObject.object;
  21972. webglObject.render = false;
  21973. if ( object.visible && object.castShadow ) {
  21974. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21975. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21976. webglObject.render = true;
  21977. }
  21978. }
  21979. }
  21980. // render regular objects
  21981. var objectMaterial, useMorphing, useSkinning;
  21982. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21983. webglObject = renderList[ j ];
  21984. if ( webglObject.render ) {
  21985. object = webglObject.object;
  21986. buffer = webglObject.buffer;
  21987. // culling is overriden globally for all objects
  21988. // while rendering depth map
  21989. // need to deal with MeshFaceMaterial somehow
  21990. // in that case just use the first of material.materials for now
  21991. // (proper solution would require to break objects by materials
  21992. // similarly to regular rendering and then set corresponding
  21993. // depth materials per each chunk instead of just once per object)
  21994. objectMaterial = getObjectMaterial( object );
  21995. useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21996. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21997. if ( object.customDepthMaterial ) {
  21998. material = object.customDepthMaterial;
  21999. } else if ( useSkinning ) {
  22000. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  22001. } else if ( useMorphing ) {
  22002. material = _depthMaterialMorph;
  22003. } else {
  22004. material = _depthMaterial;
  22005. }
  22006. if ( buffer instanceof THREE.BufferGeometry ) {
  22007. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  22008. } else {
  22009. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  22010. }
  22011. }
  22012. }
  22013. // set matrices and render immediate objects
  22014. renderList = scene.__webglObjectsImmediate;
  22015. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22016. webglObject = renderList[ j ];
  22017. object = webglObject.object;
  22018. if ( object.visible && object.castShadow ) {
  22019. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  22020. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  22021. }
  22022. }
  22023. }
  22024. // restore GL state
  22025. var clearColor = _renderer.getClearColor(),
  22026. clearAlpha = _renderer.getClearAlpha();
  22027. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  22028. _gl.enable( _gl.BLEND );
  22029. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  22030. _gl.cullFace( _gl.BACK );
  22031. }
  22032. };
  22033. function createVirtualLight( light, cascade ) {
  22034. var virtualLight = new THREE.DirectionalLight();
  22035. virtualLight.isVirtual = true;
  22036. virtualLight.onlyShadow = true;
  22037. virtualLight.castShadow = true;
  22038. virtualLight.shadowCameraNear = light.shadowCameraNear;
  22039. virtualLight.shadowCameraFar = light.shadowCameraFar;
  22040. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  22041. virtualLight.shadowCameraRight = light.shadowCameraRight;
  22042. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  22043. virtualLight.shadowCameraTop = light.shadowCameraTop;
  22044. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  22045. virtualLight.shadowDarkness = light.shadowDarkness;
  22046. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  22047. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  22048. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  22049. virtualLight.pointsWorld = [];
  22050. virtualLight.pointsFrustum = [];
  22051. var pointsWorld = virtualLight.pointsWorld,
  22052. pointsFrustum = virtualLight.pointsFrustum;
  22053. for ( var i = 0; i < 8; i ++ ) {
  22054. pointsWorld[ i ] = new THREE.Vector3();
  22055. pointsFrustum[ i ] = new THREE.Vector3();
  22056. }
  22057. var nearZ = light.shadowCascadeNearZ[ cascade ];
  22058. var farZ = light.shadowCascadeFarZ[ cascade ];
  22059. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  22060. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  22061. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  22062. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  22063. pointsFrustum[ 4 ].set( -1, -1, farZ );
  22064. pointsFrustum[ 5 ].set( 1, -1, farZ );
  22065. pointsFrustum[ 6 ].set( -1, 1, farZ );
  22066. pointsFrustum[ 7 ].set( 1, 1, farZ );
  22067. return virtualLight;
  22068. }
  22069. // Synchronize virtual light with the original light
  22070. function updateVirtualLight( light, cascade ) {
  22071. var virtualLight = light.shadowCascadeArray[ cascade ];
  22072. virtualLight.position.copy( light.position );
  22073. virtualLight.target.position.copy( light.target.position );
  22074. virtualLight.lookAt( virtualLight.target );
  22075. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  22076. virtualLight.shadowDarkness = light.shadowDarkness;
  22077. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  22078. var nearZ = light.shadowCascadeNearZ[ cascade ];
  22079. var farZ = light.shadowCascadeFarZ[ cascade ];
  22080. var pointsFrustum = virtualLight.pointsFrustum;
  22081. pointsFrustum[ 0 ].z = nearZ;
  22082. pointsFrustum[ 1 ].z = nearZ;
  22083. pointsFrustum[ 2 ].z = nearZ;
  22084. pointsFrustum[ 3 ].z = nearZ;
  22085. pointsFrustum[ 4 ].z = farZ;
  22086. pointsFrustum[ 5 ].z = farZ;
  22087. pointsFrustum[ 6 ].z = farZ;
  22088. pointsFrustum[ 7 ].z = farZ;
  22089. }
  22090. // Fit shadow camera's ortho frustum to camera frustum
  22091. function updateShadowCamera( camera, light ) {
  22092. var shadowCamera = light.shadowCamera,
  22093. pointsFrustum = light.pointsFrustum,
  22094. pointsWorld = light.pointsWorld;
  22095. _min.set( Infinity, Infinity, Infinity );
  22096. _max.set( -Infinity, -Infinity, -Infinity );
  22097. for ( var i = 0; i < 8; i ++ ) {
  22098. var p = pointsWorld[ i ];
  22099. p.copy( pointsFrustum[ i ] );
  22100. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  22101. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  22102. if ( p.x < _min.x ) _min.x = p.x;
  22103. if ( p.x > _max.x ) _max.x = p.x;
  22104. if ( p.y < _min.y ) _min.y = p.y;
  22105. if ( p.y > _max.y ) _max.y = p.y;
  22106. if ( p.z < _min.z ) _min.z = p.z;
  22107. if ( p.z > _max.z ) _max.z = p.z;
  22108. }
  22109. shadowCamera.left = _min.x;
  22110. shadowCamera.right = _max.x;
  22111. shadowCamera.top = _max.y;
  22112. shadowCamera.bottom = _min.y;
  22113. // can't really fit near/far
  22114. //shadowCamera.near = _min.z;
  22115. //shadowCamera.far = _max.z;
  22116. shadowCamera.updateProjectionMatrix();
  22117. }
  22118. // For the moment just ignore objects that have multiple materials with different animation methods
  22119. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  22120. function getObjectMaterial( object ) {
  22121. return object.material instanceof THREE.MeshFaceMaterial
  22122. ? object.material.materials[ 0 ]
  22123. : object.material;
  22124. };
  22125. };
  22126. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  22127. /**
  22128. * @author mikael emtinger / http://gomo.se/
  22129. * @author alteredq / http://alteredqualia.com/
  22130. */
  22131. THREE.SpritePlugin = function () {
  22132. var _gl, _renderer, _texture;
  22133. var vertices, faces, vertexBuffer, elementBuffer;
  22134. var program, attributes, uniforms;
  22135. this.init = function ( renderer ) {
  22136. _gl = renderer.context;
  22137. _renderer = renderer;
  22138. vertices = new Float32Array( [
  22139. - 0.5, - 0.5, 0, 0,
  22140. 0.5, - 0.5, 1, 0,
  22141. 0.5, 0.5, 1, 1,
  22142. - 0.5, 0.5, 0, 1
  22143. ] );
  22144. faces = new Uint16Array( [
  22145. 0, 1, 2,
  22146. 0, 2, 3
  22147. ] );
  22148. vertexBuffer = _gl.createBuffer();
  22149. elementBuffer = _gl.createBuffer();
  22150. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  22151. _gl.bufferData( _gl.ARRAY_BUFFER, vertices, _gl.STATIC_DRAW );
  22152. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  22153. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faces, _gl.STATIC_DRAW );
  22154. program = createProgram();
  22155. attributes = {
  22156. position: _gl.getAttribLocation ( program, 'position' ),
  22157. uv: _gl.getAttribLocation ( program, 'uv' )
  22158. };
  22159. uniforms = {
  22160. uvOffset: _gl.getUniformLocation( program, 'uvOffset' ),
  22161. uvScale: _gl.getUniformLocation( program, 'uvScale' ),
  22162. rotation: _gl.getUniformLocation( program, 'rotation' ),
  22163. scale: _gl.getUniformLocation( program, 'scale' ),
  22164. color: _gl.getUniformLocation( program, 'color' ),
  22165. map: _gl.getUniformLocation( program, 'map' ),
  22166. opacity: _gl.getUniformLocation( program, 'opacity' ),
  22167. modelViewMatrix: _gl.getUniformLocation( program, 'modelViewMatrix' ),
  22168. projectionMatrix: _gl.getUniformLocation( program, 'projectionMatrix' ),
  22169. fogType: _gl.getUniformLocation( program, 'fogType' ),
  22170. fogDensity: _gl.getUniformLocation( program, 'fogDensity' ),
  22171. fogNear: _gl.getUniformLocation( program, 'fogNear' ),
  22172. fogFar: _gl.getUniformLocation( program, 'fogFar' ),
  22173. fogColor: _gl.getUniformLocation( program, 'fogColor' ),
  22174. alphaTest: _gl.getUniformLocation( program, 'alphaTest' )
  22175. };
  22176. var canvas = document.createElement( 'canvas' );
  22177. canvas.width = 8;
  22178. canvas.height = 8;
  22179. var context = canvas.getContext( '2d' );
  22180. context.fillStyle = '#ffffff';
  22181. context.fillRect( 0, 0, canvas.width, canvas.height );
  22182. _texture = new THREE.Texture( canvas );
  22183. _texture.needsUpdate = true;
  22184. };
  22185. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  22186. var sprites = scene.__webglSprites,
  22187. nSprites = sprites.length;
  22188. if ( ! nSprites ) return;
  22189. // setup gl
  22190. _gl.useProgram( program );
  22191. _gl.enableVertexAttribArray( attributes.position );
  22192. _gl.enableVertexAttribArray( attributes.uv );
  22193. _gl.disable( _gl.CULL_FACE );
  22194. _gl.enable( _gl.BLEND );
  22195. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  22196. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  22197. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  22198. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  22199. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  22200. _gl.activeTexture( _gl.TEXTURE0 );
  22201. _gl.uniform1i( uniforms.map, 0 );
  22202. var oldFogType = 0;
  22203. var sceneFogType = 0;
  22204. var fog = scene.fog;
  22205. if ( fog ) {
  22206. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  22207. if ( fog instanceof THREE.Fog ) {
  22208. _gl.uniform1f( uniforms.fogNear, fog.near );
  22209. _gl.uniform1f( uniforms.fogFar, fog.far );
  22210. _gl.uniform1i( uniforms.fogType, 1 );
  22211. oldFogType = 1;
  22212. sceneFogType = 1;
  22213. } else if ( fog instanceof THREE.FogExp2 ) {
  22214. _gl.uniform1f( uniforms.fogDensity, fog.density );
  22215. _gl.uniform1i( uniforms.fogType, 2 );
  22216. oldFogType = 2;
  22217. sceneFogType = 2;
  22218. }
  22219. } else {
  22220. _gl.uniform1i( uniforms.fogType, 0 );
  22221. oldFogType = 0;
  22222. sceneFogType = 0;
  22223. }
  22224. // update positions and sort
  22225. var i, sprite, material, fogType, scale = [];
  22226. for( i = 0; i < nSprites; i ++ ) {
  22227. sprite = sprites[ i ];
  22228. material = sprite.material;
  22229. if ( sprite.visible === false ) continue;
  22230. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  22231. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  22232. }
  22233. sprites.sort( painterSortStable );
  22234. // render all sprites
  22235. for( i = 0; i < nSprites; i ++ ) {
  22236. sprite = sprites[ i ];
  22237. if ( sprite.visible === false ) continue;
  22238. material = sprite.material;
  22239. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  22240. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  22241. scale[ 0 ] = sprite.scale.x;
  22242. scale[ 1 ] = sprite.scale.y;
  22243. if ( scene.fog && material.fog ) {
  22244. fogType = sceneFogType;
  22245. } else {
  22246. fogType = 0;
  22247. }
  22248. if ( oldFogType !== fogType ) {
  22249. _gl.uniform1i( uniforms.fogType, fogType );
  22250. oldFogType = fogType;
  22251. }
  22252. if ( material.map !== null ) {
  22253. _gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  22254. _gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  22255. } else {
  22256. _gl.uniform2f( uniforms.uvOffset, 0, 0 );
  22257. _gl.uniform2f( uniforms.uvScale, 1, 1 );
  22258. }
  22259. _gl.uniform1f( uniforms.opacity, material.opacity );
  22260. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  22261. _gl.uniform1f( uniforms.rotation, material.rotation );
  22262. _gl.uniform2fv( uniforms.scale, scale );
  22263. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  22264. _renderer.setDepthTest( material.depthTest );
  22265. _renderer.setDepthWrite( material.depthWrite );
  22266. if ( material.map && material.map.image && material.map.image.width ) {
  22267. _renderer.setTexture( material.map, 0 );
  22268. } else {
  22269. _renderer.setTexture( _texture, 0 );
  22270. }
  22271. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  22272. }
  22273. // restore gl
  22274. _gl.enable( _gl.CULL_FACE );
  22275. };
  22276. function createProgram () {
  22277. var program = _gl.createProgram();
  22278. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  22279. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  22280. _gl.shaderSource( vertexShader, [
  22281. 'precision ' + _renderer.getPrecision() + ' float;',
  22282. 'uniform mat4 modelViewMatrix;',
  22283. 'uniform mat4 projectionMatrix;',
  22284. 'uniform float rotation;',
  22285. 'uniform vec2 scale;',
  22286. 'uniform vec2 uvOffset;',
  22287. 'uniform vec2 uvScale;',
  22288. 'attribute vec2 position;',
  22289. 'attribute vec2 uv;',
  22290. 'varying vec2 vUV;',
  22291. 'void main() {',
  22292. 'vUV = uvOffset + uv * uvScale;',
  22293. 'vec2 alignedPosition = position * scale;',
  22294. 'vec2 rotatedPosition;',
  22295. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  22296. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  22297. 'vec4 finalPosition;',
  22298. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  22299. 'finalPosition.xy += rotatedPosition;',
  22300. 'finalPosition = projectionMatrix * finalPosition;',
  22301. 'gl_Position = finalPosition;',
  22302. '}'
  22303. ].join( '\n' ) );
  22304. _gl.shaderSource( fragmentShader, [
  22305. 'precision ' + _renderer.getPrecision() + ' float;',
  22306. 'uniform vec3 color;',
  22307. 'uniform sampler2D map;',
  22308. 'uniform float opacity;',
  22309. 'uniform int fogType;',
  22310. 'uniform vec3 fogColor;',
  22311. 'uniform float fogDensity;',
  22312. 'uniform float fogNear;',
  22313. 'uniform float fogFar;',
  22314. 'uniform float alphaTest;',
  22315. 'varying vec2 vUV;',
  22316. 'void main() {',
  22317. 'vec4 texture = texture2D( map, vUV );',
  22318. 'if ( texture.a < alphaTest ) discard;',
  22319. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  22320. 'if ( fogType > 0 ) {',
  22321. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  22322. 'float fogFactor = 0.0;',
  22323. 'if ( fogType == 1 ) {',
  22324. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  22325. '} else {',
  22326. 'const float LOG2 = 1.442695;',
  22327. 'float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  22328. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  22329. '}',
  22330. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  22331. '}',
  22332. '}'
  22333. ].join( '\n' ) );
  22334. _gl.compileShader( vertexShader );
  22335. _gl.compileShader( fragmentShader );
  22336. _gl.attachShader( program, vertexShader );
  22337. _gl.attachShader( program, fragmentShader );
  22338. _gl.linkProgram( program );
  22339. return program;
  22340. };
  22341. function painterSortStable ( a, b ) {
  22342. if ( a.z !== b.z ) {
  22343. return b.z - a.z;
  22344. } else {
  22345. return b.id - a.id;
  22346. }
  22347. };
  22348. };
  22349. /**
  22350. * @author alteredq / http://alteredqualia.com/
  22351. */
  22352. THREE.DepthPassPlugin = function () {
  22353. this.enabled = false;
  22354. this.renderTarget = null;
  22355. var _gl,
  22356. _renderer,
  22357. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  22358. _frustum = new THREE.Frustum(),
  22359. _projScreenMatrix = new THREE.Matrix4();
  22360. this.init = function ( renderer ) {
  22361. _gl = renderer.context;
  22362. _renderer = renderer;
  22363. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  22364. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  22365. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  22366. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  22367. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  22368. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  22369. _depthMaterial._shadowPass = true;
  22370. _depthMaterialMorph._shadowPass = true;
  22371. _depthMaterialSkin._shadowPass = true;
  22372. _depthMaterialMorphSkin._shadowPass = true;
  22373. };
  22374. this.render = function ( scene, camera ) {
  22375. if ( ! this.enabled ) return;
  22376. this.update( scene, camera );
  22377. };
  22378. this.update = function ( scene, camera ) {
  22379. var i, il, j, jl, n,
  22380. program, buffer, material,
  22381. webglObject, object, light,
  22382. renderList,
  22383. fog = null;
  22384. // set GL state for depth map
  22385. _gl.clearColor( 1, 1, 1, 1 );
  22386. _gl.disable( _gl.BLEND );
  22387. _renderer.setDepthTest( true );
  22388. // update scene
  22389. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  22390. // update camera matrices and frustum
  22391. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  22392. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  22393. _frustum.setFromMatrix( _projScreenMatrix );
  22394. // render depth map
  22395. _renderer.setRenderTarget( this.renderTarget );
  22396. _renderer.clear();
  22397. // set object matrices & frustum culling
  22398. renderList = scene.__webglObjects;
  22399. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22400. webglObject = renderList[ j ];
  22401. object = webglObject.object;
  22402. webglObject.render = false;
  22403. if ( object.visible ) {
  22404. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  22405. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22406. webglObject.render = true;
  22407. }
  22408. }
  22409. }
  22410. // render regular objects
  22411. var objectMaterial, useMorphing, useSkinning;
  22412. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22413. webglObject = renderList[ j ];
  22414. if ( webglObject.render ) {
  22415. object = webglObject.object;
  22416. buffer = webglObject.buffer;
  22417. // todo: create proper depth material for particles
  22418. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  22419. objectMaterial = getObjectMaterial( object );
  22420. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  22421. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  22422. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  22423. if ( object.customDepthMaterial ) {
  22424. material = object.customDepthMaterial;
  22425. } else if ( useSkinning ) {
  22426. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  22427. } else if ( useMorphing ) {
  22428. material = _depthMaterialMorph;
  22429. } else {
  22430. material = _depthMaterial;
  22431. }
  22432. if ( buffer instanceof THREE.BufferGeometry ) {
  22433. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  22434. } else {
  22435. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  22436. }
  22437. }
  22438. }
  22439. // set matrices and render immediate objects
  22440. renderList = scene.__webglObjectsImmediate;
  22441. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22442. webglObject = renderList[ j ];
  22443. object = webglObject.object;
  22444. if ( object.visible ) {
  22445. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22446. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  22447. }
  22448. }
  22449. // restore GL state
  22450. var clearColor = _renderer.getClearColor(),
  22451. clearAlpha = _renderer.getClearAlpha();
  22452. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  22453. _gl.enable( _gl.BLEND );
  22454. };
  22455. // For the moment just ignore objects that have multiple materials with different animation methods
  22456. // Only the first material will be taken into account for deciding which depth material to use
  22457. function getObjectMaterial( object ) {
  22458. return object.material instanceof THREE.MeshFaceMaterial
  22459. ? object.material.materials[ 0 ]
  22460. : object.material;
  22461. };
  22462. };
  22463. /**
  22464. * @author mikael emtinger / http://gomo.se/
  22465. */
  22466. THREE.ShaderFlares = {
  22467. 'lensFlareVertexTexture': {
  22468. vertexShader: [
  22469. "uniform lowp int renderType;",
  22470. "uniform vec3 screenPosition;",
  22471. "uniform vec2 scale;",
  22472. "uniform float rotation;",
  22473. "uniform sampler2D occlusionMap;",
  22474. "attribute vec2 position;",
  22475. "attribute vec2 uv;",
  22476. "varying vec2 vUV;",
  22477. "varying float vVisibility;",
  22478. "void main() {",
  22479. "vUV = uv;",
  22480. "vec2 pos = position;",
  22481. "if( renderType == 2 ) {",
  22482. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  22483. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  22484. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  22485. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  22486. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  22487. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  22488. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  22489. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  22490. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  22491. "vVisibility = visibility.r / 9.0;",
  22492. "vVisibility *= 1.0 - visibility.g / 9.0;",
  22493. "vVisibility *= visibility.b / 9.0;",
  22494. "vVisibility *= 1.0 - visibility.a / 9.0;",
  22495. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22496. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22497. "}",
  22498. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22499. "}"
  22500. ].join( "\n" ),
  22501. fragmentShader: [
  22502. "uniform lowp int renderType;",
  22503. "uniform sampler2D map;",
  22504. "uniform float opacity;",
  22505. "uniform vec3 color;",
  22506. "varying vec2 vUV;",
  22507. "varying float vVisibility;",
  22508. "void main() {",
  22509. // pink square
  22510. "if( renderType == 0 ) {",
  22511. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  22512. // restore
  22513. "} else if( renderType == 1 ) {",
  22514. "gl_FragColor = texture2D( map, vUV );",
  22515. // flare
  22516. "} else {",
  22517. "vec4 texture = texture2D( map, vUV );",
  22518. "texture.a *= opacity * vVisibility;",
  22519. "gl_FragColor = texture;",
  22520. "gl_FragColor.rgb *= color;",
  22521. "}",
  22522. "}"
  22523. ].join( "\n" )
  22524. },
  22525. 'lensFlare': {
  22526. vertexShader: [
  22527. "uniform lowp int renderType;",
  22528. "uniform vec3 screenPosition;",
  22529. "uniform vec2 scale;",
  22530. "uniform float rotation;",
  22531. "attribute vec2 position;",
  22532. "attribute vec2 uv;",
  22533. "varying vec2 vUV;",
  22534. "void main() {",
  22535. "vUV = uv;",
  22536. "vec2 pos = position;",
  22537. "if( renderType == 2 ) {",
  22538. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22539. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22540. "}",
  22541. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22542. "}"
  22543. ].join( "\n" ),
  22544. fragmentShader: [
  22545. "precision mediump float;",
  22546. "uniform lowp int renderType;",
  22547. "uniform sampler2D map;",
  22548. "uniform sampler2D occlusionMap;",
  22549. "uniform float opacity;",
  22550. "uniform vec3 color;",
  22551. "varying vec2 vUV;",
  22552. "void main() {",
  22553. // pink square
  22554. "if( renderType == 0 ) {",
  22555. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  22556. // restore
  22557. "} else if( renderType == 1 ) {",
  22558. "gl_FragColor = texture2D( map, vUV );",
  22559. // flare
  22560. "} else {",
  22561. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  22562. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  22563. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  22564. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  22565. "visibility = ( 1.0 - visibility / 4.0 );",
  22566. "vec4 texture = texture2D( map, vUV );",
  22567. "texture.a *= opacity * visibility;",
  22568. "gl_FragColor = texture;",
  22569. "gl_FragColor.rgb *= color;",
  22570. "}",
  22571. "}"
  22572. ].join( "\n" )
  22573. }
  22574. };