three.js 823 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. * @author bhouston / http://exocortex.com
  5. */
  6. var THREE = THREE || { REVISION: '59dev' };
  7. self.console = self.console || {
  8. info: function () {},
  9. log: function () {},
  10. debug: function () {},
  11. warn: function () {},
  12. error: function () {}
  13. };
  14. String.prototype.trim = String.prototype.trim || function () {
  15. return this.replace( /^\s+|\s+$/g, '' );
  16. };
  17. // based on https://github.com/documentcloud/underscore/blob/bf657be243a075b5e72acc8a83e6f12a564d8f55/underscore.js#L767
  18. THREE.extend = function ( obj, source ) {
  19. // ECMAScript5 compatibility based on: http://www.nczonline.net/blog/2012/12/11/are-your-mixins-ecmascript-5-compatible/
  20. if ( Object.keys ) {
  21. var keys = Object.keys( source );
  22. for (var i = 0, il = keys.length; i < il; i++) {
  23. var prop = keys[i];
  24. Object.defineProperty( obj, prop, Object.getOwnPropertyDescriptor( source, prop ) );
  25. }
  26. } else {
  27. var safeHasOwnProperty = {}.hasOwnProperty;
  28. for ( var prop in source ) {
  29. if ( safeHasOwnProperty.call( source, prop ) ) {
  30. obj[prop] = source[prop];
  31. }
  32. }
  33. }
  34. return obj;
  35. };
  36. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  37. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  38. // requestAnimationFrame polyfill by Erik Möller
  39. // fixes from Paul Irish and Tino Zijdel
  40. // using 'self' instead of 'window' for compatibility with both NodeJS and IE10.
  41. ( function () {
  42. var lastTime = 0;
  43. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  44. for ( var x = 0; x < vendors.length && !self.requestAnimationFrame; ++ x ) {
  45. self.requestAnimationFrame = self[ vendors[ x ] + 'RequestAnimationFrame' ];
  46. self.cancelAnimationFrame = self[ vendors[ x ] + 'CancelAnimationFrame' ] || self[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  47. }
  48. if ( self.requestAnimationFrame === undefined && self['setTimeout'] !== undefined ) {
  49. self.requestAnimationFrame = function ( callback ) {
  50. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  51. var id = self.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  52. lastTime = currTime + timeToCall;
  53. return id;
  54. };
  55. }
  56. if( self.cancelAnimationFrame === undefined && self['clearTimeout'] !== undefined ) {
  57. self.cancelAnimationFrame = function ( id ) { self.clearTimeout( id ) };
  58. }
  59. }() );
  60. // GL STATE CONSTANTS
  61. THREE.CullFaceNone = 0;
  62. THREE.CullFaceBack = 1;
  63. THREE.CullFaceFront = 2;
  64. THREE.CullFaceFrontBack = 3;
  65. THREE.FrontFaceDirectionCW = 0;
  66. THREE.FrontFaceDirectionCCW = 1;
  67. // SHADOWING TYPES
  68. THREE.BasicShadowMap = 0;
  69. THREE.PCFShadowMap = 1;
  70. THREE.PCFSoftShadowMap = 2;
  71. // MATERIAL CONSTANTS
  72. // side
  73. THREE.FrontSide = 0;
  74. THREE.BackSide = 1;
  75. THREE.DoubleSide = 2;
  76. // shading
  77. THREE.NoShading = 0;
  78. THREE.FlatShading = 1;
  79. THREE.SmoothShading = 2;
  80. // colors
  81. THREE.NoColors = 0;
  82. THREE.FaceColors = 1;
  83. THREE.VertexColors = 2;
  84. // blending modes
  85. THREE.NoBlending = 0;
  86. THREE.NormalBlending = 1;
  87. THREE.AdditiveBlending = 2;
  88. THREE.SubtractiveBlending = 3;
  89. THREE.MultiplyBlending = 4;
  90. THREE.CustomBlending = 5;
  91. // custom blending equations
  92. // (numbers start from 100 not to clash with other
  93. // mappings to OpenGL constants defined in Texture.js)
  94. THREE.AddEquation = 100;
  95. THREE.SubtractEquation = 101;
  96. THREE.ReverseSubtractEquation = 102;
  97. // custom blending destination factors
  98. THREE.ZeroFactor = 200;
  99. THREE.OneFactor = 201;
  100. THREE.SrcColorFactor = 202;
  101. THREE.OneMinusSrcColorFactor = 203;
  102. THREE.SrcAlphaFactor = 204;
  103. THREE.OneMinusSrcAlphaFactor = 205;
  104. THREE.DstAlphaFactor = 206;
  105. THREE.OneMinusDstAlphaFactor = 207;
  106. // custom blending source factors
  107. //THREE.ZeroFactor = 200;
  108. //THREE.OneFactor = 201;
  109. //THREE.SrcAlphaFactor = 204;
  110. //THREE.OneMinusSrcAlphaFactor = 205;
  111. //THREE.DstAlphaFactor = 206;
  112. //THREE.OneMinusDstAlphaFactor = 207;
  113. THREE.DstColorFactor = 208;
  114. THREE.OneMinusDstColorFactor = 209;
  115. THREE.SrcAlphaSaturateFactor = 210;
  116. // TEXTURE CONSTANTS
  117. THREE.MultiplyOperation = 0;
  118. THREE.MixOperation = 1;
  119. THREE.AddOperation = 2;
  120. // Mapping modes
  121. THREE.UVMapping = function () {};
  122. THREE.CubeReflectionMapping = function () {};
  123. THREE.CubeRefractionMapping = function () {};
  124. THREE.SphericalReflectionMapping = function () {};
  125. THREE.SphericalRefractionMapping = function () {};
  126. // Wrapping modes
  127. THREE.RepeatWrapping = 1000;
  128. THREE.ClampToEdgeWrapping = 1001;
  129. THREE.MirroredRepeatWrapping = 1002;
  130. // Filters
  131. THREE.NearestFilter = 1003;
  132. THREE.NearestMipMapNearestFilter = 1004;
  133. THREE.NearestMipMapLinearFilter = 1005;
  134. THREE.LinearFilter = 1006;
  135. THREE.LinearMipMapNearestFilter = 1007;
  136. THREE.LinearMipMapLinearFilter = 1008;
  137. // Data types
  138. THREE.UnsignedByteType = 1009;
  139. THREE.ByteType = 1010;
  140. THREE.ShortType = 1011;
  141. THREE.UnsignedShortType = 1012;
  142. THREE.IntType = 1013;
  143. THREE.UnsignedIntType = 1014;
  144. THREE.FloatType = 1015;
  145. // Pixel types
  146. //THREE.UnsignedByteType = 1009;
  147. THREE.UnsignedShort4444Type = 1016;
  148. THREE.UnsignedShort5551Type = 1017;
  149. THREE.UnsignedShort565Type = 1018;
  150. // Pixel formats
  151. THREE.AlphaFormat = 1019;
  152. THREE.RGBFormat = 1020;
  153. THREE.RGBAFormat = 1021;
  154. THREE.LuminanceFormat = 1022;
  155. THREE.LuminanceAlphaFormat = 1023;
  156. // Compressed texture formats
  157. THREE.RGB_S3TC_DXT1_Format = 2001;
  158. THREE.RGBA_S3TC_DXT1_Format = 2002;
  159. THREE.RGBA_S3TC_DXT3_Format = 2003;
  160. THREE.RGBA_S3TC_DXT5_Format = 2004;
  161. /*
  162. // Potential future PVRTC compressed texture formats
  163. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  164. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  165. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  166. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  167. */
  168. /**
  169. * @author mrdoob / http://mrdoob.com/
  170. */
  171. THREE.Color = function ( value ) {
  172. if ( value !== undefined ) this.set( value );
  173. return this;
  174. };
  175. THREE.Color.prototype = {
  176. constructor: THREE.Color,
  177. r: 1, g: 1, b: 1,
  178. set: function ( value ) {
  179. if ( value instanceof THREE.Color ) {
  180. this.copy( value );
  181. } else if ( typeof value === 'number' ) {
  182. this.setHex( value );
  183. } else if ( typeof value === 'string' ) {
  184. this.setStyle( value );
  185. }
  186. return this;
  187. },
  188. setHex: function ( hex ) {
  189. hex = Math.floor( hex );
  190. this.r = ( hex >> 16 & 255 ) / 255;
  191. this.g = ( hex >> 8 & 255 ) / 255;
  192. this.b = ( hex & 255 ) / 255;
  193. return this;
  194. },
  195. setRGB: function ( r, g, b ) {
  196. this.r = r;
  197. this.g = g;
  198. this.b = b;
  199. return this;
  200. },
  201. setHSL: function ( h, s, l ) {
  202. // h,s,l ranges are in 0.0 - 1.0
  203. if ( s === 0 ) {
  204. this.r = this.g = this.b = l;
  205. } else {
  206. var hue2rgb = function ( p, q, t ) {
  207. if ( t < 0 ) t += 1;
  208. if ( t > 1 ) t -= 1;
  209. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  210. if ( t < 1 / 2 ) return q;
  211. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  212. return p;
  213. };
  214. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  215. var q = ( 2 * l ) - p;
  216. this.r = hue2rgb( q, p, h + 1 / 3 );
  217. this.g = hue2rgb( q, p, h );
  218. this.b = hue2rgb( q, p, h - 1 / 3 );
  219. }
  220. return this;
  221. },
  222. setStyle: function ( style ) {
  223. // rgb(255,0,0)
  224. if ( /^rgb\((\d+),(\d+),(\d+)\)$/i.test( style ) ) {
  225. var color = /^rgb\((\d+),(\d+),(\d+)\)$/i.exec( style );
  226. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  227. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  228. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  229. return this;
  230. }
  231. // rgb(100%,0%,0%)
  232. if ( /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.test( style ) ) {
  233. var color = /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.exec( style );
  234. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  235. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  236. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  237. return this;
  238. }
  239. // #ff0000
  240. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  241. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  242. this.setHex( parseInt( color[ 1 ], 16 ) );
  243. return this;
  244. }
  245. // #f00
  246. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  247. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  248. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  249. return this;
  250. }
  251. // red
  252. if ( /^(\w+)$/i.test( style ) ) {
  253. this.setHex( THREE.ColorKeywords[ style ] );
  254. return this;
  255. }
  256. },
  257. copy: function ( color ) {
  258. this.r = color.r;
  259. this.g = color.g;
  260. this.b = color.b;
  261. return this;
  262. },
  263. copyGammaToLinear: function ( color ) {
  264. this.r = color.r * color.r;
  265. this.g = color.g * color.g;
  266. this.b = color.b * color.b;
  267. return this;
  268. },
  269. copyLinearToGamma: function ( color ) {
  270. this.r = Math.sqrt( color.r );
  271. this.g = Math.sqrt( color.g );
  272. this.b = Math.sqrt( color.b );
  273. return this;
  274. },
  275. convertGammaToLinear: function () {
  276. var r = this.r, g = this.g, b = this.b;
  277. this.r = r * r;
  278. this.g = g * g;
  279. this.b = b * b;
  280. return this;
  281. },
  282. convertLinearToGamma: function () {
  283. this.r = Math.sqrt( this.r );
  284. this.g = Math.sqrt( this.g );
  285. this.b = Math.sqrt( this.b );
  286. return this;
  287. },
  288. getHex: function () {
  289. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  290. },
  291. getHexString: function () {
  292. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  293. },
  294. getHSL: function () {
  295. var hsl = { h: 0, s: 0, l: 0 };
  296. return function () {
  297. // h,s,l ranges are in 0.0 - 1.0
  298. var r = this.r, g = this.g, b = this.b;
  299. var max = Math.max( r, g, b );
  300. var min = Math.min( r, g, b );
  301. var hue, saturation;
  302. var lightness = ( min + max ) / 2.0;
  303. if ( min === max ) {
  304. hue = 0;
  305. saturation = 0;
  306. } else {
  307. var delta = max - min;
  308. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  309. switch ( max ) {
  310. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  311. case g: hue = ( b - r ) / delta + 2; break;
  312. case b: hue = ( r - g ) / delta + 4; break;
  313. }
  314. hue /= 6;
  315. }
  316. hsl.h = hue;
  317. hsl.s = saturation;
  318. hsl.l = lightness;
  319. return hsl;
  320. };
  321. }(),
  322. getStyle: function () {
  323. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  324. },
  325. offsetHSL: function ( h, s, l ) {
  326. var hsl = this.getHSL();
  327. hsl.h += h; hsl.s += s; hsl.l += l;
  328. this.setHSL( hsl.h, hsl.s, hsl.l );
  329. return this;
  330. },
  331. add: function ( color ) {
  332. this.r += color.r;
  333. this.g += color.g;
  334. this.b += color.b;
  335. return this;
  336. },
  337. addColors: function ( color1, color2 ) {
  338. this.r = color1.r + color2.r;
  339. this.g = color1.g + color2.g;
  340. this.b = color1.b + color2.b;
  341. return this;
  342. },
  343. addScalar: function ( s ) {
  344. this.r += s;
  345. this.g += s;
  346. this.b += s;
  347. return this;
  348. },
  349. multiply: function ( color ) {
  350. this.r *= color.r;
  351. this.g *= color.g;
  352. this.b *= color.b;
  353. return this;
  354. },
  355. multiplyScalar: function ( s ) {
  356. this.r *= s;
  357. this.g *= s;
  358. this.b *= s;
  359. return this;
  360. },
  361. lerp: function ( color, alpha ) {
  362. this.r += ( color.r - this.r ) * alpha;
  363. this.g += ( color.g - this.g ) * alpha;
  364. this.b += ( color.b - this.b ) * alpha;
  365. return this;
  366. },
  367. equals: function ( c ) {
  368. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  369. },
  370. clone: function () {
  371. return new THREE.Color().setRGB( this.r, this.g, this.b );
  372. }
  373. };
  374. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  375. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  376. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  377. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  378. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  379. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  380. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  381. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  382. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  383. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  384. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  385. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  386. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  387. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  388. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  389. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  390. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  391. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  392. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  393. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  394. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  395. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  396. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  397. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  398. /**
  399. * @author mikael emtinger / http://gomo.se/
  400. * @author alteredq / http://alteredqualia.com/
  401. * @author WestLangley / http://github.com/WestLangley
  402. * @author bhouston / http://exocortex.com
  403. */
  404. THREE.Quaternion = function ( x, y, z, w ) {
  405. this._x = x || 0;
  406. this._y = y || 0;
  407. this._z = z || 0;
  408. this._w = ( w !== undefined ) ? w : 1;
  409. };
  410. THREE.Quaternion.prototype = {
  411. constructor: THREE.Quaternion,
  412. _x: 0,_y: 0, _z: 0, _w: 0,
  413. _euler: undefined,
  414. _updateEuler: function ( callback ) {
  415. if ( this._euler !== undefined ) {
  416. this._euler.setFromQuaternion( this, undefined, false );
  417. }
  418. },
  419. get x () {
  420. return this._x;
  421. },
  422. set x ( value ) {
  423. this._x = value;
  424. this._updateEuler();
  425. },
  426. get y () {
  427. return this._y;
  428. },
  429. set y ( value ) {
  430. this._y = value;
  431. this._updateEuler();
  432. },
  433. get z () {
  434. return this._z;
  435. },
  436. set z ( value ) {
  437. this._z = value;
  438. this._updateEuler();
  439. },
  440. get w () {
  441. return this._w;
  442. },
  443. set w ( value ) {
  444. this._w = value;
  445. this._updateEuler();
  446. },
  447. set: function ( x, y, z, w ) {
  448. this._x = x;
  449. this._y = y;
  450. this._z = z;
  451. this._w = w;
  452. this._updateEuler();
  453. return this;
  454. },
  455. copy: function ( quaternion ) {
  456. this._x = quaternion._x;
  457. this._y = quaternion._y;
  458. this._z = quaternion._z;
  459. this._w = quaternion._w;
  460. this._updateEuler();
  461. return this;
  462. },
  463. setFromEuler: function ( euler, update ) {
  464. if ( typeof euler['order'] === undefined ) {
  465. console.error( 'ERROR: Quaternion\'s .setFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  466. }
  467. // http://www.mathworks.com/matlabcentral/fileexchange/
  468. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  469. // content/SpinCalc.m
  470. var c1 = Math.cos( euler._x / 2 );
  471. var c2 = Math.cos( euler._y / 2 );
  472. var c3 = Math.cos( euler._z / 2 );
  473. var s1 = Math.sin( euler._x / 2 );
  474. var s2 = Math.sin( euler._y / 2 );
  475. var s3 = Math.sin( euler._z / 2 );
  476. if ( euler.order === undefined || euler.order === 'XYZ' ) {
  477. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  478. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  479. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  480. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  481. } else if ( euler.order === 'YXZ' ) {
  482. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  483. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  484. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  485. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  486. } else if ( euler.order === 'ZXY' ) {
  487. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  488. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  489. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  490. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  491. } else if ( euler.order === 'ZYX' ) {
  492. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  493. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  494. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  495. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  496. } else if ( euler.order === 'YZX' ) {
  497. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  498. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  499. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  500. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  501. } else if ( euler.order === 'XZY' ) {
  502. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  503. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  504. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  505. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  506. }
  507. if ( update !== false ) this._updateEuler();
  508. return this;
  509. },
  510. setFromAxisAngle: function ( axis, angle ) {
  511. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  512. // axis have to be normalized
  513. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  514. this._x = axis.x * s;
  515. this._y = axis.y * s;
  516. this._z = axis.z * s;
  517. this._w = Math.cos( halfAngle );
  518. this._updateEuler();
  519. return this;
  520. },
  521. setFromRotationMatrix: function ( m ) {
  522. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  523. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  524. var te = m.elements,
  525. m11 = te[0], m12 = te[4], m13 = te[8],
  526. m21 = te[1], m22 = te[5], m23 = te[9],
  527. m31 = te[2], m32 = te[6], m33 = te[10],
  528. trace = m11 + m22 + m33,
  529. s;
  530. if ( trace > 0 ) {
  531. s = 0.5 / Math.sqrt( trace + 1.0 );
  532. this._w = 0.25 / s;
  533. this._x = ( m32 - m23 ) * s;
  534. this._y = ( m13 - m31 ) * s;
  535. this._z = ( m21 - m12 ) * s;
  536. } else if ( m11 > m22 && m11 > m33 ) {
  537. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  538. this._w = (m32 - m23 ) / s;
  539. this._x = 0.25 * s;
  540. this._y = (m12 + m21 ) / s;
  541. this._z = (m13 + m31 ) / s;
  542. } else if ( m22 > m33 ) {
  543. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  544. this._w = (m13 - m31 ) / s;
  545. this._x = (m12 + m21 ) / s;
  546. this._y = 0.25 * s;
  547. this._z = (m23 + m32 ) / s;
  548. } else {
  549. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  550. this._w = ( m21 - m12 ) / s;
  551. this._x = ( m13 + m31 ) / s;
  552. this._y = ( m23 + m32 ) / s;
  553. this._z = 0.25 * s;
  554. }
  555. this._updateEuler();
  556. return this;
  557. },
  558. inverse: function () {
  559. this.conjugate().normalize();
  560. return this;
  561. },
  562. conjugate: function () {
  563. this._x *= -1;
  564. this._y *= -1;
  565. this._z *= -1;
  566. this._updateEuler();
  567. return this;
  568. },
  569. lengthSq: function () {
  570. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  571. },
  572. length: function () {
  573. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  574. },
  575. normalize: function () {
  576. var l = this.length();
  577. if ( l === 0 ) {
  578. this._x = 0;
  579. this._y = 0;
  580. this._z = 0;
  581. this._w = 1;
  582. } else {
  583. l = 1 / l;
  584. this._x = this._x * l;
  585. this._y = this._y * l;
  586. this._z = this._z * l;
  587. this._w = this._w * l;
  588. }
  589. return this;
  590. },
  591. multiply: function ( q, p ) {
  592. if ( p !== undefined ) {
  593. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  594. return this.multiplyQuaternions( q, p );
  595. }
  596. return this.multiplyQuaternions( this, q );
  597. },
  598. multiplyQuaternions: function ( a, b ) {
  599. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  600. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  601. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  602. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  603. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  604. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  605. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  606. this._updateEuler();
  607. return this;
  608. },
  609. multiplyVector3: function ( vector ) {
  610. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  611. return vector.applyQuaternion( this );
  612. },
  613. slerp: function ( qb, t ) {
  614. var x = this._x, y = this._y, z = this._z, w = this._w;
  615. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  616. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  617. if ( cosHalfTheta < 0 ) {
  618. this._w = -qb._w;
  619. this._x = -qb._x;
  620. this._y = -qb._y;
  621. this._z = -qb._z;
  622. cosHalfTheta = -cosHalfTheta;
  623. } else {
  624. this.copy( qb );
  625. }
  626. if ( cosHalfTheta >= 1.0 ) {
  627. this._w = w;
  628. this._x = x;
  629. this._y = y;
  630. this._z = z;
  631. return this;
  632. }
  633. var halfTheta = Math.acos( cosHalfTheta );
  634. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  635. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  636. this._w = 0.5 * ( w + this._w );
  637. this._x = 0.5 * ( x + this._x );
  638. this._y = 0.5 * ( y + this._y );
  639. this._z = 0.5 * ( z + this._z );
  640. return this;
  641. }
  642. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  643. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  644. this._w = ( w * ratioA + this._w * ratioB );
  645. this._x = ( x * ratioA + this._x * ratioB );
  646. this._y = ( y * ratioA + this._y * ratioB );
  647. this._z = ( z * ratioA + this._z * ratioB );
  648. this._updateEuler();
  649. return this;
  650. },
  651. equals: function ( quaternion ) {
  652. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  653. },
  654. fromArray: function ( array ) {
  655. this._x = array[ 0 ];
  656. this._y = array[ 1 ];
  657. this._z = array[ 2 ];
  658. this._w = array[ 3 ];
  659. this._updateEuler();
  660. return this;
  661. },
  662. toArray: function () {
  663. return [ this._x, this._y, this._z, this._w ];
  664. },
  665. clone: function () {
  666. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  667. }
  668. };
  669. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  670. return qm.copy( qa ).slerp( qb, t );
  671. }
  672. /**
  673. * @author mrdoob / http://mrdoob.com/
  674. * @author philogb / http://blog.thejit.org/
  675. * @author egraether / http://egraether.com/
  676. * @author zz85 / http://www.lab4games.net/zz85/blog
  677. */
  678. THREE.Vector2 = function ( x, y ) {
  679. this.x = x || 0;
  680. this.y = y || 0;
  681. };
  682. THREE.Vector2.prototype = {
  683. constructor: THREE.Vector2,
  684. set: function ( x, y ) {
  685. this.x = x;
  686. this.y = y;
  687. return this;
  688. },
  689. setX: function ( x ) {
  690. this.x = x;
  691. return this;
  692. },
  693. setY: function ( y ) {
  694. this.y = y;
  695. return this;
  696. },
  697. setComponent: function ( index, value ) {
  698. switch ( index ) {
  699. case 0: this.x = value; break;
  700. case 1: this.y = value; break;
  701. default: throw new Error( "index is out of range: " + index );
  702. }
  703. },
  704. getComponent: function ( index ) {
  705. switch ( index ) {
  706. case 0: return this.x;
  707. case 1: return this.y;
  708. default: throw new Error( "index is out of range: " + index );
  709. }
  710. },
  711. copy: function ( v ) {
  712. this.x = v.x;
  713. this.y = v.y;
  714. return this;
  715. },
  716. add: function ( v, w ) {
  717. if ( w !== undefined ) {
  718. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  719. return this.addVectors( v, w );
  720. }
  721. this.x += v.x;
  722. this.y += v.y;
  723. return this;
  724. },
  725. addVectors: function ( a, b ) {
  726. this.x = a.x + b.x;
  727. this.y = a.y + b.y;
  728. return this;
  729. },
  730. addScalar: function ( s ) {
  731. this.x += s;
  732. this.y += s;
  733. return this;
  734. },
  735. sub: function ( v, w ) {
  736. if ( w !== undefined ) {
  737. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  738. return this.subVectors( v, w );
  739. }
  740. this.x -= v.x;
  741. this.y -= v.y;
  742. return this;
  743. },
  744. subVectors: function ( a, b ) {
  745. this.x = a.x - b.x;
  746. this.y = a.y - b.y;
  747. return this;
  748. },
  749. multiplyScalar: function ( s ) {
  750. this.x *= s;
  751. this.y *= s;
  752. return this;
  753. },
  754. divideScalar: function ( scalar ) {
  755. if ( scalar !== 0 ) {
  756. var invScalar = 1 / scalar;
  757. this.x *= invScalar;
  758. this.y *= invScalar;
  759. } else {
  760. this.x = 0;
  761. this.y = 0;
  762. }
  763. return this;
  764. },
  765. min: function ( v ) {
  766. if ( this.x > v.x ) {
  767. this.x = v.x;
  768. }
  769. if ( this.y > v.y ) {
  770. this.y = v.y;
  771. }
  772. return this;
  773. },
  774. max: function ( v ) {
  775. if ( this.x < v.x ) {
  776. this.x = v.x;
  777. }
  778. if ( this.y < v.y ) {
  779. this.y = v.y;
  780. }
  781. return this;
  782. },
  783. clamp: function ( min, max ) {
  784. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  785. if ( this.x < min.x ) {
  786. this.x = min.x;
  787. } else if ( this.x > max.x ) {
  788. this.x = max.x;
  789. }
  790. if ( this.y < min.y ) {
  791. this.y = min.y;
  792. } else if ( this.y > max.y ) {
  793. this.y = max.y;
  794. }
  795. return this;
  796. },
  797. negate: function() {
  798. return this.multiplyScalar( - 1 );
  799. },
  800. dot: function ( v ) {
  801. return this.x * v.x + this.y * v.y;
  802. },
  803. lengthSq: function () {
  804. return this.x * this.x + this.y * this.y;
  805. },
  806. length: function () {
  807. return Math.sqrt( this.x * this.x + this.y * this.y );
  808. },
  809. normalize: function () {
  810. return this.divideScalar( this.length() );
  811. },
  812. distanceTo: function ( v ) {
  813. return Math.sqrt( this.distanceToSquared( v ) );
  814. },
  815. distanceToSquared: function ( v ) {
  816. var dx = this.x - v.x, dy = this.y - v.y;
  817. return dx * dx + dy * dy;
  818. },
  819. setLength: function ( l ) {
  820. var oldLength = this.length();
  821. if ( oldLength !== 0 && l !== oldLength ) {
  822. this.multiplyScalar( l / oldLength );
  823. }
  824. return this;
  825. },
  826. lerp: function ( v, alpha ) {
  827. this.x += ( v.x - this.x ) * alpha;
  828. this.y += ( v.y - this.y ) * alpha;
  829. return this;
  830. },
  831. equals: function( v ) {
  832. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  833. },
  834. fromArray: function ( array ) {
  835. this.x = array[ 0 ];
  836. this.y = array[ 1 ];
  837. return this;
  838. },
  839. toArray: function () {
  840. return [ this.x, this.y ];
  841. },
  842. clone: function () {
  843. return new THREE.Vector2( this.x, this.y );
  844. }
  845. };
  846. /**
  847. * @author mrdoob / http://mrdoob.com/
  848. * @author *kile / http://kile.stravaganza.org/
  849. * @author philogb / http://blog.thejit.org/
  850. * @author mikael emtinger / http://gomo.se/
  851. * @author egraether / http://egraether.com/
  852. * @author WestLangley / http://github.com/WestLangley
  853. */
  854. THREE.Vector3 = function ( x, y, z ) {
  855. this.x = x || 0;
  856. this.y = y || 0;
  857. this.z = z || 0;
  858. };
  859. THREE.Vector3.prototype = {
  860. constructor: THREE.Vector3,
  861. set: function ( x, y, z ) {
  862. this.x = x;
  863. this.y = y;
  864. this.z = z;
  865. return this;
  866. },
  867. setX: function ( x ) {
  868. this.x = x;
  869. return this;
  870. },
  871. setY: function ( y ) {
  872. this.y = y;
  873. return this;
  874. },
  875. setZ: function ( z ) {
  876. this.z = z;
  877. return this;
  878. },
  879. setComponent: function ( index, value ) {
  880. switch ( index ) {
  881. case 0: this.x = value; break;
  882. case 1: this.y = value; break;
  883. case 2: this.z = value; break;
  884. default: throw new Error( "index is out of range: " + index );
  885. }
  886. },
  887. getComponent: function ( index ) {
  888. switch ( index ) {
  889. case 0: return this.x;
  890. case 1: return this.y;
  891. case 2: return this.z;
  892. default: throw new Error( "index is out of range: " + index );
  893. }
  894. },
  895. copy: function ( v ) {
  896. this.x = v.x;
  897. this.y = v.y;
  898. this.z = v.z;
  899. return this;
  900. },
  901. add: function ( v, w ) {
  902. if ( w !== undefined ) {
  903. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  904. return this.addVectors( v, w );
  905. }
  906. this.x += v.x;
  907. this.y += v.y;
  908. this.z += v.z;
  909. return this;
  910. },
  911. addScalar: function ( s ) {
  912. this.x += s;
  913. this.y += s;
  914. this.z += s;
  915. return this;
  916. },
  917. addVectors: function ( a, b ) {
  918. this.x = a.x + b.x;
  919. this.y = a.y + b.y;
  920. this.z = a.z + b.z;
  921. return this;
  922. },
  923. sub: function ( v, w ) {
  924. if ( w !== undefined ) {
  925. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  926. return this.subVectors( v, w );
  927. }
  928. this.x -= v.x;
  929. this.y -= v.y;
  930. this.z -= v.z;
  931. return this;
  932. },
  933. subVectors: function ( a, b ) {
  934. this.x = a.x - b.x;
  935. this.y = a.y - b.y;
  936. this.z = a.z - b.z;
  937. return this;
  938. },
  939. multiply: function ( v, w ) {
  940. if ( w !== undefined ) {
  941. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  942. return this.multiplyVectors( v, w );
  943. }
  944. this.x *= v.x;
  945. this.y *= v.y;
  946. this.z *= v.z;
  947. return this;
  948. },
  949. multiplyScalar: function ( scalar ) {
  950. this.x *= scalar;
  951. this.y *= scalar;
  952. this.z *= scalar;
  953. return this;
  954. },
  955. multiplyVectors: function ( a, b ) {
  956. this.x = a.x * b.x;
  957. this.y = a.y * b.y;
  958. this.z = a.z * b.z;
  959. return this;
  960. },
  961. applyMatrix3: function ( m ) {
  962. var x = this.x;
  963. var y = this.y;
  964. var z = this.z;
  965. var e = m.elements;
  966. this.x = e[0] * x + e[3] * y + e[6] * z;
  967. this.y = e[1] * x + e[4] * y + e[7] * z;
  968. this.z = e[2] * x + e[5] * y + e[8] * z;
  969. return this;
  970. },
  971. applyMatrix4: function ( m ) {
  972. // input: THREE.Matrix4 affine matrix
  973. var x = this.x, y = this.y, z = this.z;
  974. var e = m.elements;
  975. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  976. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  977. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  978. return this;
  979. },
  980. applyProjection: function ( m ) {
  981. // input: THREE.Matrix4 projection matrix
  982. var x = this.x, y = this.y, z = this.z;
  983. var e = m.elements;
  984. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  985. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  986. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  987. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  988. return this;
  989. },
  990. applyQuaternion: function ( q ) {
  991. var x = this.x;
  992. var y = this.y;
  993. var z = this.z;
  994. var qx = q.x;
  995. var qy = q.y;
  996. var qz = q.z;
  997. var qw = q.w;
  998. // calculate quat * vector
  999. var ix = qw * x + qy * z - qz * y;
  1000. var iy = qw * y + qz * x - qx * z;
  1001. var iz = qw * z + qx * y - qy * x;
  1002. var iw = -qx * x - qy * y - qz * z;
  1003. // calculate result * inverse quat
  1004. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  1005. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  1006. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  1007. return this;
  1008. },
  1009. transformDirection: function ( m ) {
  1010. // input: THREE.Matrix4 affine matrix
  1011. // vector interpreted as a direction
  1012. var x = this.x, y = this.y, z = this.z;
  1013. var e = m.elements;
  1014. this.x = e[0] * x + e[4] * y + e[8] * z;
  1015. this.y = e[1] * x + e[5] * y + e[9] * z;
  1016. this.z = e[2] * x + e[6] * y + e[10] * z;
  1017. this.normalize();
  1018. return this;
  1019. },
  1020. divide: function ( v ) {
  1021. this.x /= v.x;
  1022. this.y /= v.y;
  1023. this.z /= v.z;
  1024. return this;
  1025. },
  1026. divideScalar: function ( scalar ) {
  1027. if ( scalar !== 0 ) {
  1028. var invScalar = 1 / scalar;
  1029. this.x *= invScalar;
  1030. this.y *= invScalar;
  1031. this.z *= invScalar;
  1032. } else {
  1033. this.x = 0;
  1034. this.y = 0;
  1035. this.z = 0;
  1036. }
  1037. return this;
  1038. },
  1039. min: function ( v ) {
  1040. if ( this.x > v.x ) {
  1041. this.x = v.x;
  1042. }
  1043. if ( this.y > v.y ) {
  1044. this.y = v.y;
  1045. }
  1046. if ( this.z > v.z ) {
  1047. this.z = v.z;
  1048. }
  1049. return this;
  1050. },
  1051. max: function ( v ) {
  1052. if ( this.x < v.x ) {
  1053. this.x = v.x;
  1054. }
  1055. if ( this.y < v.y ) {
  1056. this.y = v.y;
  1057. }
  1058. if ( this.z < v.z ) {
  1059. this.z = v.z;
  1060. }
  1061. return this;
  1062. },
  1063. clamp: function ( min, max ) {
  1064. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1065. if ( this.x < min.x ) {
  1066. this.x = min.x;
  1067. } else if ( this.x > max.x ) {
  1068. this.x = max.x;
  1069. }
  1070. if ( this.y < min.y ) {
  1071. this.y = min.y;
  1072. } else if ( this.y > max.y ) {
  1073. this.y = max.y;
  1074. }
  1075. if ( this.z < min.z ) {
  1076. this.z = min.z;
  1077. } else if ( this.z > max.z ) {
  1078. this.z = max.z;
  1079. }
  1080. return this;
  1081. },
  1082. negate: function () {
  1083. return this.multiplyScalar( - 1 );
  1084. },
  1085. dot: function ( v ) {
  1086. return this.x * v.x + this.y * v.y + this.z * v.z;
  1087. },
  1088. lengthSq: function () {
  1089. return this.x * this.x + this.y * this.y + this.z * this.z;
  1090. },
  1091. length: function () {
  1092. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1093. },
  1094. lengthManhattan: function () {
  1095. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1096. },
  1097. normalize: function () {
  1098. return this.divideScalar( this.length() );
  1099. },
  1100. setLength: function ( l ) {
  1101. var oldLength = this.length();
  1102. if ( oldLength !== 0 && l !== oldLength ) {
  1103. this.multiplyScalar( l / oldLength );
  1104. }
  1105. return this;
  1106. },
  1107. lerp: function ( v, alpha ) {
  1108. this.x += ( v.x - this.x ) * alpha;
  1109. this.y += ( v.y - this.y ) * alpha;
  1110. this.z += ( v.z - this.z ) * alpha;
  1111. return this;
  1112. },
  1113. cross: function ( v, w ) {
  1114. if ( w !== undefined ) {
  1115. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1116. return this.crossVectors( v, w );
  1117. }
  1118. var x = this.x, y = this.y, z = this.z;
  1119. this.x = y * v.z - z * v.y;
  1120. this.y = z * v.x - x * v.z;
  1121. this.z = x * v.y - y * v.x;
  1122. return this;
  1123. },
  1124. crossVectors: function ( a, b ) {
  1125. this.x = a.y * b.z - a.z * b.y;
  1126. this.y = a.z * b.x - a.x * b.z;
  1127. this.z = a.x * b.y - a.y * b.x;
  1128. return this;
  1129. },
  1130. angleTo: function ( v ) {
  1131. var theta = this.dot( v ) / ( this.length() * v.length() );
  1132. // clamp, to handle numerical problems
  1133. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1134. },
  1135. distanceTo: function ( v ) {
  1136. return Math.sqrt( this.distanceToSquared( v ) );
  1137. },
  1138. distanceToSquared: function ( v ) {
  1139. var dx = this.x - v.x;
  1140. var dy = this.y - v.y;
  1141. var dz = this.z - v.z;
  1142. return dx * dx + dy * dy + dz * dz;
  1143. },
  1144. setEulerFromRotationMatrix: function ( m, order ) {
  1145. console.error( "REMOVED: Vector3\'s setEulerFromRotationMatrix has been removed in favor of Euler.setFromRotationMatrix(), please update your code.");
  1146. },
  1147. setEulerFromQuaternion: function ( q, order ) {
  1148. console.error( "REMOVED: Vector3\'s setEulerFromQuaternion: has been removed in favor of Euler.setFromQuaternion(), please update your code.");
  1149. },
  1150. getPositionFromMatrix: function ( m ) {
  1151. this.x = m.elements[12];
  1152. this.y = m.elements[13];
  1153. this.z = m.elements[14];
  1154. return this;
  1155. },
  1156. getScaleFromMatrix: function ( m ) {
  1157. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  1158. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  1159. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  1160. this.x = sx;
  1161. this.y = sy;
  1162. this.z = sz;
  1163. return this;
  1164. },
  1165. getColumnFromMatrix: function ( index, matrix ) {
  1166. var offset = index * 4;
  1167. var me = matrix.elements;
  1168. this.x = me[ offset ];
  1169. this.y = me[ offset + 1 ];
  1170. this.z = me[ offset + 2 ];
  1171. return this;
  1172. },
  1173. equals: function ( v ) {
  1174. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1175. },
  1176. fromArray: function ( array ) {
  1177. this.x = array[ 0 ];
  1178. this.y = array[ 1 ];
  1179. this.z = array[ 2 ];
  1180. return this;
  1181. },
  1182. toArray: function () {
  1183. return [ this.x, this.y, this.z ];
  1184. },
  1185. clone: function () {
  1186. return new THREE.Vector3( this.x, this.y, this.z );
  1187. }
  1188. };
  1189. THREE.extend( THREE.Vector3.prototype, {
  1190. applyEuler: function () {
  1191. var q1 = new THREE.Quaternion();
  1192. return function ( rotation ) {
  1193. if( typeof rotation['order'] === undefined ) {
  1194. console.error( 'ERROR: Vector3\'s .applyEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  1195. }
  1196. var quaternion = q1.setFromEuler( rotation );
  1197. this.applyQuaternion( quaternion );
  1198. return this;
  1199. };
  1200. }(),
  1201. applyAxisAngle: function () {
  1202. var q1 = new THREE.Quaternion();
  1203. return function ( axis, angle ) {
  1204. var quaternion = q1.setFromAxisAngle( axis, angle );
  1205. this.applyQuaternion( quaternion );
  1206. return this;
  1207. };
  1208. }(),
  1209. projectOnVector: function () {
  1210. var v1 = new THREE.Vector3();
  1211. return function ( vector ) {
  1212. v1.copy( vector ).normalize();
  1213. var d = this.dot( v1 );
  1214. return this.copy( v1 ).multiplyScalar( d );
  1215. };
  1216. }(),
  1217. projectOnPlane: function () {
  1218. var v1 = new THREE.Vector3();
  1219. return function ( planeNormal ) {
  1220. v1.copy( this ).projectOnVector( planeNormal );
  1221. return this.sub( v1 );
  1222. }
  1223. }(),
  1224. reflect: function () {
  1225. var v1 = new THREE.Vector3();
  1226. return function ( vector ) {
  1227. v1.copy( this ).projectOnVector( vector ).multiplyScalar( 2 );
  1228. return this.subVectors( v1, this );
  1229. }
  1230. }()
  1231. } );
  1232. /**
  1233. * @author supereggbert / http://www.paulbrunt.co.uk/
  1234. * @author philogb / http://blog.thejit.org/
  1235. * @author mikael emtinger / http://gomo.se/
  1236. * @author egraether / http://egraether.com/
  1237. * @author WestLangley / http://github.com/WestLangley
  1238. */
  1239. THREE.Vector4 = function ( x, y, z, w ) {
  1240. this.x = x || 0;
  1241. this.y = y || 0;
  1242. this.z = z || 0;
  1243. this.w = ( w !== undefined ) ? w : 1;
  1244. };
  1245. THREE.Vector4.prototype = {
  1246. constructor: THREE.Vector4,
  1247. set: function ( x, y, z, w ) {
  1248. this.x = x;
  1249. this.y = y;
  1250. this.z = z;
  1251. this.w = w;
  1252. return this;
  1253. },
  1254. setX: function ( x ) {
  1255. this.x = x;
  1256. return this;
  1257. },
  1258. setY: function ( y ) {
  1259. this.y = y;
  1260. return this;
  1261. },
  1262. setZ: function ( z ) {
  1263. this.z = z;
  1264. return this;
  1265. },
  1266. setW: function ( w ) {
  1267. this.w = w;
  1268. return this;
  1269. },
  1270. setComponent: function ( index, value ) {
  1271. switch ( index ) {
  1272. case 0: this.x = value; break;
  1273. case 1: this.y = value; break;
  1274. case 2: this.z = value; break;
  1275. case 3: this.w = value; break;
  1276. default: throw new Error( "index is out of range: " + index );
  1277. }
  1278. },
  1279. getComponent: function ( index ) {
  1280. switch ( index ) {
  1281. case 0: return this.x;
  1282. case 1: return this.y;
  1283. case 2: return this.z;
  1284. case 3: return this.w;
  1285. default: throw new Error( "index is out of range: " + index );
  1286. }
  1287. },
  1288. copy: function ( v ) {
  1289. this.x = v.x;
  1290. this.y = v.y;
  1291. this.z = v.z;
  1292. this.w = ( v.w !== undefined ) ? v.w : 1;
  1293. return this;
  1294. },
  1295. add: function ( v, w ) {
  1296. if ( w !== undefined ) {
  1297. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1298. return this.addVectors( v, w );
  1299. }
  1300. this.x += v.x;
  1301. this.y += v.y;
  1302. this.z += v.z;
  1303. this.w += v.w;
  1304. return this;
  1305. },
  1306. addScalar: function ( s ) {
  1307. this.x += s;
  1308. this.y += s;
  1309. this.z += s;
  1310. this.w += s;
  1311. return this;
  1312. },
  1313. addVectors: function ( a, b ) {
  1314. this.x = a.x + b.x;
  1315. this.y = a.y + b.y;
  1316. this.z = a.z + b.z;
  1317. this.w = a.w + b.w;
  1318. return this;
  1319. },
  1320. sub: function ( v, w ) {
  1321. if ( w !== undefined ) {
  1322. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1323. return this.subVectors( v, w );
  1324. }
  1325. this.x -= v.x;
  1326. this.y -= v.y;
  1327. this.z -= v.z;
  1328. this.w -= v.w;
  1329. return this;
  1330. },
  1331. subVectors: function ( a, b ) {
  1332. this.x = a.x - b.x;
  1333. this.y = a.y - b.y;
  1334. this.z = a.z - b.z;
  1335. this.w = a.w - b.w;
  1336. return this;
  1337. },
  1338. multiplyScalar: function ( scalar ) {
  1339. this.x *= scalar;
  1340. this.y *= scalar;
  1341. this.z *= scalar;
  1342. this.w *= scalar;
  1343. return this;
  1344. },
  1345. applyMatrix4: function ( m ) {
  1346. var x = this.x;
  1347. var y = this.y;
  1348. var z = this.z;
  1349. var w = this.w;
  1350. var e = m.elements;
  1351. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1352. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1353. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1354. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1355. return this;
  1356. },
  1357. divideScalar: function ( scalar ) {
  1358. if ( scalar !== 0 ) {
  1359. var invScalar = 1 / scalar;
  1360. this.x *= invScalar;
  1361. this.y *= invScalar;
  1362. this.z *= invScalar;
  1363. this.w *= invScalar;
  1364. } else {
  1365. this.x = 0;
  1366. this.y = 0;
  1367. this.z = 0;
  1368. this.w = 1;
  1369. }
  1370. return this;
  1371. },
  1372. setAxisAngleFromQuaternion: function ( q ) {
  1373. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1374. // q is assumed to be normalized
  1375. this.w = 2 * Math.acos( q.w );
  1376. var s = Math.sqrt( 1 - q.w * q.w );
  1377. if ( s < 0.0001 ) {
  1378. this.x = 1;
  1379. this.y = 0;
  1380. this.z = 0;
  1381. } else {
  1382. this.x = q.x / s;
  1383. this.y = q.y / s;
  1384. this.z = q.z / s;
  1385. }
  1386. return this;
  1387. },
  1388. setAxisAngleFromRotationMatrix: function ( m ) {
  1389. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1390. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1391. var angle, x, y, z, // variables for result
  1392. epsilon = 0.01, // margin to allow for rounding errors
  1393. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1394. te = m.elements,
  1395. m11 = te[0], m12 = te[4], m13 = te[8],
  1396. m21 = te[1], m22 = te[5], m23 = te[9],
  1397. m31 = te[2], m32 = te[6], m33 = te[10];
  1398. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1399. && ( Math.abs( m13 - m31 ) < epsilon )
  1400. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1401. // singularity found
  1402. // first check for identity matrix which must have +1 for all terms
  1403. // in leading diagonal and zero in other terms
  1404. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1405. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1406. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1407. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1408. // this singularity is identity matrix so angle = 0
  1409. this.set( 1, 0, 0, 0 );
  1410. return this; // zero angle, arbitrary axis
  1411. }
  1412. // otherwise this singularity is angle = 180
  1413. angle = Math.PI;
  1414. var xx = ( m11 + 1 ) / 2;
  1415. var yy = ( m22 + 1 ) / 2;
  1416. var zz = ( m33 + 1 ) / 2;
  1417. var xy = ( m12 + m21 ) / 4;
  1418. var xz = ( m13 + m31 ) / 4;
  1419. var yz = ( m23 + m32 ) / 4;
  1420. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1421. if ( xx < epsilon ) {
  1422. x = 0;
  1423. y = 0.707106781;
  1424. z = 0.707106781;
  1425. } else {
  1426. x = Math.sqrt( xx );
  1427. y = xy / x;
  1428. z = xz / x;
  1429. }
  1430. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1431. if ( yy < epsilon ) {
  1432. x = 0.707106781;
  1433. y = 0;
  1434. z = 0.707106781;
  1435. } else {
  1436. y = Math.sqrt( yy );
  1437. x = xy / y;
  1438. z = yz / y;
  1439. }
  1440. } else { // m33 is the largest diagonal term so base result on this
  1441. if ( zz < epsilon ) {
  1442. x = 0.707106781;
  1443. y = 0.707106781;
  1444. z = 0;
  1445. } else {
  1446. z = Math.sqrt( zz );
  1447. x = xz / z;
  1448. y = yz / z;
  1449. }
  1450. }
  1451. this.set( x, y, z, angle );
  1452. return this; // return 180 deg rotation
  1453. }
  1454. // as we have reached here there are no singularities so we can handle normally
  1455. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1456. + ( m13 - m31 ) * ( m13 - m31 )
  1457. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1458. if ( Math.abs( s ) < 0.001 ) s = 1;
  1459. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1460. // caught by singularity test above, but I've left it in just in case
  1461. this.x = ( m32 - m23 ) / s;
  1462. this.y = ( m13 - m31 ) / s;
  1463. this.z = ( m21 - m12 ) / s;
  1464. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1465. return this;
  1466. },
  1467. min: function ( v ) {
  1468. if ( this.x > v.x ) {
  1469. this.x = v.x;
  1470. }
  1471. if ( this.y > v.y ) {
  1472. this.y = v.y;
  1473. }
  1474. if ( this.z > v.z ) {
  1475. this.z = v.z;
  1476. }
  1477. if ( this.w > v.w ) {
  1478. this.w = v.w;
  1479. }
  1480. return this;
  1481. },
  1482. max: function ( v ) {
  1483. if ( this.x < v.x ) {
  1484. this.x = v.x;
  1485. }
  1486. if ( this.y < v.y ) {
  1487. this.y = v.y;
  1488. }
  1489. if ( this.z < v.z ) {
  1490. this.z = v.z;
  1491. }
  1492. if ( this.w < v.w ) {
  1493. this.w = v.w;
  1494. }
  1495. return this;
  1496. },
  1497. clamp: function ( min, max ) {
  1498. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1499. if ( this.x < min.x ) {
  1500. this.x = min.x;
  1501. } else if ( this.x > max.x ) {
  1502. this.x = max.x;
  1503. }
  1504. if ( this.y < min.y ) {
  1505. this.y = min.y;
  1506. } else if ( this.y > max.y ) {
  1507. this.y = max.y;
  1508. }
  1509. if ( this.z < min.z ) {
  1510. this.z = min.z;
  1511. } else if ( this.z > max.z ) {
  1512. this.z = max.z;
  1513. }
  1514. if ( this.w < min.w ) {
  1515. this.w = min.w;
  1516. } else if ( this.w > max.w ) {
  1517. this.w = max.w;
  1518. }
  1519. return this;
  1520. },
  1521. negate: function() {
  1522. return this.multiplyScalar( -1 );
  1523. },
  1524. dot: function ( v ) {
  1525. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1526. },
  1527. lengthSq: function () {
  1528. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1529. },
  1530. length: function () {
  1531. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1532. },
  1533. lengthManhattan: function () {
  1534. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1535. },
  1536. normalize: function () {
  1537. return this.divideScalar( this.length() );
  1538. },
  1539. setLength: function ( l ) {
  1540. var oldLength = this.length();
  1541. if ( oldLength !== 0 && l !== oldLength ) {
  1542. this.multiplyScalar( l / oldLength );
  1543. }
  1544. return this;
  1545. },
  1546. lerp: function ( v, alpha ) {
  1547. this.x += ( v.x - this.x ) * alpha;
  1548. this.y += ( v.y - this.y ) * alpha;
  1549. this.z += ( v.z - this.z ) * alpha;
  1550. this.w += ( v.w - this.w ) * alpha;
  1551. return this;
  1552. },
  1553. equals: function ( v ) {
  1554. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1555. },
  1556. fromArray: function ( array ) {
  1557. this.x = array[ 0 ];
  1558. this.y = array[ 1 ];
  1559. this.z = array[ 2 ];
  1560. this.w = array[ 3 ];
  1561. return this;
  1562. },
  1563. toArray: function () {
  1564. return [ this.x, this.y, this.z, this.w ];
  1565. },
  1566. clone: function () {
  1567. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1568. }
  1569. };
  1570. /**
  1571. * @author mrdoob / http://mrdoob.com/
  1572. * @author WestLangley / http://github.com/WestLangley
  1573. * @author bhouston / http://exocortex.com
  1574. */
  1575. THREE.Euler = function ( x, y, z, order ) {
  1576. this._x = x || 0;
  1577. this._y = y || 0;
  1578. this._z = z || 0;
  1579. this._order = order || THREE.Euler.DefaultOrder;
  1580. };
  1581. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1582. THREE.Euler.DefaultOrder = 'XYZ';
  1583. THREE.Euler.prototype = {
  1584. constructor: THREE.Euler,
  1585. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1586. _quaternion: undefined,
  1587. _updateQuaternion: function () {
  1588. if ( this._quaternion !== undefined ) {
  1589. this._quaternion.setFromEuler( this, false );
  1590. }
  1591. },
  1592. get x () {
  1593. return this._x;
  1594. },
  1595. set x ( value ) {
  1596. this._x = value;
  1597. this._updateQuaternion();
  1598. },
  1599. get y () {
  1600. return this._y;
  1601. },
  1602. set y ( value ) {
  1603. this._y = value;
  1604. this._updateQuaternion();
  1605. },
  1606. get z () {
  1607. return this._z;
  1608. },
  1609. set z ( value ) {
  1610. this._z = value;
  1611. this._updateQuaternion();
  1612. },
  1613. get order () {
  1614. return this._order;
  1615. },
  1616. set order ( value ) {
  1617. this._order = value;
  1618. this._updateQuaternion();
  1619. },
  1620. set: function ( x, y, z, order ) {
  1621. this._x = x;
  1622. this._y = y;
  1623. this._z = z;
  1624. this._order = order || this._order;
  1625. this._updateQuaternion();
  1626. return this;
  1627. },
  1628. copy: function ( euler ) {
  1629. this._x = euler._x;
  1630. this._y = euler._y;
  1631. this._z = euler._z;
  1632. this._order = euler._order;
  1633. this._updateQuaternion();
  1634. return this;
  1635. },
  1636. setFromRotationMatrix: function ( m, order ) {
  1637. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1638. // clamp, to handle numerical problems
  1639. function clamp( x ) {
  1640. return Math.min( Math.max( x, -1 ), 1 );
  1641. }
  1642. var te = m.elements;
  1643. var m11 = te[0], m12 = te[4], m13 = te[8];
  1644. var m21 = te[1], m22 = te[5], m23 = te[9];
  1645. var m31 = te[2], m32 = te[6], m33 = te[10];
  1646. order = order || this._order;
  1647. if ( order === 'XYZ' ) {
  1648. this._y = Math.asin( clamp( m13 ) );
  1649. if ( Math.abs( m13 ) < 0.99999 ) {
  1650. this._x = Math.atan2( - m23, m33 );
  1651. this._z = Math.atan2( - m12, m11 );
  1652. } else {
  1653. this._x = Math.atan2( m32, m22 );
  1654. this._z = 0;
  1655. }
  1656. } else if ( order === 'YXZ' ) {
  1657. this._x = Math.asin( - clamp( m23 ) );
  1658. if ( Math.abs( m23 ) < 0.99999 ) {
  1659. this._y = Math.atan2( m13, m33 );
  1660. this._z = Math.atan2( m21, m22 );
  1661. } else {
  1662. this._y = Math.atan2( - m31, m11 );
  1663. this._z = 0;
  1664. }
  1665. } else if ( order === 'ZXY' ) {
  1666. this._x = Math.asin( clamp( m32 ) );
  1667. if ( Math.abs( m32 ) < 0.99999 ) {
  1668. this._y = Math.atan2( - m31, m33 );
  1669. this._z = Math.atan2( - m12, m22 );
  1670. } else {
  1671. this._y = 0;
  1672. this._z = Math.atan2( m21, m11 );
  1673. }
  1674. } else if ( order === 'ZYX' ) {
  1675. this._y = Math.asin( - clamp( m31 ) );
  1676. if ( Math.abs( m31 ) < 0.99999 ) {
  1677. this._x = Math.atan2( m32, m33 );
  1678. this._z = Math.atan2( m21, m11 );
  1679. } else {
  1680. this._x = 0;
  1681. this._z = Math.atan2( - m12, m22 );
  1682. }
  1683. } else if ( order === 'YZX' ) {
  1684. this._z = Math.asin( clamp( m21 ) );
  1685. if ( Math.abs( m21 ) < 0.99999 ) {
  1686. this._x = Math.atan2( - m23, m22 );
  1687. this._y = Math.atan2( - m31, m11 );
  1688. } else {
  1689. this._x = 0;
  1690. this._y = Math.atan2( m13, m33 );
  1691. }
  1692. } else if ( order === 'XZY' ) {
  1693. this._z = Math.asin( - clamp( m12 ) );
  1694. if ( Math.abs( m12 ) < 0.99999 ) {
  1695. this._x = Math.atan2( m32, m22 );
  1696. this._y = Math.atan2( m13, m11 );
  1697. } else {
  1698. this._x = Math.atan2( - m23, m33 );
  1699. this._y = 0;
  1700. }
  1701. } else {
  1702. console.warn( 'WARNING: Euler.setFromRotationMatrix() given unsupported order: ' + order )
  1703. }
  1704. this._order = order;
  1705. this._updateQuaternion();
  1706. return this;
  1707. },
  1708. setFromQuaternion: function ( q, order, update ) {
  1709. // q is assumed to be normalized
  1710. // clamp, to handle numerical problems
  1711. function clamp( x ) {
  1712. return Math.min( Math.max( x, -1 ), 1 );
  1713. }
  1714. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1715. var sqx = q.x * q.x;
  1716. var sqy = q.y * q.y;
  1717. var sqz = q.z * q.z;
  1718. var sqw = q.w * q.w;
  1719. order = order || this._order;
  1720. if ( order === 'XYZ' ) {
  1721. this._x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1722. this._y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  1723. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1724. } else if ( order === 'YXZ' ) {
  1725. this._x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  1726. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1727. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1728. } else if ( order === 'ZXY' ) {
  1729. this._x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  1730. this._y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1731. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1732. } else if ( order === 'ZYX' ) {
  1733. this._x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1734. this._y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  1735. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1736. } else if ( order === 'YZX' ) {
  1737. this._x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1738. this._y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1739. this._z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  1740. } else if ( order === 'XZY' ) {
  1741. this._x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1742. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1743. this._z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  1744. } else {
  1745. console.warn( 'WARNING: Euler.setFromQuaternion() given unsupported order: ' + order )
  1746. }
  1747. this._order = order;
  1748. if ( update !== false ) this._updateQuaternion();
  1749. return this;
  1750. },
  1751. reorder: function () {
  1752. // WARNING: this discards revolution information -bhouston
  1753. var q = new THREE.Quaternion();
  1754. return function ( newOrder ) {
  1755. q.setFromEuler( this );
  1756. this.setFromQuaternion( q, newOrder );
  1757. };
  1758. }(),
  1759. fromArray: function ( array ) {
  1760. this._x = array[ 0 ];
  1761. this._y = array[ 1 ];
  1762. this._z = array[ 2 ];
  1763. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  1764. this._updateQuaternion();
  1765. return this;
  1766. },
  1767. toArray: function () {
  1768. return [ this._x, this._y, this._z, this._order ];
  1769. },
  1770. equals: function ( euler ) {
  1771. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  1772. },
  1773. clone: function () {
  1774. return new THREE.Euler( this._x, this._y, this._z, this._order );
  1775. }
  1776. };
  1777. /**
  1778. * @author bhouston / http://exocortex.com
  1779. */
  1780. THREE.Line3 = function ( start, end ) {
  1781. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1782. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1783. };
  1784. THREE.Line3.prototype = {
  1785. constructor: THREE.Line3,
  1786. set: function ( start, end ) {
  1787. this.start.copy( start );
  1788. this.end.copy( end );
  1789. return this;
  1790. },
  1791. copy: function ( line ) {
  1792. this.start.copy( line.start );
  1793. this.end.copy( line.end );
  1794. return this;
  1795. },
  1796. center: function ( optionalTarget ) {
  1797. var result = optionalTarget || new THREE.Vector3();
  1798. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1799. },
  1800. delta: function ( optionalTarget ) {
  1801. var result = optionalTarget || new THREE.Vector3();
  1802. return result.subVectors( this.end, this.start );
  1803. },
  1804. distanceSq: function () {
  1805. return this.start.distanceToSquared( this.end );
  1806. },
  1807. distance: function () {
  1808. return this.start.distanceTo( this.end );
  1809. },
  1810. at: function ( t, optionalTarget ) {
  1811. var result = optionalTarget || new THREE.Vector3();
  1812. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1813. },
  1814. closestPointToPointParameter: function() {
  1815. var startP = new THREE.Vector3();
  1816. var startEnd = new THREE.Vector3();
  1817. return function ( point, clampToLine ) {
  1818. startP.subVectors( point, this.start );
  1819. startEnd.subVectors( this.end, this.start );
  1820. var startEnd2 = startEnd.dot( startEnd );
  1821. var startEnd_startP = startEnd.dot( startP );
  1822. var t = startEnd_startP / startEnd2;
  1823. if ( clampToLine ) {
  1824. t = THREE.Math.clamp( t, 0, 1 );
  1825. }
  1826. return t;
  1827. };
  1828. }(),
  1829. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1830. var t = this.closestPointToPointParameter( point, clampToLine );
  1831. var result = optionalTarget || new THREE.Vector3();
  1832. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1833. },
  1834. applyMatrix4: function ( matrix ) {
  1835. this.start.applyMatrix4( matrix );
  1836. this.end.applyMatrix4( matrix );
  1837. return this;
  1838. },
  1839. equals: function ( line ) {
  1840. return line.start.equals( this.start ) && line.end.equals( this.end );
  1841. },
  1842. clone: function () {
  1843. return new THREE.Line3().copy( this );
  1844. }
  1845. };
  1846. /**
  1847. * @author bhouston / http://exocortex.com
  1848. */
  1849. THREE.Box2 = function ( min, max ) {
  1850. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1851. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1852. };
  1853. THREE.Box2.prototype = {
  1854. constructor: THREE.Box2,
  1855. set: function ( min, max ) {
  1856. this.min.copy( min );
  1857. this.max.copy( max );
  1858. return this;
  1859. },
  1860. setFromPoints: function ( points ) {
  1861. if ( points.length > 0 ) {
  1862. var point = points[ 0 ];
  1863. this.min.copy( point );
  1864. this.max.copy( point );
  1865. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1866. point = points[ i ];
  1867. if ( point.x < this.min.x ) {
  1868. this.min.x = point.x;
  1869. } else if ( point.x > this.max.x ) {
  1870. this.max.x = point.x;
  1871. }
  1872. if ( point.y < this.min.y ) {
  1873. this.min.y = point.y;
  1874. } else if ( point.y > this.max.y ) {
  1875. this.max.y = point.y;
  1876. }
  1877. }
  1878. } else {
  1879. this.makeEmpty();
  1880. }
  1881. return this;
  1882. },
  1883. setFromCenterAndSize: function () {
  1884. var v1 = new THREE.Vector2();
  1885. return function ( center, size ) {
  1886. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1887. this.min.copy( center ).sub( halfSize );
  1888. this.max.copy( center ).add( halfSize );
  1889. return this;
  1890. };
  1891. }(),
  1892. copy: function ( box ) {
  1893. this.min.copy( box.min );
  1894. this.max.copy( box.max );
  1895. return this;
  1896. },
  1897. makeEmpty: function () {
  1898. this.min.x = this.min.y = Infinity;
  1899. this.max.x = this.max.y = -Infinity;
  1900. return this;
  1901. },
  1902. empty: function () {
  1903. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1904. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1905. },
  1906. center: function ( optionalTarget ) {
  1907. var result = optionalTarget || new THREE.Vector2();
  1908. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1909. },
  1910. size: function ( optionalTarget ) {
  1911. var result = optionalTarget || new THREE.Vector2();
  1912. return result.subVectors( this.max, this.min );
  1913. },
  1914. expandByPoint: function ( point ) {
  1915. this.min.min( point );
  1916. this.max.max( point );
  1917. return this;
  1918. },
  1919. expandByVector: function ( vector ) {
  1920. this.min.sub( vector );
  1921. this.max.add( vector );
  1922. return this;
  1923. },
  1924. expandByScalar: function ( scalar ) {
  1925. this.min.addScalar( -scalar );
  1926. this.max.addScalar( scalar );
  1927. return this;
  1928. },
  1929. containsPoint: function ( point ) {
  1930. if ( point.x < this.min.x || point.x > this.max.x ||
  1931. point.y < this.min.y || point.y > this.max.y ) {
  1932. return false;
  1933. }
  1934. return true;
  1935. },
  1936. containsBox: function ( box ) {
  1937. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1938. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1939. return true;
  1940. }
  1941. return false;
  1942. },
  1943. getParameter: function ( point ) {
  1944. // This can potentially have a divide by zero if the box
  1945. // has a size dimension of 0.
  1946. return new THREE.Vector2(
  1947. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1948. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1949. );
  1950. },
  1951. isIntersectionBox: function ( box ) {
  1952. // using 6 splitting planes to rule out intersections.
  1953. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1954. box.max.y < this.min.y || box.min.y > this.max.y ) {
  1955. return false;
  1956. }
  1957. return true;
  1958. },
  1959. clampPoint: function ( point, optionalTarget ) {
  1960. var result = optionalTarget || new THREE.Vector2();
  1961. return result.copy( point ).clamp( this.min, this.max );
  1962. },
  1963. distanceToPoint: function () {
  1964. var v1 = new THREE.Vector2();
  1965. return function ( point ) {
  1966. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1967. return clampedPoint.sub( point ).length();
  1968. };
  1969. }(),
  1970. intersect: function ( box ) {
  1971. this.min.max( box.min );
  1972. this.max.min( box.max );
  1973. return this;
  1974. },
  1975. union: function ( box ) {
  1976. this.min.min( box.min );
  1977. this.max.max( box.max );
  1978. return this;
  1979. },
  1980. translate: function ( offset ) {
  1981. this.min.add( offset );
  1982. this.max.add( offset );
  1983. return this;
  1984. },
  1985. equals: function ( box ) {
  1986. return box.min.equals( this.min ) && box.max.equals( this.max );
  1987. },
  1988. clone: function () {
  1989. return new THREE.Box2().copy( this );
  1990. }
  1991. };
  1992. /**
  1993. * @author bhouston / http://exocortex.com
  1994. * @author WestLangley / http://github.com/WestLangley
  1995. */
  1996. THREE.Box3 = function ( min, max ) {
  1997. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  1998. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  1999. };
  2000. THREE.Box3.prototype = {
  2001. constructor: THREE.Box3,
  2002. set: function ( min, max ) {
  2003. this.min.copy( min );
  2004. this.max.copy( max );
  2005. return this;
  2006. },
  2007. setFromPoints: function ( points ) {
  2008. if ( points.length > 0 ) {
  2009. var point = points[ 0 ];
  2010. this.min.copy( point );
  2011. this.max.copy( point );
  2012. for ( var i = 1, il = points.length; i < il; i ++ ) {
  2013. point = points[ i ];
  2014. if ( point.x < this.min.x ) {
  2015. this.min.x = point.x;
  2016. } else if ( point.x > this.max.x ) {
  2017. this.max.x = point.x;
  2018. }
  2019. if ( point.y < this.min.y ) {
  2020. this.min.y = point.y;
  2021. } else if ( point.y > this.max.y ) {
  2022. this.max.y = point.y;
  2023. }
  2024. if ( point.z < this.min.z ) {
  2025. this.min.z = point.z;
  2026. } else if ( point.z > this.max.z ) {
  2027. this.max.z = point.z;
  2028. }
  2029. }
  2030. } else {
  2031. this.makeEmpty();
  2032. }
  2033. return this;
  2034. },
  2035. setFromCenterAndSize: function() {
  2036. var v1 = new THREE.Vector3();
  2037. return function ( center, size ) {
  2038. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2039. this.min.copy( center ).sub( halfSize );
  2040. this.max.copy( center ).add( halfSize );
  2041. return this;
  2042. };
  2043. }(),
  2044. setFromObject: function() {
  2045. // Computes the world-axis-aligned bounding box of an object (including its children),
  2046. // accounting for both the object's, and childrens', world transforms
  2047. var v1 = new THREE.Vector3();
  2048. return function( object ) {
  2049. var scope = this;
  2050. object.updateMatrixWorld( true );
  2051. this.makeEmpty();
  2052. object.traverse( function ( node ) {
  2053. if ( node.geometry !== undefined && node.geometry.vertices !== undefined ) {
  2054. var vertices = node.geometry.vertices;
  2055. for ( var i = 0, il = vertices.length; i < il; i++ ) {
  2056. v1.copy( vertices[ i ] );
  2057. v1.applyMatrix4( node.matrixWorld );
  2058. scope.expandByPoint( v1 );
  2059. }
  2060. }
  2061. } );
  2062. return this;
  2063. };
  2064. }(),
  2065. copy: function ( box ) {
  2066. this.min.copy( box.min );
  2067. this.max.copy( box.max );
  2068. return this;
  2069. },
  2070. makeEmpty: function () {
  2071. this.min.x = this.min.y = this.min.z = Infinity;
  2072. this.max.x = this.max.y = this.max.z = -Infinity;
  2073. return this;
  2074. },
  2075. empty: function () {
  2076. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2077. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2078. },
  2079. center: function ( optionalTarget ) {
  2080. var result = optionalTarget || new THREE.Vector3();
  2081. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2082. },
  2083. size: function ( optionalTarget ) {
  2084. var result = optionalTarget || new THREE.Vector3();
  2085. return result.subVectors( this.max, this.min );
  2086. },
  2087. expandByPoint: function ( point ) {
  2088. this.min.min( point );
  2089. this.max.max( point );
  2090. return this;
  2091. },
  2092. expandByVector: function ( vector ) {
  2093. this.min.sub( vector );
  2094. this.max.add( vector );
  2095. return this;
  2096. },
  2097. expandByScalar: function ( scalar ) {
  2098. this.min.addScalar( -scalar );
  2099. this.max.addScalar( scalar );
  2100. return this;
  2101. },
  2102. containsPoint: function ( point ) {
  2103. if ( point.x < this.min.x || point.x > this.max.x ||
  2104. point.y < this.min.y || point.y > this.max.y ||
  2105. point.z < this.min.z || point.z > this.max.z ) {
  2106. return false;
  2107. }
  2108. return true;
  2109. },
  2110. containsBox: function ( box ) {
  2111. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2112. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2113. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2114. return true;
  2115. }
  2116. return false;
  2117. },
  2118. getParameter: function ( point ) {
  2119. // This can potentially have a divide by zero if the box
  2120. // has a size dimension of 0.
  2121. return new THREE.Vector3(
  2122. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2123. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2124. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2125. );
  2126. },
  2127. isIntersectionBox: function ( box ) {
  2128. // using 6 splitting planes to rule out intersections.
  2129. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2130. box.max.y < this.min.y || box.min.y > this.max.y ||
  2131. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2132. return false;
  2133. }
  2134. return true;
  2135. },
  2136. clampPoint: function ( point, optionalTarget ) {
  2137. var result = optionalTarget || new THREE.Vector3();
  2138. return result.copy( point ).clamp( this.min, this.max );
  2139. },
  2140. distanceToPoint: function() {
  2141. var v1 = new THREE.Vector3();
  2142. return function ( point ) {
  2143. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2144. return clampedPoint.sub( point ).length();
  2145. };
  2146. }(),
  2147. getBoundingSphere: function() {
  2148. var v1 = new THREE.Vector3();
  2149. return function ( optionalTarget ) {
  2150. var result = optionalTarget || new THREE.Sphere();
  2151. result.center = this.center();
  2152. result.radius = this.size( v1 ).length() * 0.5;
  2153. return result;
  2154. };
  2155. }(),
  2156. intersect: function ( box ) {
  2157. this.min.max( box.min );
  2158. this.max.min( box.max );
  2159. return this;
  2160. },
  2161. union: function ( box ) {
  2162. this.min.min( box.min );
  2163. this.max.max( box.max );
  2164. return this;
  2165. },
  2166. applyMatrix4: function() {
  2167. var points = [
  2168. new THREE.Vector3(),
  2169. new THREE.Vector3(),
  2170. new THREE.Vector3(),
  2171. new THREE.Vector3(),
  2172. new THREE.Vector3(),
  2173. new THREE.Vector3(),
  2174. new THREE.Vector3(),
  2175. new THREE.Vector3()
  2176. ];
  2177. return function ( matrix ) {
  2178. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2179. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2180. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2181. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2182. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2183. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2184. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2185. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2186. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2187. this.makeEmpty();
  2188. this.setFromPoints( points );
  2189. return this;
  2190. };
  2191. }(),
  2192. translate: function ( offset ) {
  2193. this.min.add( offset );
  2194. this.max.add( offset );
  2195. return this;
  2196. },
  2197. equals: function ( box ) {
  2198. return box.min.equals( this.min ) && box.max.equals( this.max );
  2199. },
  2200. clone: function () {
  2201. return new THREE.Box3().copy( this );
  2202. }
  2203. };
  2204. /**
  2205. * @author alteredq / http://alteredqualia.com/
  2206. * @author WestLangley / http://github.com/WestLangley
  2207. * @author bhouston / http://exocortex.com
  2208. */
  2209. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2210. this.elements = new Float32Array(9);
  2211. this.set(
  2212. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  2213. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  2214. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  2215. );
  2216. };
  2217. THREE.Matrix3.prototype = {
  2218. constructor: THREE.Matrix3,
  2219. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2220. var te = this.elements;
  2221. te[0] = n11; te[3] = n12; te[6] = n13;
  2222. te[1] = n21; te[4] = n22; te[7] = n23;
  2223. te[2] = n31; te[5] = n32; te[8] = n33;
  2224. return this;
  2225. },
  2226. identity: function () {
  2227. this.set(
  2228. 1, 0, 0,
  2229. 0, 1, 0,
  2230. 0, 0, 1
  2231. );
  2232. return this;
  2233. },
  2234. copy: function ( m ) {
  2235. var me = m.elements;
  2236. this.set(
  2237. me[0], me[3], me[6],
  2238. me[1], me[4], me[7],
  2239. me[2], me[5], me[8]
  2240. );
  2241. return this;
  2242. },
  2243. multiplyVector3: function ( vector ) {
  2244. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2245. return vector.applyMatrix3( this );
  2246. },
  2247. multiplyVector3Array: function() {
  2248. var v1 = new THREE.Vector3();
  2249. return function ( a ) {
  2250. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2251. v1.x = a[ i ];
  2252. v1.y = a[ i + 1 ];
  2253. v1.z = a[ i + 2 ];
  2254. v1.applyMatrix3(this);
  2255. a[ i ] = v1.x;
  2256. a[ i + 1 ] = v1.y;
  2257. a[ i + 2 ] = v1.z;
  2258. }
  2259. return a;
  2260. };
  2261. }(),
  2262. multiplyScalar: function ( s ) {
  2263. var te = this.elements;
  2264. te[0] *= s; te[3] *= s; te[6] *= s;
  2265. te[1] *= s; te[4] *= s; te[7] *= s;
  2266. te[2] *= s; te[5] *= s; te[8] *= s;
  2267. return this;
  2268. },
  2269. determinant: function () {
  2270. var te = this.elements;
  2271. var a = te[0], b = te[1], c = te[2],
  2272. d = te[3], e = te[4], f = te[5],
  2273. g = te[6], h = te[7], i = te[8];
  2274. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2275. },
  2276. getInverse: function ( matrix, throwOnInvertible ) {
  2277. // input: THREE.Matrix4
  2278. // ( based on http://code.google.com/p/webgl-mjs/ )
  2279. var me = matrix.elements;
  2280. var te = this.elements;
  2281. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2282. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2283. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2284. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2285. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2286. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2287. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2288. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2289. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2290. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2291. // no inverse
  2292. if ( det === 0 ) {
  2293. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2294. if ( throwOnInvertible || false ) {
  2295. throw new Error( msg );
  2296. } else {
  2297. console.warn( msg );
  2298. }
  2299. this.identity();
  2300. return this;
  2301. }
  2302. this.multiplyScalar( 1.0 / det );
  2303. return this;
  2304. },
  2305. transpose: function () {
  2306. var tmp, m = this.elements;
  2307. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2308. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2309. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2310. return this;
  2311. },
  2312. getNormalMatrix: function ( m ) {
  2313. // input: THREE.Matrix4
  2314. this.getInverse( m ).transpose();
  2315. return this;
  2316. },
  2317. transposeIntoArray: function ( r ) {
  2318. var m = this.elements;
  2319. r[ 0 ] = m[ 0 ];
  2320. r[ 1 ] = m[ 3 ];
  2321. r[ 2 ] = m[ 6 ];
  2322. r[ 3 ] = m[ 1 ];
  2323. r[ 4 ] = m[ 4 ];
  2324. r[ 5 ] = m[ 7 ];
  2325. r[ 6 ] = m[ 2 ];
  2326. r[ 7 ] = m[ 5 ];
  2327. r[ 8 ] = m[ 8 ];
  2328. return this;
  2329. },
  2330. clone: function () {
  2331. var te = this.elements;
  2332. return new THREE.Matrix3(
  2333. te[0], te[3], te[6],
  2334. te[1], te[4], te[7],
  2335. te[2], te[5], te[8]
  2336. );
  2337. }
  2338. };
  2339. /**
  2340. * @author mrdoob / http://mrdoob.com/
  2341. * @author supereggbert / http://www.paulbrunt.co.uk/
  2342. * @author philogb / http://blog.thejit.org/
  2343. * @author jordi_ros / http://plattsoft.com
  2344. * @author D1plo1d / http://github.com/D1plo1d
  2345. * @author alteredq / http://alteredqualia.com/
  2346. * @author mikael emtinger / http://gomo.se/
  2347. * @author timknip / http://www.floorplanner.com/
  2348. * @author bhouston / http://exocortex.com
  2349. * @author WestLangley / http://github.com/WestLangley
  2350. */
  2351. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2352. this.elements = new Float32Array( 16 );
  2353. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2354. // we should not support semi specification of Matrix4, it is just weird.
  2355. var te = this.elements;
  2356. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2357. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2358. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2359. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2360. };
  2361. THREE.Matrix4.prototype = {
  2362. constructor: THREE.Matrix4,
  2363. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2364. var te = this.elements;
  2365. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2366. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2367. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2368. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2369. return this;
  2370. },
  2371. identity: function () {
  2372. this.set(
  2373. 1, 0, 0, 0,
  2374. 0, 1, 0, 0,
  2375. 0, 0, 1, 0,
  2376. 0, 0, 0, 1
  2377. );
  2378. return this;
  2379. },
  2380. copy: function ( m ) {
  2381. this.elements.set( m.elements );
  2382. return this;
  2383. },
  2384. extractPosition: function ( m ) {
  2385. console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' );
  2386. return this.copyPosition( m );
  2387. },
  2388. copyPosition: function ( m ) {
  2389. var te = this.elements;
  2390. var me = m.elements;
  2391. te[12] = me[12];
  2392. te[13] = me[13];
  2393. te[14] = me[14];
  2394. return this;
  2395. },
  2396. extractRotation: function () {
  2397. var v1 = new THREE.Vector3();
  2398. return function ( m ) {
  2399. var te = this.elements;
  2400. var me = m.elements;
  2401. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2402. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2403. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2404. te[0] = me[0] * scaleX;
  2405. te[1] = me[1] * scaleX;
  2406. te[2] = me[2] * scaleX;
  2407. te[4] = me[4] * scaleY;
  2408. te[5] = me[5] * scaleY;
  2409. te[6] = me[6] * scaleY;
  2410. te[8] = me[8] * scaleZ;
  2411. te[9] = me[9] * scaleZ;
  2412. te[10] = me[10] * scaleZ;
  2413. return this;
  2414. };
  2415. }(),
  2416. makeRotationFromEuler: function ( euler ) {
  2417. if ( typeof euler['order'] === undefined ) {
  2418. console.error( 'ERROR: Matrix\'s .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  2419. }
  2420. var te = this.elements;
  2421. var x = euler.x, y = euler.y, z = euler.z;
  2422. var a = Math.cos( x ), b = Math.sin( x );
  2423. var c = Math.cos( y ), d = Math.sin( y );
  2424. var e = Math.cos( z ), f = Math.sin( z );
  2425. if ( euler.order === undefined || euler.order === 'XYZ' ) {
  2426. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2427. te[0] = c * e;
  2428. te[4] = - c * f;
  2429. te[8] = d;
  2430. te[1] = af + be * d;
  2431. te[5] = ae - bf * d;
  2432. te[9] = - b * c;
  2433. te[2] = bf - ae * d;
  2434. te[6] = be + af * d;
  2435. te[10] = a * c;
  2436. } else if ( euler.order === 'YXZ' ) {
  2437. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2438. te[0] = ce + df * b;
  2439. te[4] = de * b - cf;
  2440. te[8] = a * d;
  2441. te[1] = a * f;
  2442. te[5] = a * e;
  2443. te[9] = - b;
  2444. te[2] = cf * b - de;
  2445. te[6] = df + ce * b;
  2446. te[10] = a * c;
  2447. } else if ( euler.order === 'ZXY' ) {
  2448. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2449. te[0] = ce - df * b;
  2450. te[4] = - a * f;
  2451. te[8] = de + cf * b;
  2452. te[1] = cf + de * b;
  2453. te[5] = a * e;
  2454. te[9] = df - ce * b;
  2455. te[2] = - a * d;
  2456. te[6] = b;
  2457. te[10] = a * c;
  2458. } else if ( euler.order === 'ZYX' ) {
  2459. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2460. te[0] = c * e;
  2461. te[4] = be * d - af;
  2462. te[8] = ae * d + bf;
  2463. te[1] = c * f;
  2464. te[5] = bf * d + ae;
  2465. te[9] = af * d - be;
  2466. te[2] = - d;
  2467. te[6] = b * c;
  2468. te[10] = a * c;
  2469. } else if ( euler.order === 'YZX' ) {
  2470. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2471. te[0] = c * e;
  2472. te[4] = bd - ac * f;
  2473. te[8] = bc * f + ad;
  2474. te[1] = f;
  2475. te[5] = a * e;
  2476. te[9] = - b * e;
  2477. te[2] = - d * e;
  2478. te[6] = ad * f + bc;
  2479. te[10] = ac - bd * f;
  2480. } else if ( euler.order === 'XZY' ) {
  2481. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2482. te[0] = c * e;
  2483. te[4] = - f;
  2484. te[8] = d * e;
  2485. te[1] = ac * f + bd;
  2486. te[5] = a * e;
  2487. te[9] = ad * f - bc;
  2488. te[2] = bc * f - ad;
  2489. te[6] = b * e;
  2490. te[10] = bd * f + ac;
  2491. }
  2492. // last column
  2493. te[3] = 0;
  2494. te[7] = 0;
  2495. te[11] = 0;
  2496. // bottom row
  2497. te[12] = 0;
  2498. te[13] = 0;
  2499. te[14] = 0;
  2500. te[15] = 1;
  2501. return this;
  2502. },
  2503. setRotationFromQuaternion: function ( q ) {
  2504. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' );
  2505. return this.makeRotationFromQuaternion( q );
  2506. },
  2507. makeRotationFromQuaternion: function ( q ) {
  2508. var te = this.elements;
  2509. var x = q.x, y = q.y, z = q.z, w = q.w;
  2510. var x2 = x + x, y2 = y + y, z2 = z + z;
  2511. var xx = x * x2, xy = x * y2, xz = x * z2;
  2512. var yy = y * y2, yz = y * z2, zz = z * z2;
  2513. var wx = w * x2, wy = w * y2, wz = w * z2;
  2514. te[0] = 1 - ( yy + zz );
  2515. te[4] = xy - wz;
  2516. te[8] = xz + wy;
  2517. te[1] = xy + wz;
  2518. te[5] = 1 - ( xx + zz );
  2519. te[9] = yz - wx;
  2520. te[2] = xz - wy;
  2521. te[6] = yz + wx;
  2522. te[10] = 1 - ( xx + yy );
  2523. // last column
  2524. te[3] = 0;
  2525. te[7] = 0;
  2526. te[11] = 0;
  2527. // bottom row
  2528. te[12] = 0;
  2529. te[13] = 0;
  2530. te[14] = 0;
  2531. te[15] = 1;
  2532. return this;
  2533. },
  2534. lookAt: function() {
  2535. var x = new THREE.Vector3();
  2536. var y = new THREE.Vector3();
  2537. var z = new THREE.Vector3();
  2538. return function ( eye, target, up ) {
  2539. var te = this.elements;
  2540. z.subVectors( eye, target ).normalize();
  2541. if ( z.length() === 0 ) {
  2542. z.z = 1;
  2543. }
  2544. x.crossVectors( up, z ).normalize();
  2545. if ( x.length() === 0 ) {
  2546. z.x += 0.0001;
  2547. x.crossVectors( up, z ).normalize();
  2548. }
  2549. y.crossVectors( z, x );
  2550. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2551. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2552. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2553. return this;
  2554. };
  2555. }(),
  2556. multiply: function ( m, n ) {
  2557. if ( n !== undefined ) {
  2558. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2559. return this.multiplyMatrices( m, n );
  2560. }
  2561. return this.multiplyMatrices( this, m );
  2562. },
  2563. multiplyMatrices: function ( a, b ) {
  2564. var ae = a.elements;
  2565. var be = b.elements;
  2566. var te = this.elements;
  2567. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2568. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2569. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2570. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2571. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2572. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2573. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2574. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2575. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2576. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2577. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2578. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2579. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2580. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2581. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2582. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2583. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2584. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2585. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2586. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2587. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2588. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2589. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2590. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2591. return this;
  2592. },
  2593. multiplyToArray: function ( a, b, r ) {
  2594. var te = this.elements;
  2595. this.multiplyMatrices( a, b );
  2596. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2597. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2598. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2599. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2600. return this;
  2601. },
  2602. multiplyScalar: function ( s ) {
  2603. var te = this.elements;
  2604. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2605. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2606. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2607. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2608. return this;
  2609. },
  2610. multiplyVector3: function ( vector ) {
  2611. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2612. return vector.applyProjection( this );
  2613. },
  2614. multiplyVector4: function ( vector ) {
  2615. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2616. return vector.applyMatrix4( this );
  2617. },
  2618. multiplyVector3Array: function() {
  2619. var v1 = new THREE.Vector3();
  2620. return function ( a ) {
  2621. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2622. v1.x = a[ i ];
  2623. v1.y = a[ i + 1 ];
  2624. v1.z = a[ i + 2 ];
  2625. v1.applyProjection( this );
  2626. a[ i ] = v1.x;
  2627. a[ i + 1 ] = v1.y;
  2628. a[ i + 2 ] = v1.z;
  2629. }
  2630. return a;
  2631. };
  2632. }(),
  2633. rotateAxis: function ( v ) {
  2634. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2635. v.transformDirection( this );
  2636. },
  2637. crossVector: function ( vector ) {
  2638. console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2639. return vector.applyMatrix4( this );
  2640. },
  2641. determinant: function () {
  2642. var te = this.elements;
  2643. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2644. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2645. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2646. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2647. //TODO: make this more efficient
  2648. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2649. return (
  2650. n41 * (
  2651. +n14 * n23 * n32
  2652. -n13 * n24 * n32
  2653. -n14 * n22 * n33
  2654. +n12 * n24 * n33
  2655. +n13 * n22 * n34
  2656. -n12 * n23 * n34
  2657. ) +
  2658. n42 * (
  2659. +n11 * n23 * n34
  2660. -n11 * n24 * n33
  2661. +n14 * n21 * n33
  2662. -n13 * n21 * n34
  2663. +n13 * n24 * n31
  2664. -n14 * n23 * n31
  2665. ) +
  2666. n43 * (
  2667. +n11 * n24 * n32
  2668. -n11 * n22 * n34
  2669. -n14 * n21 * n32
  2670. +n12 * n21 * n34
  2671. +n14 * n22 * n31
  2672. -n12 * n24 * n31
  2673. ) +
  2674. n44 * (
  2675. -n13 * n22 * n31
  2676. -n11 * n23 * n32
  2677. +n11 * n22 * n33
  2678. +n13 * n21 * n32
  2679. -n12 * n21 * n33
  2680. +n12 * n23 * n31
  2681. )
  2682. );
  2683. },
  2684. transpose: function () {
  2685. var te = this.elements;
  2686. var tmp;
  2687. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2688. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2689. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2690. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2691. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2692. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2693. return this;
  2694. },
  2695. flattenToArray: function ( flat ) {
  2696. var te = this.elements;
  2697. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2698. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2699. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2700. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2701. return flat;
  2702. },
  2703. flattenToArrayOffset: function( flat, offset ) {
  2704. var te = this.elements;
  2705. flat[ offset ] = te[0];
  2706. flat[ offset + 1 ] = te[1];
  2707. flat[ offset + 2 ] = te[2];
  2708. flat[ offset + 3 ] = te[3];
  2709. flat[ offset + 4 ] = te[4];
  2710. flat[ offset + 5 ] = te[5];
  2711. flat[ offset + 6 ] = te[6];
  2712. flat[ offset + 7 ] = te[7];
  2713. flat[ offset + 8 ] = te[8];
  2714. flat[ offset + 9 ] = te[9];
  2715. flat[ offset + 10 ] = te[10];
  2716. flat[ offset + 11 ] = te[11];
  2717. flat[ offset + 12 ] = te[12];
  2718. flat[ offset + 13 ] = te[13];
  2719. flat[ offset + 14 ] = te[14];
  2720. flat[ offset + 15 ] = te[15];
  2721. return flat;
  2722. },
  2723. getPosition: function() {
  2724. var v1 = new THREE.Vector3();
  2725. return function () {
  2726. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.getPositionFromMatrix( matrix ) instead.' );
  2727. var te = this.elements;
  2728. return v1.set( te[12], te[13], te[14] );
  2729. };
  2730. }(),
  2731. setPosition: function ( v ) {
  2732. var te = this.elements;
  2733. te[12] = v.x;
  2734. te[13] = v.y;
  2735. te[14] = v.z;
  2736. return this;
  2737. },
  2738. getInverse: function ( m, throwOnInvertible ) {
  2739. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2740. var te = this.elements;
  2741. var me = m.elements;
  2742. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2743. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2744. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2745. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2746. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2747. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2748. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2749. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2750. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2751. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2752. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2753. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2754. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2755. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2756. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2757. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2758. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2759. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2760. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2761. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2762. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  2763. if ( det == 0 ) {
  2764. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2765. if ( throwOnInvertible || false ) {
  2766. throw new Error( msg );
  2767. } else {
  2768. console.warn( msg );
  2769. }
  2770. this.identity();
  2771. return this;
  2772. }
  2773. this.multiplyScalar( 1 / det );
  2774. return this;
  2775. },
  2776. translate: function ( v ) {
  2777. console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.');
  2778. },
  2779. rotateX: function ( angle ) {
  2780. console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.');
  2781. },
  2782. rotateY: function ( angle ) {
  2783. console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.');
  2784. },
  2785. rotateZ: function ( angle ) {
  2786. console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.');
  2787. },
  2788. rotateByAxis: function ( axis, angle ) {
  2789. console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.');
  2790. },
  2791. scale: function ( v ) {
  2792. var te = this.elements;
  2793. var x = v.x, y = v.y, z = v.z;
  2794. te[0] *= x; te[4] *= y; te[8] *= z;
  2795. te[1] *= x; te[5] *= y; te[9] *= z;
  2796. te[2] *= x; te[6] *= y; te[10] *= z;
  2797. te[3] *= x; te[7] *= y; te[11] *= z;
  2798. return this;
  2799. },
  2800. getMaxScaleOnAxis: function () {
  2801. var te = this.elements;
  2802. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2803. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2804. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2805. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2806. },
  2807. makeTranslation: function ( x, y, z ) {
  2808. this.set(
  2809. 1, 0, 0, x,
  2810. 0, 1, 0, y,
  2811. 0, 0, 1, z,
  2812. 0, 0, 0, 1
  2813. );
  2814. return this;
  2815. },
  2816. makeRotationX: function ( theta ) {
  2817. var c = Math.cos( theta ), s = Math.sin( theta );
  2818. this.set(
  2819. 1, 0, 0, 0,
  2820. 0, c, -s, 0,
  2821. 0, s, c, 0,
  2822. 0, 0, 0, 1
  2823. );
  2824. return this;
  2825. },
  2826. makeRotationY: function ( theta ) {
  2827. var c = Math.cos( theta ), s = Math.sin( theta );
  2828. this.set(
  2829. c, 0, s, 0,
  2830. 0, 1, 0, 0,
  2831. -s, 0, c, 0,
  2832. 0, 0, 0, 1
  2833. );
  2834. return this;
  2835. },
  2836. makeRotationZ: function ( theta ) {
  2837. var c = Math.cos( theta ), s = Math.sin( theta );
  2838. this.set(
  2839. c, -s, 0, 0,
  2840. s, c, 0, 0,
  2841. 0, 0, 1, 0,
  2842. 0, 0, 0, 1
  2843. );
  2844. return this;
  2845. },
  2846. makeRotationAxis: function ( axis, angle ) {
  2847. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2848. var c = Math.cos( angle );
  2849. var s = Math.sin( angle );
  2850. var t = 1 - c;
  2851. var x = axis.x, y = axis.y, z = axis.z;
  2852. var tx = t * x, ty = t * y;
  2853. this.set(
  2854. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2855. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2856. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2857. 0, 0, 0, 1
  2858. );
  2859. return this;
  2860. },
  2861. makeScale: function ( x, y, z ) {
  2862. this.set(
  2863. x, 0, 0, 0,
  2864. 0, y, 0, 0,
  2865. 0, 0, z, 0,
  2866. 0, 0, 0, 1
  2867. );
  2868. return this;
  2869. },
  2870. compose: function ( position, quaternion, scale ) {
  2871. this.makeRotationFromQuaternion( quaternion );
  2872. this.scale( scale );
  2873. this.setPosition( position );
  2874. return this;
  2875. },
  2876. decompose: function () {
  2877. var vector = new THREE.Vector3();
  2878. var matrix = new THREE.Matrix4();
  2879. return function ( position, quaternion, scale ) {
  2880. var te = this.elements;
  2881. var sx = vector.set( te[0], te[1], te[2] ).length();
  2882. var sy = vector.set( te[4], te[5], te[6] ).length();
  2883. var sz = vector.set( te[8], te[9], te[10] ).length();
  2884. position.x = te[12];
  2885. position.y = te[13];
  2886. position.z = te[14];
  2887. // scale the rotation part
  2888. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  2889. var invSX = 1 / sx;
  2890. var invSY = 1 / sy;
  2891. var invSZ = 1 / sz;
  2892. matrix.elements[0] *= invSX;
  2893. matrix.elements[1] *= invSX;
  2894. matrix.elements[2] *= invSX;
  2895. matrix.elements[4] *= invSY;
  2896. matrix.elements[5] *= invSY;
  2897. matrix.elements[6] *= invSY;
  2898. matrix.elements[8] *= invSZ;
  2899. matrix.elements[9] *= invSZ;
  2900. matrix.elements[10] *= invSZ;
  2901. quaternion.setFromRotationMatrix( matrix );
  2902. scale.x = sx;
  2903. scale.y = sy;
  2904. scale.z = sz;
  2905. return this;
  2906. };
  2907. }(),
  2908. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2909. var te = this.elements;
  2910. var x = 2 * near / ( right - left );
  2911. var y = 2 * near / ( top - bottom );
  2912. var a = ( right + left ) / ( right - left );
  2913. var b = ( top + bottom ) / ( top - bottom );
  2914. var c = - ( far + near ) / ( far - near );
  2915. var d = - 2 * far * near / ( far - near );
  2916. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2917. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2918. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2919. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2920. return this;
  2921. },
  2922. makePerspective: function ( fov, aspect, near, far ) {
  2923. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  2924. var ymin = - ymax;
  2925. var xmin = ymin * aspect;
  2926. var xmax = ymax * aspect;
  2927. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2928. },
  2929. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2930. var te = this.elements;
  2931. var w = right - left;
  2932. var h = top - bottom;
  2933. var p = far - near;
  2934. var x = ( right + left ) / w;
  2935. var y = ( top + bottom ) / h;
  2936. var z = ( far + near ) / p;
  2937. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2938. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2939. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  2940. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2941. return this;
  2942. },
  2943. fromArray: function ( array ) {
  2944. this.elements.set( array );
  2945. return this;
  2946. },
  2947. toArray: function () {
  2948. var te = this.elements;
  2949. return [
  2950. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  2951. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  2952. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  2953. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  2954. ];
  2955. },
  2956. clone: function () {
  2957. var te = this.elements;
  2958. return new THREE.Matrix4(
  2959. te[0], te[4], te[8], te[12],
  2960. te[1], te[5], te[9], te[13],
  2961. te[2], te[6], te[10], te[14],
  2962. te[3], te[7], te[11], te[15]
  2963. );
  2964. }
  2965. };
  2966. /**
  2967. * @author bhouston / http://exocortex.com
  2968. */
  2969. THREE.Ray = function ( origin, direction ) {
  2970. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  2971. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  2972. };
  2973. THREE.Ray.prototype = {
  2974. constructor: THREE.Ray,
  2975. set: function ( origin, direction ) {
  2976. this.origin.copy( origin );
  2977. this.direction.copy( direction );
  2978. return this;
  2979. },
  2980. copy: function ( ray ) {
  2981. this.origin.copy( ray.origin );
  2982. this.direction.copy( ray.direction );
  2983. return this;
  2984. },
  2985. at: function ( t, optionalTarget ) {
  2986. var result = optionalTarget || new THREE.Vector3();
  2987. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2988. },
  2989. recast: function () {
  2990. var v1 = new THREE.Vector3();
  2991. return function ( t ) {
  2992. this.origin.copy( this.at( t, v1 ) );
  2993. return this;
  2994. };
  2995. }(),
  2996. closestPointToPoint: function ( point, optionalTarget ) {
  2997. var result = optionalTarget || new THREE.Vector3();
  2998. result.subVectors( point, this.origin );
  2999. var directionDistance = result.dot( this.direction );
  3000. if ( directionDistance < 0 ) {
  3001. return this.origin.clone();
  3002. }
  3003. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3004. },
  3005. distanceToPoint: function () {
  3006. var v1 = new THREE.Vector3();
  3007. return function ( point ) {
  3008. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3009. // point behind the ray
  3010. if ( directionDistance < 0 ) {
  3011. return this.origin.distanceTo( point );
  3012. }
  3013. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3014. return v1.distanceTo( point );
  3015. };
  3016. }(),
  3017. distanceToSegment: function( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3018. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3019. // It returns the min distance between the ray and the segment
  3020. // defined by v0 and v1
  3021. // It can also set two optional targets :
  3022. // - The closest point on the ray
  3023. // - The closest point on the segment
  3024. var segCenter = v0.clone().add( v1 ).multiplyScalar( 0.5 );
  3025. var segDir = v1.clone().sub( v0 ).normalize();
  3026. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3027. var diff = this.origin.clone().sub( segCenter );
  3028. var a01 = - this.direction.dot( segDir );
  3029. var b0 = diff.dot( this.direction );
  3030. var b1 = - diff.dot( segDir );
  3031. var c = diff.lengthSq();
  3032. var det = Math.abs( 1 - a01 * a01 );
  3033. var s0, s1, sqrDist, extDet;
  3034. if ( det >= 0 ) {
  3035. // The ray and segment are not parallel.
  3036. s0 = a01 * b1 - b0;
  3037. s1 = a01 * b0 - b1;
  3038. extDet = segExtent * det;
  3039. if ( s0 >= 0 ) {
  3040. if ( s1 >= - extDet ) {
  3041. if ( s1 <= extDet ) {
  3042. // region 0
  3043. // Minimum at interior points of ray and segment.
  3044. var invDet = 1 / det;
  3045. s0 *= invDet;
  3046. s1 *= invDet;
  3047. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3048. } else {
  3049. // region 1
  3050. s1 = segExtent;
  3051. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3052. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3053. }
  3054. } else {
  3055. // region 5
  3056. s1 = - segExtent;
  3057. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3058. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3059. }
  3060. } else {
  3061. if ( s1 <= - extDet) {
  3062. // region 4
  3063. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3064. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3065. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3066. } else if ( s1 <= extDet ) {
  3067. // region 3
  3068. s0 = 0;
  3069. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3070. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3071. } else {
  3072. // region 2
  3073. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3074. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3075. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3076. }
  3077. }
  3078. } else {
  3079. // Ray and segment are parallel.
  3080. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3081. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3082. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3083. }
  3084. if ( optionalPointOnRay ) {
  3085. optionalPointOnRay.copy( this.direction.clone().multiplyScalar( s0 ).add( this.origin ) );
  3086. }
  3087. if ( optionalPointOnSegment ) {
  3088. optionalPointOnSegment.copy( segDir.clone().multiplyScalar( s1 ).add( segCenter ) );
  3089. }
  3090. return sqrDist;
  3091. },
  3092. isIntersectionSphere: function ( sphere ) {
  3093. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3094. },
  3095. isIntersectionPlane: function ( plane ) {
  3096. // check if the ray lies on the plane first
  3097. var distToPoint = plane.distanceToPoint( this.origin );
  3098. if ( distToPoint === 0 ) {
  3099. return true;
  3100. }
  3101. var denominator = plane.normal.dot( this.direction );
  3102. if ( denominator * distToPoint < 0 ) {
  3103. return true
  3104. }
  3105. // ray origin is behind the plane (and is pointing behind it)
  3106. return false;
  3107. },
  3108. distanceToPlane: function ( plane ) {
  3109. var denominator = plane.normal.dot( this.direction );
  3110. if ( denominator == 0 ) {
  3111. // line is coplanar, return origin
  3112. if( plane.distanceToPoint( this.origin ) == 0 ) {
  3113. return 0;
  3114. }
  3115. // Null is preferable to undefined since undefined means.... it is undefined
  3116. return null;
  3117. }
  3118. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3119. // Return if the ray never intersects the plane
  3120. return t >= 0 ? t : null;
  3121. },
  3122. intersectPlane: function ( plane, optionalTarget ) {
  3123. var t = this.distanceToPlane( plane );
  3124. if ( t === null ) {
  3125. return null;
  3126. }
  3127. return this.at( t, optionalTarget );
  3128. },
  3129. applyMatrix4: function ( matrix4 ) {
  3130. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3131. this.origin.applyMatrix4( matrix4 );
  3132. this.direction.sub( this.origin );
  3133. return this;
  3134. },
  3135. equals: function ( ray ) {
  3136. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3137. },
  3138. clone: function () {
  3139. return new THREE.Ray().copy( this );
  3140. }
  3141. };
  3142. /**
  3143. * @author bhouston / http://exocortex.com
  3144. * @author mrdoob / http://mrdoob.com/
  3145. */
  3146. THREE.Sphere = function ( center, radius ) {
  3147. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3148. this.radius = ( radius !== undefined ) ? radius : 0;
  3149. };
  3150. THREE.Sphere.prototype = {
  3151. constructor: THREE.Sphere,
  3152. set: function ( center, radius ) {
  3153. this.center.copy( center );
  3154. this.radius = radius;
  3155. return this;
  3156. },
  3157. setFromPoints: function ( points ) {
  3158. var radiusSq, maxRadiusSq = 0;
  3159. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3160. radiusSq = points[ i ].lengthSq();
  3161. maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
  3162. }
  3163. this.center.set( 0, 0, 0 );
  3164. this.radius = Math.sqrt( maxRadiusSq );
  3165. return this;
  3166. },
  3167. copy: function ( sphere ) {
  3168. this.center.copy( sphere.center );
  3169. this.radius = sphere.radius;
  3170. return this;
  3171. },
  3172. empty: function () {
  3173. return ( this.radius <= 0 );
  3174. },
  3175. containsPoint: function ( point ) {
  3176. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3177. },
  3178. distanceToPoint: function ( point ) {
  3179. return ( point.distanceTo( this.center ) - this.radius );
  3180. },
  3181. intersectsSphere: function ( sphere ) {
  3182. var radiusSum = this.radius + sphere.radius;
  3183. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3184. },
  3185. clampPoint: function ( point, optionalTarget ) {
  3186. var deltaLengthSq = this.center.distanceToSquared( point );
  3187. var result = optionalTarget || new THREE.Vector3();
  3188. result.copy( point );
  3189. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3190. result.sub( this.center ).normalize();
  3191. result.multiplyScalar( this.radius ).add( this.center );
  3192. }
  3193. return result;
  3194. },
  3195. getBoundingBox: function ( optionalTarget ) {
  3196. var box = optionalTarget || new THREE.Box3();
  3197. box.set( this.center, this.center );
  3198. box.expandByScalar( this.radius );
  3199. return box;
  3200. },
  3201. applyMatrix4: function ( matrix ) {
  3202. this.center.applyMatrix4( matrix );
  3203. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3204. return this;
  3205. },
  3206. translate: function ( offset ) {
  3207. this.center.add( offset );
  3208. return this;
  3209. },
  3210. equals: function ( sphere ) {
  3211. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3212. },
  3213. clone: function () {
  3214. return new THREE.Sphere().copy( this );
  3215. }
  3216. };
  3217. /**
  3218. * @author mrdoob / http://mrdoob.com/
  3219. * @author alteredq / http://alteredqualia.com/
  3220. * @author bhouston / http://exocortex.com
  3221. */
  3222. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3223. this.planes = [
  3224. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3225. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3226. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3227. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3228. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3229. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3230. ];
  3231. };
  3232. THREE.Frustum.prototype = {
  3233. constructor: THREE.Frustum,
  3234. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3235. var planes = this.planes;
  3236. planes[0].copy( p0 );
  3237. planes[1].copy( p1 );
  3238. planes[2].copy( p2 );
  3239. planes[3].copy( p3 );
  3240. planes[4].copy( p4 );
  3241. planes[5].copy( p5 );
  3242. return this;
  3243. },
  3244. copy: function ( frustum ) {
  3245. var planes = this.planes;
  3246. for( var i = 0; i < 6; i ++ ) {
  3247. planes[i].copy( frustum.planes[i] );
  3248. }
  3249. return this;
  3250. },
  3251. setFromMatrix: function ( m ) {
  3252. var planes = this.planes;
  3253. var me = m.elements;
  3254. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  3255. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  3256. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  3257. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  3258. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3259. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3260. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3261. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3262. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3263. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3264. return this;
  3265. },
  3266. intersectsObject: function () {
  3267. var center = new THREE.Vector3();
  3268. return function ( object ) {
  3269. // this method is expanded inlined for performance reasons.
  3270. var geometry = object.geometry;
  3271. var matrix = object.matrixWorld;
  3272. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3273. var negRadius = - geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  3274. center.getPositionFromMatrix( matrix );
  3275. var planes = this.planes;
  3276. for ( var i = 0; i < 6; i ++ ) {
  3277. var distance = planes[ i ].distanceToPoint( center );
  3278. if ( distance < negRadius ) {
  3279. return false;
  3280. }
  3281. }
  3282. return true;
  3283. };
  3284. }(),
  3285. intersectsSphere: function ( sphere ) {
  3286. var planes = this.planes;
  3287. var center = sphere.center;
  3288. var negRadius = -sphere.radius;
  3289. for ( var i = 0; i < 6; i ++ ) {
  3290. var distance = planes[ i ].distanceToPoint( center );
  3291. if ( distance < negRadius ) {
  3292. return false;
  3293. }
  3294. }
  3295. return true;
  3296. },
  3297. intersectsBox : function() {
  3298. var p1 = new THREE.Vector3(),
  3299. p2 = new THREE.Vector3();
  3300. return function( box ) {
  3301. var planes = this.planes;
  3302. for ( var i = 0; i < 6 ; i ++ ) {
  3303. var plane = planes[i];
  3304. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3305. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3306. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3307. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3308. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3309. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3310. var d1 = plane.distanceToPoint( p1 );
  3311. var d2 = plane.distanceToPoint( p2 );
  3312. // if both outside plane, no intersection
  3313. if ( d1 < 0 && d2 < 0 ) {
  3314. return false;
  3315. }
  3316. }
  3317. return true;
  3318. };
  3319. }(),
  3320. containsPoint: function ( point ) {
  3321. var planes = this.planes;
  3322. for ( var i = 0; i < 6; i ++ ) {
  3323. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3324. return false;
  3325. }
  3326. }
  3327. return true;
  3328. },
  3329. clone: function () {
  3330. return new THREE.Frustum().copy( this );
  3331. }
  3332. };
  3333. /**
  3334. * @author bhouston / http://exocortex.com
  3335. */
  3336. THREE.Plane = function ( normal, constant ) {
  3337. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3338. this.constant = ( constant !== undefined ) ? constant : 0;
  3339. };
  3340. THREE.Plane.prototype = {
  3341. constructor: THREE.Plane,
  3342. set: function ( normal, constant ) {
  3343. this.normal.copy( normal );
  3344. this.constant = constant;
  3345. return this;
  3346. },
  3347. setComponents: function ( x, y, z, w ) {
  3348. this.normal.set( x, y, z );
  3349. this.constant = w;
  3350. return this;
  3351. },
  3352. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3353. this.normal.copy( normal );
  3354. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3355. return this;
  3356. },
  3357. setFromCoplanarPoints: function() {
  3358. var v1 = new THREE.Vector3();
  3359. var v2 = new THREE.Vector3();
  3360. return function ( a, b, c ) {
  3361. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3362. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3363. this.setFromNormalAndCoplanarPoint( normal, a );
  3364. return this;
  3365. };
  3366. }(),
  3367. copy: function ( plane ) {
  3368. this.normal.copy( plane.normal );
  3369. this.constant = plane.constant;
  3370. return this;
  3371. },
  3372. normalize: function () {
  3373. // Note: will lead to a divide by zero if the plane is invalid.
  3374. var inverseNormalLength = 1.0 / this.normal.length();
  3375. this.normal.multiplyScalar( inverseNormalLength );
  3376. this.constant *= inverseNormalLength;
  3377. return this;
  3378. },
  3379. negate: function () {
  3380. this.constant *= -1;
  3381. this.normal.negate();
  3382. return this;
  3383. },
  3384. distanceToPoint: function ( point ) {
  3385. return this.normal.dot( point ) + this.constant;
  3386. },
  3387. distanceToSphere: function ( sphere ) {
  3388. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3389. },
  3390. projectPoint: function ( point, optionalTarget ) {
  3391. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3392. },
  3393. orthoPoint: function ( point, optionalTarget ) {
  3394. var perpendicularMagnitude = this.distanceToPoint( point );
  3395. var result = optionalTarget || new THREE.Vector3();
  3396. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3397. },
  3398. isIntersectionLine: function ( line ) {
  3399. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3400. var startSign = this.distanceToPoint( line.start );
  3401. var endSign = this.distanceToPoint( line.end );
  3402. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3403. },
  3404. intersectLine: function() {
  3405. var v1 = new THREE.Vector3();
  3406. return function ( line, optionalTarget ) {
  3407. var result = optionalTarget || new THREE.Vector3();
  3408. var direction = line.delta( v1 );
  3409. var denominator = this.normal.dot( direction );
  3410. if ( denominator == 0 ) {
  3411. // line is coplanar, return origin
  3412. if( this.distanceToPoint( line.start ) == 0 ) {
  3413. return result.copy( line.start );
  3414. }
  3415. // Unsure if this is the correct method to handle this case.
  3416. return undefined;
  3417. }
  3418. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3419. if( t < 0 || t > 1 ) {
  3420. return undefined;
  3421. }
  3422. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3423. };
  3424. }(),
  3425. coplanarPoint: function ( optionalTarget ) {
  3426. var result = optionalTarget || new THREE.Vector3();
  3427. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3428. },
  3429. applyMatrix4: function() {
  3430. var v1 = new THREE.Vector3();
  3431. var v2 = new THREE.Vector3();
  3432. return function ( matrix, optionalNormalMatrix ) {
  3433. // compute new normal based on theory here:
  3434. // http://www.songho.ca/opengl/gl_normaltransform.html
  3435. optionalNormalMatrix = optionalNormalMatrix || new THREE.Matrix3().getNormalMatrix( matrix );
  3436. var newNormal = v1.copy( this.normal ).applyMatrix3( optionalNormalMatrix );
  3437. var newCoplanarPoint = this.coplanarPoint( v2 );
  3438. newCoplanarPoint.applyMatrix4( matrix );
  3439. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3440. return this;
  3441. };
  3442. }(),
  3443. translate: function ( offset ) {
  3444. this.constant = this.constant - offset.dot( this.normal );
  3445. return this;
  3446. },
  3447. equals: function ( plane ) {
  3448. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3449. },
  3450. clone: function () {
  3451. return new THREE.Plane().copy( this );
  3452. }
  3453. };
  3454. /**
  3455. * @author alteredq / http://alteredqualia.com/
  3456. * @author mrdoob / http://mrdoob.com/
  3457. */
  3458. THREE.Math = {
  3459. PI2: Math.PI * 2,
  3460. generateUUID: function () {
  3461. // http://www.broofa.com/Tools/Math.uuid.htm
  3462. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  3463. var uuid = new Array(36);
  3464. var rnd = 0, r;
  3465. return function () {
  3466. for ( var i = 0; i < 36; i ++ ) {
  3467. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3468. uuid[ i ] = '-';
  3469. } else if ( i == 14 ) {
  3470. uuid[ i ] = '4';
  3471. } else {
  3472. if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
  3473. r = rnd & 0xf;
  3474. rnd = rnd >> 4;
  3475. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  3476. }
  3477. }
  3478. return uuid.join('');
  3479. };
  3480. }(),
  3481. // Clamp value to range <a, b>
  3482. clamp: function ( x, a, b ) {
  3483. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3484. },
  3485. // Clamp value to range <a, inf)
  3486. clampBottom: function ( x, a ) {
  3487. return x < a ? a : x;
  3488. },
  3489. // Linear mapping from range <a1, a2> to range <b1, b2>
  3490. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3491. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3492. },
  3493. // http://en.wikipedia.org/wiki/Smoothstep
  3494. smoothstep: function ( x, min, max ) {
  3495. if ( x <= min ) return 0;
  3496. if ( x >= max ) return 1;
  3497. x = ( x - min )/( max - min );
  3498. return x*x*(3 - 2*x);
  3499. },
  3500. smootherstep: function ( x, min, max ) {
  3501. if ( x <= min ) return 0;
  3502. if ( x >= max ) return 1;
  3503. x = ( x - min )/( max - min );
  3504. return x*x*x*(x*(x*6 - 15) + 10);
  3505. },
  3506. // Random float from <0, 1> with 16 bits of randomness
  3507. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3508. random16: function () {
  3509. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3510. },
  3511. // Random integer from <low, high> interval
  3512. randInt: function ( low, high ) {
  3513. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3514. },
  3515. // Random float from <low, high> interval
  3516. randFloat: function ( low, high ) {
  3517. return low + Math.random() * ( high - low );
  3518. },
  3519. // Random float from <-range/2, range/2> interval
  3520. randFloatSpread: function ( range ) {
  3521. return range * ( 0.5 - Math.random() );
  3522. },
  3523. sign: function ( x ) {
  3524. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  3525. },
  3526. degToRad: function() {
  3527. var degreeToRadiansFactor = Math.PI / 180;
  3528. return function ( degrees ) {
  3529. return degrees * degreeToRadiansFactor;
  3530. };
  3531. }(),
  3532. radToDeg: function() {
  3533. var radianToDegreesFactor = 180 / Math.PI;
  3534. return function ( radians ) {
  3535. return radians * radianToDegreesFactor;
  3536. };
  3537. }()
  3538. };
  3539. /**
  3540. * Spline from Tween.js, slightly optimized (and trashed)
  3541. * http://sole.github.com/tween.js/examples/05_spline.html
  3542. *
  3543. * @author mrdoob / http://mrdoob.com/
  3544. * @author alteredq / http://alteredqualia.com/
  3545. */
  3546. THREE.Spline = function ( points ) {
  3547. this.points = points;
  3548. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3549. point, intPoint, weight, w2, w3,
  3550. pa, pb, pc, pd;
  3551. this.initFromArray = function( a ) {
  3552. this.points = [];
  3553. for ( var i = 0; i < a.length; i++ ) {
  3554. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3555. }
  3556. };
  3557. this.getPoint = function ( k ) {
  3558. point = ( this.points.length - 1 ) * k;
  3559. intPoint = Math.floor( point );
  3560. weight = point - intPoint;
  3561. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3562. c[ 1 ] = intPoint;
  3563. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3564. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3565. pa = this.points[ c[ 0 ] ];
  3566. pb = this.points[ c[ 1 ] ];
  3567. pc = this.points[ c[ 2 ] ];
  3568. pd = this.points[ c[ 3 ] ];
  3569. w2 = weight * weight;
  3570. w3 = weight * w2;
  3571. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3572. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3573. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3574. return v3;
  3575. };
  3576. this.getControlPointsArray = function () {
  3577. var i, p, l = this.points.length,
  3578. coords = [];
  3579. for ( i = 0; i < l; i ++ ) {
  3580. p = this.points[ i ];
  3581. coords[ i ] = [ p.x, p.y, p.z ];
  3582. }
  3583. return coords;
  3584. };
  3585. // approximate length by summing linear segments
  3586. this.getLength = function ( nSubDivisions ) {
  3587. var i, index, nSamples, position,
  3588. point = 0, intPoint = 0, oldIntPoint = 0,
  3589. oldPosition = new THREE.Vector3(),
  3590. tmpVec = new THREE.Vector3(),
  3591. chunkLengths = [],
  3592. totalLength = 0;
  3593. // first point has 0 length
  3594. chunkLengths[ 0 ] = 0;
  3595. if ( !nSubDivisions ) nSubDivisions = 100;
  3596. nSamples = this.points.length * nSubDivisions;
  3597. oldPosition.copy( this.points[ 0 ] );
  3598. for ( i = 1; i < nSamples; i ++ ) {
  3599. index = i / nSamples;
  3600. position = this.getPoint( index );
  3601. tmpVec.copy( position );
  3602. totalLength += tmpVec.distanceTo( oldPosition );
  3603. oldPosition.copy( position );
  3604. point = ( this.points.length - 1 ) * index;
  3605. intPoint = Math.floor( point );
  3606. if ( intPoint != oldIntPoint ) {
  3607. chunkLengths[ intPoint ] = totalLength;
  3608. oldIntPoint = intPoint;
  3609. }
  3610. }
  3611. // last point ends with total length
  3612. chunkLengths[ chunkLengths.length ] = totalLength;
  3613. return { chunks: chunkLengths, total: totalLength };
  3614. };
  3615. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3616. var i, j,
  3617. index, indexCurrent, indexNext,
  3618. linearDistance, realDistance,
  3619. sampling, position,
  3620. newpoints = [],
  3621. tmpVec = new THREE.Vector3(),
  3622. sl = this.getLength();
  3623. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3624. for ( i = 1; i < this.points.length; i++ ) {
  3625. //tmpVec.copy( this.points[ i - 1 ] );
  3626. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3627. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3628. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3629. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3630. indexNext = i / ( this.points.length - 1 );
  3631. for ( j = 1; j < sampling - 1; j++ ) {
  3632. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3633. position = this.getPoint( index );
  3634. newpoints.push( tmpVec.copy( position ).clone() );
  3635. }
  3636. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3637. }
  3638. this.points = newpoints;
  3639. };
  3640. // Catmull-Rom
  3641. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3642. var v0 = ( p2 - p0 ) * 0.5,
  3643. v1 = ( p3 - p1 ) * 0.5;
  3644. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3645. };
  3646. };
  3647. /**
  3648. * @author bhouston / http://exocortex.com
  3649. * @author mrdoob / http://mrdoob.com/
  3650. */
  3651. THREE.Triangle = function ( a, b, c ) {
  3652. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3653. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3654. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3655. };
  3656. THREE.Triangle.normal = function() {
  3657. var v0 = new THREE.Vector3();
  3658. return function ( a, b, c, optionalTarget ) {
  3659. var result = optionalTarget || new THREE.Vector3();
  3660. result.subVectors( c, b );
  3661. v0.subVectors( a, b );
  3662. result.cross( v0 );
  3663. var resultLengthSq = result.lengthSq();
  3664. if( resultLengthSq > 0 ) {
  3665. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3666. }
  3667. return result.set( 0, 0, 0 );
  3668. };
  3669. }();
  3670. // static/instance method to calculate barycoordinates
  3671. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3672. THREE.Triangle.barycoordFromPoint = function() {
  3673. var v0 = new THREE.Vector3();
  3674. var v1 = new THREE.Vector3();
  3675. var v2 = new THREE.Vector3();
  3676. return function ( point, a, b, c, optionalTarget ) {
  3677. v0.subVectors( c, a );
  3678. v1.subVectors( b, a );
  3679. v2.subVectors( point, a );
  3680. var dot00 = v0.dot( v0 );
  3681. var dot01 = v0.dot( v1 );
  3682. var dot02 = v0.dot( v2 );
  3683. var dot11 = v1.dot( v1 );
  3684. var dot12 = v1.dot( v2 );
  3685. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3686. var result = optionalTarget || new THREE.Vector3();
  3687. // colinear or singular triangle
  3688. if( denom == 0 ) {
  3689. // arbitrary location outside of triangle?
  3690. // not sure if this is the best idea, maybe should be returning undefined
  3691. return result.set( -2, -1, -1 );
  3692. }
  3693. var invDenom = 1 / denom;
  3694. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3695. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3696. // barycoordinates must always sum to 1
  3697. return result.set( 1 - u - v, v, u );
  3698. };
  3699. }();
  3700. THREE.Triangle.containsPoint = function() {
  3701. var v1 = new THREE.Vector3();
  3702. return function ( point, a, b, c ) {
  3703. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3704. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3705. };
  3706. }();
  3707. THREE.Triangle.prototype = {
  3708. constructor: THREE.Triangle,
  3709. set: function ( a, b, c ) {
  3710. this.a.copy( a );
  3711. this.b.copy( b );
  3712. this.c.copy( c );
  3713. return this;
  3714. },
  3715. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3716. this.a.copy( points[i0] );
  3717. this.b.copy( points[i1] );
  3718. this.c.copy( points[i2] );
  3719. return this;
  3720. },
  3721. copy: function ( triangle ) {
  3722. this.a.copy( triangle.a );
  3723. this.b.copy( triangle.b );
  3724. this.c.copy( triangle.c );
  3725. return this;
  3726. },
  3727. area: function() {
  3728. var v0 = new THREE.Vector3();
  3729. var v1 = new THREE.Vector3();
  3730. return function () {
  3731. v0.subVectors( this.c, this.b );
  3732. v1.subVectors( this.a, this.b );
  3733. return v0.cross( v1 ).length() * 0.5;
  3734. };
  3735. }(),
  3736. midpoint: function ( optionalTarget ) {
  3737. var result = optionalTarget || new THREE.Vector3();
  3738. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3739. },
  3740. normal: function ( optionalTarget ) {
  3741. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3742. },
  3743. plane: function ( optionalTarget ) {
  3744. var result = optionalTarget || new THREE.Plane();
  3745. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3746. },
  3747. barycoordFromPoint: function ( point, optionalTarget ) {
  3748. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3749. },
  3750. containsPoint: function ( point ) {
  3751. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3752. },
  3753. equals: function ( triangle ) {
  3754. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3755. },
  3756. clone: function () {
  3757. return new THREE.Triangle().copy( this );
  3758. }
  3759. };
  3760. /**
  3761. * @author mrdoob / http://mrdoob.com/
  3762. */
  3763. THREE.Vertex = function ( v ) {
  3764. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3765. return v;
  3766. };
  3767. /**
  3768. * @author mrdoob / http://mrdoob.com/
  3769. */
  3770. THREE.UV = function ( u, v ) {
  3771. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3772. return new THREE.Vector2( u, v );
  3773. };
  3774. /**
  3775. * @author alteredq / http://alteredqualia.com/
  3776. */
  3777. THREE.Clock = function ( autoStart ) {
  3778. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3779. this.startTime = 0;
  3780. this.oldTime = 0;
  3781. this.elapsedTime = 0;
  3782. this.running = false;
  3783. };
  3784. THREE.Clock.prototype = {
  3785. constructor: THREE.Clock,
  3786. start: function () {
  3787. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  3788. ? self.performance.now()
  3789. : Date.now();
  3790. this.oldTime = this.startTime;
  3791. this.running = true;
  3792. },
  3793. stop: function () {
  3794. this.getElapsedTime();
  3795. this.running = false;
  3796. },
  3797. getElapsedTime: function () {
  3798. this.getDelta();
  3799. return this.elapsedTime;
  3800. },
  3801. getDelta: function () {
  3802. var diff = 0;
  3803. if ( this.autoStart && ! this.running ) {
  3804. this.start();
  3805. }
  3806. if ( this.running ) {
  3807. var newTime = self.performance !== undefined && self.performance.now !== undefined
  3808. ? self.performance.now()
  3809. : Date.now();
  3810. diff = 0.001 * ( newTime - this.oldTime );
  3811. this.oldTime = newTime;
  3812. this.elapsedTime += diff;
  3813. }
  3814. return diff;
  3815. }
  3816. };
  3817. /**
  3818. * https://github.com/mrdoob/eventdispatcher.js/
  3819. */
  3820. THREE.EventDispatcher = function () {}
  3821. THREE.EventDispatcher.prototype = {
  3822. constructor: THREE.EventDispatcher,
  3823. addEventListener: function ( type, listener ) {
  3824. if ( this._listeners === undefined ) this._listeners = {};
  3825. var listeners = this._listeners;
  3826. if ( listeners[ type ] === undefined ) {
  3827. listeners[ type ] = [];
  3828. }
  3829. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3830. listeners[ type ].push( listener );
  3831. }
  3832. },
  3833. hasEventListener: function ( type, listener ) {
  3834. if ( this._listeners === undefined ) return false;
  3835. var listeners = this._listeners;
  3836. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  3837. return true;
  3838. }
  3839. return false;
  3840. },
  3841. removeEventListener: function ( type, listener ) {
  3842. if ( this._listeners === undefined ) return;
  3843. var listeners = this._listeners;
  3844. var index = listeners[ type ].indexOf( listener );
  3845. if ( index !== - 1 ) {
  3846. listeners[ type ].splice( index, 1 );
  3847. }
  3848. },
  3849. dispatchEvent: function ( event ) {
  3850. if ( this._listeners === undefined ) return;
  3851. var listeners = this._listeners;
  3852. var listenerArray = listeners[ event.type ];
  3853. if ( listenerArray !== undefined ) {
  3854. event.target = this;
  3855. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  3856. listenerArray[ i ].call( this, event );
  3857. }
  3858. }
  3859. }
  3860. };
  3861. /**
  3862. * @author mrdoob / http://mrdoob.com/
  3863. * @author bhouston / http://exocortex.com/
  3864. */
  3865. ( function ( THREE ) {
  3866. THREE.Raycaster = function ( origin, direction, near, far ) {
  3867. this.ray = new THREE.Ray( origin, direction );
  3868. // normalized ray.direction required for accurate distance calculations
  3869. if ( this.ray.direction.lengthSq() > 0 ) {
  3870. this.ray.direction.normalize();
  3871. }
  3872. this.near = near || 0;
  3873. this.far = far || Infinity;
  3874. };
  3875. var sphere = new THREE.Sphere();
  3876. var localRay = new THREE.Ray();
  3877. var facePlane = new THREE.Plane();
  3878. var intersectPoint = new THREE.Vector3();
  3879. var matrixPosition = new THREE.Vector3();
  3880. var inverseMatrix = new THREE.Matrix4();
  3881. var descSort = function ( a, b ) {
  3882. return a.distance - b.distance;
  3883. };
  3884. var intersectObject = function ( object, raycaster, intersects ) {
  3885. if ( object instanceof THREE.Particle ) {
  3886. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3887. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  3888. if ( distance > object.scale.x ) {
  3889. return intersects;
  3890. }
  3891. intersects.push( {
  3892. distance: distance,
  3893. point: object.position,
  3894. face: null,
  3895. object: object
  3896. } );
  3897. } else if ( object instanceof THREE.LOD ) {
  3898. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3899. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  3900. intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );
  3901. } else if ( object instanceof THREE.Mesh ) {
  3902. var geometry = object.geometry;
  3903. // Checking boundingSphere distance to ray
  3904. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3905. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3906. sphere.set( matrixPosition, geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis() );
  3907. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  3908. return intersects;
  3909. }
  3910. var vertices = geometry.vertices;
  3911. if ( geometry instanceof THREE.BufferGeometry ) {
  3912. var material = object.material;
  3913. if ( material === undefined ) return intersects;
  3914. if ( geometry.dynamic === false ) return intersects;
  3915. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3916. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3917. var side = object.material.side;
  3918. var a, b, c;
  3919. var precision = raycaster.precision;
  3920. inverseMatrix.getInverse( object.matrixWorld );
  3921. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  3922. var fl;
  3923. var indexed = false;
  3924. if ( geometry.attributes.index ) {
  3925. indexed = true;
  3926. fl = geometry.attributes.index.numItems / 3;
  3927. } else {
  3928. fl = geometry.attributes.position.numItems / 9;
  3929. }
  3930. var vA = new THREE.Vector3();
  3931. var vB = new THREE.Vector3();
  3932. var vC = new THREE.Vector3();
  3933. var vCB = new THREE.Vector3();
  3934. var vAB = new THREE.Vector3();
  3935. for ( var oi = 0; oi < geometry.offsets.length; ++oi ) {
  3936. var start = geometry.offsets[ oi ].start;
  3937. var count = geometry.offsets[ oi ].count;
  3938. var index = geometry.offsets[ oi ].index;
  3939. for ( var i = start, il = start + count; i < il; i += 3 ) {
  3940. if ( indexed ) {
  3941. a = index + geometry.attributes.index.array[ i ];
  3942. b = index + geometry.attributes.index.array[ i + 1 ];
  3943. c = index + geometry.attributes.index.array[ i + 2 ];
  3944. } else {
  3945. a = index;
  3946. b = index + 1;
  3947. c = index + 2;
  3948. }
  3949. vA.set(
  3950. geometry.attributes.position.array[ a * 3 ],
  3951. geometry.attributes.position.array[ a * 3 + 1 ],
  3952. geometry.attributes.position.array[ a * 3 + 2 ]
  3953. );
  3954. vB.set(
  3955. geometry.attributes.position.array[ b * 3 ],
  3956. geometry.attributes.position.array[ b * 3 + 1 ],
  3957. geometry.attributes.position.array[ b * 3 + 2 ]
  3958. );
  3959. vC.set(
  3960. geometry.attributes.position.array[ c * 3 ],
  3961. geometry.attributes.position.array[ c * 3 + 1 ],
  3962. geometry.attributes.position.array[ c * 3 + 2 ]
  3963. );
  3964. facePlane.setFromCoplanarPoints( vA, vB, vC );
  3965. var planeDistance = localRay.distanceToPlane( facePlane );
  3966. // bail if the ray is too close to the plane
  3967. if ( planeDistance < precision ) continue;
  3968. // bail if the ray is behind the plane
  3969. if ( planeDistance === null ) continue;
  3970. // check if we hit the wrong side of a single sided face
  3971. side = material.side;
  3972. if ( side !== THREE.DoubleSide ) {
  3973. var planeSign = localRay.direction.dot( facePlane.normal );
  3974. if ( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) {
  3975. continue;
  3976. }
  3977. }
  3978. // this can be done using the planeDistance from localRay because
  3979. // localRay wasn't normalized, but ray was
  3980. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) {
  3981. continue;
  3982. }
  3983. // passing in intersectPoint avoids a copy
  3984. intersectPoint = localRay.at( planeDistance, intersectPoint );
  3985. if ( THREE.Triangle.containsPoint( intersectPoint, vA, vB, vC ) === false ) {
  3986. continue;
  3987. }
  3988. intersects.push( {
  3989. // this works because the original ray was normalized,
  3990. // and the transformed localRay wasn't
  3991. distance: planeDistance,
  3992. point: raycaster.ray.at( planeDistance ),
  3993. face: null,
  3994. faceIndex: null,
  3995. object: object
  3996. } );
  3997. }
  3998. }
  3999. } else if ( geometry instanceof THREE.Geometry ) {
  4000. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4001. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  4002. var side = object.material.side;
  4003. var a, b, c, d;
  4004. var precision = raycaster.precision;
  4005. inverseMatrix.getInverse( object.matrixWorld );
  4006. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4007. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  4008. var face = geometry.faces[ f ];
  4009. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  4010. if ( material === undefined ) continue;
  4011. facePlane.setFromNormalAndCoplanarPoint( face.normal, vertices[face.a] );
  4012. var planeDistance = localRay.distanceToPlane( facePlane );
  4013. // bail if the ray is too close to the plane
  4014. if ( planeDistance < precision ) continue;
  4015. // bail if the ray is behind the plane
  4016. if ( planeDistance === null ) continue;
  4017. // check if we hit the wrong side of a single sided face
  4018. side = material.side;
  4019. if ( side !== THREE.DoubleSide ) {
  4020. var planeSign = localRay.direction.dot( facePlane.normal );
  4021. if ( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) {
  4022. continue;
  4023. }
  4024. }
  4025. // this can be done using the planeDistance from localRay because localRay
  4026. // wasn't normalized, but ray was
  4027. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  4028. // passing in intersectPoint avoids a copy
  4029. intersectPoint = localRay.at( planeDistance, intersectPoint );
  4030. if ( face instanceof THREE.Face3 ) {
  4031. a = vertices[ face.a ];
  4032. b = vertices[ face.b ];
  4033. c = vertices[ face.c ];
  4034. if ( THREE.Triangle.containsPoint( intersectPoint, a, b, c ) === false ) {
  4035. continue;
  4036. }
  4037. } else if ( face instanceof THREE.Face4 ) {
  4038. a = vertices[ face.a ];
  4039. b = vertices[ face.b ];
  4040. c = vertices[ face.c ];
  4041. d = vertices[ face.d ];
  4042. if ( THREE.Triangle.containsPoint( intersectPoint, a, b, d ) === false &&
  4043. THREE.Triangle.containsPoint( intersectPoint, b, c, d ) === false ) {
  4044. continue;
  4045. }
  4046. } else {
  4047. // This is added because if we call out of this if/else group when
  4048. // none of the cases match it will add a point to the intersection
  4049. // list erroneously.
  4050. throw Error( "face type not supported" );
  4051. }
  4052. intersects.push( {
  4053. // this works because the original ray was normalized,
  4054. // and the transformed localRay wasn't
  4055. distance: planeDistance,
  4056. point: raycaster.ray.at( planeDistance ),
  4057. face: face,
  4058. faceIndex: f,
  4059. object: object
  4060. } );
  4061. }
  4062. }
  4063. } else if ( object instanceof THREE.Line ) {
  4064. var precision = raycaster.linePrecision;
  4065. var precisionSq = precision * precision;
  4066. var geometry = object.geometry;
  4067. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4068. // Checking boundingSphere distance to ray
  4069. matrixPosition.getPositionFromMatrix(object.matrixWorld);
  4070. sphere.set( matrixPosition, geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis() );
  4071. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4072. return intersects;
  4073. }
  4074. inverseMatrix.getInverse( object.matrixWorld );
  4075. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4076. localRay.direction.normalize(); // for scale matrix
  4077. var vertices = geometry.vertices;
  4078. var nbVertices = vertices.length;
  4079. var interSegment = new THREE.Vector3();
  4080. var interRay = new THREE.Vector3();
  4081. var step = object.type === THREE.LineStrip ? 1 : 2;
  4082. for ( var i = 0; i < nbVertices - 1; i = i + step ) {
  4083. localRay.distanceToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  4084. interSegment.applyMatrix4( object.matrixWorld );
  4085. interRay.applyMatrix4( object.matrixWorld );
  4086. if ( interRay.distanceToSquared( interSegment ) <= precisionSq ) {
  4087. var distance = raycaster.ray.origin.distanceTo( interRay );
  4088. if ( raycaster.near <= distance && distance <= raycaster.far ) {
  4089. intersects.push( {
  4090. distance: distance,
  4091. point: interSegment.clone(),
  4092. face: null,
  4093. faceIndex: null,
  4094. object: object
  4095. } );
  4096. }
  4097. }
  4098. }
  4099. }
  4100. };
  4101. var intersectDescendants = function ( object, raycaster, intersects ) {
  4102. var descendants = object.getDescendants();
  4103. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  4104. intersectObject( descendants[ i ], raycaster, intersects );
  4105. }
  4106. };
  4107. //
  4108. THREE.Raycaster.prototype.precision = 0.0001;
  4109. THREE.Raycaster.prototype.linePrecision = 1;
  4110. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  4111. this.ray.set( origin, direction );
  4112. // normalized ray.direction required for accurate distance calculations
  4113. if ( this.ray.direction.length() > 0 ) {
  4114. this.ray.direction.normalize();
  4115. }
  4116. };
  4117. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  4118. var intersects = [];
  4119. if ( recursive === true ) {
  4120. intersectDescendants( object, this, intersects );
  4121. }
  4122. intersectObject( object, this, intersects );
  4123. intersects.sort( descSort );
  4124. return intersects;
  4125. };
  4126. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  4127. var intersects = [];
  4128. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4129. intersectObject( objects[ i ], this, intersects );
  4130. if ( recursive === true ) {
  4131. intersectDescendants( objects[ i ], this, intersects );
  4132. }
  4133. }
  4134. intersects.sort( descSort );
  4135. return intersects;
  4136. };
  4137. }( THREE ) );
  4138. /**
  4139. * @author mrdoob / http://mrdoob.com/
  4140. * @author mikael emtinger / http://gomo.se/
  4141. * @author alteredq / http://alteredqualia.com/
  4142. * @author WestLangley / http://github.com/WestLangley
  4143. */
  4144. THREE.Object3D = function () {
  4145. this.id = THREE.Object3DIdCount ++;
  4146. this.uuid = THREE.Math.generateUUID();
  4147. this.name = '';
  4148. this.parent = undefined;
  4149. this.children = [];
  4150. this.up = new THREE.Vector3( 0, 1, 0 );
  4151. this.position = new THREE.Vector3();
  4152. this.rotation = new THREE.Euler();
  4153. this.quaternion = new THREE.Quaternion();
  4154. this.scale = new THREE.Vector3( 1, 1, 1 );
  4155. // keep rotation and quaternion in sync
  4156. this.rotation._quaternion = this.quaternion;
  4157. this.quaternion._euler = this.rotation;
  4158. this.renderDepth = null;
  4159. this.rotationAutoUpdate = true;
  4160. this.matrix = new THREE.Matrix4();
  4161. this.matrixWorld = new THREE.Matrix4();
  4162. this.matrixAutoUpdate = true;
  4163. this.matrixWorldNeedsUpdate = true;
  4164. this.visible = true;
  4165. this.castShadow = false;
  4166. this.receiveShadow = false;
  4167. this.frustumCulled = true;
  4168. this.userData = {};
  4169. };
  4170. THREE.Object3D.prototype = {
  4171. constructor: THREE.Object3D,
  4172. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  4173. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  4174. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  4175. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  4176. get eulerOrder () {
  4177. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4178. return this.rotation.order;
  4179. },
  4180. set eulerOrder ( value ) {
  4181. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4182. this.rotation.order = value;
  4183. },
  4184. get useQuaternion () {
  4185. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4186. },
  4187. set useQuaternion ( value ) {
  4188. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4189. },
  4190. applyMatrix: function () {
  4191. var m1 = new THREE.Matrix4();
  4192. return function ( matrix ) {
  4193. this.matrix.multiplyMatrices( matrix, this.matrix );
  4194. this.position.getPositionFromMatrix( this.matrix );
  4195. this.scale.getScaleFromMatrix( this.matrix );
  4196. m1.extractRotation( this.matrix );
  4197. this.quaternion.setFromRotationMatrix( m1 );
  4198. }
  4199. }(),
  4200. setRotationFromAxisAngle: function ( axis, angle ) {
  4201. // assumes axis is normalized
  4202. this.quaternion.setFromAxisAngle( axis, angle );
  4203. },
  4204. setRotationFromEuler: function ( euler ) {
  4205. this.quaternion.setFromEuler( euler, true );
  4206. },
  4207. setRotationFromMatrix: function ( m ) {
  4208. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4209. this.quaternion.setFromRotationMatrix( m );
  4210. },
  4211. setRotationFromQuaternion: function ( q ) {
  4212. // assumes q is normalized
  4213. this.quaternion.copy( q );
  4214. },
  4215. rotateOnAxis: function() {
  4216. // rotate object on axis in object space
  4217. // axis is assumed to be normalized
  4218. var q1 = new THREE.Quaternion();
  4219. return function ( axis, angle ) {
  4220. q1.setFromAxisAngle( axis, angle );
  4221. this.quaternion.multiply( q1 );
  4222. return this;
  4223. }
  4224. }(),
  4225. rotateX: function () {
  4226. var v1 = new THREE.Vector3( 1, 0, 0 );
  4227. return function ( angle ) {
  4228. return this.rotateOnAxis( v1, angle );
  4229. };
  4230. }(),
  4231. rotateY: function () {
  4232. var v1 = new THREE.Vector3( 0, 1, 0 );
  4233. return function ( angle ) {
  4234. return this.rotateOnAxis( v1, angle );
  4235. };
  4236. }(),
  4237. rotateZ: function () {
  4238. var v1 = new THREE.Vector3( 0, 0, 1 );
  4239. return function ( angle ) {
  4240. return this.rotateOnAxis( v1, angle );
  4241. };
  4242. }(),
  4243. translateOnAxis: function () {
  4244. // translate object by distance along axis in object space
  4245. // axis is assumed to be normalized
  4246. var v1 = new THREE.Vector3();
  4247. return function ( axis, distance ) {
  4248. v1.copy( axis );
  4249. v1.applyQuaternion( this.quaternion );
  4250. this.position.add( v1.multiplyScalar( distance ) );
  4251. return this;
  4252. }
  4253. }(),
  4254. translate: function ( distance, axis ) {
  4255. console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
  4256. return this.translateOnAxis( axis, distance );
  4257. },
  4258. translateX: function () {
  4259. var v1 = new THREE.Vector3( 1, 0, 0 );
  4260. return function ( distance ) {
  4261. return this.translateOnAxis( v1, distance );
  4262. };
  4263. }(),
  4264. translateY: function () {
  4265. var v1 = new THREE.Vector3( 0, 1, 0 );
  4266. return function ( distance ) {
  4267. return this.translateOnAxis( v1, distance );
  4268. };
  4269. }(),
  4270. translateZ: function () {
  4271. var v1 = new THREE.Vector3( 0, 0, 1 );
  4272. return function ( distance ) {
  4273. return this.translateOnAxis( v1, distance );
  4274. };
  4275. }(),
  4276. localToWorld: function ( vector ) {
  4277. return vector.applyMatrix4( this.matrixWorld );
  4278. },
  4279. worldToLocal: function () {
  4280. var m1 = new THREE.Matrix4();
  4281. return function ( vector ) {
  4282. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4283. };
  4284. }(),
  4285. lookAt: function () {
  4286. // This routine does not support objects with rotated and/or translated parent(s)
  4287. var m1 = new THREE.Matrix4();
  4288. return function ( vector ) {
  4289. m1.lookAt( vector, this.position, this.up );
  4290. this.quaternion.setFromRotationMatrix( m1 );
  4291. };
  4292. }(),
  4293. add: function ( object ) {
  4294. if ( object === this ) {
  4295. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  4296. return;
  4297. }
  4298. if ( object instanceof THREE.Object3D ) {
  4299. if ( object.parent !== undefined ) {
  4300. object.parent.remove( object );
  4301. }
  4302. object.parent = this;
  4303. object.dispatchEvent( { type: 'added' } );
  4304. this.children.push( object );
  4305. // add to scene
  4306. var scene = this;
  4307. while ( scene.parent !== undefined ) {
  4308. scene = scene.parent;
  4309. }
  4310. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4311. scene.__addObject( object );
  4312. }
  4313. }
  4314. },
  4315. remove: function ( object ) {
  4316. var index = this.children.indexOf( object );
  4317. if ( index !== - 1 ) {
  4318. object.parent = undefined;
  4319. object.dispatchEvent( { type: 'removed' } );
  4320. this.children.splice( index, 1 );
  4321. // remove from scene
  4322. var scene = this;
  4323. while ( scene.parent !== undefined ) {
  4324. scene = scene.parent;
  4325. }
  4326. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4327. scene.__removeObject( object );
  4328. }
  4329. }
  4330. },
  4331. traverse: function ( callback ) {
  4332. callback( this );
  4333. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4334. this.children[ i ].traverse( callback );
  4335. }
  4336. },
  4337. getObjectById: function ( id, recursive ) {
  4338. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4339. var child = this.children[ i ];
  4340. if ( child.id === id ) {
  4341. return child;
  4342. }
  4343. if ( recursive === true ) {
  4344. child = child.getObjectById( id, recursive );
  4345. if ( child !== undefined ) {
  4346. return child;
  4347. }
  4348. }
  4349. }
  4350. return undefined;
  4351. },
  4352. getObjectByName: function ( name, recursive ) {
  4353. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4354. var child = this.children[ i ];
  4355. if ( child.name === name ) {
  4356. return child;
  4357. }
  4358. if ( recursive === true ) {
  4359. child = child.getObjectByName( name, recursive );
  4360. if ( child !== undefined ) {
  4361. return child;
  4362. }
  4363. }
  4364. }
  4365. return undefined;
  4366. },
  4367. getChildByName: function ( name, recursive ) {
  4368. console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
  4369. return this.getObjectByName( name, recursive );
  4370. },
  4371. getDescendants: function ( array ) {
  4372. if ( array === undefined ) array = [];
  4373. Array.prototype.push.apply( array, this.children );
  4374. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4375. this.children[ i ].getDescendants( array );
  4376. }
  4377. return array;
  4378. },
  4379. updateMatrix: function () {
  4380. this.matrix.compose( this.position, this.quaternion, this.scale );
  4381. this.matrixWorldNeedsUpdate = true;
  4382. },
  4383. updateMatrixWorld: function ( force ) {
  4384. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4385. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4386. if ( this.parent === undefined ) {
  4387. this.matrixWorld.copy( this.matrix );
  4388. } else {
  4389. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4390. }
  4391. this.matrixWorldNeedsUpdate = false;
  4392. force = true;
  4393. }
  4394. // update children
  4395. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4396. this.children[ i ].updateMatrixWorld( force );
  4397. }
  4398. },
  4399. clone: function ( object, recursive ) {
  4400. if ( object === undefined ) object = new THREE.Object3D();
  4401. if ( recursive === undefined ) recursive = true;
  4402. object.name = this.name;
  4403. object.up.copy( this.up );
  4404. object.position.copy( this.position );
  4405. object.quaternion.copy( this.quaternion );
  4406. object.scale.copy( this.scale );
  4407. object.renderDepth = this.renderDepth;
  4408. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4409. object.matrix.copy( this.matrix );
  4410. object.matrixWorld.copy( this.matrixWorld );
  4411. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4412. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4413. object.visible = this.visible;
  4414. object.castShadow = this.castShadow;
  4415. object.receiveShadow = this.receiveShadow;
  4416. object.frustumCulled = this.frustumCulled;
  4417. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4418. if ( recursive === true ) {
  4419. for ( var i = 0; i < this.children.length; i ++ ) {
  4420. var child = this.children[ i ];
  4421. object.add( child.clone() );
  4422. }
  4423. }
  4424. return object;
  4425. }
  4426. };
  4427. THREE.Object3DIdCount = 0;
  4428. /**
  4429. * @author mrdoob / http://mrdoob.com/
  4430. * @author supereggbert / http://www.paulbrunt.co.uk/
  4431. * @author julianwa / https://github.com/julianwa
  4432. */
  4433. THREE.Projector = function () {
  4434. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  4435. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  4436. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  4437. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  4438. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  4439. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  4440. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  4441. _vector3 = new THREE.Vector3(),
  4442. _vector4 = new THREE.Vector4(),
  4443. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  4444. _boundingBox = new THREE.Box3(),
  4445. _points3 = new Array( 3 ),
  4446. _points4 = new Array( 4 ),
  4447. _viewMatrix = new THREE.Matrix4(),
  4448. _viewProjectionMatrix = new THREE.Matrix4(),
  4449. _modelMatrix,
  4450. _modelViewProjectionMatrix = new THREE.Matrix4(),
  4451. _normalMatrix = new THREE.Matrix3(),
  4452. _normalViewMatrix = new THREE.Matrix3(),
  4453. _centroid = new THREE.Vector3(),
  4454. _frustum = new THREE.Frustum(),
  4455. _clippedVertex1PositionScreen = new THREE.Vector4(),
  4456. _clippedVertex2PositionScreen = new THREE.Vector4();
  4457. this.projectVector = function ( vector, camera ) {
  4458. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4459. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  4460. return vector.applyProjection( _viewProjectionMatrix );
  4461. };
  4462. this.unprojectVector = function ( vector, camera ) {
  4463. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  4464. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, camera.projectionMatrixInverse );
  4465. return vector.applyProjection( _viewProjectionMatrix );
  4466. };
  4467. this.pickingRay = function ( vector, camera ) {
  4468. // set two vectors with opposing z values
  4469. vector.z = -1.0;
  4470. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4471. this.unprojectVector( vector, camera );
  4472. this.unprojectVector( end, camera );
  4473. // find direction from vector to end
  4474. end.sub( vector ).normalize();
  4475. return new THREE.Raycaster( vector, end );
  4476. };
  4477. var getObject = function ( object ) {
  4478. _object = getNextObjectInPool();
  4479. _object.id = object.id;
  4480. _object.object = object;
  4481. if ( object.renderDepth !== null ) {
  4482. _object.z = object.renderDepth;
  4483. } else {
  4484. _vector3.getPositionFromMatrix( object.matrixWorld );
  4485. _vector3.applyProjection( _viewProjectionMatrix );
  4486. _object.z = _vector3.z;
  4487. }
  4488. return _object;
  4489. };
  4490. var projectObject = function ( object ) {
  4491. if ( object.visible === false ) return;
  4492. if ( object instanceof THREE.Light ) {
  4493. _renderData.lights.push( object );
  4494. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  4495. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4496. _renderData.objects.push( getObject( object ) );
  4497. }
  4498. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  4499. _renderData.sprites.push( getObject( object ) );
  4500. }
  4501. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  4502. projectObject( object.children[ i ] );
  4503. }
  4504. };
  4505. var projectGraph = function ( root, sortObjects ) {
  4506. _objectCount = 0;
  4507. _renderData.objects.length = 0;
  4508. _renderData.sprites.length = 0;
  4509. _renderData.lights.length = 0;
  4510. projectObject( root );
  4511. if ( sortObjects === true ) {
  4512. _renderData.objects.sort( painterSort );
  4513. }
  4514. };
  4515. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4516. var visible = false,
  4517. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  4518. geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, uvs,
  4519. v1, v2, v3, v4, isFaceMaterial, objectMaterials;
  4520. _face3Count = 0;
  4521. _face4Count = 0;
  4522. _lineCount = 0;
  4523. _particleCount = 0;
  4524. _renderData.elements.length = 0;
  4525. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4526. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4527. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4528. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4529. _normalViewMatrix.getNormalMatrix( _viewMatrix );
  4530. _frustum.setFromMatrix( _viewProjectionMatrix );
  4531. projectGraph( scene, sortObjects );
  4532. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4533. object = _renderData.objects[ o ].object;
  4534. _modelMatrix = object.matrixWorld;
  4535. _vertexCount = 0;
  4536. if ( object instanceof THREE.Mesh ) {
  4537. geometry = object.geometry;
  4538. vertices = geometry.vertices;
  4539. faces = geometry.faces;
  4540. faceVertexUvs = geometry.faceVertexUvs;
  4541. _normalMatrix.getNormalMatrix( _modelMatrix );
  4542. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4543. objectMaterials = isFaceMaterial === true ? object.material : null;
  4544. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  4545. _vertex = getNextVertexInPool();
  4546. _vertex.positionWorld.copy( vertices[ v ] ).applyMatrix4( _modelMatrix );
  4547. _vertex.positionScreen.copy( _vertex.positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4548. var invW = 1 / _vertex.positionScreen.w;
  4549. _vertex.positionScreen.x *= invW;
  4550. _vertex.positionScreen.y *= invW;
  4551. _vertex.positionScreen.z *= invW;
  4552. _vertex.visible = ! ( _vertex.positionScreen.x < -1 || _vertex.positionScreen.x > 1 ||
  4553. _vertex.positionScreen.y < -1 || _vertex.positionScreen.y > 1 ||
  4554. _vertex.positionScreen.z < -1 || _vertex.positionScreen.z > 1 );
  4555. }
  4556. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  4557. face = faces[ f ];
  4558. var material = isFaceMaterial === true
  4559. ? objectMaterials.materials[ face.materialIndex ]
  4560. : object.material;
  4561. if ( material === undefined ) continue;
  4562. var side = material.side;
  4563. if ( face instanceof THREE.Face3 ) {
  4564. v1 = _vertexPool[ face.a ];
  4565. v2 = _vertexPool[ face.b ];
  4566. v3 = _vertexPool[ face.c ];
  4567. _points3[ 0 ] = v1.positionScreen;
  4568. _points3[ 1 ] = v2.positionScreen;
  4569. _points3[ 2 ] = v3.positionScreen;
  4570. if ( v1.visible === true || v2.visible === true || v3.visible === true ||
  4571. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
  4572. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4573. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4574. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4575. _face = getNextFace3InPool();
  4576. _face.id = object.id;
  4577. _face.v1.copy( v1 );
  4578. _face.v2.copy( v2 );
  4579. _face.v3.copy( v3 );
  4580. } else {
  4581. continue;
  4582. }
  4583. } else {
  4584. continue;
  4585. }
  4586. } else if ( face instanceof THREE.Face4 ) {
  4587. v1 = _vertexPool[ face.a ];
  4588. v2 = _vertexPool[ face.b ];
  4589. v3 = _vertexPool[ face.c ];
  4590. v4 = _vertexPool[ face.d ];
  4591. _points4[ 0 ] = v1.positionScreen;
  4592. _points4[ 1 ] = v2.positionScreen;
  4593. _points4[ 2 ] = v3.positionScreen;
  4594. _points4[ 3 ] = v4.positionScreen;
  4595. if ( v1.visible === true || v2.visible === true || v3.visible === true || v4.visible === true ||
  4596. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points4 ) ) ) {
  4597. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4598. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  4599. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  4600. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  4601. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4602. _face = getNextFace4InPool();
  4603. _face.id = object.id;
  4604. _face.v1.copy( v1 );
  4605. _face.v2.copy( v2 );
  4606. _face.v3.copy( v3 );
  4607. _face.v4.copy( v4 );
  4608. } else {
  4609. continue;
  4610. }
  4611. } else {
  4612. continue;
  4613. }
  4614. }
  4615. _face.normalModel.copy( face.normal );
  4616. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4617. _face.normalModel.negate();
  4618. }
  4619. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4620. _face.normalModelView.copy( _face.normalModel ).applyMatrix3( _normalViewMatrix );
  4621. _face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix );
  4622. faceVertexNormals = face.vertexNormals;
  4623. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  4624. var normalModel = _face.vertexNormalsModel[ n ];
  4625. normalModel.copy( faceVertexNormals[ n ] );
  4626. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4627. normalModel.negate();
  4628. }
  4629. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4630. var normalModelView = _face.vertexNormalsModelView[ n ];
  4631. normalModelView.copy( normalModel ).applyMatrix3( _normalViewMatrix );
  4632. }
  4633. _face.vertexNormalsLength = faceVertexNormals.length;
  4634. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  4635. uvs = faceVertexUvs[ c ][ f ];
  4636. if ( uvs === undefined ) continue;
  4637. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  4638. _face.uvs[ c ][ u ] = uvs[ u ];
  4639. }
  4640. }
  4641. _face.color = face.color;
  4642. _face.material = material;
  4643. _centroid.copy( _face.centroidModel ).applyProjection( _viewProjectionMatrix );
  4644. _face.z = _centroid.z;
  4645. _renderData.elements.push( _face );
  4646. }
  4647. } else if ( object instanceof THREE.Line ) {
  4648. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  4649. vertices = object.geometry.vertices;
  4650. v1 = getNextVertexInPool();
  4651. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  4652. // Handle LineStrip and LinePieces
  4653. var step = object.type === THREE.LinePieces ? 2 : 1;
  4654. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  4655. v1 = getNextVertexInPool();
  4656. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  4657. if ( ( v + 1 ) % step > 0 ) continue;
  4658. v2 = _vertexPool[ _vertexCount - 2 ];
  4659. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  4660. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  4661. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  4662. // Perform the perspective divide
  4663. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  4664. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  4665. _line = getNextLineInPool();
  4666. _line.id = object.id;
  4667. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  4668. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  4669. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  4670. _line.material = object.material;
  4671. if ( object.material.vertexColors === THREE.VertexColors ) {
  4672. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  4673. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  4674. }
  4675. _renderData.elements.push( _line );
  4676. }
  4677. }
  4678. }
  4679. }
  4680. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  4681. object = _renderData.sprites[ o ].object;
  4682. _modelMatrix = object.matrixWorld;
  4683. if ( object instanceof THREE.Particle ) {
  4684. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  4685. _vector4.applyMatrix4( _viewProjectionMatrix );
  4686. var invW = 1 / _vector4.w;
  4687. _vector4.z *= invW;
  4688. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  4689. _particle = getNextParticleInPool();
  4690. _particle.id = object.id;
  4691. _particle.x = _vector4.x * invW;
  4692. _particle.y = _vector4.y * invW;
  4693. _particle.z = _vector4.z;
  4694. _particle.object = object;
  4695. _particle.rotation = object.rotation.z;
  4696. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  4697. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  4698. _particle.material = object.material;
  4699. _renderData.elements.push( _particle );
  4700. }
  4701. }
  4702. }
  4703. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4704. return _renderData;
  4705. };
  4706. // Pools
  4707. function getNextObjectInPool() {
  4708. if ( _objectCount === _objectPoolLength ) {
  4709. var object = new THREE.RenderableObject();
  4710. _objectPool.push( object );
  4711. _objectPoolLength ++;
  4712. _objectCount ++;
  4713. return object;
  4714. }
  4715. return _objectPool[ _objectCount ++ ];
  4716. }
  4717. function getNextVertexInPool() {
  4718. if ( _vertexCount === _vertexPoolLength ) {
  4719. var vertex = new THREE.RenderableVertex();
  4720. _vertexPool.push( vertex );
  4721. _vertexPoolLength ++;
  4722. _vertexCount ++;
  4723. return vertex;
  4724. }
  4725. return _vertexPool[ _vertexCount ++ ];
  4726. }
  4727. function getNextFace3InPool() {
  4728. if ( _face3Count === _face3PoolLength ) {
  4729. var face = new THREE.RenderableFace3();
  4730. _face3Pool.push( face );
  4731. _face3PoolLength ++;
  4732. _face3Count ++;
  4733. return face;
  4734. }
  4735. return _face3Pool[ _face3Count ++ ];
  4736. }
  4737. function getNextFace4InPool() {
  4738. if ( _face4Count === _face4PoolLength ) {
  4739. var face = new THREE.RenderableFace4();
  4740. _face4Pool.push( face );
  4741. _face4PoolLength ++;
  4742. _face4Count ++;
  4743. return face;
  4744. }
  4745. return _face4Pool[ _face4Count ++ ];
  4746. }
  4747. function getNextLineInPool() {
  4748. if ( _lineCount === _linePoolLength ) {
  4749. var line = new THREE.RenderableLine();
  4750. _linePool.push( line );
  4751. _linePoolLength ++;
  4752. _lineCount ++
  4753. return line;
  4754. }
  4755. return _linePool[ _lineCount ++ ];
  4756. }
  4757. function getNextParticleInPool() {
  4758. if ( _particleCount === _particlePoolLength ) {
  4759. var particle = new THREE.RenderableParticle();
  4760. _particlePool.push( particle );
  4761. _particlePoolLength ++;
  4762. _particleCount ++
  4763. return particle;
  4764. }
  4765. return _particlePool[ _particleCount ++ ];
  4766. }
  4767. //
  4768. function painterSort( a, b ) {
  4769. if ( a.z !== b.z ) {
  4770. return b.z - a.z;
  4771. } else if ( a.id !== b.id ) {
  4772. return a.id - b.id;
  4773. } else {
  4774. return 0;
  4775. }
  4776. }
  4777. function clipLine( s1, s2 ) {
  4778. var alpha1 = 0, alpha2 = 1,
  4779. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4780. // Z = -1 and Z = +1, respectively.
  4781. bc1near = s1.z + s1.w,
  4782. bc2near = s2.z + s2.w,
  4783. bc1far = - s1.z + s1.w,
  4784. bc2far = - s2.z + s2.w;
  4785. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4786. // Both vertices lie entirely within all clip planes.
  4787. return true;
  4788. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  4789. // Both vertices lie entirely outside one of the clip planes.
  4790. return false;
  4791. } else {
  4792. // The line segment spans at least one clip plane.
  4793. if ( bc1near < 0 ) {
  4794. // v1 lies outside the near plane, v2 inside
  4795. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4796. } else if ( bc2near < 0 ) {
  4797. // v2 lies outside the near plane, v1 inside
  4798. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4799. }
  4800. if ( bc1far < 0 ) {
  4801. // v1 lies outside the far plane, v2 inside
  4802. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4803. } else if ( bc2far < 0 ) {
  4804. // v2 lies outside the far plane, v2 inside
  4805. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4806. }
  4807. if ( alpha2 < alpha1 ) {
  4808. // The line segment spans two boundaries, but is outside both of them.
  4809. // (This can't happen when we're only clipping against just near/far but good
  4810. // to leave the check here for future usage if other clip planes are added.)
  4811. return false;
  4812. } else {
  4813. // Update the s1 and s2 vertices to match the clipped line segment.
  4814. s1.lerp( s2, alpha1 );
  4815. s2.lerp( s1, 1 - alpha2 );
  4816. return true;
  4817. }
  4818. }
  4819. }
  4820. };
  4821. /**
  4822. * @author mrdoob / http://mrdoob.com/
  4823. * @author alteredq / http://alteredqualia.com/
  4824. */
  4825. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4826. this.a = a;
  4827. this.b = b;
  4828. this.c = c;
  4829. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4830. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4831. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4832. this.vertexColors = color instanceof Array ? color : [];
  4833. this.vertexTangents = [];
  4834. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4835. this.centroid = new THREE.Vector3();
  4836. };
  4837. THREE.Face3.prototype = {
  4838. constructor: THREE.Face3,
  4839. clone: function () {
  4840. var face = new THREE.Face3( this.a, this.b, this.c );
  4841. face.normal.copy( this.normal );
  4842. face.color.copy( this.color );
  4843. face.centroid.copy( this.centroid );
  4844. face.materialIndex = this.materialIndex;
  4845. var i, il;
  4846. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4847. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4848. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4849. return face;
  4850. }
  4851. };
  4852. /**
  4853. * @author mrdoob / http://mrdoob.com/
  4854. * @author alteredq / http://alteredqualia.com/
  4855. */
  4856. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4857. this.a = a;
  4858. this.b = b;
  4859. this.c = c;
  4860. this.d = d;
  4861. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4862. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4863. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4864. this.vertexColors = color instanceof Array ? color : [];
  4865. this.vertexTangents = [];
  4866. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4867. this.centroid = new THREE.Vector3();
  4868. };
  4869. THREE.Face4.prototype = {
  4870. constructor: THREE.Face4,
  4871. clone: function () {
  4872. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  4873. face.normal.copy( this.normal );
  4874. face.color.copy( this.color );
  4875. face.centroid.copy( this.centroid );
  4876. face.materialIndex = this.materialIndex;
  4877. var i, il;
  4878. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4879. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4880. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4881. return face;
  4882. }
  4883. };
  4884. /**
  4885. * @author mrdoob / http://mrdoob.com/
  4886. * @author kile / http://kile.stravaganza.org/
  4887. * @author alteredq / http://alteredqualia.com/
  4888. * @author mikael emtinger / http://gomo.se/
  4889. * @author zz85 / http://www.lab4games.net/zz85/blog
  4890. * @author bhouston / http://exocortex.com
  4891. */
  4892. THREE.Geometry = function () {
  4893. this.id = THREE.GeometryIdCount ++;
  4894. this.uuid = THREE.Math.generateUUID();
  4895. this.name = '';
  4896. this.vertices = [];
  4897. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  4898. this.normals = []; // one-to-one vertex normals, used in Ribbon
  4899. this.faces = [];
  4900. this.faceUvs = [[]];
  4901. this.faceVertexUvs = [[]];
  4902. this.morphTargets = [];
  4903. this.morphColors = [];
  4904. this.morphNormals = [];
  4905. this.skinWeights = [];
  4906. this.skinIndices = [];
  4907. this.lineDistances = [];
  4908. this.boundingBox = null;
  4909. this.boundingSphere = null;
  4910. this.hasTangents = false;
  4911. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  4912. // update flags
  4913. this.verticesNeedUpdate = false;
  4914. this.elementsNeedUpdate = false;
  4915. this.uvsNeedUpdate = false;
  4916. this.normalsNeedUpdate = false;
  4917. this.tangentsNeedUpdate = false;
  4918. this.colorsNeedUpdate = false;
  4919. this.lineDistancesNeedUpdate = false;
  4920. this.buffersNeedUpdate = false;
  4921. };
  4922. THREE.Geometry.prototype = {
  4923. constructor: THREE.Geometry,
  4924. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  4925. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  4926. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  4927. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  4928. applyMatrix: function ( matrix ) {
  4929. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  4930. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  4931. var vertex = this.vertices[ i ];
  4932. vertex.applyMatrix4( matrix );
  4933. }
  4934. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  4935. var face = this.faces[ i ];
  4936. face.normal.applyMatrix3( normalMatrix ).normalize();
  4937. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  4938. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  4939. }
  4940. face.centroid.applyMatrix4( matrix );
  4941. }
  4942. if ( this.boundingBox instanceof THREE.Box3 ) {
  4943. this.computeBoundingBox();
  4944. }
  4945. if ( this.boundingSphere instanceof THREE.Sphere ) {
  4946. this.computeBoundingSphere();
  4947. }
  4948. },
  4949. computeCentroids: function () {
  4950. var f, fl, face;
  4951. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4952. face = this.faces[ f ];
  4953. face.centroid.set( 0, 0, 0 );
  4954. if ( face instanceof THREE.Face3 ) {
  4955. face.centroid.add( this.vertices[ face.a ] );
  4956. face.centroid.add( this.vertices[ face.b ] );
  4957. face.centroid.add( this.vertices[ face.c ] );
  4958. face.centroid.divideScalar( 3 );
  4959. } else if ( face instanceof THREE.Face4 ) {
  4960. face.centroid.add( this.vertices[ face.a ] );
  4961. face.centroid.add( this.vertices[ face.b ] );
  4962. face.centroid.add( this.vertices[ face.c ] );
  4963. face.centroid.add( this.vertices[ face.d ] );
  4964. face.centroid.divideScalar( 4 );
  4965. }
  4966. }
  4967. },
  4968. computeFaceNormals: function () {
  4969. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  4970. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4971. var face = this.faces[ f ];
  4972. var vA = this.vertices[ face.a ];
  4973. var vB = this.vertices[ face.b ];
  4974. var vC = this.vertices[ face.c ];
  4975. cb.subVectors( vC, vB );
  4976. ab.subVectors( vA, vB );
  4977. cb.cross( ab );
  4978. cb.normalize();
  4979. face.normal.copy( cb );
  4980. }
  4981. },
  4982. computeVertexNormals: function ( areaWeighted ) {
  4983. var v, vl, f, fl, face, vertices;
  4984. // create internal buffers for reuse when calling this method repeatedly
  4985. // (otherwise memory allocation / deallocation every frame is big resource hog)
  4986. if ( this.__tmpVertices === undefined ) {
  4987. this.__tmpVertices = new Array( this.vertices.length );
  4988. vertices = this.__tmpVertices;
  4989. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4990. vertices[ v ] = new THREE.Vector3();
  4991. }
  4992. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4993. face = this.faces[ f ];
  4994. if ( face instanceof THREE.Face3 ) {
  4995. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4996. } else if ( face instanceof THREE.Face4 ) {
  4997. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4998. }
  4999. }
  5000. } else {
  5001. vertices = this.__tmpVertices;
  5002. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5003. vertices[ v ].set( 0, 0, 0 );
  5004. }
  5005. }
  5006. if ( areaWeighted ) {
  5007. // vertex normals weighted by triangle areas
  5008. // http://www.iquilezles.org/www/articles/normals/normals.htm
  5009. var vA, vB, vC, vD;
  5010. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  5011. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  5012. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5013. face = this.faces[ f ];
  5014. if ( face instanceof THREE.Face3 ) {
  5015. vA = this.vertices[ face.a ];
  5016. vB = this.vertices[ face.b ];
  5017. vC = this.vertices[ face.c ];
  5018. cb.subVectors( vC, vB );
  5019. ab.subVectors( vA, vB );
  5020. cb.cross( ab );
  5021. vertices[ face.a ].add( cb );
  5022. vertices[ face.b ].add( cb );
  5023. vertices[ face.c ].add( cb );
  5024. } else if ( face instanceof THREE.Face4 ) {
  5025. vA = this.vertices[ face.a ];
  5026. vB = this.vertices[ face.b ];
  5027. vC = this.vertices[ face.c ];
  5028. vD = this.vertices[ face.d ];
  5029. // abd
  5030. db.subVectors( vD, vB );
  5031. ab.subVectors( vA, vB );
  5032. db.cross( ab );
  5033. vertices[ face.a ].add( db );
  5034. vertices[ face.b ].add( db );
  5035. vertices[ face.d ].add( db );
  5036. // bcd
  5037. dc.subVectors( vD, vC );
  5038. bc.subVectors( vB, vC );
  5039. dc.cross( bc );
  5040. vertices[ face.b ].add( dc );
  5041. vertices[ face.c ].add( dc );
  5042. vertices[ face.d ].add( dc );
  5043. }
  5044. }
  5045. } else {
  5046. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5047. face = this.faces[ f ];
  5048. if ( face instanceof THREE.Face3 ) {
  5049. vertices[ face.a ].add( face.normal );
  5050. vertices[ face.b ].add( face.normal );
  5051. vertices[ face.c ].add( face.normal );
  5052. } else if ( face instanceof THREE.Face4 ) {
  5053. vertices[ face.a ].add( face.normal );
  5054. vertices[ face.b ].add( face.normal );
  5055. vertices[ face.c ].add( face.normal );
  5056. vertices[ face.d ].add( face.normal );
  5057. }
  5058. }
  5059. }
  5060. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5061. vertices[ v ].normalize();
  5062. }
  5063. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5064. face = this.faces[ f ];
  5065. if ( face instanceof THREE.Face3 ) {
  5066. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  5067. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  5068. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  5069. } else if ( face instanceof THREE.Face4 ) {
  5070. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  5071. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  5072. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  5073. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  5074. }
  5075. }
  5076. },
  5077. computeMorphNormals: function () {
  5078. var i, il, f, fl, face;
  5079. // save original normals
  5080. // - create temp variables on first access
  5081. // otherwise just copy (for faster repeated calls)
  5082. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5083. face = this.faces[ f ];
  5084. if ( ! face.__originalFaceNormal ) {
  5085. face.__originalFaceNormal = face.normal.clone();
  5086. } else {
  5087. face.__originalFaceNormal.copy( face.normal );
  5088. }
  5089. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  5090. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  5091. if ( ! face.__originalVertexNormals[ i ] ) {
  5092. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  5093. } else {
  5094. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  5095. }
  5096. }
  5097. }
  5098. // use temp geometry to compute face and vertex normals for each morph
  5099. var tmpGeo = new THREE.Geometry();
  5100. tmpGeo.faces = this.faces;
  5101. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  5102. // create on first access
  5103. if ( ! this.morphNormals[ i ] ) {
  5104. this.morphNormals[ i ] = {};
  5105. this.morphNormals[ i ].faceNormals = [];
  5106. this.morphNormals[ i ].vertexNormals = [];
  5107. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  5108. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  5109. var faceNormal, vertexNormals;
  5110. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5111. face = this.faces[ f ];
  5112. faceNormal = new THREE.Vector3();
  5113. if ( face instanceof THREE.Face3 ) {
  5114. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  5115. } else {
  5116. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  5117. }
  5118. dstNormalsFace.push( faceNormal );
  5119. dstNormalsVertex.push( vertexNormals );
  5120. }
  5121. }
  5122. var morphNormals = this.morphNormals[ i ];
  5123. // set vertices to morph target
  5124. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  5125. // compute morph normals
  5126. tmpGeo.computeFaceNormals();
  5127. tmpGeo.computeVertexNormals();
  5128. // store morph normals
  5129. var faceNormal, vertexNormals;
  5130. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5131. face = this.faces[ f ];
  5132. faceNormal = morphNormals.faceNormals[ f ];
  5133. vertexNormals = morphNormals.vertexNormals[ f ];
  5134. faceNormal.copy( face.normal );
  5135. if ( face instanceof THREE.Face3 ) {
  5136. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  5137. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  5138. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  5139. } else {
  5140. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  5141. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  5142. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  5143. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  5144. }
  5145. }
  5146. }
  5147. // restore original normals
  5148. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5149. face = this.faces[ f ];
  5150. face.normal = face.__originalFaceNormal;
  5151. face.vertexNormals = face.__originalVertexNormals;
  5152. }
  5153. },
  5154. computeTangents: function () {
  5155. // based on http://www.terathon.com/code/tangent.html
  5156. // tangents go to vertices
  5157. var f, fl, v, vl, i, il, vertexIndex,
  5158. face, uv, vA, vB, vC, uvA, uvB, uvC,
  5159. x1, x2, y1, y2, z1, z2,
  5160. s1, s2, t1, t2, r, t, test,
  5161. tan1 = [], tan2 = [],
  5162. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  5163. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  5164. n = new THREE.Vector3(), w;
  5165. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5166. tan1[ v ] = new THREE.Vector3();
  5167. tan2[ v ] = new THREE.Vector3();
  5168. }
  5169. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  5170. vA = context.vertices[ a ];
  5171. vB = context.vertices[ b ];
  5172. vC = context.vertices[ c ];
  5173. uvA = uv[ ua ];
  5174. uvB = uv[ ub ];
  5175. uvC = uv[ uc ];
  5176. x1 = vB.x - vA.x;
  5177. x2 = vC.x - vA.x;
  5178. y1 = vB.y - vA.y;
  5179. y2 = vC.y - vA.y;
  5180. z1 = vB.z - vA.z;
  5181. z2 = vC.z - vA.z;
  5182. s1 = uvB.x - uvA.x;
  5183. s2 = uvC.x - uvA.x;
  5184. t1 = uvB.y - uvA.y;
  5185. t2 = uvC.y - uvA.y;
  5186. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5187. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  5188. ( t2 * y1 - t1 * y2 ) * r,
  5189. ( t2 * z1 - t1 * z2 ) * r );
  5190. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  5191. ( s1 * y2 - s2 * y1 ) * r,
  5192. ( s1 * z2 - s2 * z1 ) * r );
  5193. tan1[ a ].add( sdir );
  5194. tan1[ b ].add( sdir );
  5195. tan1[ c ].add( sdir );
  5196. tan2[ a ].add( tdir );
  5197. tan2[ b ].add( tdir );
  5198. tan2[ c ].add( tdir );
  5199. }
  5200. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5201. face = this.faces[ f ];
  5202. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  5203. if ( face instanceof THREE.Face3 ) {
  5204. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  5205. } else if ( face instanceof THREE.Face4 ) {
  5206. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  5207. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  5208. }
  5209. }
  5210. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  5211. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5212. face = this.faces[ f ];
  5213. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  5214. n.copy( face.vertexNormals[ i ] );
  5215. vertexIndex = face[ faceIndex[ i ] ];
  5216. t = tan1[ vertexIndex ];
  5217. // Gram-Schmidt orthogonalize
  5218. tmp.copy( t );
  5219. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5220. // Calculate handedness
  5221. tmp2.crossVectors( face.vertexNormals[ i ], t );
  5222. test = tmp2.dot( tan2[ vertexIndex ] );
  5223. w = (test < 0.0) ? -1.0 : 1.0;
  5224. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  5225. }
  5226. }
  5227. this.hasTangents = true;
  5228. },
  5229. computeLineDistances: function ( ) {
  5230. var d = 0;
  5231. var vertices = this.vertices;
  5232. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5233. if ( i > 0 ) {
  5234. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  5235. }
  5236. this.lineDistances[ i ] = d;
  5237. }
  5238. },
  5239. computeBoundingBox: function () {
  5240. if ( this.boundingBox === null ) {
  5241. this.boundingBox = new THREE.Box3();
  5242. }
  5243. this.boundingBox.setFromPoints( this.vertices );
  5244. },
  5245. computeBoundingSphere: function () {
  5246. if ( this.boundingSphere === null ) {
  5247. this.boundingSphere = new THREE.Sphere();
  5248. }
  5249. this.boundingSphere.setFromPoints( this.vertices );
  5250. },
  5251. /*
  5252. * Checks for duplicate vertices with hashmap.
  5253. * Duplicated vertices are removed
  5254. * and faces' vertices are updated.
  5255. */
  5256. mergeVertices: function () {
  5257. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  5258. var unique = [], changes = [];
  5259. var v, key;
  5260. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  5261. var precision = Math.pow( 10, precisionPoints );
  5262. var i,il, face;
  5263. var indices, k, j, jl, u;
  5264. // reset cache of vertices as it now will be changing.
  5265. this.__tmpVertices = undefined;
  5266. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  5267. v = this.vertices[ i ];
  5268. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  5269. if ( verticesMap[ key ] === undefined ) {
  5270. verticesMap[ key ] = i;
  5271. unique.push( this.vertices[ i ] );
  5272. changes[ i ] = unique.length - 1;
  5273. } else {
  5274. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  5275. changes[ i ] = changes[ verticesMap[ key ] ];
  5276. }
  5277. };
  5278. // if faces are completely degenerate after merging vertices, we
  5279. // have to remove them from the geometry.
  5280. var faceIndicesToRemove = [];
  5281. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  5282. face = this.faces[ i ];
  5283. if ( face instanceof THREE.Face3 ) {
  5284. face.a = changes[ face.a ];
  5285. face.b = changes[ face.b ];
  5286. face.c = changes[ face.c ];
  5287. indices = [ face.a, face.b, face.c ];
  5288. var dupIndex = -1;
  5289. // if any duplicate vertices are found in a Face3
  5290. // we have to remove the face as nothing can be saved
  5291. for ( var n = 0; n < 3; n ++ ) {
  5292. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  5293. dupIndex = n;
  5294. faceIndicesToRemove.push( i );
  5295. break;
  5296. }
  5297. }
  5298. } else if ( face instanceof THREE.Face4 ) {
  5299. face.a = changes[ face.a ];
  5300. face.b = changes[ face.b ];
  5301. face.c = changes[ face.c ];
  5302. face.d = changes[ face.d ];
  5303. // check dups in (a, b, c, d) and convert to -> face3
  5304. indices = [ face.a, face.b, face.c, face.d ];
  5305. var dupIndex = -1;
  5306. for ( var n = 0; n < 4; n ++ ) {
  5307. if ( indices[ n ] == indices[ ( n + 1 ) % 4 ] ) {
  5308. // if more than one duplicated vertex is found
  5309. // we can't generate any valid Face3's, thus
  5310. // we need to remove this face complete.
  5311. if ( dupIndex >= 0 ) {
  5312. faceIndicesToRemove.push( i );
  5313. }
  5314. dupIndex = n;
  5315. }
  5316. }
  5317. if ( dupIndex >= 0 ) {
  5318. indices.splice( dupIndex, 1 );
  5319. var newFace = new THREE.Face3( indices[0], indices[1], indices[2], face.normal, face.color, face.materialIndex );
  5320. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  5321. u = this.faceVertexUvs[ j ][ i ];
  5322. if ( u ) {
  5323. u.splice( dupIndex, 1 );
  5324. }
  5325. }
  5326. if( face.vertexNormals && face.vertexNormals.length > 0) {
  5327. newFace.vertexNormals = face.vertexNormals;
  5328. newFace.vertexNormals.splice( dupIndex, 1 );
  5329. }
  5330. if( face.vertexColors && face.vertexColors.length > 0 ) {
  5331. newFace.vertexColors = face.vertexColors;
  5332. newFace.vertexColors.splice( dupIndex, 1 );
  5333. }
  5334. this.faces[ i ] = newFace;
  5335. }
  5336. }
  5337. }
  5338. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  5339. this.faces.splice( i, 1 );
  5340. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  5341. this.faceVertexUvs[ j ].splice( i, 1 );
  5342. }
  5343. }
  5344. // Use unique set of vertices
  5345. var diff = this.vertices.length - unique.length;
  5346. this.vertices = unique;
  5347. return diff;
  5348. },
  5349. clone: function () {
  5350. var geometry = new THREE.Geometry();
  5351. var vertices = this.vertices;
  5352. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5353. geometry.vertices.push( vertices[ i ].clone() );
  5354. }
  5355. var faces = this.faces;
  5356. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  5357. geometry.faces.push( faces[ i ].clone() );
  5358. }
  5359. var uvs = this.faceVertexUvs[ 0 ];
  5360. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  5361. var uv = uvs[ i ], uvCopy = [];
  5362. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  5363. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  5364. }
  5365. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  5366. }
  5367. return geometry;
  5368. },
  5369. dispose: function () {
  5370. this.dispatchEvent( { type: 'dispose' } );
  5371. }
  5372. };
  5373. THREE.GeometryIdCount = 0;
  5374. /**
  5375. * @author alteredq / http://alteredqualia.com/
  5376. */
  5377. THREE.BufferGeometry = function () {
  5378. this.id = THREE.GeometryIdCount ++;
  5379. this.uuid = THREE.Math.generateUUID();
  5380. // attributes
  5381. this.attributes = {};
  5382. // attributes typed arrays are kept only if dynamic flag is set
  5383. this.dynamic = false;
  5384. // offsets for chunks when using indexed elements
  5385. this.offsets = [];
  5386. // boundings
  5387. this.boundingBox = null;
  5388. this.boundingSphere = null;
  5389. this.hasTangents = false;
  5390. // for compatibility
  5391. this.morphTargets = [];
  5392. };
  5393. THREE.BufferGeometry.prototype = {
  5394. constructor: THREE.BufferGeometry,
  5395. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  5396. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  5397. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  5398. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  5399. applyMatrix: function ( matrix ) {
  5400. var positionArray;
  5401. var normalArray;
  5402. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  5403. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  5404. if ( positionArray !== undefined ) {
  5405. matrix.multiplyVector3Array( positionArray );
  5406. this.verticesNeedUpdate = true;
  5407. }
  5408. if ( normalArray !== undefined ) {
  5409. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5410. normalMatrix.multiplyVector3Array( normalArray );
  5411. this.normalizeNormals();
  5412. this.normalsNeedUpdate = true;
  5413. }
  5414. },
  5415. computeBoundingBox: function () {
  5416. if ( this.boundingBox === null ) {
  5417. this.boundingBox = new THREE.Box3();
  5418. }
  5419. var positions = this.attributes[ "position" ].array;
  5420. if ( positions ) {
  5421. var bb = this.boundingBox;
  5422. var x, y, z;
  5423. if( positions.length >= 3 ) {
  5424. bb.min.x = bb.max.x = positions[ 0 ];
  5425. bb.min.y = bb.max.y = positions[ 1 ];
  5426. bb.min.z = bb.max.z = positions[ 2 ];
  5427. }
  5428. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  5429. x = positions[ i ];
  5430. y = positions[ i + 1 ];
  5431. z = positions[ i + 2 ];
  5432. // bounding box
  5433. if ( x < bb.min.x ) {
  5434. bb.min.x = x;
  5435. } else if ( x > bb.max.x ) {
  5436. bb.max.x = x;
  5437. }
  5438. if ( y < bb.min.y ) {
  5439. bb.min.y = y;
  5440. } else if ( y > bb.max.y ) {
  5441. bb.max.y = y;
  5442. }
  5443. if ( z < bb.min.z ) {
  5444. bb.min.z = z;
  5445. } else if ( z > bb.max.z ) {
  5446. bb.max.z = z;
  5447. }
  5448. }
  5449. }
  5450. if ( positions === undefined || positions.length === 0 ) {
  5451. this.boundingBox.min.set( 0, 0, 0 );
  5452. this.boundingBox.max.set( 0, 0, 0 );
  5453. }
  5454. },
  5455. computeBoundingSphere: function () {
  5456. if ( this.boundingSphere === null ) {
  5457. this.boundingSphere = new THREE.Sphere();
  5458. }
  5459. var positions = this.attributes[ "position" ].array;
  5460. if ( positions ) {
  5461. var radiusSq, maxRadiusSq = 0;
  5462. var x, y, z;
  5463. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5464. x = positions[ i ];
  5465. y = positions[ i + 1 ];
  5466. z = positions[ i + 2 ];
  5467. radiusSq = x * x + y * y + z * z;
  5468. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  5469. }
  5470. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5471. }
  5472. },
  5473. computeVertexNormals: function () {
  5474. if ( this.attributes[ "position" ] ) {
  5475. var i, il;
  5476. var j, jl;
  5477. var nVertexElements = this.attributes[ "position" ].array.length;
  5478. if ( this.attributes[ "normal" ] === undefined ) {
  5479. this.attributes[ "normal" ] = {
  5480. itemSize: 3,
  5481. array: new Float32Array( nVertexElements )
  5482. };
  5483. } else {
  5484. // reset existing normals to zero
  5485. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  5486. this.attributes[ "normal" ].array[ i ] = 0;
  5487. }
  5488. }
  5489. var positions = this.attributes[ "position" ].array;
  5490. var normals = this.attributes[ "normal" ].array;
  5491. var vA, vB, vC, x, y, z,
  5492. pA = new THREE.Vector3(),
  5493. pB = new THREE.Vector3(),
  5494. pC = new THREE.Vector3(),
  5495. cb = new THREE.Vector3(),
  5496. ab = new THREE.Vector3();
  5497. // indexed elements
  5498. if ( this.attributes[ "index" ] ) {
  5499. var indices = this.attributes[ "index" ].array;
  5500. var offsets = this.offsets;
  5501. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5502. var start = offsets[ j ].start;
  5503. var count = offsets[ j ].count;
  5504. var index = offsets[ j ].index;
  5505. for ( i = start, il = start + count; i < il; i += 3 ) {
  5506. vA = index + indices[ i ];
  5507. vB = index + indices[ i + 1 ];
  5508. vC = index + indices[ i + 2 ];
  5509. x = positions[ vA * 3 ];
  5510. y = positions[ vA * 3 + 1 ];
  5511. z = positions[ vA * 3 + 2 ];
  5512. pA.set( x, y, z );
  5513. x = positions[ vB * 3 ];
  5514. y = positions[ vB * 3 + 1 ];
  5515. z = positions[ vB * 3 + 2 ];
  5516. pB.set( x, y, z );
  5517. x = positions[ vC * 3 ];
  5518. y = positions[ vC * 3 + 1 ];
  5519. z = positions[ vC * 3 + 2 ];
  5520. pC.set( x, y, z );
  5521. cb.subVectors( pC, pB );
  5522. ab.subVectors( pA, pB );
  5523. cb.cross( ab );
  5524. normals[ vA * 3 ] += cb.x;
  5525. normals[ vA * 3 + 1 ] += cb.y;
  5526. normals[ vA * 3 + 2 ] += cb.z;
  5527. normals[ vB * 3 ] += cb.x;
  5528. normals[ vB * 3 + 1 ] += cb.y;
  5529. normals[ vB * 3 + 2 ] += cb.z;
  5530. normals[ vC * 3 ] += cb.x;
  5531. normals[ vC * 3 + 1 ] += cb.y;
  5532. normals[ vC * 3 + 2 ] += cb.z;
  5533. }
  5534. }
  5535. // non-indexed elements (unconnected triangle soup)
  5536. } else {
  5537. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5538. x = positions[ i ];
  5539. y = positions[ i + 1 ];
  5540. z = positions[ i + 2 ];
  5541. pA.set( x, y, z );
  5542. x = positions[ i + 3 ];
  5543. y = positions[ i + 4 ];
  5544. z = positions[ i + 5 ];
  5545. pB.set( x, y, z );
  5546. x = positions[ i + 6 ];
  5547. y = positions[ i + 7 ];
  5548. z = positions[ i + 8 ];
  5549. pC.set( x, y, z );
  5550. cb.subVectors( pC, pB );
  5551. ab.subVectors( pA, pB );
  5552. cb.cross( ab );
  5553. normals[ i ] = cb.x;
  5554. normals[ i + 1 ] = cb.y;
  5555. normals[ i + 2 ] = cb.z;
  5556. normals[ i + 3 ] = cb.x;
  5557. normals[ i + 4 ] = cb.y;
  5558. normals[ i + 5 ] = cb.z;
  5559. normals[ i + 6 ] = cb.x;
  5560. normals[ i + 7 ] = cb.y;
  5561. normals[ i + 8 ] = cb.z;
  5562. }
  5563. }
  5564. this.normalizeNormals();
  5565. this.normalsNeedUpdate = true;
  5566. }
  5567. },
  5568. normalizeNormals: function () {
  5569. var normals = this.attributes[ "normal" ].array;
  5570. var x, y, z, n;
  5571. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5572. x = normals[ i ];
  5573. y = normals[ i + 1 ];
  5574. z = normals[ i + 2 ];
  5575. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5576. normals[ i ] *= n;
  5577. normals[ i + 1 ] *= n;
  5578. normals[ i + 2 ] *= n;
  5579. }
  5580. },
  5581. computeTangents: function () {
  5582. // based on http://www.terathon.com/code/tangent.html
  5583. // (per vertex tangents)
  5584. if ( this.attributes[ "index" ] === undefined ||
  5585. this.attributes[ "position" ] === undefined ||
  5586. this.attributes[ "normal" ] === undefined ||
  5587. this.attributes[ "uv" ] === undefined ) {
  5588. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5589. return;
  5590. }
  5591. var indices = this.attributes[ "index" ].array;
  5592. var positions = this.attributes[ "position" ].array;
  5593. var normals = this.attributes[ "normal" ].array;
  5594. var uvs = this.attributes[ "uv" ].array;
  5595. var nVertices = positions.length / 3;
  5596. if ( this.attributes[ "tangent" ] === undefined ) {
  5597. var nTangentElements = 4 * nVertices;
  5598. this.attributes[ "tangent" ] = {
  5599. itemSize: 4,
  5600. array: new Float32Array( nTangentElements )
  5601. };
  5602. }
  5603. var tangents = this.attributes[ "tangent" ].array;
  5604. var tan1 = [], tan2 = [];
  5605. for ( var k = 0; k < nVertices; k ++ ) {
  5606. tan1[ k ] = new THREE.Vector3();
  5607. tan2[ k ] = new THREE.Vector3();
  5608. }
  5609. var xA, yA, zA,
  5610. xB, yB, zB,
  5611. xC, yC, zC,
  5612. uA, vA,
  5613. uB, vB,
  5614. uC, vC,
  5615. x1, x2, y1, y2, z1, z2,
  5616. s1, s2, t1, t2, r;
  5617. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5618. function handleTriangle( a, b, c ) {
  5619. xA = positions[ a * 3 ];
  5620. yA = positions[ a * 3 + 1 ];
  5621. zA = positions[ a * 3 + 2 ];
  5622. xB = positions[ b * 3 ];
  5623. yB = positions[ b * 3 + 1 ];
  5624. zB = positions[ b * 3 + 2 ];
  5625. xC = positions[ c * 3 ];
  5626. yC = positions[ c * 3 + 1 ];
  5627. zC = positions[ c * 3 + 2 ];
  5628. uA = uvs[ a * 2 ];
  5629. vA = uvs[ a * 2 + 1 ];
  5630. uB = uvs[ b * 2 ];
  5631. vB = uvs[ b * 2 + 1 ];
  5632. uC = uvs[ c * 2 ];
  5633. vC = uvs[ c * 2 + 1 ];
  5634. x1 = xB - xA;
  5635. x2 = xC - xA;
  5636. y1 = yB - yA;
  5637. y2 = yC - yA;
  5638. z1 = zB - zA;
  5639. z2 = zC - zA;
  5640. s1 = uB - uA;
  5641. s2 = uC - uA;
  5642. t1 = vB - vA;
  5643. t2 = vC - vA;
  5644. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5645. sdir.set(
  5646. ( t2 * x1 - t1 * x2 ) * r,
  5647. ( t2 * y1 - t1 * y2 ) * r,
  5648. ( t2 * z1 - t1 * z2 ) * r
  5649. );
  5650. tdir.set(
  5651. ( s1 * x2 - s2 * x1 ) * r,
  5652. ( s1 * y2 - s2 * y1 ) * r,
  5653. ( s1 * z2 - s2 * z1 ) * r
  5654. );
  5655. tan1[ a ].add( sdir );
  5656. tan1[ b ].add( sdir );
  5657. tan1[ c ].add( sdir );
  5658. tan2[ a ].add( tdir );
  5659. tan2[ b ].add( tdir );
  5660. tan2[ c ].add( tdir );
  5661. }
  5662. var i, il;
  5663. var j, jl;
  5664. var iA, iB, iC;
  5665. var offsets = this.offsets;
  5666. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5667. var start = offsets[ j ].start;
  5668. var count = offsets[ j ].count;
  5669. var index = offsets[ j ].index;
  5670. for ( i = start, il = start + count; i < il; i += 3 ) {
  5671. iA = index + indices[ i ];
  5672. iB = index + indices[ i + 1 ];
  5673. iC = index + indices[ i + 2 ];
  5674. handleTriangle( iA, iB, iC );
  5675. }
  5676. }
  5677. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5678. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5679. var w, t, test;
  5680. function handleVertex( v ) {
  5681. n.x = normals[ v * 3 ];
  5682. n.y = normals[ v * 3 + 1 ];
  5683. n.z = normals[ v * 3 + 2 ];
  5684. n2.copy( n );
  5685. t = tan1[ v ];
  5686. // Gram-Schmidt orthogonalize
  5687. tmp.copy( t );
  5688. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5689. // Calculate handedness
  5690. tmp2.crossVectors( n2, t );
  5691. test = tmp2.dot( tan2[ v ] );
  5692. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5693. tangents[ v * 4 ] = tmp.x;
  5694. tangents[ v * 4 + 1 ] = tmp.y;
  5695. tangents[ v * 4 + 2 ] = tmp.z;
  5696. tangents[ v * 4 + 3 ] = w;
  5697. }
  5698. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5699. var start = offsets[ j ].start;
  5700. var count = offsets[ j ].count;
  5701. var index = offsets[ j ].index;
  5702. for ( i = start, il = start + count; i < il; i += 3 ) {
  5703. iA = index + indices[ i ];
  5704. iB = index + indices[ i + 1 ];
  5705. iC = index + indices[ i + 2 ];
  5706. handleVertex( iA );
  5707. handleVertex( iB );
  5708. handleVertex( iC );
  5709. }
  5710. }
  5711. this.hasTangents = true;
  5712. this.tangentsNeedUpdate = true;
  5713. },
  5714. dispose: function () {
  5715. this.dispatchEvent( { type: 'dispose' } );
  5716. }
  5717. };
  5718. /**
  5719. * @author mrdoob / http://mrdoob.com/
  5720. * @author mikael emtinger / http://gomo.se/
  5721. * @author WestLangley / http://github.com/WestLangley
  5722. */
  5723. THREE.Camera = function () {
  5724. THREE.Object3D.call( this );
  5725. this.matrixWorldInverse = new THREE.Matrix4();
  5726. this.projectionMatrix = new THREE.Matrix4();
  5727. this.projectionMatrixInverse = new THREE.Matrix4();
  5728. };
  5729. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  5730. THREE.Camera.prototype.lookAt = function () {
  5731. // This routine does not support cameras with rotated and/or translated parent(s)
  5732. var m1 = new THREE.Matrix4();
  5733. return function ( vector ) {
  5734. m1.lookAt( this.position, vector, this.up );
  5735. this.quaternion.setFromRotationMatrix( m1 );
  5736. };
  5737. }();
  5738. /**
  5739. * @author alteredq / http://alteredqualia.com/
  5740. */
  5741. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  5742. THREE.Camera.call( this );
  5743. this.left = left;
  5744. this.right = right;
  5745. this.top = top;
  5746. this.bottom = bottom;
  5747. this.near = ( near !== undefined ) ? near : 0.1;
  5748. this.far = ( far !== undefined ) ? far : 2000;
  5749. this.updateProjectionMatrix();
  5750. };
  5751. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  5752. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  5753. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  5754. };
  5755. /**
  5756. * @author mrdoob / http://mrdoob.com/
  5757. * @author greggman / http://games.greggman.com/
  5758. * @author zz85 / http://www.lab4games.net/zz85/blog
  5759. */
  5760. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  5761. THREE.Camera.call( this );
  5762. this.fov = fov !== undefined ? fov : 50;
  5763. this.aspect = aspect !== undefined ? aspect : 1;
  5764. this.near = near !== undefined ? near : 0.1;
  5765. this.far = far !== undefined ? far : 2000;
  5766. this.updateProjectionMatrix();
  5767. };
  5768. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  5769. /**
  5770. * Uses Focal Length (in mm) to estimate and set FOV
  5771. * 35mm (fullframe) camera is used if frame size is not specified;
  5772. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  5773. */
  5774. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  5775. if ( frameHeight === undefined ) frameHeight = 24;
  5776. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  5777. this.updateProjectionMatrix();
  5778. }
  5779. /**
  5780. * Sets an offset in a larger frustum. This is useful for multi-window or
  5781. * multi-monitor/multi-machine setups.
  5782. *
  5783. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  5784. * the monitors are in grid like this
  5785. *
  5786. * +---+---+---+
  5787. * | A | B | C |
  5788. * +---+---+---+
  5789. * | D | E | F |
  5790. * +---+---+---+
  5791. *
  5792. * then for each monitor you would call it like this
  5793. *
  5794. * var w = 1920;
  5795. * var h = 1080;
  5796. * var fullWidth = w * 3;
  5797. * var fullHeight = h * 2;
  5798. *
  5799. * --A--
  5800. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  5801. * --B--
  5802. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  5803. * --C--
  5804. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  5805. * --D--
  5806. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  5807. * --E--
  5808. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  5809. * --F--
  5810. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  5811. *
  5812. * Note there is no reason monitors have to be the same size or in a grid.
  5813. */
  5814. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  5815. this.fullWidth = fullWidth;
  5816. this.fullHeight = fullHeight;
  5817. this.x = x;
  5818. this.y = y;
  5819. this.width = width;
  5820. this.height = height;
  5821. this.updateProjectionMatrix();
  5822. };
  5823. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  5824. if ( this.fullWidth ) {
  5825. var aspect = this.fullWidth / this.fullHeight;
  5826. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  5827. var bottom = -top;
  5828. var left = aspect * bottom;
  5829. var right = aspect * top;
  5830. var width = Math.abs( right - left );
  5831. var height = Math.abs( top - bottom );
  5832. this.projectionMatrix.makeFrustum(
  5833. left + this.x * width / this.fullWidth,
  5834. left + ( this.x + this.width ) * width / this.fullWidth,
  5835. top - ( this.y + this.height ) * height / this.fullHeight,
  5836. top - this.y * height / this.fullHeight,
  5837. this.near,
  5838. this.far
  5839. );
  5840. } else {
  5841. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  5842. }
  5843. };
  5844. /**
  5845. * @author mrdoob / http://mrdoob.com/
  5846. * @author alteredq / http://alteredqualia.com/
  5847. */
  5848. THREE.Light = function ( hex ) {
  5849. THREE.Object3D.call( this );
  5850. this.color = new THREE.Color( hex );
  5851. };
  5852. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  5853. THREE.Light.prototype.clone = function ( light ) {
  5854. if ( light === undefined ) light = new THREE.Light();
  5855. THREE.Object3D.prototype.clone.call( this, light );
  5856. light.color.copy( this.color );
  5857. return light;
  5858. };
  5859. /**
  5860. * @author mrdoob / http://mrdoob.com/
  5861. */
  5862. THREE.AmbientLight = function ( hex ) {
  5863. THREE.Light.call( this, hex );
  5864. };
  5865. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  5866. THREE.AmbientLight.prototype.clone = function () {
  5867. var light = new THREE.AmbientLight();
  5868. THREE.Light.prototype.clone.call( this, light );
  5869. return light;
  5870. };
  5871. /**
  5872. * @author MPanknin / http://www.redplant.de/
  5873. * @author alteredq / http://alteredqualia.com/
  5874. */
  5875. THREE.AreaLight = function ( hex, intensity ) {
  5876. THREE.Light.call( this, hex );
  5877. this.normal = new THREE.Vector3( 0, -1, 0 );
  5878. this.right = new THREE.Vector3( 1, 0, 0 );
  5879. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5880. this.width = 1.0;
  5881. this.height = 1.0;
  5882. this.constantAttenuation = 1.5;
  5883. this.linearAttenuation = 0.5;
  5884. this.quadraticAttenuation = 0.1;
  5885. };
  5886. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  5887. /**
  5888. * @author mrdoob / http://mrdoob.com/
  5889. * @author alteredq / http://alteredqualia.com/
  5890. */
  5891. THREE.DirectionalLight = function ( hex, intensity ) {
  5892. THREE.Light.call( this, hex );
  5893. this.position.set( 0, 1, 0 );
  5894. this.target = new THREE.Object3D();
  5895. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5896. this.castShadow = false;
  5897. this.onlyShadow = false;
  5898. //
  5899. this.shadowCameraNear = 50;
  5900. this.shadowCameraFar = 5000;
  5901. this.shadowCameraLeft = -500;
  5902. this.shadowCameraRight = 500;
  5903. this.shadowCameraTop = 500;
  5904. this.shadowCameraBottom = -500;
  5905. this.shadowCameraVisible = false;
  5906. this.shadowBias = 0;
  5907. this.shadowDarkness = 0.5;
  5908. this.shadowMapWidth = 512;
  5909. this.shadowMapHeight = 512;
  5910. //
  5911. this.shadowCascade = false;
  5912. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  5913. this.shadowCascadeCount = 2;
  5914. this.shadowCascadeBias = [ 0, 0, 0 ];
  5915. this.shadowCascadeWidth = [ 512, 512, 512 ];
  5916. this.shadowCascadeHeight = [ 512, 512, 512 ];
  5917. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  5918. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  5919. this.shadowCascadeArray = [];
  5920. //
  5921. this.shadowMap = null;
  5922. this.shadowMapSize = null;
  5923. this.shadowCamera = null;
  5924. this.shadowMatrix = null;
  5925. };
  5926. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  5927. THREE.DirectionalLight.prototype.clone = function () {
  5928. var light = new THREE.DirectionalLight();
  5929. THREE.Light.prototype.clone.call( this, light );
  5930. light.target = this.target.clone();
  5931. light.intensity = this.intensity;
  5932. light.castShadow = this.castShadow;
  5933. light.onlyShadow = this.onlyShadow;
  5934. return light;
  5935. };
  5936. /**
  5937. * @author alteredq / http://alteredqualia.com/
  5938. */
  5939. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  5940. THREE.Light.call( this, skyColorHex );
  5941. this.position.set( 0, 100, 0 );
  5942. this.groundColor = new THREE.Color( groundColorHex );
  5943. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5944. };
  5945. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  5946. THREE.HemisphereLight.prototype.clone = function () {
  5947. var light = new THREE.PointLight();
  5948. THREE.Light.prototype.clone.call( this, light );
  5949. light.groundColor.copy( this.groundColor );
  5950. light.intensity = this.intensity;
  5951. return light;
  5952. };
  5953. /**
  5954. * @author mrdoob / http://mrdoob.com/
  5955. */
  5956. THREE.PointLight = function ( hex, intensity, distance ) {
  5957. THREE.Light.call( this, hex );
  5958. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5959. this.distance = ( distance !== undefined ) ? distance : 0;
  5960. };
  5961. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  5962. THREE.PointLight.prototype.clone = function () {
  5963. var light = new THREE.PointLight();
  5964. THREE.Light.prototype.clone.call( this, light );
  5965. light.intensity = this.intensity;
  5966. light.distance = this.distance;
  5967. return light;
  5968. };
  5969. /**
  5970. * @author alteredq / http://alteredqualia.com/
  5971. */
  5972. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  5973. THREE.Light.call( this, hex );
  5974. this.position.set( 0, 1, 0 );
  5975. this.target = new THREE.Object3D();
  5976. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5977. this.distance = ( distance !== undefined ) ? distance : 0;
  5978. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  5979. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  5980. this.castShadow = false;
  5981. this.onlyShadow = false;
  5982. //
  5983. this.shadowCameraNear = 50;
  5984. this.shadowCameraFar = 5000;
  5985. this.shadowCameraFov = 50;
  5986. this.shadowCameraVisible = false;
  5987. this.shadowBias = 0;
  5988. this.shadowDarkness = 0.5;
  5989. this.shadowMapWidth = 512;
  5990. this.shadowMapHeight = 512;
  5991. //
  5992. this.shadowMap = null;
  5993. this.shadowMapSize = null;
  5994. this.shadowCamera = null;
  5995. this.shadowMatrix = null;
  5996. };
  5997. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  5998. THREE.SpotLight.prototype.clone = function () {
  5999. var light = new THREE.SpotLight();
  6000. THREE.Light.prototype.clone.call( this, light );
  6001. light.target = this.target.clone();
  6002. light.intensity = this.intensity;
  6003. light.distance = this.distance;
  6004. light.angle = this.angle;
  6005. light.exponent = this.exponent;
  6006. light.castShadow = this.castShadow;
  6007. light.onlyShadow = this.onlyShadow;
  6008. return light;
  6009. };
  6010. /**
  6011. * @author alteredq / http://alteredqualia.com/
  6012. */
  6013. THREE.Loader = function ( showStatus ) {
  6014. this.showStatus = showStatus;
  6015. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  6016. this.onLoadStart = function () {};
  6017. this.onLoadProgress = function () {};
  6018. this.onLoadComplete = function () {};
  6019. };
  6020. THREE.Loader.prototype = {
  6021. constructor: THREE.Loader,
  6022. crossOrigin: 'anonymous',
  6023. addStatusElement: function () {
  6024. var e = document.createElement( "div" );
  6025. e.style.position = "absolute";
  6026. e.style.right = "0px";
  6027. e.style.top = "0px";
  6028. e.style.fontSize = "0.8em";
  6029. e.style.textAlign = "left";
  6030. e.style.background = "rgba(0,0,0,0.25)";
  6031. e.style.color = "#fff";
  6032. e.style.width = "120px";
  6033. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  6034. e.style.zIndex = 1000;
  6035. e.innerHTML = "Loading ...";
  6036. return e;
  6037. },
  6038. updateProgress: function ( progress ) {
  6039. var message = "Loaded ";
  6040. if ( progress.total ) {
  6041. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  6042. } else {
  6043. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  6044. }
  6045. this.statusDomElement.innerHTML = message;
  6046. },
  6047. extractUrlBase: function ( url ) {
  6048. var parts = url.split( '/' );
  6049. parts.pop();
  6050. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  6051. },
  6052. initMaterials: function ( materials, texturePath ) {
  6053. var array = [];
  6054. for ( var i = 0; i < materials.length; ++ i ) {
  6055. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  6056. }
  6057. return array;
  6058. },
  6059. needsTangents: function ( materials ) {
  6060. for( var i = 0, il = materials.length; i < il; i ++ ) {
  6061. var m = materials[ i ];
  6062. if ( m instanceof THREE.ShaderMaterial ) return true;
  6063. }
  6064. return false;
  6065. },
  6066. createMaterial: function ( m, texturePath ) {
  6067. var _this = this;
  6068. function is_pow2( n ) {
  6069. var l = Math.log( n ) / Math.LN2;
  6070. return Math.floor( l ) == l;
  6071. }
  6072. function nearest_pow2( n ) {
  6073. var l = Math.log( n ) / Math.LN2;
  6074. return Math.pow( 2, Math.round( l ) );
  6075. }
  6076. function load_image( where, url ) {
  6077. var image = new Image();
  6078. image.onload = function () {
  6079. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  6080. var width = nearest_pow2( this.width );
  6081. var height = nearest_pow2( this.height );
  6082. where.image.width = width;
  6083. where.image.height = height;
  6084. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  6085. } else {
  6086. where.image = this;
  6087. }
  6088. where.needsUpdate = true;
  6089. };
  6090. image.crossOrigin = _this.crossOrigin;
  6091. image.src = url;
  6092. }
  6093. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  6094. var isCompressed = /\.dds$/i.test( sourceFile );
  6095. var fullPath = texturePath + "/" + sourceFile;
  6096. if ( isCompressed ) {
  6097. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  6098. where[ name ] = texture;
  6099. } else {
  6100. var texture = document.createElement( 'canvas' );
  6101. where[ name ] = new THREE.Texture( texture );
  6102. }
  6103. where[ name ].sourceFile = sourceFile;
  6104. if( repeat ) {
  6105. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  6106. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  6107. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  6108. }
  6109. if ( offset ) {
  6110. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  6111. }
  6112. if ( wrap ) {
  6113. var wrapMap = {
  6114. "repeat": THREE.RepeatWrapping,
  6115. "mirror": THREE.MirroredRepeatWrapping
  6116. }
  6117. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  6118. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  6119. }
  6120. if ( anisotropy ) {
  6121. where[ name ].anisotropy = anisotropy;
  6122. }
  6123. if ( ! isCompressed ) {
  6124. load_image( where[ name ], fullPath );
  6125. }
  6126. }
  6127. function rgb2hex( rgb ) {
  6128. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  6129. }
  6130. // defaults
  6131. var mtype = "MeshLambertMaterial";
  6132. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  6133. // parameters from model file
  6134. if ( m.shading ) {
  6135. var shading = m.shading.toLowerCase();
  6136. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  6137. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  6138. }
  6139. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  6140. mpars.blending = THREE[ m.blending ];
  6141. }
  6142. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  6143. mpars.transparent = m.transparent;
  6144. }
  6145. if ( m.depthTest !== undefined ) {
  6146. mpars.depthTest = m.depthTest;
  6147. }
  6148. if ( m.depthWrite !== undefined ) {
  6149. mpars.depthWrite = m.depthWrite;
  6150. }
  6151. if ( m.visible !== undefined ) {
  6152. mpars.visible = m.visible;
  6153. }
  6154. if ( m.flipSided !== undefined ) {
  6155. mpars.side = THREE.BackSide;
  6156. }
  6157. if ( m.doubleSided !== undefined ) {
  6158. mpars.side = THREE.DoubleSide;
  6159. }
  6160. if ( m.wireframe !== undefined ) {
  6161. mpars.wireframe = m.wireframe;
  6162. }
  6163. if ( m.vertexColors !== undefined ) {
  6164. if ( m.vertexColors === "face" ) {
  6165. mpars.vertexColors = THREE.FaceColors;
  6166. } else if ( m.vertexColors ) {
  6167. mpars.vertexColors = THREE.VertexColors;
  6168. }
  6169. }
  6170. // colors
  6171. if ( m.colorDiffuse ) {
  6172. mpars.color = rgb2hex( m.colorDiffuse );
  6173. } else if ( m.DbgColor ) {
  6174. mpars.color = m.DbgColor;
  6175. }
  6176. if ( m.colorSpecular ) {
  6177. mpars.specular = rgb2hex( m.colorSpecular );
  6178. }
  6179. if ( m.colorAmbient ) {
  6180. mpars.ambient = rgb2hex( m.colorAmbient );
  6181. }
  6182. // modifiers
  6183. if ( m.transparency ) {
  6184. mpars.opacity = m.transparency;
  6185. }
  6186. if ( m.specularCoef ) {
  6187. mpars.shininess = m.specularCoef;
  6188. }
  6189. // textures
  6190. if ( m.mapDiffuse && texturePath ) {
  6191. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  6192. }
  6193. if ( m.mapLight && texturePath ) {
  6194. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  6195. }
  6196. if ( m.mapBump && texturePath ) {
  6197. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  6198. }
  6199. if ( m.mapNormal && texturePath ) {
  6200. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  6201. }
  6202. if ( m.mapSpecular && texturePath ) {
  6203. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  6204. }
  6205. //
  6206. if ( m.mapBumpScale ) {
  6207. mpars.bumpScale = m.mapBumpScale;
  6208. }
  6209. // special case for normal mapped material
  6210. if ( m.mapNormal ) {
  6211. var shader = THREE.ShaderLib[ "normalmap" ];
  6212. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6213. uniforms[ "tNormal" ].value = mpars.normalMap;
  6214. if ( m.mapNormalFactor ) {
  6215. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  6216. }
  6217. if ( mpars.map ) {
  6218. uniforms[ "tDiffuse" ].value = mpars.map;
  6219. uniforms[ "enableDiffuse" ].value = true;
  6220. }
  6221. if ( mpars.specularMap ) {
  6222. uniforms[ "tSpecular" ].value = mpars.specularMap;
  6223. uniforms[ "enableSpecular" ].value = true;
  6224. }
  6225. if ( mpars.lightMap ) {
  6226. uniforms[ "tAO" ].value = mpars.lightMap;
  6227. uniforms[ "enableAO" ].value = true;
  6228. }
  6229. // for the moment don't handle displacement texture
  6230. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  6231. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  6232. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  6233. uniforms[ "uShininess" ].value = mpars.shininess;
  6234. if ( mpars.opacity !== undefined ) {
  6235. uniforms[ "uOpacity" ].value = mpars.opacity;
  6236. }
  6237. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6238. var material = new THREE.ShaderMaterial( parameters );
  6239. if ( mpars.transparent ) {
  6240. material.transparent = true;
  6241. }
  6242. } else {
  6243. var material = new THREE[ mtype ]( mpars );
  6244. }
  6245. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6246. return material;
  6247. }
  6248. };
  6249. /**
  6250. * @author mrdoob / http://mrdoob.com/
  6251. */
  6252. THREE.XHRLoader = function ( manager ) {
  6253. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6254. };
  6255. THREE.XHRLoader.prototype = {
  6256. constructor: THREE.XHRLoader,
  6257. load: function ( url, onLoad, onProgress, onError ) {
  6258. var scope = this;
  6259. var request = new XMLHttpRequest();
  6260. if ( onLoad !== undefined ) {
  6261. request.addEventListener( 'load', function ( event ) {
  6262. scope.manager.itemEnd( url );
  6263. onLoad( event.target.responseText );
  6264. }, false );
  6265. }
  6266. if ( onProgress !== undefined ) {
  6267. request.addEventListener( 'progress', function ( event ) {
  6268. onProgress( event );
  6269. }, false );
  6270. }
  6271. if ( onError !== undefined ) {
  6272. request.addEventListener( 'error', function ( event ) {
  6273. onError( event );
  6274. }, false );
  6275. }
  6276. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  6277. request.open( 'GET', url, true );
  6278. request.send( null );
  6279. scope.manager.itemStart( url );
  6280. },
  6281. setCrossOrigin: function ( value ) {
  6282. this.crossOrigin = value;
  6283. }
  6284. };
  6285. /**
  6286. * @author mrdoob / http://mrdoob.com/
  6287. */
  6288. THREE.ImageLoader = function ( manager ) {
  6289. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6290. };
  6291. THREE.ImageLoader.prototype = {
  6292. constructor: THREE.ImageLoader,
  6293. load: function ( url, onLoad, onProgress, onError ) {
  6294. var scope = this;
  6295. var image = document.createElement( 'img' );
  6296. if ( onLoad !== undefined ) {
  6297. image.addEventListener( 'load', function ( event ) {
  6298. scope.manager.itemEnd( url );
  6299. onLoad( this );
  6300. }, false );
  6301. }
  6302. if ( onProgress !== undefined ) {
  6303. image.addEventListener( 'progress', function ( event ) {
  6304. onProgress( event );
  6305. }, false );
  6306. }
  6307. if ( onError !== undefined ) {
  6308. image.addEventListener( 'error', function ( event ) {
  6309. onError( event );
  6310. }, false );
  6311. }
  6312. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  6313. image.src = url;
  6314. scope.manager.itemStart( url );
  6315. },
  6316. setCrossOrigin: function ( value ) {
  6317. this.crossOrigin = value;
  6318. }
  6319. }
  6320. /**
  6321. * @author mrdoob / http://mrdoob.com/
  6322. * @author alteredq / http://alteredqualia.com/
  6323. */
  6324. THREE.JSONLoader = function ( showStatus ) {
  6325. THREE.Loader.call( this, showStatus );
  6326. this.withCredentials = false;
  6327. };
  6328. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  6329. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  6330. var scope = this;
  6331. // todo: unify load API to for easier SceneLoader use
  6332. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  6333. this.onLoadStart();
  6334. this.loadAjaxJSON( this, url, callback, texturePath );
  6335. };
  6336. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  6337. var xhr = new XMLHttpRequest();
  6338. var length = 0;
  6339. xhr.onreadystatechange = function () {
  6340. if ( xhr.readyState === xhr.DONE ) {
  6341. if ( xhr.status === 200 || xhr.status === 0 ) {
  6342. if ( xhr.responseText ) {
  6343. var json = JSON.parse( xhr.responseText );
  6344. var result = context.parse( json, texturePath );
  6345. callback( result.geometry, result.materials );
  6346. } else {
  6347. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  6348. }
  6349. // in context of more complex asset initialization
  6350. // do not block on single failed file
  6351. // maybe should go even one more level up
  6352. context.onLoadComplete();
  6353. } else {
  6354. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  6355. }
  6356. } else if ( xhr.readyState === xhr.LOADING ) {
  6357. if ( callbackProgress ) {
  6358. if ( length === 0 ) {
  6359. length = xhr.getResponseHeader( "Content-Length" );
  6360. }
  6361. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  6362. }
  6363. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  6364. if ( callbackProgress !== undefined ) {
  6365. length = xhr.getResponseHeader( "Content-Length" );
  6366. }
  6367. }
  6368. };
  6369. xhr.open( "GET", url, true );
  6370. xhr.withCredentials = this.withCredentials;
  6371. xhr.send( null );
  6372. };
  6373. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  6374. var scope = this,
  6375. geometry = new THREE.Geometry(),
  6376. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  6377. parseModel( scale );
  6378. parseSkin();
  6379. parseMorphing( scale );
  6380. geometry.computeCentroids();
  6381. geometry.computeFaceNormals();
  6382. geometry.computeBoundingSphere();
  6383. function parseModel( scale ) {
  6384. function isBitSet( value, position ) {
  6385. return value & ( 1 << position );
  6386. }
  6387. var i, j, fi,
  6388. offset, zLength, nVertices,
  6389. colorIndex, normalIndex, uvIndex, materialIndex,
  6390. type,
  6391. isQuad,
  6392. hasMaterial,
  6393. hasFaceUv, hasFaceVertexUv,
  6394. hasFaceNormal, hasFaceVertexNormal,
  6395. hasFaceColor, hasFaceVertexColor,
  6396. vertex, face, color, normal,
  6397. uvLayer, uvs, u, v,
  6398. faces = json.faces,
  6399. vertices = json.vertices,
  6400. normals = json.normals,
  6401. colors = json.colors,
  6402. nUvLayers = 0;
  6403. if ( json.uvs !== undefined ) {
  6404. // disregard empty arrays
  6405. for ( i = 0; i < json.uvs.length; i++ ) {
  6406. if ( json.uvs[ i ].length ) nUvLayers ++;
  6407. }
  6408. for ( i = 0; i < nUvLayers; i++ ) {
  6409. geometry.faceUvs[ i ] = [];
  6410. geometry.faceVertexUvs[ i ] = [];
  6411. }
  6412. }
  6413. offset = 0;
  6414. zLength = vertices.length;
  6415. while ( offset < zLength ) {
  6416. vertex = new THREE.Vector3();
  6417. vertex.x = vertices[ offset ++ ] * scale;
  6418. vertex.y = vertices[ offset ++ ] * scale;
  6419. vertex.z = vertices[ offset ++ ] * scale;
  6420. geometry.vertices.push( vertex );
  6421. }
  6422. offset = 0;
  6423. zLength = faces.length;
  6424. while ( offset < zLength ) {
  6425. type = faces[ offset ++ ];
  6426. isQuad = isBitSet( type, 0 );
  6427. hasMaterial = isBitSet( type, 1 );
  6428. hasFaceUv = isBitSet( type, 2 );
  6429. hasFaceVertexUv = isBitSet( type, 3 );
  6430. hasFaceNormal = isBitSet( type, 4 );
  6431. hasFaceVertexNormal = isBitSet( type, 5 );
  6432. hasFaceColor = isBitSet( type, 6 );
  6433. hasFaceVertexColor = isBitSet( type, 7 );
  6434. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  6435. if ( isQuad ) {
  6436. face = new THREE.Face4();
  6437. face.a = faces[ offset ++ ];
  6438. face.b = faces[ offset ++ ];
  6439. face.c = faces[ offset ++ ];
  6440. face.d = faces[ offset ++ ];
  6441. nVertices = 4;
  6442. } else {
  6443. face = new THREE.Face3();
  6444. face.a = faces[ offset ++ ];
  6445. face.b = faces[ offset ++ ];
  6446. face.c = faces[ offset ++ ];
  6447. nVertices = 3;
  6448. }
  6449. if ( hasMaterial ) {
  6450. materialIndex = faces[ offset ++ ];
  6451. face.materialIndex = materialIndex;
  6452. }
  6453. // to get face <=> uv index correspondence
  6454. fi = geometry.faces.length;
  6455. if ( hasFaceUv ) {
  6456. for ( i = 0; i < nUvLayers; i++ ) {
  6457. uvLayer = json.uvs[ i ];
  6458. uvIndex = faces[ offset ++ ];
  6459. u = uvLayer[ uvIndex * 2 ];
  6460. v = uvLayer[ uvIndex * 2 + 1 ];
  6461. geometry.faceUvs[ i ][ fi ] = new THREE.Vector2( u, v );
  6462. }
  6463. }
  6464. if ( hasFaceVertexUv ) {
  6465. for ( i = 0; i < nUvLayers; i++ ) {
  6466. uvLayer = json.uvs[ i ];
  6467. uvs = [];
  6468. for ( j = 0; j < nVertices; j ++ ) {
  6469. uvIndex = faces[ offset ++ ];
  6470. u = uvLayer[ uvIndex * 2 ];
  6471. v = uvLayer[ uvIndex * 2 + 1 ];
  6472. uvs[ j ] = new THREE.Vector2( u, v );
  6473. }
  6474. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  6475. }
  6476. }
  6477. if ( hasFaceNormal ) {
  6478. normalIndex = faces[ offset ++ ] * 3;
  6479. normal = new THREE.Vector3();
  6480. normal.x = normals[ normalIndex ++ ];
  6481. normal.y = normals[ normalIndex ++ ];
  6482. normal.z = normals[ normalIndex ];
  6483. face.normal = normal;
  6484. }
  6485. if ( hasFaceVertexNormal ) {
  6486. for ( i = 0; i < nVertices; i++ ) {
  6487. normalIndex = faces[ offset ++ ] * 3;
  6488. normal = new THREE.Vector3();
  6489. normal.x = normals[ normalIndex ++ ];
  6490. normal.y = normals[ normalIndex ++ ];
  6491. normal.z = normals[ normalIndex ];
  6492. face.vertexNormals.push( normal );
  6493. }
  6494. }
  6495. if ( hasFaceColor ) {
  6496. colorIndex = faces[ offset ++ ];
  6497. color = new THREE.Color( colors[ colorIndex ] );
  6498. face.color = color;
  6499. }
  6500. if ( hasFaceVertexColor ) {
  6501. for ( i = 0; i < nVertices; i++ ) {
  6502. colorIndex = faces[ offset ++ ];
  6503. color = new THREE.Color( colors[ colorIndex ] );
  6504. face.vertexColors.push( color );
  6505. }
  6506. }
  6507. geometry.faces.push( face );
  6508. }
  6509. };
  6510. function parseSkin() {
  6511. var i, l, x, y, z, w, a, b, c, d;
  6512. if ( json.skinWeights ) {
  6513. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  6514. x = json.skinWeights[ i ];
  6515. y = json.skinWeights[ i + 1 ];
  6516. z = 0;
  6517. w = 0;
  6518. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  6519. }
  6520. }
  6521. if ( json.skinIndices ) {
  6522. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  6523. a = json.skinIndices[ i ];
  6524. b = json.skinIndices[ i + 1 ];
  6525. c = 0;
  6526. d = 0;
  6527. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  6528. }
  6529. }
  6530. geometry.bones = json.bones;
  6531. geometry.animation = json.animation;
  6532. };
  6533. function parseMorphing( scale ) {
  6534. if ( json.morphTargets !== undefined ) {
  6535. var i, l, v, vl, dstVertices, srcVertices;
  6536. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  6537. geometry.morphTargets[ i ] = {};
  6538. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  6539. geometry.morphTargets[ i ].vertices = [];
  6540. dstVertices = geometry.morphTargets[ i ].vertices;
  6541. srcVertices = json.morphTargets [ i ].vertices;
  6542. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  6543. var vertex = new THREE.Vector3();
  6544. vertex.x = srcVertices[ v ] * scale;
  6545. vertex.y = srcVertices[ v + 1 ] * scale;
  6546. vertex.z = srcVertices[ v + 2 ] * scale;
  6547. dstVertices.push( vertex );
  6548. }
  6549. }
  6550. }
  6551. if ( json.morphColors !== undefined ) {
  6552. var i, l, c, cl, dstColors, srcColors, color;
  6553. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  6554. geometry.morphColors[ i ] = {};
  6555. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  6556. geometry.morphColors[ i ].colors = [];
  6557. dstColors = geometry.morphColors[ i ].colors;
  6558. srcColors = json.morphColors [ i ].colors;
  6559. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  6560. color = new THREE.Color( 0xffaa00 );
  6561. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  6562. dstColors.push( color );
  6563. }
  6564. }
  6565. }
  6566. };
  6567. if ( json.materials === undefined ) {
  6568. return { geometry: geometry };
  6569. } else {
  6570. var materials = this.initMaterials( json.materials, texturePath );
  6571. if ( this.needsTangents( materials ) ) {
  6572. geometry.computeTangents();
  6573. }
  6574. return { geometry: geometry, materials: materials };
  6575. }
  6576. };
  6577. /**
  6578. * @author mrdoob / http://mrdoob.com/
  6579. */
  6580. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  6581. var scope = this;
  6582. var loaded = 0, total = 0;
  6583. this.onLoad = onLoad;
  6584. this.onProgress = onProgress;
  6585. this.onError = onError;
  6586. this.itemStart = function ( url ) {
  6587. total ++;
  6588. };
  6589. this.itemEnd = function ( url ) {
  6590. loaded ++;
  6591. if ( scope.onProgress !== undefined ) {
  6592. scope.onProgress( url, loaded, total );
  6593. }
  6594. if ( loaded === total && scope.onLoad !== undefined ) {
  6595. scope.onLoad();
  6596. }
  6597. };
  6598. };
  6599. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  6600. /**
  6601. * @author mrdoob / http://mrdoob.com/
  6602. */
  6603. THREE.GeometryLoader = function ( manager ) {
  6604. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6605. };
  6606. THREE.GeometryLoader.prototype = {
  6607. constructor: THREE.GeometryLoader,
  6608. load: function ( url, onLoad, onProgress, onError ) {
  6609. var scope = this;
  6610. var loader = new THREE.XHRLoader();
  6611. loader.setCrossOrigin( this.crossOrigin );
  6612. loader.load( url, function ( text ) {
  6613. onLoad( scope.parse( JSON.parse( text ) ) );
  6614. } );
  6615. },
  6616. setCrossOrigin: function ( value ) {
  6617. this.crossOrigin = value;
  6618. },
  6619. parse: function ( json ) {
  6620. }
  6621. };
  6622. /**
  6623. * @author mrdoob / http://mrdoob.com/
  6624. */
  6625. THREE.MaterialLoader = function ( manager ) {
  6626. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6627. };
  6628. THREE.MaterialLoader.prototype = {
  6629. constructor: THREE.MaterialLoader,
  6630. load: function ( url, onLoad, onProgress, onError ) {
  6631. var scope = this;
  6632. var loader = new THREE.XHRLoader();
  6633. loader.setCrossOrigin( this.crossOrigin );
  6634. loader.load( url, function ( text ) {
  6635. onLoad( scope.parse( JSON.parse( text ) ) );
  6636. } );
  6637. },
  6638. setCrossOrigin: function ( value ) {
  6639. this.crossOrigin = value;
  6640. },
  6641. parse: function ( json ) {
  6642. var material;
  6643. switch ( json.type ) {
  6644. case 'MeshBasicMaterial':
  6645. material = new THREE.MeshBasicMaterial( {
  6646. color: json.color,
  6647. opacity: json.opacity,
  6648. transparent: json.transparent,
  6649. wireframe: json.wireframe
  6650. } );
  6651. break;
  6652. case 'MeshLambertMaterial':
  6653. material = new THREE.MeshLambertMaterial( {
  6654. color: json.color,
  6655. ambient: json.ambient,
  6656. emissive: json.emissive,
  6657. opacity: json.opacity,
  6658. transparent: json.transparent,
  6659. wireframe: json.wireframe
  6660. } );
  6661. break;
  6662. case 'MeshPhongMaterial':
  6663. material = new THREE.MeshPhongMaterial( {
  6664. color: json.color,
  6665. ambient: json.ambient,
  6666. emissive: json.emissive,
  6667. specular: json.specular,
  6668. shininess: json.shininess,
  6669. opacity: json.opacity,
  6670. transparent: json.transparent,
  6671. wireframe: json.wireframe
  6672. } );
  6673. break;
  6674. case 'MeshNormalMaterial':
  6675. material = new THREE.MeshNormalMaterial( {
  6676. opacity: json.opacity,
  6677. transparent: json.transparent,
  6678. wireframe: json.wireframe
  6679. } );
  6680. break;
  6681. case 'MeshDepthMaterial':
  6682. material = new THREE.MeshDepthMaterial( {
  6683. opacity: json.opacity,
  6684. transparent: json.transparent,
  6685. wireframe: json.wireframe
  6686. } );
  6687. break;
  6688. }
  6689. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  6690. return material;
  6691. }
  6692. };
  6693. /**
  6694. * @author mrdoob / http://mrdoob.com/
  6695. */
  6696. THREE.ObjectLoader = function ( manager ) {
  6697. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6698. };
  6699. THREE.ObjectLoader.prototype = {
  6700. constructor: THREE.ObjectLoader,
  6701. load: function ( url, onLoad, onProgress, onError ) {
  6702. var scope = this;
  6703. var loader = new THREE.XHRLoader( scope.manager );
  6704. loader.setCrossOrigin( this.crossOrigin );
  6705. loader.load( url, function ( text ) {
  6706. onLoad( scope.parse( JSON.parse( text ) ) );
  6707. } );
  6708. },
  6709. setCrossOrigin: function ( value ) {
  6710. this.crossOrigin = value;
  6711. },
  6712. parse: function ( json ) {
  6713. var geometries = this.parseGeometries( json.geometries );
  6714. var materials = this.parseMaterials( json.materials );
  6715. var object = this.parseObject( json.object, geometries, materials );
  6716. return object;
  6717. },
  6718. parseGeometries: function ( json ) {
  6719. var geometries = {};
  6720. if ( json !== undefined ) {
  6721. var loader = new THREE.JSONLoader();
  6722. for ( var i = 0, l = json.length; i < l; i ++ ) {
  6723. var geometry;
  6724. var data = json[ i ];
  6725. switch ( data.type ) {
  6726. case 'PlaneGeometry':
  6727. geometry = new THREE.PlaneGeometry(
  6728. data.width,
  6729. data.height,
  6730. data.widthSegments,
  6731. data.heightSegments
  6732. );
  6733. break;
  6734. case 'CubeGeometry':
  6735. geometry = new THREE.CubeGeometry(
  6736. data.width,
  6737. data.height,
  6738. data.depth,
  6739. data.widthSegments,
  6740. data.heightSegments,
  6741. data.depthSegments
  6742. );
  6743. break;
  6744. case 'CylinderGeometry':
  6745. geometry = new THREE.CylinderGeometry(
  6746. data.radiusTop,
  6747. data.radiusBottom,
  6748. data.height,
  6749. data.radiusSegments,
  6750. data.heightSegments,
  6751. data.openEnded
  6752. );
  6753. break;
  6754. case 'SphereGeometry':
  6755. geometry = new THREE.SphereGeometry(
  6756. data.radius,
  6757. data.widthSegments,
  6758. data.heightSegments,
  6759. data.phiStart,
  6760. data.phiLength,
  6761. data.thetaStart,
  6762. data.thetaLength
  6763. );
  6764. break;
  6765. case 'IcosahedronGeometry':
  6766. geometry = new THREE.IcosahedronGeometry(
  6767. data.radius,
  6768. data.detail
  6769. );
  6770. break;
  6771. case 'TorusGeometry':
  6772. geometry = new THREE.TorusGeometry(
  6773. data.radius,
  6774. data.tube,
  6775. data.radialSegments,
  6776. data.tubularSegments,
  6777. data.arc
  6778. );
  6779. break;
  6780. case 'TorusKnotGeometry':
  6781. geometry = new THREE.TorusKnotGeometry(
  6782. data.radius,
  6783. data.tube,
  6784. data.radialSegments,
  6785. data.tubularSegments,
  6786. data.p,
  6787. data.q,
  6788. data.heightScale
  6789. );
  6790. break;
  6791. case 'Geometry':
  6792. geometry = loader.parse( data.data ).geometry;
  6793. break;
  6794. }
  6795. geometry.uuid = data.uuid;
  6796. if ( data.name !== undefined ) geometry.name = data.name;
  6797. geometries[ data.uuid ] = geometry;
  6798. }
  6799. }
  6800. return geometries;
  6801. },
  6802. parseMaterials: function ( json ) {
  6803. var materials = {};
  6804. if ( json !== undefined ) {
  6805. var loader = new THREE.MaterialLoader();
  6806. for ( var i = 0, l = json.length; i < l; i ++ ) {
  6807. var data = json[ i ];
  6808. var material = loader.parse( data );
  6809. material.uuid = data.uuid;
  6810. if ( data.name !== undefined ) material.name = data.name;
  6811. materials[ data.uuid ] = material;
  6812. }
  6813. }
  6814. return materials;
  6815. },
  6816. parseObject: function () {
  6817. var matrix = new THREE.Matrix4();
  6818. return function ( data, geometries, materials ) {
  6819. var object;
  6820. switch ( data.type ) {
  6821. case 'Scene':
  6822. object = new THREE.Scene();
  6823. break;
  6824. case 'PerspectiveCamera':
  6825. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  6826. break;
  6827. case 'OrthographicCamera':
  6828. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  6829. break;
  6830. case 'AmbientLight':
  6831. object = new THREE.AmbientLight( data.color );
  6832. break;
  6833. case 'DirectionalLight':
  6834. object = new THREE.DirectionalLight( data.color, data.intensity );
  6835. break;
  6836. case 'PointLight':
  6837. object = new THREE.PointLight( data.color, data.intensity, data.distance );
  6838. break;
  6839. case 'SpotLight':
  6840. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent );
  6841. break;
  6842. case 'HemisphereLight':
  6843. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  6844. break;
  6845. case 'Mesh':
  6846. var geometry = geometries[ data.geometry ];
  6847. var material = materials[ data.material ];
  6848. if ( geometry === undefined ) {
  6849. console.error( 'THREE.ObjectLoader: Undefined geometry ' + data.geometry );
  6850. }
  6851. if ( material === undefined ) {
  6852. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  6853. }
  6854. object = new THREE.Mesh( geometry, material );
  6855. break;
  6856. default:
  6857. object = new THREE.Object3D();
  6858. }
  6859. object.uuid = data.uuid;
  6860. if ( data.name !== undefined ) object.name = data.name;
  6861. if ( data.matrix !== undefined ) {
  6862. matrix.fromArray( data.matrix );
  6863. matrix.decompose( object.position, object.quaternion, object.scale );
  6864. } else {
  6865. if ( data.position !== undefined ) object.position.fromArray( data.position );
  6866. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  6867. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  6868. }
  6869. if ( data.visible !== undefined ) object.visible = data.visible;
  6870. if ( data.userData !== undefined ) object.userData = data.userData;
  6871. if ( data.children !== undefined ) {
  6872. for ( var child in data.children ) {
  6873. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  6874. }
  6875. }
  6876. return object;
  6877. }
  6878. }()
  6879. };
  6880. /**
  6881. * @author alteredq / http://alteredqualia.com/
  6882. */
  6883. THREE.SceneLoader = function () {
  6884. this.onLoadStart = function () {};
  6885. this.onLoadProgress = function() {};
  6886. this.onLoadComplete = function () {};
  6887. this.callbackSync = function () {};
  6888. this.callbackProgress = function () {};
  6889. this.geometryHandlers = {};
  6890. this.hierarchyHandlers = {};
  6891. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  6892. };
  6893. THREE.SceneLoader.prototype = {
  6894. constructor: THREE.SceneLoader,
  6895. load: function ( url, onLoad, onProgress, onError ) {
  6896. var scope = this;
  6897. var loader = new THREE.XHRLoader( scope.manager );
  6898. loader.setCrossOrigin( this.crossOrigin );
  6899. loader.load( url, function ( text ) {
  6900. scope.parse( JSON.parse( text ), onLoad, url );
  6901. } );
  6902. },
  6903. setCrossOrigin: function ( value ) {
  6904. this.crossOrigin = value;
  6905. },
  6906. addGeometryHandler: function ( typeID, loaderClass ) {
  6907. this.geometryHandlers[ typeID ] = { "loaderClass": loaderClass };
  6908. },
  6909. addHierarchyHandler: function ( typeID, loaderClass ) {
  6910. this.hierarchyHandlers[ typeID ] = { "loaderClass": loaderClass };
  6911. },
  6912. parse: function ( json, callbackFinished, url ) {
  6913. var scope = this;
  6914. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  6915. var geometry, material, camera, fog,
  6916. texture, images, color,
  6917. light, hex, intensity,
  6918. counter_models, counter_textures,
  6919. total_models, total_textures,
  6920. result;
  6921. var target_array = [];
  6922. var data = json;
  6923. // async geometry loaders
  6924. for ( var typeID in this.geometryHandlers ) {
  6925. var loaderClass = this.geometryHandlers[ typeID ][ "loaderClass" ];
  6926. this.geometryHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  6927. }
  6928. // async hierachy loaders
  6929. for ( var typeID in this.hierarchyHandlers ) {
  6930. var loaderClass = this.hierarchyHandlers[ typeID ][ "loaderClass" ];
  6931. this.hierarchyHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  6932. }
  6933. counter_models = 0;
  6934. counter_textures = 0;
  6935. result = {
  6936. scene: new THREE.Scene(),
  6937. geometries: {},
  6938. face_materials: {},
  6939. materials: {},
  6940. textures: {},
  6941. objects: {},
  6942. cameras: {},
  6943. lights: {},
  6944. fogs: {},
  6945. empties: {},
  6946. groups: {}
  6947. };
  6948. if ( data.transform ) {
  6949. var position = data.transform.position,
  6950. rotation = data.transform.rotation,
  6951. scale = data.transform.scale;
  6952. if ( position ) {
  6953. result.scene.position.fromArray( position );
  6954. }
  6955. if ( rotation ) {
  6956. result.scene.rotation.fromArray( rotation );
  6957. }
  6958. if ( scale ) {
  6959. result.scene.scale.fromArray( scale );
  6960. }
  6961. if ( position || rotation || scale ) {
  6962. result.scene.updateMatrix();
  6963. result.scene.updateMatrixWorld();
  6964. }
  6965. }
  6966. function get_url( source_url, url_type ) {
  6967. if ( url_type == "relativeToHTML" ) {
  6968. return source_url;
  6969. } else {
  6970. return urlBase + "/" + source_url;
  6971. }
  6972. };
  6973. // toplevel loader function, delegates to handle_children
  6974. function handle_objects() {
  6975. handle_children( result.scene, data.objects );
  6976. }
  6977. // handle all the children from the loaded json and attach them to given parent
  6978. function handle_children( parent, children ) {
  6979. var mat, dst, pos, rot, scl, quat;
  6980. for ( var objID in children ) {
  6981. // check by id if child has already been handled,
  6982. // if not, create new object
  6983. var object = result.objects[ objID ];
  6984. var objJSON = children[ objID ];
  6985. if ( object === undefined ) {
  6986. // meshes
  6987. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  6988. if ( objJSON.loading === undefined ) {
  6989. var reservedTypes = {
  6990. "type": 1, "url": 1, "material": 1,
  6991. "position": 1, "rotation": 1, "scale" : 1,
  6992. "visible": 1, "children": 1, "userData": 1,
  6993. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1
  6994. };
  6995. var loaderParameters = {};
  6996. for ( var parType in objJSON ) {
  6997. if ( ! ( parType in reservedTypes ) ) {
  6998. loaderParameters[ parType ] = objJSON[ parType ];
  6999. }
  7000. }
  7001. material = result.materials[ objJSON.material ];
  7002. objJSON.loading = true;
  7003. var loader = scope.hierarchyHandlers[ objJSON.type ][ "loaderObject" ];
  7004. // ColladaLoader
  7005. if ( loader.options ) {
  7006. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  7007. // UTF8Loader
  7008. // OBJLoader
  7009. } else {
  7010. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  7011. }
  7012. }
  7013. } else if ( objJSON.geometry !== undefined ) {
  7014. geometry = result.geometries[ objJSON.geometry ];
  7015. // geometry already loaded
  7016. if ( geometry ) {
  7017. var needsTangents = false;
  7018. material = result.materials[ objJSON.material ];
  7019. needsTangents = material instanceof THREE.ShaderMaterial;
  7020. pos = objJSON.position;
  7021. rot = objJSON.rotation;
  7022. scl = objJSON.scale;
  7023. mat = objJSON.matrix;
  7024. quat = objJSON.quaternion;
  7025. // use materials from the model file
  7026. // if there is no material specified in the object
  7027. if ( ! objJSON.material ) {
  7028. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7029. }
  7030. // use materials from the model file
  7031. // if there is just empty face material
  7032. // (must create new material as each model has its own face material)
  7033. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  7034. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7035. }
  7036. if ( material instanceof THREE.MeshFaceMaterial ) {
  7037. for ( var i = 0; i < material.materials.length; i ++ ) {
  7038. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  7039. }
  7040. }
  7041. if ( needsTangents ) {
  7042. geometry.computeTangents();
  7043. }
  7044. if ( objJSON.skin ) {
  7045. object = new THREE.SkinnedMesh( geometry, material );
  7046. } else if ( objJSON.morph ) {
  7047. object = new THREE.MorphAnimMesh( geometry, material );
  7048. if ( objJSON.duration !== undefined ) {
  7049. object.duration = objJSON.duration;
  7050. }
  7051. if ( objJSON.time !== undefined ) {
  7052. object.time = objJSON.time;
  7053. }
  7054. if ( objJSON.mirroredLoop !== undefined ) {
  7055. object.mirroredLoop = objJSON.mirroredLoop;
  7056. }
  7057. if ( material.morphNormals ) {
  7058. geometry.computeMorphNormals();
  7059. }
  7060. } else {
  7061. object = new THREE.Mesh( geometry, material );
  7062. }
  7063. object.name = objID;
  7064. if ( mat ) {
  7065. object.matrixAutoUpdate = false;
  7066. object.matrix.set(
  7067. mat[0], mat[1], mat[2], mat[3],
  7068. mat[4], mat[5], mat[6], mat[7],
  7069. mat[8], mat[9], mat[10], mat[11],
  7070. mat[12], mat[13], mat[14], mat[15]
  7071. );
  7072. } else {
  7073. object.position.fromArray( pos );
  7074. if ( quat ) {
  7075. object.quaternion.fromArray( quat );
  7076. } else {
  7077. object.rotation.fromArray( rot );
  7078. }
  7079. object.scale.fromArray( scl );
  7080. }
  7081. object.visible = objJSON.visible;
  7082. object.castShadow = objJSON.castShadow;
  7083. object.receiveShadow = objJSON.receiveShadow;
  7084. parent.add( object );
  7085. result.objects[ objID ] = object;
  7086. }
  7087. // lights
  7088. } else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
  7089. hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
  7090. intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
  7091. if ( objJSON.type === "DirectionalLight" ) {
  7092. pos = objJSON.direction;
  7093. light = new THREE.DirectionalLight( hex, intensity );
  7094. light.position.fromArray( pos );
  7095. if ( objJSON.target ) {
  7096. target_array.push( { "object": light, "targetName" : objJSON.target } );
  7097. // kill existing default target
  7098. // otherwise it gets added to scene when parent gets added
  7099. light.target = null;
  7100. }
  7101. } else if ( objJSON.type === "PointLight" ) {
  7102. pos = objJSON.position;
  7103. dst = objJSON.distance;
  7104. light = new THREE.PointLight( hex, intensity, dst );
  7105. light.position.fromArray( pos );
  7106. } else if ( objJSON.type === "AmbientLight" ) {
  7107. light = new THREE.AmbientLight( hex );
  7108. }
  7109. parent.add( light );
  7110. light.name = objID;
  7111. result.lights[ objID ] = light;
  7112. result.objects[ objID ] = light;
  7113. // cameras
  7114. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  7115. pos = objJSON.position;
  7116. rot = objJSON.rotation;
  7117. quat = objJSON.quaternion;
  7118. if ( objJSON.type === "PerspectiveCamera" ) {
  7119. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  7120. } else if ( objJSON.type === "OrthographicCamera" ) {
  7121. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  7122. }
  7123. camera.name = objID;
  7124. camera.position.fromArray( pos );
  7125. if ( quat !== undefined ) {
  7126. camera.quaternion.fromArray( quat );
  7127. } else if ( rot !== undefined ) {
  7128. camera.rotation.fromArray( rot );
  7129. }
  7130. parent.add( camera );
  7131. result.cameras[ objID ] = camera;
  7132. result.objects[ objID ] = camera;
  7133. // pure Object3D
  7134. } else {
  7135. pos = objJSON.position;
  7136. rot = objJSON.rotation;
  7137. scl = objJSON.scale;
  7138. quat = objJSON.quaternion;
  7139. object = new THREE.Object3D();
  7140. object.name = objID;
  7141. object.position.fromArray( pos );
  7142. if ( quat ) {
  7143. object.quaternion.fromArray( quat );
  7144. } else {
  7145. object.rotation.fromArray( rot );
  7146. }
  7147. object.scale.fromArray( scl );
  7148. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  7149. parent.add( object );
  7150. result.objects[ objID ] = object;
  7151. result.empties[ objID ] = object;
  7152. }
  7153. if ( object ) {
  7154. if ( objJSON.userData !== undefined ) {
  7155. for ( var key in objJSON.userData ) {
  7156. var value = objJSON.userData[ key ];
  7157. object.userData[ key ] = value;
  7158. }
  7159. }
  7160. if ( objJSON.groups !== undefined ) {
  7161. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  7162. var groupID = objJSON.groups[ i ];
  7163. if ( result.groups[ groupID ] === undefined ) {
  7164. result.groups[ groupID ] = [];
  7165. }
  7166. result.groups[ groupID ].push( objID );
  7167. }
  7168. }
  7169. }
  7170. }
  7171. if ( object !== undefined && objJSON.children !== undefined ) {
  7172. handle_children( object, objJSON.children );
  7173. }
  7174. }
  7175. };
  7176. function handle_mesh( geo, mat, id ) {
  7177. result.geometries[ id ] = geo;
  7178. result.face_materials[ id ] = mat;
  7179. handle_objects();
  7180. };
  7181. function handle_hierarchy( node, id, parent, material, obj ) {
  7182. var p = obj.position;
  7183. var r = obj.rotation;
  7184. var q = obj.quaternion;
  7185. var s = obj.scale;
  7186. node.position.fromArray( p );
  7187. if ( q ) {
  7188. node.quaternion.fromArray( q );
  7189. } else {
  7190. node.rotation.fromArray( r );
  7191. }
  7192. node.scale.fromArray( s );
  7193. // override children materials
  7194. // if object material was specified in JSON explicitly
  7195. if ( material ) {
  7196. node.traverse( function ( child ) {
  7197. child.material = material;
  7198. } );
  7199. }
  7200. // override children visibility
  7201. // with root node visibility as specified in JSON
  7202. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  7203. node.traverse( function ( child ) {
  7204. child.visible = visible;
  7205. } );
  7206. parent.add( node );
  7207. node.name = id;
  7208. result.objects[ id ] = node;
  7209. handle_objects();
  7210. };
  7211. function create_callback_geometry( id ) {
  7212. return function ( geo, mat ) {
  7213. geo.name = id;
  7214. handle_mesh( geo, mat, id );
  7215. counter_models -= 1;
  7216. scope.onLoadComplete();
  7217. async_callback_gate();
  7218. }
  7219. };
  7220. function create_callback_hierachy( id, parent, material, obj ) {
  7221. return function ( event ) {
  7222. var result;
  7223. // loaders which use EventDispatcher
  7224. if ( event.content ) {
  7225. result = event.content;
  7226. // ColladaLoader
  7227. } else if ( event.dae ) {
  7228. result = event.scene;
  7229. // UTF8Loader
  7230. } else {
  7231. result = event;
  7232. }
  7233. handle_hierarchy( result, id, parent, material, obj );
  7234. counter_models -= 1;
  7235. scope.onLoadComplete();
  7236. async_callback_gate();
  7237. }
  7238. };
  7239. function create_callback_embed( id ) {
  7240. return function ( geo, mat ) {
  7241. geo.name = id;
  7242. result.geometries[ id ] = geo;
  7243. result.face_materials[ id ] = mat;
  7244. }
  7245. };
  7246. function async_callback_gate() {
  7247. var progress = {
  7248. totalModels : total_models,
  7249. totalTextures : total_textures,
  7250. loadedModels : total_models - counter_models,
  7251. loadedTextures : total_textures - counter_textures
  7252. };
  7253. scope.callbackProgress( progress, result );
  7254. scope.onLoadProgress();
  7255. if ( counter_models === 0 && counter_textures === 0 ) {
  7256. finalize();
  7257. callbackFinished( result );
  7258. }
  7259. };
  7260. function finalize() {
  7261. // take care of targets which could be asynchronously loaded objects
  7262. for ( var i = 0; i < target_array.length; i ++ ) {
  7263. var ta = target_array[ i ];
  7264. var target = result.objects[ ta.targetName ];
  7265. if ( target ) {
  7266. ta.object.target = target;
  7267. } else {
  7268. // if there was error and target of specified name doesn't exist in the scene file
  7269. // create instead dummy target
  7270. // (target must be added to scene explicitly as parent is already added)
  7271. ta.object.target = new THREE.Object3D();
  7272. result.scene.add( ta.object.target );
  7273. }
  7274. ta.object.target.userData.targetInverse = ta.object;
  7275. }
  7276. };
  7277. var callbackTexture = function ( count ) {
  7278. counter_textures -= count;
  7279. async_callback_gate();
  7280. scope.onLoadComplete();
  7281. };
  7282. // must use this instead of just directly calling callbackTexture
  7283. // because of closure in the calling context loop
  7284. var generateTextureCallback = function ( count ) {
  7285. return function () {
  7286. callbackTexture( count );
  7287. };
  7288. };
  7289. function traverse_json_hierarchy( objJSON, callback ) {
  7290. callback( objJSON );
  7291. if ( objJSON.children !== undefined ) {
  7292. for ( var objChildID in objJSON.children ) {
  7293. traverse_json_hierarchy( objJSON.children[ objChildID ], callback );
  7294. }
  7295. }
  7296. };
  7297. // first go synchronous elements
  7298. // fogs
  7299. var fogID, fogJSON;
  7300. for ( fogID in data.fogs ) {
  7301. fogJSON = data.fogs[ fogID ];
  7302. if ( fogJSON.type === "linear" ) {
  7303. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  7304. } else if ( fogJSON.type === "exp2" ) {
  7305. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  7306. }
  7307. color = fogJSON.color;
  7308. fog.color.setRGB( color[0], color[1], color[2] );
  7309. result.fogs[ fogID ] = fog;
  7310. }
  7311. // now come potentially asynchronous elements
  7312. // geometries
  7313. // count how many geometries will be loaded asynchronously
  7314. var geoID, geoJSON;
  7315. for ( geoID in data.geometries ) {
  7316. geoJSON = data.geometries[ geoID ];
  7317. if ( geoJSON.type in this.geometryHandlers ) {
  7318. counter_models += 1;
  7319. scope.onLoadStart();
  7320. }
  7321. }
  7322. // count how many hierarchies will be loaded asynchronously
  7323. for ( var objID in data.objects ) {
  7324. traverse_json_hierarchy( data.objects[ objID ], function ( objJSON ) {
  7325. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7326. counter_models += 1;
  7327. scope.onLoadStart();
  7328. }
  7329. });
  7330. }
  7331. total_models = counter_models;
  7332. for ( geoID in data.geometries ) {
  7333. geoJSON = data.geometries[ geoID ];
  7334. if ( geoJSON.type === "cube" ) {
  7335. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  7336. geometry.name = geoID;
  7337. result.geometries[ geoID ] = geometry;
  7338. } else if ( geoJSON.type === "plane" ) {
  7339. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  7340. geometry.name = geoID;
  7341. result.geometries[ geoID ] = geometry;
  7342. } else if ( geoJSON.type === "sphere" ) {
  7343. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  7344. geometry.name = geoID;
  7345. result.geometries[ geoID ] = geometry;
  7346. } else if ( geoJSON.type === "cylinder" ) {
  7347. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  7348. geometry.name = geoID;
  7349. result.geometries[ geoID ] = geometry;
  7350. } else if ( geoJSON.type === "torus" ) {
  7351. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  7352. geometry.name = geoID;
  7353. result.geometries[ geoID ] = geometry;
  7354. } else if ( geoJSON.type === "icosahedron" ) {
  7355. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  7356. geometry.name = geoID;
  7357. result.geometries[ geoID ] = geometry;
  7358. } else if ( geoJSON.type in this.geometryHandlers ) {
  7359. var loaderParameters = {};
  7360. for ( var parType in geoJSON ) {
  7361. if ( parType !== "type" && parType !== "url" ) {
  7362. loaderParameters[ parType ] = geoJSON[ parType ];
  7363. }
  7364. }
  7365. var loader = this.geometryHandlers[ geoJSON.type ][ "loaderObject" ];
  7366. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  7367. } else if ( geoJSON.type === "embedded" ) {
  7368. var modelJson = data.embeds[ geoJSON.id ],
  7369. texture_path = "";
  7370. // pass metadata along to jsonLoader so it knows the format version
  7371. modelJson.metadata = data.metadata;
  7372. if ( modelJson ) {
  7373. var jsonLoader = this.geometryHandlers[ "ascii" ][ "loaderObject" ];
  7374. var model = jsonLoader.parse( modelJson, texture_path );
  7375. create_callback_embed( geoID )( model.geometry, model.materials );
  7376. }
  7377. }
  7378. }
  7379. // textures
  7380. // count how many textures will be loaded asynchronously
  7381. var textureID, textureJSON;
  7382. for ( textureID in data.textures ) {
  7383. textureJSON = data.textures[ textureID ];
  7384. if ( textureJSON.url instanceof Array ) {
  7385. counter_textures += textureJSON.url.length;
  7386. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  7387. scope.onLoadStart();
  7388. }
  7389. } else {
  7390. counter_textures += 1;
  7391. scope.onLoadStart();
  7392. }
  7393. }
  7394. total_textures = counter_textures;
  7395. for ( textureID in data.textures ) {
  7396. textureJSON = data.textures[ textureID ];
  7397. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  7398. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  7399. }
  7400. if ( textureJSON.url instanceof Array ) {
  7401. var count = textureJSON.url.length;
  7402. var url_array = [];
  7403. for( var i = 0; i < count; i ++ ) {
  7404. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  7405. }
  7406. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  7407. if ( isCompressed ) {
  7408. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7409. } else {
  7410. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7411. }
  7412. } else {
  7413. var isCompressed = /\.dds$/i.test( textureJSON.url );
  7414. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  7415. var textureCallback = generateTextureCallback( 1 );
  7416. if ( isCompressed ) {
  7417. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  7418. } else {
  7419. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  7420. }
  7421. if ( THREE[ textureJSON.minFilter ] !== undefined )
  7422. texture.minFilter = THREE[ textureJSON.minFilter ];
  7423. if ( THREE[ textureJSON.magFilter ] !== undefined )
  7424. texture.magFilter = THREE[ textureJSON.magFilter ];
  7425. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  7426. if ( textureJSON.repeat ) {
  7427. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  7428. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  7429. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  7430. }
  7431. if ( textureJSON.offset ) {
  7432. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  7433. }
  7434. // handle wrap after repeat so that default repeat can be overriden
  7435. if ( textureJSON.wrap ) {
  7436. var wrapMap = {
  7437. "repeat": THREE.RepeatWrapping,
  7438. "mirror": THREE.MirroredRepeatWrapping
  7439. }
  7440. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  7441. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  7442. }
  7443. }
  7444. result.textures[ textureID ] = texture;
  7445. }
  7446. // materials
  7447. var matID, matJSON;
  7448. var parID;
  7449. for ( matID in data.materials ) {
  7450. matJSON = data.materials[ matID ];
  7451. for ( parID in matJSON.parameters ) {
  7452. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  7453. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  7454. } else if ( parID === "shading" ) {
  7455. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  7456. } else if ( parID === "side" ) {
  7457. if ( matJSON.parameters[ parID ] == "double" ) {
  7458. matJSON.parameters[ parID ] = THREE.DoubleSide;
  7459. } else if ( matJSON.parameters[ parID ] == "back" ) {
  7460. matJSON.parameters[ parID ] = THREE.BackSide;
  7461. } else {
  7462. matJSON.parameters[ parID ] = THREE.FrontSide;
  7463. }
  7464. } else if ( parID === "blending" ) {
  7465. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  7466. } else if ( parID === "combine" ) {
  7467. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  7468. } else if ( parID === "vertexColors" ) {
  7469. if ( matJSON.parameters[ parID ] == "face" ) {
  7470. matJSON.parameters[ parID ] = THREE.FaceColors;
  7471. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  7472. } else if ( matJSON.parameters[ parID ] ) {
  7473. matJSON.parameters[ parID ] = THREE.VertexColors;
  7474. }
  7475. } else if ( parID === "wrapRGB" ) {
  7476. var v3 = matJSON.parameters[ parID ];
  7477. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  7478. }
  7479. }
  7480. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  7481. matJSON.parameters.transparent = true;
  7482. }
  7483. if ( matJSON.parameters.normalMap ) {
  7484. var shader = THREE.ShaderLib[ "normalmap" ];
  7485. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  7486. var diffuse = matJSON.parameters.color;
  7487. var specular = matJSON.parameters.specular;
  7488. var ambient = matJSON.parameters.ambient;
  7489. var shininess = matJSON.parameters.shininess;
  7490. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  7491. if ( matJSON.parameters.normalScale ) {
  7492. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  7493. }
  7494. if ( matJSON.parameters.map ) {
  7495. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  7496. uniforms[ "enableDiffuse" ].value = true;
  7497. }
  7498. if ( matJSON.parameters.envMap ) {
  7499. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  7500. uniforms[ "enableReflection" ].value = true;
  7501. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  7502. }
  7503. if ( matJSON.parameters.lightMap ) {
  7504. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  7505. uniforms[ "enableAO" ].value = true;
  7506. }
  7507. if ( matJSON.parameters.specularMap ) {
  7508. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  7509. uniforms[ "enableSpecular" ].value = true;
  7510. }
  7511. if ( matJSON.parameters.displacementMap ) {
  7512. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  7513. uniforms[ "enableDisplacement" ].value = true;
  7514. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  7515. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  7516. }
  7517. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  7518. uniforms[ "uSpecularColor" ].value.setHex( specular );
  7519. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  7520. uniforms[ "uShininess" ].value = shininess;
  7521. if ( matJSON.parameters.opacity ) {
  7522. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  7523. }
  7524. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  7525. material = new THREE.ShaderMaterial( parameters );
  7526. } else {
  7527. material = new THREE[ matJSON.type ]( matJSON.parameters );
  7528. }
  7529. material.name = matID;
  7530. result.materials[ matID ] = material;
  7531. }
  7532. // second pass through all materials to initialize MeshFaceMaterials
  7533. // that could be referring to other materials out of order
  7534. for ( matID in data.materials ) {
  7535. matJSON = data.materials[ matID ];
  7536. if ( matJSON.parameters.materials ) {
  7537. var materialArray = [];
  7538. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  7539. var label = matJSON.parameters.materials[ i ];
  7540. materialArray.push( result.materials[ label ] );
  7541. }
  7542. result.materials[ matID ].materials = materialArray;
  7543. }
  7544. }
  7545. // objects ( synchronous init of procedural primitives )
  7546. handle_objects();
  7547. // defaults
  7548. if ( result.cameras && data.defaults.camera ) {
  7549. result.currentCamera = result.cameras[ data.defaults.camera ];
  7550. }
  7551. if ( result.fogs && data.defaults.fog ) {
  7552. result.scene.fog = result.fogs[ data.defaults.fog ];
  7553. }
  7554. // synchronous callback
  7555. scope.callbackSync( result );
  7556. // just in case there are no async elements
  7557. async_callback_gate();
  7558. }
  7559. }
  7560. /**
  7561. * @author mrdoob / http://mrdoob.com/
  7562. */
  7563. THREE.TextureLoader = function ( manager ) {
  7564. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7565. };
  7566. THREE.TextureLoader.prototype = {
  7567. constructor: THREE.TextureLoader,
  7568. load: function ( url, onLoad, onProgress, onError ) {
  7569. var scope = this;
  7570. var loader = new THREE.ImageLoader( scope.manager );
  7571. loader.setCrossOrigin( this.crossOrigin );
  7572. loader.load( url, function ( image ) {
  7573. var texture = new THREE.Texture( image );
  7574. texture.needsUpdate = true;
  7575. if ( onLoad !== undefined ) {
  7576. onLoad( texture );
  7577. }
  7578. } );
  7579. },
  7580. setCrossOrigin: function ( value ) {
  7581. this.crossOrigin = value;
  7582. }
  7583. };
  7584. /**
  7585. * @author mrdoob / http://mrdoob.com/
  7586. * @author alteredq / http://alteredqualia.com/
  7587. */
  7588. THREE.Material = function () {
  7589. this.id = THREE.MaterialIdCount ++;
  7590. this.uuid = THREE.Math.generateUUID();
  7591. this.name = '';
  7592. this.side = THREE.FrontSide;
  7593. this.opacity = 1;
  7594. this.transparent = false;
  7595. this.blending = THREE.NormalBlending;
  7596. this.blendSrc = THREE.SrcAlphaFactor;
  7597. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  7598. this.blendEquation = THREE.AddEquation;
  7599. this.depthTest = true;
  7600. this.depthWrite = true;
  7601. this.polygonOffset = false;
  7602. this.polygonOffsetFactor = 0;
  7603. this.polygonOffsetUnits = 0;
  7604. this.alphaTest = 0;
  7605. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  7606. this.visible = true;
  7607. this.needsUpdate = true;
  7608. };
  7609. THREE.Material.prototype = {
  7610. constructor: THREE.Material,
  7611. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  7612. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  7613. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  7614. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  7615. setValues: function ( values ) {
  7616. if ( values === undefined ) return;
  7617. for ( var key in values ) {
  7618. var newValue = values[ key ];
  7619. if ( newValue === undefined ) {
  7620. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  7621. continue;
  7622. }
  7623. if ( key in this ) {
  7624. var currentValue = this[ key ];
  7625. if ( currentValue instanceof THREE.Color ) {
  7626. currentValue.set( newValue );
  7627. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  7628. currentValue.copy( newValue );
  7629. } else if ( key == 'overdraw') {
  7630. // ensure overdraw is backwards-compatable with legacy boolean type
  7631. this[ key ] = Number(newValue);
  7632. } else {
  7633. this[ key ] = newValue;
  7634. }
  7635. }
  7636. }
  7637. },
  7638. clone: function ( material ) {
  7639. if ( material === undefined ) material = new THREE.Material();
  7640. material.name = this.name;
  7641. material.side = this.side;
  7642. material.opacity = this.opacity;
  7643. material.transparent = this.transparent;
  7644. material.blending = this.blending;
  7645. material.blendSrc = this.blendSrc;
  7646. material.blendDst = this.blendDst;
  7647. material.blendEquation = this.blendEquation;
  7648. material.depthTest = this.depthTest;
  7649. material.depthWrite = this.depthWrite;
  7650. material.polygonOffset = this.polygonOffset;
  7651. material.polygonOffsetFactor = this.polygonOffsetFactor;
  7652. material.polygonOffsetUnits = this.polygonOffsetUnits;
  7653. material.alphaTest = this.alphaTest;
  7654. material.overdraw = this.overdraw;
  7655. material.visible = this.visible;
  7656. return material;
  7657. },
  7658. dispose: function () {
  7659. this.dispatchEvent( { type: 'dispose' } );
  7660. }
  7661. };
  7662. THREE.MaterialIdCount = 0;
  7663. /**
  7664. * @author mrdoob / http://mrdoob.com/
  7665. * @author alteredq / http://alteredqualia.com/
  7666. *
  7667. * parameters = {
  7668. * color: <hex>,
  7669. * opacity: <float>,
  7670. *
  7671. * blending: THREE.NormalBlending,
  7672. * depthTest: <bool>,
  7673. * depthWrite: <bool>,
  7674. *
  7675. * linewidth: <float>,
  7676. * linecap: "round",
  7677. * linejoin: "round",
  7678. *
  7679. * vertexColors: <bool>
  7680. *
  7681. * fog: <bool>
  7682. * }
  7683. */
  7684. THREE.LineBasicMaterial = function ( parameters ) {
  7685. THREE.Material.call( this );
  7686. this.color = new THREE.Color( 0xffffff );
  7687. this.linewidth = 1;
  7688. this.linecap = 'round';
  7689. this.linejoin = 'round';
  7690. this.vertexColors = false;
  7691. this.fog = true;
  7692. this.setValues( parameters );
  7693. };
  7694. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7695. THREE.LineBasicMaterial.prototype.clone = function () {
  7696. var material = new THREE.LineBasicMaterial();
  7697. THREE.Material.prototype.clone.call( this, material );
  7698. material.color.copy( this.color );
  7699. material.linewidth = this.linewidth;
  7700. material.linecap = this.linecap;
  7701. material.linejoin = this.linejoin;
  7702. material.vertexColors = this.vertexColors;
  7703. material.fog = this.fog;
  7704. return material;
  7705. };
  7706. /**
  7707. * @author alteredq / http://alteredqualia.com/
  7708. *
  7709. * parameters = {
  7710. * color: <hex>,
  7711. * opacity: <float>,
  7712. *
  7713. * blending: THREE.NormalBlending,
  7714. * depthTest: <bool>,
  7715. * depthWrite: <bool>,
  7716. *
  7717. * linewidth: <float>,
  7718. *
  7719. * scale: <float>,
  7720. * dashSize: <float>,
  7721. * gapSize: <float>,
  7722. *
  7723. * vertexColors: <bool>
  7724. *
  7725. * fog: <bool>
  7726. * }
  7727. */
  7728. THREE.LineDashedMaterial = function ( parameters ) {
  7729. THREE.Material.call( this );
  7730. this.color = new THREE.Color( 0xffffff );
  7731. this.linewidth = 1;
  7732. this.scale = 1;
  7733. this.dashSize = 3;
  7734. this.gapSize = 1;
  7735. this.vertexColors = false;
  7736. this.fog = true;
  7737. this.setValues( parameters );
  7738. };
  7739. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  7740. THREE.LineDashedMaterial.prototype.clone = function () {
  7741. var material = new THREE.LineDashedMaterial();
  7742. THREE.Material.prototype.clone.call( this, material );
  7743. material.color.copy( this.color );
  7744. material.linewidth = this.linewidth;
  7745. material.scale = this.scale;
  7746. material.dashSize = this.dashSize;
  7747. material.gapSize = this.gapSize;
  7748. material.vertexColors = this.vertexColors;
  7749. material.fog = this.fog;
  7750. return material;
  7751. };
  7752. /**
  7753. * @author mrdoob / http://mrdoob.com/
  7754. * @author alteredq / http://alteredqualia.com/
  7755. *
  7756. * parameters = {
  7757. * color: <hex>,
  7758. * opacity: <float>,
  7759. * map: new THREE.Texture( <Image> ),
  7760. *
  7761. * lightMap: new THREE.Texture( <Image> ),
  7762. *
  7763. * specularMap: new THREE.Texture( <Image> ),
  7764. *
  7765. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7766. * combine: THREE.Multiply,
  7767. * reflectivity: <float>,
  7768. * refractionRatio: <float>,
  7769. *
  7770. * shading: THREE.SmoothShading,
  7771. * blending: THREE.NormalBlending,
  7772. * depthTest: <bool>,
  7773. * depthWrite: <bool>,
  7774. *
  7775. * wireframe: <boolean>,
  7776. * wireframeLinewidth: <float>,
  7777. *
  7778. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7779. *
  7780. * skinning: <bool>,
  7781. * morphTargets: <bool>,
  7782. *
  7783. * fog: <bool>
  7784. * }
  7785. */
  7786. THREE.MeshBasicMaterial = function ( parameters ) {
  7787. THREE.Material.call( this );
  7788. this.color = new THREE.Color( 0xffffff ); // emissive
  7789. this.map = null;
  7790. this.lightMap = null;
  7791. this.specularMap = null;
  7792. this.envMap = null;
  7793. this.combine = THREE.MultiplyOperation;
  7794. this.reflectivity = 1;
  7795. this.refractionRatio = 0.98;
  7796. this.fog = true;
  7797. this.shading = THREE.SmoothShading;
  7798. this.wireframe = false;
  7799. this.wireframeLinewidth = 1;
  7800. this.wireframeLinecap = 'round';
  7801. this.wireframeLinejoin = 'round';
  7802. this.vertexColors = THREE.NoColors;
  7803. this.skinning = false;
  7804. this.morphTargets = false;
  7805. this.setValues( parameters );
  7806. };
  7807. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7808. THREE.MeshBasicMaterial.prototype.clone = function () {
  7809. var material = new THREE.MeshBasicMaterial();
  7810. THREE.Material.prototype.clone.call( this, material );
  7811. material.color.copy( this.color );
  7812. material.map = this.map;
  7813. material.lightMap = this.lightMap;
  7814. material.specularMap = this.specularMap;
  7815. material.envMap = this.envMap;
  7816. material.combine = this.combine;
  7817. material.reflectivity = this.reflectivity;
  7818. material.refractionRatio = this.refractionRatio;
  7819. material.fog = this.fog;
  7820. material.shading = this.shading;
  7821. material.wireframe = this.wireframe;
  7822. material.wireframeLinewidth = this.wireframeLinewidth;
  7823. material.wireframeLinecap = this.wireframeLinecap;
  7824. material.wireframeLinejoin = this.wireframeLinejoin;
  7825. material.vertexColors = this.vertexColors;
  7826. material.skinning = this.skinning;
  7827. material.morphTargets = this.morphTargets;
  7828. return material;
  7829. };
  7830. /**
  7831. * @author mrdoob / http://mrdoob.com/
  7832. * @author alteredq / http://alteredqualia.com/
  7833. *
  7834. * parameters = {
  7835. * color: <hex>,
  7836. * ambient: <hex>,
  7837. * emissive: <hex>,
  7838. * opacity: <float>,
  7839. *
  7840. * map: new THREE.Texture( <Image> ),
  7841. *
  7842. * lightMap: new THREE.Texture( <Image> ),
  7843. *
  7844. * specularMap: new THREE.Texture( <Image> ),
  7845. *
  7846. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7847. * combine: THREE.Multiply,
  7848. * reflectivity: <float>,
  7849. * refractionRatio: <float>,
  7850. *
  7851. * shading: THREE.SmoothShading,
  7852. * blending: THREE.NormalBlending,
  7853. * depthTest: <bool>,
  7854. * depthWrite: <bool>,
  7855. *
  7856. * wireframe: <boolean>,
  7857. * wireframeLinewidth: <float>,
  7858. *
  7859. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7860. *
  7861. * skinning: <bool>,
  7862. * morphTargets: <bool>,
  7863. * morphNormals: <bool>,
  7864. *
  7865. * fog: <bool>
  7866. * }
  7867. */
  7868. THREE.MeshLambertMaterial = function ( parameters ) {
  7869. THREE.Material.call( this );
  7870. this.color = new THREE.Color( 0xffffff ); // diffuse
  7871. this.ambient = new THREE.Color( 0xffffff );
  7872. this.emissive = new THREE.Color( 0x000000 );
  7873. this.wrapAround = false;
  7874. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7875. this.map = null;
  7876. this.lightMap = null;
  7877. this.specularMap = null;
  7878. this.envMap = null;
  7879. this.combine = THREE.MultiplyOperation;
  7880. this.reflectivity = 1;
  7881. this.refractionRatio = 0.98;
  7882. this.fog = true;
  7883. this.shading = THREE.SmoothShading;
  7884. this.wireframe = false;
  7885. this.wireframeLinewidth = 1;
  7886. this.wireframeLinecap = 'round';
  7887. this.wireframeLinejoin = 'round';
  7888. this.vertexColors = THREE.NoColors;
  7889. this.skinning = false;
  7890. this.morphTargets = false;
  7891. this.morphNormals = false;
  7892. this.setValues( parameters );
  7893. };
  7894. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  7895. THREE.MeshLambertMaterial.prototype.clone = function () {
  7896. var material = new THREE.MeshLambertMaterial();
  7897. THREE.Material.prototype.clone.call( this, material );
  7898. material.color.copy( this.color );
  7899. material.ambient.copy( this.ambient );
  7900. material.emissive.copy( this.emissive );
  7901. material.wrapAround = this.wrapAround;
  7902. material.wrapRGB.copy( this.wrapRGB );
  7903. material.map = this.map;
  7904. material.lightMap = this.lightMap;
  7905. material.specularMap = this.specularMap;
  7906. material.envMap = this.envMap;
  7907. material.combine = this.combine;
  7908. material.reflectivity = this.reflectivity;
  7909. material.refractionRatio = this.refractionRatio;
  7910. material.fog = this.fog;
  7911. material.shading = this.shading;
  7912. material.wireframe = this.wireframe;
  7913. material.wireframeLinewidth = this.wireframeLinewidth;
  7914. material.wireframeLinecap = this.wireframeLinecap;
  7915. material.wireframeLinejoin = this.wireframeLinejoin;
  7916. material.vertexColors = this.vertexColors;
  7917. material.skinning = this.skinning;
  7918. material.morphTargets = this.morphTargets;
  7919. material.morphNormals = this.morphNormals;
  7920. return material;
  7921. };
  7922. /**
  7923. * @author mrdoob / http://mrdoob.com/
  7924. * @author alteredq / http://alteredqualia.com/
  7925. *
  7926. * parameters = {
  7927. * color: <hex>,
  7928. * ambient: <hex>,
  7929. * emissive: <hex>,
  7930. * specular: <hex>,
  7931. * shininess: <float>,
  7932. * opacity: <float>,
  7933. *
  7934. * map: new THREE.Texture( <Image> ),
  7935. *
  7936. * lightMap: new THREE.Texture( <Image> ),
  7937. *
  7938. * bumpMap: new THREE.Texture( <Image> ),
  7939. * bumpScale: <float>,
  7940. *
  7941. * normalMap: new THREE.Texture( <Image> ),
  7942. * normalScale: <Vector2>,
  7943. *
  7944. * specularMap: new THREE.Texture( <Image> ),
  7945. *
  7946. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7947. * combine: THREE.Multiply,
  7948. * reflectivity: <float>,
  7949. * refractionRatio: <float>,
  7950. *
  7951. * shading: THREE.SmoothShading,
  7952. * blending: THREE.NormalBlending,
  7953. * depthTest: <bool>,
  7954. * depthWrite: <bool>,
  7955. *
  7956. * wireframe: <boolean>,
  7957. * wireframeLinewidth: <float>,
  7958. *
  7959. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7960. *
  7961. * skinning: <bool>,
  7962. * morphTargets: <bool>,
  7963. * morphNormals: <bool>,
  7964. *
  7965. * fog: <bool>
  7966. * }
  7967. */
  7968. THREE.MeshPhongMaterial = function ( parameters ) {
  7969. THREE.Material.call( this );
  7970. this.color = new THREE.Color( 0xffffff ); // diffuse
  7971. this.ambient = new THREE.Color( 0xffffff );
  7972. this.emissive = new THREE.Color( 0x000000 );
  7973. this.specular = new THREE.Color( 0x111111 );
  7974. this.shininess = 30;
  7975. this.metal = false;
  7976. this.perPixel = true;
  7977. this.wrapAround = false;
  7978. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7979. this.map = null;
  7980. this.lightMap = null;
  7981. this.bumpMap = null;
  7982. this.bumpScale = 1;
  7983. this.normalMap = null;
  7984. this.normalScale = new THREE.Vector2( 1, 1 );
  7985. this.specularMap = null;
  7986. this.envMap = null;
  7987. this.combine = THREE.MultiplyOperation;
  7988. this.reflectivity = 1;
  7989. this.refractionRatio = 0.98;
  7990. this.fog = true;
  7991. this.shading = THREE.SmoothShading;
  7992. this.wireframe = false;
  7993. this.wireframeLinewidth = 1;
  7994. this.wireframeLinecap = 'round';
  7995. this.wireframeLinejoin = 'round';
  7996. this.vertexColors = THREE.NoColors;
  7997. this.skinning = false;
  7998. this.morphTargets = false;
  7999. this.morphNormals = false;
  8000. this.setValues( parameters );
  8001. };
  8002. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  8003. THREE.MeshPhongMaterial.prototype.clone = function () {
  8004. var material = new THREE.MeshPhongMaterial();
  8005. THREE.Material.prototype.clone.call( this, material );
  8006. material.color.copy( this.color );
  8007. material.ambient.copy( this.ambient );
  8008. material.emissive.copy( this.emissive );
  8009. material.specular.copy( this.specular );
  8010. material.shininess = this.shininess;
  8011. material.metal = this.metal;
  8012. material.perPixel = this.perPixel;
  8013. material.wrapAround = this.wrapAround;
  8014. material.wrapRGB.copy( this.wrapRGB );
  8015. material.map = this.map;
  8016. material.lightMap = this.lightMap;
  8017. material.bumpMap = this.bumpMap;
  8018. material.bumpScale = this.bumpScale;
  8019. material.normalMap = this.normalMap;
  8020. material.normalScale.copy( this.normalScale );
  8021. material.specularMap = this.specularMap;
  8022. material.envMap = this.envMap;
  8023. material.combine = this.combine;
  8024. material.reflectivity = this.reflectivity;
  8025. material.refractionRatio = this.refractionRatio;
  8026. material.fog = this.fog;
  8027. material.shading = this.shading;
  8028. material.wireframe = this.wireframe;
  8029. material.wireframeLinewidth = this.wireframeLinewidth;
  8030. material.wireframeLinecap = this.wireframeLinecap;
  8031. material.wireframeLinejoin = this.wireframeLinejoin;
  8032. material.vertexColors = this.vertexColors;
  8033. material.skinning = this.skinning;
  8034. material.morphTargets = this.morphTargets;
  8035. material.morphNormals = this.morphNormals;
  8036. return material;
  8037. };
  8038. /**
  8039. * @author mrdoob / http://mrdoob.com/
  8040. * @author alteredq / http://alteredqualia.com/
  8041. *
  8042. * parameters = {
  8043. * opacity: <float>,
  8044. *
  8045. * blending: THREE.NormalBlending,
  8046. * depthTest: <bool>,
  8047. * depthWrite: <bool>,
  8048. *
  8049. * wireframe: <boolean>,
  8050. * wireframeLinewidth: <float>
  8051. * }
  8052. */
  8053. THREE.MeshDepthMaterial = function ( parameters ) {
  8054. THREE.Material.call( this );
  8055. this.wireframe = false;
  8056. this.wireframeLinewidth = 1;
  8057. this.setValues( parameters );
  8058. };
  8059. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  8060. THREE.MeshDepthMaterial.prototype.clone = function () {
  8061. var material = new THREE.MeshDepthMaterial();
  8062. THREE.Material.prototype.clone.call( this, material );
  8063. material.wireframe = this.wireframe;
  8064. material.wireframeLinewidth = this.wireframeLinewidth;
  8065. return material;
  8066. };
  8067. /**
  8068. * @author mrdoob / http://mrdoob.com/
  8069. *
  8070. * parameters = {
  8071. * opacity: <float>,
  8072. *
  8073. * shading: THREE.FlatShading,
  8074. * blending: THREE.NormalBlending,
  8075. * depthTest: <bool>,
  8076. * depthWrite: <bool>,
  8077. *
  8078. * wireframe: <boolean>,
  8079. * wireframeLinewidth: <float>
  8080. * }
  8081. */
  8082. THREE.MeshNormalMaterial = function ( parameters ) {
  8083. THREE.Material.call( this, parameters );
  8084. this.shading = THREE.FlatShading;
  8085. this.wireframe = false;
  8086. this.wireframeLinewidth = 1;
  8087. this.morphTargets = false;
  8088. this.setValues( parameters );
  8089. };
  8090. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  8091. THREE.MeshNormalMaterial.prototype.clone = function () {
  8092. var material = new THREE.MeshNormalMaterial();
  8093. THREE.Material.prototype.clone.call( this, material );
  8094. material.shading = this.shading;
  8095. material.wireframe = this.wireframe;
  8096. material.wireframeLinewidth = this.wireframeLinewidth;
  8097. return material;
  8098. };
  8099. /**
  8100. * @author mrdoob / http://mrdoob.com/
  8101. */
  8102. THREE.MeshFaceMaterial = function ( materials ) {
  8103. this.materials = materials instanceof Array ? materials : [];
  8104. };
  8105. THREE.MeshFaceMaterial.prototype.clone = function () {
  8106. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  8107. };
  8108. /**
  8109. * @author mrdoob / http://mrdoob.com/
  8110. * @author alteredq / http://alteredqualia.com/
  8111. *
  8112. * parameters = {
  8113. * color: <hex>,
  8114. * opacity: <float>,
  8115. * map: new THREE.Texture( <Image> ),
  8116. *
  8117. * size: <float>,
  8118. *
  8119. * blending: THREE.NormalBlending,
  8120. * depthTest: <bool>,
  8121. * depthWrite: <bool>,
  8122. *
  8123. * vertexColors: <bool>,
  8124. *
  8125. * fog: <bool>
  8126. * }
  8127. */
  8128. THREE.ParticleBasicMaterial = function ( parameters ) {
  8129. THREE.Material.call( this );
  8130. this.color = new THREE.Color( 0xffffff );
  8131. this.map = null;
  8132. this.size = 1;
  8133. this.sizeAttenuation = true;
  8134. this.vertexColors = false;
  8135. this.fog = true;
  8136. this.setValues( parameters );
  8137. };
  8138. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8139. THREE.ParticleBasicMaterial.prototype.clone = function () {
  8140. var material = new THREE.ParticleBasicMaterial();
  8141. THREE.Material.prototype.clone.call( this, material );
  8142. material.color.copy( this.color );
  8143. material.map = this.map;
  8144. material.size = this.size;
  8145. material.sizeAttenuation = this.sizeAttenuation;
  8146. material.vertexColors = this.vertexColors;
  8147. material.fog = this.fog;
  8148. return material;
  8149. };
  8150. /**
  8151. * @author mrdoob / http://mrdoob.com/
  8152. *
  8153. * parameters = {
  8154. * color: <hex>,
  8155. * program: <function>,
  8156. * opacity: <float>,
  8157. * blending: THREE.NormalBlending
  8158. * }
  8159. */
  8160. THREE.ParticleCanvasMaterial = function ( parameters ) {
  8161. THREE.Material.call( this );
  8162. this.color = new THREE.Color( 0xffffff );
  8163. this.program = function ( context, color ) {};
  8164. this.setValues( parameters );
  8165. };
  8166. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  8167. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  8168. var material = new THREE.ParticleCanvasMaterial();
  8169. THREE.Material.prototype.clone.call( this, material );
  8170. material.color.copy( this.color );
  8171. material.program = this.program;
  8172. return material;
  8173. };
  8174. /**
  8175. * @author alteredq / http://alteredqualia.com/
  8176. *
  8177. * parameters = {
  8178. * fragmentShader: <string>,
  8179. * vertexShader: <string>,
  8180. *
  8181. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  8182. *
  8183. * defines: { "label" : "value" },
  8184. *
  8185. * shading: THREE.SmoothShading,
  8186. * blending: THREE.NormalBlending,
  8187. * depthTest: <bool>,
  8188. * depthWrite: <bool>,
  8189. *
  8190. * wireframe: <boolean>,
  8191. * wireframeLinewidth: <float>,
  8192. *
  8193. * lights: <bool>,
  8194. *
  8195. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8196. *
  8197. * skinning: <bool>,
  8198. * morphTargets: <bool>,
  8199. * morphNormals: <bool>,
  8200. *
  8201. * fog: <bool>
  8202. * }
  8203. */
  8204. THREE.ShaderMaterial = function ( parameters ) {
  8205. THREE.Material.call( this );
  8206. this.fragmentShader = "void main() {}";
  8207. this.vertexShader = "void main() {}";
  8208. this.uniforms = {};
  8209. this.defines = {};
  8210. this.attributes = null;
  8211. this.shading = THREE.SmoothShading;
  8212. this.linewidth = 1;
  8213. this.wireframe = false;
  8214. this.wireframeLinewidth = 1;
  8215. this.fog = false; // set to use scene fog
  8216. this.lights = false; // set to use scene lights
  8217. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  8218. this.skinning = false; // set to use skinning attribute streams
  8219. this.morphTargets = false; // set to use morph targets
  8220. this.morphNormals = false; // set to use morph normals
  8221. this.setValues( parameters );
  8222. };
  8223. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  8224. THREE.ShaderMaterial.prototype.clone = function () {
  8225. var material = new THREE.ShaderMaterial();
  8226. THREE.Material.prototype.clone.call( this, material );
  8227. material.fragmentShader = this.fragmentShader;
  8228. material.vertexShader = this.vertexShader;
  8229. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  8230. material.attributes = this.attributes;
  8231. material.defines = this.defines;
  8232. material.shading = this.shading;
  8233. material.wireframe = this.wireframe;
  8234. material.wireframeLinewidth = this.wireframeLinewidth;
  8235. material.fog = this.fog;
  8236. material.lights = this.lights;
  8237. material.vertexColors = this.vertexColors;
  8238. material.skinning = this.skinning;
  8239. material.morphTargets = this.morphTargets;
  8240. material.morphNormals = this.morphNormals;
  8241. return material;
  8242. };
  8243. /**
  8244. * @author alteredq / http://alteredqualia.com/
  8245. *
  8246. * parameters = {
  8247. * color: <hex>,
  8248. * opacity: <float>,
  8249. * map: new THREE.Texture( <Image> ),
  8250. *
  8251. * blending: THREE.NormalBlending,
  8252. * depthTest: <bool>,
  8253. * depthWrite: <bool>,
  8254. *
  8255. * useScreenCoordinates: <bool>,
  8256. * sizeAttenuation: <bool>,
  8257. * scaleByViewport: <bool>,
  8258. * alignment: THREE.SpriteAlignment.center,
  8259. *
  8260. * uvOffset: new THREE.Vector2(),
  8261. * uvScale: new THREE.Vector2(),
  8262. *
  8263. * fog: <bool>
  8264. * }
  8265. */
  8266. THREE.SpriteMaterial = function ( parameters ) {
  8267. THREE.Material.call( this );
  8268. // defaults
  8269. this.color = new THREE.Color( 0xffffff );
  8270. this.map = new THREE.Texture();
  8271. this.useScreenCoordinates = true;
  8272. this.depthTest = !this.useScreenCoordinates;
  8273. this.sizeAttenuation = !this.useScreenCoordinates;
  8274. this.scaleByViewport = !this.sizeAttenuation;
  8275. this.alignment = THREE.SpriteAlignment.center.clone();
  8276. this.fog = false;
  8277. this.uvOffset = new THREE.Vector2( 0, 0 );
  8278. this.uvScale = new THREE.Vector2( 1, 1 );
  8279. // set parameters
  8280. this.setValues( parameters );
  8281. // override coupled defaults if not specified explicitly by parameters
  8282. parameters = parameters || {};
  8283. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  8284. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  8285. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  8286. };
  8287. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  8288. THREE.SpriteMaterial.prototype.clone = function () {
  8289. var material = new THREE.SpriteMaterial();
  8290. THREE.Material.prototype.clone.call( this, material );
  8291. material.color.copy( this.color );
  8292. material.map = this.map;
  8293. material.useScreenCoordinates = this.useScreenCoordinates;
  8294. material.sizeAttenuation = this.sizeAttenuation;
  8295. material.scaleByViewport = this.scaleByViewport;
  8296. material.alignment.copy( this.alignment );
  8297. material.uvOffset.copy( this.uvOffset );
  8298. material.uvScale.copy( this.uvScale );
  8299. material.fog = this.fog;
  8300. return material;
  8301. };
  8302. // Alignment enums
  8303. THREE.SpriteAlignment = {};
  8304. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  8305. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  8306. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  8307. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  8308. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  8309. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  8310. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  8311. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  8312. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  8313. /**
  8314. * @author mrdoob / http://mrdoob.com/
  8315. * @author alteredq / http://alteredqualia.com/
  8316. * @author szimek / https://github.com/szimek/
  8317. */
  8318. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8319. this.id = THREE.TextureIdCount ++;
  8320. this.uuid = THREE.Math.generateUUID();
  8321. this.name = '';
  8322. this.image = image;
  8323. this.mipmaps = [];
  8324. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  8325. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  8326. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  8327. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  8328. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  8329. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  8330. this.format = format !== undefined ? format : THREE.RGBAFormat;
  8331. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  8332. this.offset = new THREE.Vector2( 0, 0 );
  8333. this.repeat = new THREE.Vector2( 1, 1 );
  8334. this.generateMipmaps = true;
  8335. this.premultiplyAlpha = false;
  8336. this.flipY = true;
  8337. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  8338. this.needsUpdate = false;
  8339. this.onUpdate = null;
  8340. };
  8341. THREE.Texture.prototype = {
  8342. constructor: THREE.Texture,
  8343. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  8344. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  8345. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  8346. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  8347. clone: function ( texture ) {
  8348. if ( texture === undefined ) texture = new THREE.Texture();
  8349. texture.image = this.image;
  8350. texture.mipmaps = this.mipmaps.slice(0);
  8351. texture.mapping = this.mapping;
  8352. texture.wrapS = this.wrapS;
  8353. texture.wrapT = this.wrapT;
  8354. texture.magFilter = this.magFilter;
  8355. texture.minFilter = this.minFilter;
  8356. texture.anisotropy = this.anisotropy;
  8357. texture.format = this.format;
  8358. texture.type = this.type;
  8359. texture.offset.copy( this.offset );
  8360. texture.repeat.copy( this.repeat );
  8361. texture.generateMipmaps = this.generateMipmaps;
  8362. texture.premultiplyAlpha = this.premultiplyAlpha;
  8363. texture.flipY = this.flipY;
  8364. texture.unpackAlignment = this.unpackAlignment;
  8365. return texture;
  8366. },
  8367. dispose: function () {
  8368. this.dispatchEvent( { type: 'dispose' } );
  8369. }
  8370. };
  8371. THREE.TextureIdCount = 0;
  8372. /**
  8373. * @author alteredq / http://alteredqualia.com/
  8374. */
  8375. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8376. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8377. this.image = { width: width, height: height };
  8378. this.mipmaps = mipmaps;
  8379. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  8380. };
  8381. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  8382. THREE.CompressedTexture.prototype.clone = function () {
  8383. var texture = new THREE.CompressedTexture();
  8384. THREE.Texture.prototype.clone.call( this, texture );
  8385. return texture;
  8386. };
  8387. /**
  8388. * @author alteredq / http://alteredqualia.com/
  8389. */
  8390. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8391. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8392. this.image = { data: data, width: width, height: height };
  8393. };
  8394. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  8395. THREE.DataTexture.prototype.clone = function () {
  8396. var texture = new THREE.DataTexture();
  8397. THREE.Texture.prototype.clone.call( this, texture );
  8398. return texture;
  8399. };
  8400. /**
  8401. * @author mrdoob / http://mrdoob.com/
  8402. */
  8403. THREE.Particle = function ( material ) {
  8404. THREE.Object3D.call( this );
  8405. this.material = material;
  8406. };
  8407. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  8408. THREE.Particle.prototype.clone = function ( object ) {
  8409. if ( object === undefined ) object = new THREE.Particle( this.material );
  8410. THREE.Object3D.prototype.clone.call( this, object );
  8411. return object;
  8412. };
  8413. /**
  8414. * @author alteredq / http://alteredqualia.com/
  8415. */
  8416. THREE.ParticleSystem = function ( geometry, material ) {
  8417. THREE.Object3D.call( this );
  8418. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8419. this.material = material !== undefined ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  8420. this.sortParticles = false;
  8421. this.frustumCulled = false;
  8422. };
  8423. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  8424. THREE.ParticleSystem.prototype.clone = function ( object ) {
  8425. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  8426. object.sortParticles = this.sortParticles;
  8427. THREE.Object3D.prototype.clone.call( this, object );
  8428. return object;
  8429. };
  8430. /**
  8431. * @author mrdoob / http://mrdoob.com/
  8432. */
  8433. THREE.Line = function ( geometry, material, type ) {
  8434. THREE.Object3D.call( this );
  8435. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8436. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  8437. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  8438. };
  8439. THREE.LineStrip = 0;
  8440. THREE.LinePieces = 1;
  8441. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  8442. THREE.Line.prototype.clone = function ( object ) {
  8443. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  8444. THREE.Object3D.prototype.clone.call( this, object );
  8445. return object;
  8446. };
  8447. /**
  8448. * @author mrdoob / http://mrdoob.com/
  8449. * @author alteredq / http://alteredqualia.com/
  8450. * @author mikael emtinger / http://gomo.se/
  8451. * @author jonobr1 / http://jonobr1.com/
  8452. */
  8453. THREE.Mesh = function ( geometry, material ) {
  8454. THREE.Object3D.call( this );
  8455. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8456. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  8457. this.updateMorphTargets();
  8458. };
  8459. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  8460. THREE.Mesh.prototype.updateMorphTargets = function () {
  8461. if ( this.geometry.morphTargets.length > 0 ) {
  8462. this.morphTargetBase = -1;
  8463. this.morphTargetForcedOrder = [];
  8464. this.morphTargetInfluences = [];
  8465. this.morphTargetDictionary = {};
  8466. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  8467. this.morphTargetInfluences.push( 0 );
  8468. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  8469. }
  8470. }
  8471. };
  8472. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  8473. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  8474. return this.morphTargetDictionary[ name ];
  8475. }
  8476. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  8477. return 0;
  8478. };
  8479. THREE.Mesh.prototype.clone = function ( object ) {
  8480. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  8481. THREE.Object3D.prototype.clone.call( this, object );
  8482. return object;
  8483. };
  8484. /**
  8485. * @author mikael emtinger / http://gomo.se/
  8486. * @author alteredq / http://alteredqualia.com/
  8487. */
  8488. THREE.Bone = function( belongsToSkin ) {
  8489. THREE.Object3D.call( this );
  8490. this.skin = belongsToSkin;
  8491. this.skinMatrix = new THREE.Matrix4();
  8492. };
  8493. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  8494. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  8495. // update local
  8496. if ( this.matrixAutoUpdate ) {
  8497. forceUpdate |= this.updateMatrix();
  8498. }
  8499. // update skin matrix
  8500. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  8501. if( parentSkinMatrix ) {
  8502. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  8503. } else {
  8504. this.skinMatrix.copy( this.matrix );
  8505. }
  8506. this.matrixWorldNeedsUpdate = false;
  8507. forceUpdate = true;
  8508. }
  8509. // update children
  8510. var child, i, l = this.children.length;
  8511. for ( i = 0; i < l; i ++ ) {
  8512. this.children[ i ].update( this.skinMatrix, forceUpdate );
  8513. }
  8514. };
  8515. /**
  8516. * @author mikael emtinger / http://gomo.se/
  8517. * @author alteredq / http://alteredqualia.com/
  8518. */
  8519. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  8520. THREE.Mesh.call( this, geometry, material );
  8521. //
  8522. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  8523. // init bones
  8524. this.identityMatrix = new THREE.Matrix4();
  8525. this.bones = [];
  8526. this.boneMatrices = [];
  8527. var b, bone, gbone, p, q, s;
  8528. if ( this.geometry && this.geometry.bones !== undefined ) {
  8529. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  8530. gbone = this.geometry.bones[ b ];
  8531. p = gbone.pos;
  8532. q = gbone.rotq;
  8533. s = gbone.scl;
  8534. bone = this.addBone();
  8535. bone.name = gbone.name;
  8536. bone.position.set( p[0], p[1], p[2] );
  8537. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  8538. if ( s !== undefined ) {
  8539. bone.scale.set( s[0], s[1], s[2] );
  8540. } else {
  8541. bone.scale.set( 1, 1, 1 );
  8542. }
  8543. }
  8544. for ( b = 0; b < this.bones.length; b ++ ) {
  8545. gbone = this.geometry.bones[ b ];
  8546. bone = this.bones[ b ];
  8547. if ( gbone.parent === -1 ) {
  8548. this.add( bone );
  8549. } else {
  8550. this.bones[ gbone.parent ].add( bone );
  8551. }
  8552. }
  8553. //
  8554. var nBones = this.bones.length;
  8555. if ( this.useVertexTexture ) {
  8556. // layout (1 matrix = 4 pixels)
  8557. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8558. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  8559. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  8560. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  8561. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  8562. var size;
  8563. if ( nBones > 256 )
  8564. size = 64;
  8565. else if ( nBones > 64 )
  8566. size = 32;
  8567. else if ( nBones > 16 )
  8568. size = 16;
  8569. else
  8570. size = 8;
  8571. this.boneTextureWidth = size;
  8572. this.boneTextureHeight = size;
  8573. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  8574. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  8575. this.boneTexture.minFilter = THREE.NearestFilter;
  8576. this.boneTexture.magFilter = THREE.NearestFilter;
  8577. this.boneTexture.generateMipmaps = false;
  8578. this.boneTexture.flipY = false;
  8579. } else {
  8580. this.boneMatrices = new Float32Array( 16 * nBones );
  8581. }
  8582. this.pose();
  8583. }
  8584. };
  8585. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  8586. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  8587. if ( bone === undefined ) {
  8588. bone = new THREE.Bone( this );
  8589. }
  8590. this.bones.push( bone );
  8591. return bone;
  8592. };
  8593. THREE.SkinnedMesh.prototype.updateMatrixWorld = function () {
  8594. var offsetMatrix = new THREE.Matrix4();
  8595. return function ( force ) {
  8596. this.matrixAutoUpdate && this.updateMatrix();
  8597. // update matrixWorld
  8598. if ( this.matrixWorldNeedsUpdate || force ) {
  8599. if ( this.parent ) {
  8600. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  8601. } else {
  8602. this.matrixWorld.copy( this.matrix );
  8603. }
  8604. this.matrixWorldNeedsUpdate = false;
  8605. force = true;
  8606. }
  8607. // update children
  8608. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  8609. var child = this.children[ i ];
  8610. if ( child instanceof THREE.Bone ) {
  8611. child.update( this.identityMatrix, false );
  8612. } else {
  8613. child.updateMatrixWorld( true );
  8614. }
  8615. }
  8616. // make a snapshot of the bones' rest position
  8617. if ( this.boneInverses == undefined ) {
  8618. this.boneInverses = [];
  8619. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8620. var inverse = new THREE.Matrix4();
  8621. inverse.getInverse( this.bones[ b ].skinMatrix );
  8622. this.boneInverses.push( inverse );
  8623. }
  8624. }
  8625. // flatten bone matrices to array
  8626. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8627. // compute the offset between the current and the original transform;
  8628. // TODO: we could get rid of this multiplication step if the skinMatrix
  8629. // was already representing the offset; however, this requires some
  8630. // major changes to the animation system
  8631. offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  8632. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  8633. }
  8634. if ( this.useVertexTexture ) {
  8635. this.boneTexture.needsUpdate = true;
  8636. }
  8637. };
  8638. }();
  8639. THREE.SkinnedMesh.prototype.pose = function () {
  8640. this.updateMatrixWorld( true );
  8641. this.normalizeSkinWeights();
  8642. };
  8643. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  8644. if ( this.geometry instanceof THREE.Geometry ) {
  8645. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  8646. var sw = this.geometry.skinWeights[ i ];
  8647. var scale = 1.0 / sw.lengthManhattan();
  8648. if ( scale !== Infinity ) {
  8649. sw.multiplyScalar( scale );
  8650. } else {
  8651. sw.set( 1 ); // this will be normalized by the shader anyway
  8652. }
  8653. }
  8654. } else {
  8655. // skinning weights assumed to be normalized for THREE.BufferGeometry
  8656. }
  8657. };
  8658. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  8659. if ( object === undefined ) {
  8660. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  8661. }
  8662. THREE.Mesh.prototype.clone.call( this, object );
  8663. return object;
  8664. };
  8665. /**
  8666. * @author alteredq / http://alteredqualia.com/
  8667. */
  8668. THREE.MorphAnimMesh = function ( geometry, material ) {
  8669. THREE.Mesh.call( this, geometry, material );
  8670. // API
  8671. this.duration = 1000; // milliseconds
  8672. this.mirroredLoop = false;
  8673. this.time = 0;
  8674. // internals
  8675. this.lastKeyframe = 0;
  8676. this.currentKeyframe = 0;
  8677. this.direction = 1;
  8678. this.directionBackwards = false;
  8679. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  8680. };
  8681. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  8682. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  8683. this.startKeyframe = start;
  8684. this.endKeyframe = end;
  8685. this.length = this.endKeyframe - this.startKeyframe + 1;
  8686. };
  8687. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  8688. this.direction = 1;
  8689. this.directionBackwards = false;
  8690. };
  8691. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  8692. this.direction = -1;
  8693. this.directionBackwards = true;
  8694. };
  8695. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  8696. var geometry = this.geometry;
  8697. if ( ! geometry.animations ) geometry.animations = {};
  8698. var firstAnimation, animations = geometry.animations;
  8699. var pattern = /([a-z]+)(\d+)/;
  8700. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  8701. var morph = geometry.morphTargets[ i ];
  8702. var parts = morph.name.match( pattern );
  8703. if ( parts && parts.length > 1 ) {
  8704. var label = parts[ 1 ];
  8705. var num = parts[ 2 ];
  8706. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  8707. var animation = animations[ label ];
  8708. if ( i < animation.start ) animation.start = i;
  8709. if ( i > animation.end ) animation.end = i;
  8710. if ( ! firstAnimation ) firstAnimation = label;
  8711. }
  8712. }
  8713. geometry.firstAnimation = firstAnimation;
  8714. };
  8715. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  8716. if ( ! this.geometry.animations ) this.geometry.animations = {};
  8717. this.geometry.animations[ label ] = { start: start, end: end };
  8718. };
  8719. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  8720. var animation = this.geometry.animations[ label ];
  8721. if ( animation ) {
  8722. this.setFrameRange( animation.start, animation.end );
  8723. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  8724. this.time = 0;
  8725. } else {
  8726. console.warn( "animation[" + label + "] undefined" );
  8727. }
  8728. };
  8729. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  8730. var frameTime = this.duration / this.length;
  8731. this.time += this.direction * delta;
  8732. if ( this.mirroredLoop ) {
  8733. if ( this.time > this.duration || this.time < 0 ) {
  8734. this.direction *= -1;
  8735. if ( this.time > this.duration ) {
  8736. this.time = this.duration;
  8737. this.directionBackwards = true;
  8738. }
  8739. if ( this.time < 0 ) {
  8740. this.time = 0;
  8741. this.directionBackwards = false;
  8742. }
  8743. }
  8744. } else {
  8745. this.time = this.time % this.duration;
  8746. if ( this.time < 0 ) this.time += this.duration;
  8747. }
  8748. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  8749. if ( keyframe !== this.currentKeyframe ) {
  8750. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  8751. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  8752. this.morphTargetInfluences[ keyframe ] = 0;
  8753. this.lastKeyframe = this.currentKeyframe;
  8754. this.currentKeyframe = keyframe;
  8755. }
  8756. var mix = ( this.time % frameTime ) / frameTime;
  8757. if ( this.directionBackwards ) {
  8758. mix = 1 - mix;
  8759. }
  8760. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  8761. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  8762. };
  8763. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  8764. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  8765. object.duration = this.duration;
  8766. object.mirroredLoop = this.mirroredLoop;
  8767. object.time = this.time;
  8768. object.lastKeyframe = this.lastKeyframe;
  8769. object.currentKeyframe = this.currentKeyframe;
  8770. object.direction = this.direction;
  8771. object.directionBackwards = this.directionBackwards;
  8772. THREE.Mesh.prototype.clone.call( this, object );
  8773. return object;
  8774. };
  8775. /**
  8776. * @author alteredq / http://alteredqualia.com/
  8777. */
  8778. THREE.Ribbon = function ( geometry, material ) {
  8779. THREE.Object3D.call( this );
  8780. this.geometry = geometry;
  8781. this.material = material;
  8782. };
  8783. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  8784. THREE.Ribbon.prototype.clone = function ( object ) {
  8785. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  8786. THREE.Object3D.prototype.clone.call( this, object );
  8787. return object;
  8788. };
  8789. /**
  8790. * @author mikael emtinger / http://gomo.se/
  8791. * @author alteredq / http://alteredqualia.com/
  8792. * @author mrdoob / http://mrdoob.com/
  8793. */
  8794. THREE.LOD = function () {
  8795. THREE.Object3D.call( this );
  8796. this.objects = [];
  8797. };
  8798. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  8799. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  8800. if ( distance === undefined ) distance = 0;
  8801. distance = Math.abs( distance );
  8802. for ( var l = 0; l < this.objects.length; l ++ ) {
  8803. if ( distance < this.objects[ l ].distance ) {
  8804. break;
  8805. }
  8806. }
  8807. this.objects.splice( l, 0, { distance: distance, object: object } );
  8808. this.add( object );
  8809. };
  8810. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  8811. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8812. if ( distance < this.objects[ i ].distance ) {
  8813. break;
  8814. }
  8815. }
  8816. return this.objects[ i - 1 ].object;
  8817. };
  8818. THREE.LOD.prototype.update = function () {
  8819. var v1 = new THREE.Vector3();
  8820. var v2 = new THREE.Vector3();
  8821. return function ( camera ) {
  8822. if ( this.objects.length > 1 ) {
  8823. v1.getPositionFromMatrix( camera.matrixWorld );
  8824. v2.getPositionFromMatrix( this.matrixWorld );
  8825. var distance = v1.distanceTo( v2 );
  8826. this.objects[ 0 ].object.visible = true;
  8827. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8828. if ( distance >= this.objects[ i ].distance ) {
  8829. this.objects[ i - 1 ].object.visible = false;
  8830. this.objects[ i ].object.visible = true;
  8831. } else {
  8832. break;
  8833. }
  8834. }
  8835. for( ; i < l; i ++ ) {
  8836. this.objects[ i ].object.visible = false;
  8837. }
  8838. }
  8839. };
  8840. }();
  8841. THREE.LOD.prototype.clone = function () {
  8842. // TODO
  8843. };
  8844. /**
  8845. * @author mikael emtinger / http://gomo.se/
  8846. * @author alteredq / http://alteredqualia.com/
  8847. */
  8848. THREE.Sprite = function ( material ) {
  8849. THREE.Object3D.call( this );
  8850. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  8851. this.rotation3d = this.rotation;
  8852. this.rotation = 0;
  8853. };
  8854. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  8855. /*
  8856. * Custom update matrix
  8857. */
  8858. THREE.Sprite.prototype.updateMatrix = function () {
  8859. this.rotation3d.set( 0, 0, this.rotation, this.rotation3d.order );
  8860. this.quaternion.setFromEuler( this.rotation3d );
  8861. this.matrix.compose( this.position, this.quaternion, this.scale );
  8862. this.matrixWorldNeedsUpdate = true;
  8863. };
  8864. THREE.Sprite.prototype.clone = function ( object ) {
  8865. if ( object === undefined ) object = new THREE.Sprite( this.material );
  8866. THREE.Object3D.prototype.clone.call( this, object );
  8867. return object;
  8868. };
  8869. /**
  8870. * @author mrdoob / http://mrdoob.com/
  8871. */
  8872. THREE.Scene = function () {
  8873. THREE.Object3D.call( this );
  8874. this.fog = null;
  8875. this.overrideMaterial = null;
  8876. this.autoUpdate = true; // checked by the renderer
  8877. this.matrixAutoUpdate = false;
  8878. this.__objects = [];
  8879. this.__lights = [];
  8880. this.__objectsAdded = [];
  8881. this.__objectsRemoved = [];
  8882. };
  8883. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  8884. THREE.Scene.prototype.__addObject = function ( object ) {
  8885. if ( object instanceof THREE.Light ) {
  8886. if ( this.__lights.indexOf( object ) === - 1 ) {
  8887. this.__lights.push( object );
  8888. }
  8889. if ( object.target && object.target.parent === undefined ) {
  8890. this.add( object.target );
  8891. }
  8892. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  8893. if ( this.__objects.indexOf( object ) === - 1 ) {
  8894. this.__objects.push( object );
  8895. this.__objectsAdded.push( object );
  8896. // check if previously removed
  8897. var i = this.__objectsRemoved.indexOf( object );
  8898. if ( i !== -1 ) {
  8899. this.__objectsRemoved.splice( i, 1 );
  8900. }
  8901. }
  8902. }
  8903. for ( var c = 0; c < object.children.length; c ++ ) {
  8904. this.__addObject( object.children[ c ] );
  8905. }
  8906. };
  8907. THREE.Scene.prototype.__removeObject = function ( object ) {
  8908. if ( object instanceof THREE.Light ) {
  8909. var i = this.__lights.indexOf( object );
  8910. if ( i !== -1 ) {
  8911. this.__lights.splice( i, 1 );
  8912. }
  8913. } else if ( !( object instanceof THREE.Camera ) ) {
  8914. var i = this.__objects.indexOf( object );
  8915. if( i !== -1 ) {
  8916. this.__objects.splice( i, 1 );
  8917. this.__objectsRemoved.push( object );
  8918. // check if previously added
  8919. var ai = this.__objectsAdded.indexOf( object );
  8920. if ( ai !== -1 ) {
  8921. this.__objectsAdded.splice( ai, 1 );
  8922. }
  8923. }
  8924. }
  8925. for ( var c = 0; c < object.children.length; c ++ ) {
  8926. this.__removeObject( object.children[ c ] );
  8927. }
  8928. };
  8929. THREE.Scene.prototype.clone = function ( object ) {
  8930. if ( object === undefined ) object = new THREE.Scene();
  8931. THREE.Object3D.prototype.clone.call(this, object);
  8932. if ( this.fog !== null ) object.fog = this.fog.clone();
  8933. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  8934. object.autoUpdate = this.autoUpdate;
  8935. object.matrixAutoUpdate = this.matrixAutoUpdate;
  8936. return object;
  8937. };
  8938. /**
  8939. * @author mrdoob / http://mrdoob.com/
  8940. * @author alteredq / http://alteredqualia.com/
  8941. */
  8942. THREE.Fog = function ( hex, near, far ) {
  8943. this.name = '';
  8944. this.color = new THREE.Color( hex );
  8945. this.near = ( near !== undefined ) ? near : 1;
  8946. this.far = ( far !== undefined ) ? far : 1000;
  8947. };
  8948. THREE.Fog.prototype.clone = function () {
  8949. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  8950. };
  8951. /**
  8952. * @author mrdoob / http://mrdoob.com/
  8953. * @author alteredq / http://alteredqualia.com/
  8954. */
  8955. THREE.FogExp2 = function ( hex, density ) {
  8956. this.name = '';
  8957. this.color = new THREE.Color( hex );
  8958. this.density = ( density !== undefined ) ? density : 0.00025;
  8959. };
  8960. THREE.FogExp2.prototype.clone = function () {
  8961. return new THREE.FogExp2( this.color.getHex(), this.density );
  8962. };
  8963. /**
  8964. * @author mrdoob / http://mrdoob.com/
  8965. */
  8966. THREE.CanvasRenderer = function ( parameters ) {
  8967. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  8968. var smoothstep = THREE.Math.smoothstep;
  8969. parameters = parameters || {};
  8970. var _this = this,
  8971. _renderData, _elements, _lights,
  8972. _projector = new THREE.Projector(),
  8973. _canvas = parameters.canvas !== undefined
  8974. ? parameters.canvas
  8975. : document.createElement( 'canvas' ),
  8976. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  8977. _context = _canvas.getContext( '2d' ),
  8978. _clearColor = new THREE.Color( 0x000000 ),
  8979. _clearAlpha = 0,
  8980. _contextGlobalAlpha = 1,
  8981. _contextGlobalCompositeOperation = 0,
  8982. _contextStrokeStyle = null,
  8983. _contextFillStyle = null,
  8984. _contextLineWidth = null,
  8985. _contextLineCap = null,
  8986. _contextLineJoin = null,
  8987. _contextDashSize = null,
  8988. _contextGapSize = 0,
  8989. _camera,
  8990. _v1, _v2, _v3, _v4,
  8991. _v5 = new THREE.RenderableVertex(),
  8992. _v6 = new THREE.RenderableVertex(),
  8993. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  8994. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  8995. _color = new THREE.Color(),
  8996. _color1 = new THREE.Color(),
  8997. _color2 = new THREE.Color(),
  8998. _color3 = new THREE.Color(),
  8999. _color4 = new THREE.Color(),
  9000. _diffuseColor = new THREE.Color(),
  9001. _emissiveColor = new THREE.Color(),
  9002. _lightColor = new THREE.Color(),
  9003. _patterns = {}, _imagedatas = {},
  9004. _near, _far,
  9005. _image, _uvs,
  9006. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  9007. _clipBox = new THREE.Box2(),
  9008. _clearBox = new THREE.Box2(),
  9009. _elemBox = new THREE.Box2(),
  9010. _ambientLight = new THREE.Color(),
  9011. _directionalLights = new THREE.Color(),
  9012. _pointLights = new THREE.Color(),
  9013. _vector3 = new THREE.Vector3(), // Needed for PointLight
  9014. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  9015. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  9016. _pixelMap = document.createElement( 'canvas' );
  9017. _pixelMap.width = _pixelMap.height = 2;
  9018. _pixelMapContext = _pixelMap.getContext( '2d' );
  9019. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  9020. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  9021. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  9022. _pixelMapData = _pixelMapImage.data;
  9023. _gradientMap = document.createElement( 'canvas' );
  9024. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  9025. _gradientMapContext = _gradientMap.getContext( '2d' );
  9026. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  9027. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  9028. _gradientMapQuality --; // Fix UVs
  9029. // dash+gap fallbacks for Firefox and everything else
  9030. if ( _context.setLineDash === undefined ) {
  9031. if ( _context.mozDash !== undefined ) {
  9032. _context.setLineDash = function ( values ) {
  9033. _context.mozDash = values[ 0 ] !== null ? values : null;
  9034. }
  9035. } else {
  9036. _context.setLineDash = function () {}
  9037. }
  9038. }
  9039. this.domElement = _canvas;
  9040. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  9041. ? parameters.devicePixelRatio
  9042. : window.devicePixelRatio !== undefined
  9043. ? window.devicePixelRatio
  9044. : 1;
  9045. this.autoClear = true;
  9046. this.sortObjects = true;
  9047. this.sortElements = true;
  9048. this.info = {
  9049. render: {
  9050. vertices: 0,
  9051. faces: 0
  9052. }
  9053. }
  9054. // WebGLRenderer compatibility
  9055. this.supportsVertexTextures = function () {};
  9056. this.setFaceCulling = function () {};
  9057. this.setSize = function ( width, height, updateStyle ) {
  9058. _canvasWidth = width * this.devicePixelRatio;
  9059. _canvasHeight = height * this.devicePixelRatio;
  9060. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  9061. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  9062. _canvas.width = _canvasWidth;
  9063. _canvas.height = _canvasHeight;
  9064. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  9065. _canvas.style.width = width + 'px';
  9066. _canvas.style.height = height + 'px';
  9067. }
  9068. _clipBox.set(
  9069. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  9070. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  9071. );
  9072. _clearBox.set(
  9073. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  9074. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  9075. );
  9076. _contextGlobalAlpha = 1;
  9077. _contextGlobalCompositeOperation = 0;
  9078. _contextStrokeStyle = null;
  9079. _contextFillStyle = null;
  9080. _contextLineWidth = null;
  9081. _contextLineCap = null;
  9082. _contextLineJoin = null;
  9083. };
  9084. this.setClearColor = function ( color, alpha ) {
  9085. _clearColor.set( color );
  9086. _clearAlpha = alpha !== undefined ? alpha : 1;
  9087. _clearBox.set(
  9088. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  9089. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  9090. );
  9091. };
  9092. this.setClearColorHex = function ( hex, alpha ) {
  9093. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  9094. this.setClearColor( hex, alpha );
  9095. };
  9096. this.getMaxAnisotropy = function () {
  9097. return 0;
  9098. };
  9099. this.clear = function () {
  9100. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  9101. if ( _clearBox.empty() === false ) {
  9102. _clearBox.intersect( _clipBox );
  9103. _clearBox.expandByScalar( 2 );
  9104. if ( _clearAlpha < 1 ) {
  9105. _context.clearRect(
  9106. _clearBox.min.x | 0,
  9107. _clearBox.min.y | 0,
  9108. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9109. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9110. );
  9111. }
  9112. if ( _clearAlpha > 0 ) {
  9113. setBlending( THREE.NormalBlending );
  9114. setOpacity( 1 );
  9115. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  9116. _context.fillRect(
  9117. _clearBox.min.x | 0,
  9118. _clearBox.min.y | 0,
  9119. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9120. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9121. );
  9122. }
  9123. _clearBox.makeEmpty();
  9124. }
  9125. };
  9126. this.render = function ( scene, camera ) {
  9127. if ( camera instanceof THREE.Camera === false ) {
  9128. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  9129. return;
  9130. }
  9131. if ( this.autoClear === true ) this.clear();
  9132. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  9133. _this.info.render.vertices = 0;
  9134. _this.info.render.faces = 0;
  9135. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  9136. _elements = _renderData.elements;
  9137. _lights = _renderData.lights;
  9138. _camera = camera;
  9139. /* DEBUG
  9140. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  9141. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  9142. */
  9143. calculateLights();
  9144. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  9145. var element = _elements[ e ];
  9146. var material = element.material;
  9147. if ( material === undefined || material.visible === false ) continue;
  9148. _elemBox.makeEmpty();
  9149. if ( element instanceof THREE.RenderableParticle ) {
  9150. _v1 = element;
  9151. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  9152. renderParticle( _v1, element, material );
  9153. } else if ( element instanceof THREE.RenderableLine ) {
  9154. _v1 = element.v1; _v2 = element.v2;
  9155. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9156. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9157. _elemBox.setFromPoints( [
  9158. _v1.positionScreen,
  9159. _v2.positionScreen
  9160. ] );
  9161. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9162. renderLine( _v1, _v2, element, material );
  9163. }
  9164. } else if ( element instanceof THREE.RenderableFace3 ) {
  9165. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  9166. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  9167. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  9168. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  9169. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9170. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9171. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  9172. if ( material.overdraw > 0 ) {
  9173. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  9174. expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
  9175. expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
  9176. }
  9177. _elemBox.setFromPoints( [
  9178. _v1.positionScreen,
  9179. _v2.positionScreen,
  9180. _v3.positionScreen
  9181. ] );
  9182. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9183. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  9184. }
  9185. } else if ( element instanceof THREE.RenderableFace4 ) {
  9186. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  9187. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  9188. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  9189. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  9190. if ( _v4.positionScreen.z < -1 || _v4.positionScreen.z > 1 ) continue;
  9191. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9192. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9193. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  9194. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  9195. _v5.positionScreen.copy( _v2.positionScreen );
  9196. _v6.positionScreen.copy( _v4.positionScreen );
  9197. if ( material.overdraw > 0 ) {
  9198. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  9199. expand( _v2.positionScreen, _v4.positionScreen, material.overdraw );
  9200. expand( _v4.positionScreen, _v1.positionScreen, material.overdraw );
  9201. expand( _v3.positionScreen, _v5.positionScreen, material.overdraw );
  9202. expand( _v3.positionScreen, _v6.positionScreen, material.overdraw );
  9203. }
  9204. _elemBox.setFromPoints( [
  9205. _v1.positionScreen,
  9206. _v2.positionScreen,
  9207. _v3.positionScreen,
  9208. _v4.positionScreen
  9209. ] );
  9210. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9211. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material );
  9212. }
  9213. }
  9214. /* DEBUG
  9215. setLineWidth( 1 );
  9216. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  9217. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  9218. */
  9219. _clearBox.union( _elemBox );
  9220. }
  9221. /* DEBUG
  9222. setLineWidth( 1 );
  9223. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  9224. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  9225. */
  9226. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  9227. };
  9228. //
  9229. function calculateLights() {
  9230. _ambientLight.setRGB( 0, 0, 0 );
  9231. _directionalLights.setRGB( 0, 0, 0 );
  9232. _pointLights.setRGB( 0, 0, 0 );
  9233. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9234. var light = _lights[ l ];
  9235. var lightColor = light.color;
  9236. if ( light instanceof THREE.AmbientLight ) {
  9237. _ambientLight.add( lightColor );
  9238. } else if ( light instanceof THREE.DirectionalLight ) {
  9239. // for particles
  9240. _directionalLights.add( lightColor );
  9241. } else if ( light instanceof THREE.PointLight ) {
  9242. // for particles
  9243. _pointLights.add( lightColor );
  9244. }
  9245. }
  9246. }
  9247. function calculateLight( position, normal, color ) {
  9248. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9249. var light = _lights[ l ];
  9250. _lightColor.copy( light.color );
  9251. if ( light instanceof THREE.DirectionalLight ) {
  9252. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld ).normalize();
  9253. var amount = normal.dot( lightPosition );
  9254. if ( amount <= 0 ) continue;
  9255. amount *= light.intensity;
  9256. color.add( _lightColor.multiplyScalar( amount ) );
  9257. } else if ( light instanceof THREE.PointLight ) {
  9258. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld );
  9259. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  9260. if ( amount <= 0 ) continue;
  9261. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  9262. if ( amount == 0 ) continue;
  9263. amount *= light.intensity;
  9264. color.add( _lightColor.multiplyScalar( amount ) );
  9265. }
  9266. }
  9267. }
  9268. function renderParticle( v1, element, material ) {
  9269. setOpacity( material.opacity );
  9270. setBlending( material.blending );
  9271. var width, height, scaleX, scaleY,
  9272. bitmap, bitmapWidth, bitmapHeight;
  9273. if ( material instanceof THREE.ParticleBasicMaterial ) {
  9274. if ( material.map === null ) {
  9275. scaleX = element.object.scale.x;
  9276. scaleY = element.object.scale.y;
  9277. // TODO: Be able to disable this
  9278. scaleX *= element.scale.x * _canvasWidthHalf;
  9279. scaleY *= element.scale.y * _canvasHeightHalf;
  9280. _elemBox.min.set( v1.x - scaleX, v1.y - scaleY );
  9281. _elemBox.max.set( v1.x + scaleX, v1.y + scaleY );
  9282. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  9283. _elemBox.makeEmpty();
  9284. return;
  9285. }
  9286. setFillStyle( material.color.getStyle() );
  9287. _context.save();
  9288. _context.translate( v1.x, v1.y );
  9289. _context.rotate( - element.rotation );
  9290. _context.scale( scaleX, scaleY );
  9291. _context.fillRect( -1, -1, 2, 2 );
  9292. _context.restore();
  9293. } else {
  9294. bitmap = material.map.image;
  9295. bitmapWidth = bitmap.width >> 1;
  9296. bitmapHeight = bitmap.height >> 1;
  9297. scaleX = element.scale.x * _canvasWidthHalf;
  9298. scaleY = element.scale.y * _canvasHeightHalf;
  9299. width = scaleX * bitmapWidth;
  9300. height = scaleY * bitmapHeight;
  9301. // TODO: Rotations break this...
  9302. _elemBox.min.set( v1.x - width, v1.y - height );
  9303. _elemBox.max.set( v1.x + width, v1.y + height );
  9304. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  9305. _elemBox.makeEmpty();
  9306. return;
  9307. }
  9308. _context.save();
  9309. _context.translate( v1.x, v1.y );
  9310. _context.rotate( - element.rotation );
  9311. _context.scale( scaleX, - scaleY );
  9312. _context.translate( - bitmapWidth, - bitmapHeight );
  9313. _context.drawImage( bitmap, 0, 0 );
  9314. _context.restore();
  9315. }
  9316. /* DEBUG
  9317. setStrokeStyle( 'rgb(255,255,0)' );
  9318. _context.beginPath();
  9319. _context.moveTo( v1.x - 10, v1.y );
  9320. _context.lineTo( v1.x + 10, v1.y );
  9321. _context.moveTo( v1.x, v1.y - 10 );
  9322. _context.lineTo( v1.x, v1.y + 10 );
  9323. _context.stroke();
  9324. */
  9325. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  9326. width = element.scale.x * _canvasWidthHalf;
  9327. height = element.scale.y * _canvasHeightHalf;
  9328. _elemBox.min.set( v1.x - width, v1.y - height );
  9329. _elemBox.max.set( v1.x + width, v1.y + height );
  9330. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  9331. _elemBox.makeEmpty();
  9332. return;
  9333. }
  9334. setStrokeStyle( material.color.getStyle() );
  9335. setFillStyle( material.color.getStyle() );
  9336. _context.save();
  9337. _context.translate( v1.x, v1.y );
  9338. _context.rotate( - element.rotation );
  9339. _context.scale( width, height );
  9340. material.program( _context );
  9341. _context.restore();
  9342. }
  9343. }
  9344. function renderLine( v1, v2, element, material ) {
  9345. setOpacity( material.opacity );
  9346. setBlending( material.blending );
  9347. _context.beginPath();
  9348. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  9349. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  9350. if ( material instanceof THREE.LineBasicMaterial ) {
  9351. setLineWidth( material.linewidth );
  9352. setLineCap( material.linecap );
  9353. setLineJoin( material.linejoin );
  9354. if ( material.vertexColors !== THREE.VertexColors ) {
  9355. setStrokeStyle( material.color.getStyle() );
  9356. } else {
  9357. var colorStyle1 = element.vertexColors[0].getStyle();
  9358. var colorStyle2 = element.vertexColors[1].getStyle();
  9359. if ( colorStyle1 === colorStyle2 ) {
  9360. setStrokeStyle( colorStyle1 );
  9361. } else {
  9362. try {
  9363. var grad = _context.createLinearGradient(
  9364. v1.positionScreen.x,
  9365. v1.positionScreen.y,
  9366. v2.positionScreen.x,
  9367. v2.positionScreen.y
  9368. );
  9369. grad.addColorStop( 0, colorStyle1 );
  9370. grad.addColorStop( 1, colorStyle2 );
  9371. } catch ( exception ) {
  9372. grad = colorStyle1;
  9373. }
  9374. setStrokeStyle( grad );
  9375. }
  9376. }
  9377. _context.stroke();
  9378. _elemBox.expandByScalar( material.linewidth * 2 );
  9379. } else if ( material instanceof THREE.LineDashedMaterial ) {
  9380. setLineWidth( material.linewidth );
  9381. setLineCap( material.linecap );
  9382. setLineJoin( material.linejoin );
  9383. setStrokeStyle( material.color.getStyle() );
  9384. setDashAndGap( material.dashSize, material.gapSize );
  9385. _context.stroke();
  9386. _elemBox.expandByScalar( material.linewidth * 2 );
  9387. setDashAndGap( null, null );
  9388. }
  9389. }
  9390. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  9391. _this.info.render.vertices += 3;
  9392. _this.info.render.faces ++;
  9393. setOpacity( material.opacity );
  9394. setBlending( material.blending );
  9395. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9396. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9397. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9398. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  9399. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  9400. _diffuseColor.copy( material.color );
  9401. _emissiveColor.copy( material.emissive );
  9402. if ( material.vertexColors === THREE.FaceColors ) {
  9403. _diffuseColor.multiply( element.color );
  9404. }
  9405. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  9406. _color1.copy( _ambientLight );
  9407. _color2.copy( _ambientLight );
  9408. _color3.copy( _ambientLight );
  9409. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  9410. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  9411. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  9412. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  9413. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  9414. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  9415. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9416. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9417. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9418. } else {
  9419. _color.copy( _ambientLight );
  9420. calculateLight( element.centroidModel, element.normalModel, _color );
  9421. _color.multiply( _diffuseColor ).add( _emissiveColor );
  9422. material.wireframe === true
  9423. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9424. : fillPath( _color );
  9425. }
  9426. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  9427. if ( material.map !== null ) {
  9428. if ( material.map.mapping instanceof THREE.UVMapping ) {
  9429. _uvs = element.uvs[ 0 ];
  9430. 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 );
  9431. }
  9432. } else if ( material.envMap !== null ) {
  9433. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  9434. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  9435. _uv1x = 0.5 * _vector3.x + 0.5;
  9436. _uv1y = 0.5 * _vector3.y + 0.5;
  9437. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  9438. _uv2x = 0.5 * _vector3.x + 0.5;
  9439. _uv2y = 0.5 * _vector3.y + 0.5;
  9440. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  9441. _uv3x = 0.5 * _vector3.x + 0.5;
  9442. _uv3y = 0.5 * _vector3.y + 0.5;
  9443. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  9444. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  9445. }*/
  9446. } else {
  9447. _color.copy( material.color );
  9448. if ( material.vertexColors === THREE.FaceColors ) {
  9449. _color.multiply( element.color );
  9450. }
  9451. material.wireframe === true
  9452. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9453. : fillPath( _color );
  9454. }
  9455. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  9456. _near = _camera.near;
  9457. _far = _camera.far;
  9458. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  9459. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  9460. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  9461. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9462. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9463. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9464. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  9465. var normal;
  9466. if ( material.shading == THREE.FlatShading ) {
  9467. normal = element.normalModelView;
  9468. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9469. material.wireframe === true
  9470. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9471. : fillPath( _color );
  9472. } else if ( material.shading == THREE.SmoothShading ) {
  9473. normal = element.vertexNormalsModelView[ uv1 ];
  9474. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9475. normal = element.vertexNormalsModelView[ uv2 ];
  9476. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9477. normal = element.vertexNormalsModelView[ uv3 ];
  9478. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9479. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9480. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9481. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9482. }
  9483. }
  9484. }
  9485. function renderFace4( v1, v2, v3, v4, v5, v6, element, material ) {
  9486. _this.info.render.vertices += 4;
  9487. _this.info.render.faces ++;
  9488. setOpacity( material.opacity );
  9489. setBlending( material.blending );
  9490. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  9491. // Let renderFace3() handle this
  9492. renderFace3( v1, v2, v4, 0, 1, 3, element, material );
  9493. renderFace3( v5, v3, v6, 1, 2, 3, element, material );
  9494. return;
  9495. }
  9496. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9497. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9498. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9499. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  9500. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  9501. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  9502. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  9503. _diffuseColor.copy( material.color );
  9504. _emissiveColor.copy( material.emissive );
  9505. if ( material.vertexColors === THREE.FaceColors ) {
  9506. _diffuseColor.multiply( element.color );
  9507. }
  9508. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  9509. _color1.copy( _ambientLight );
  9510. _color2.copy( _ambientLight );
  9511. _color3.copy( _ambientLight );
  9512. _color4.copy( _ambientLight );
  9513. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  9514. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  9515. calculateLight( element.v4.positionWorld, element.vertexNormalsModel[ 3 ], _color3 );
  9516. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color4 );
  9517. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  9518. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  9519. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  9520. _color4.multiply( _diffuseColor ).add( _emissiveColor );
  9521. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9522. // TODO: UVs are incorrect, v4->v3?
  9523. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  9524. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  9525. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  9526. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  9527. } else {
  9528. _color.copy( _ambientLight );
  9529. calculateLight( element.centroidModel, element.normalModel, _color );
  9530. _color.multiply( _diffuseColor ).add( _emissiveColor );
  9531. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  9532. material.wireframe === true
  9533. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9534. : fillPath( _color );
  9535. }
  9536. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  9537. _color.copy( material.color );
  9538. if ( material.vertexColors === THREE.FaceColors ) {
  9539. _color.multiply( element.color );
  9540. }
  9541. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  9542. material.wireframe === true
  9543. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9544. : fillPath( _color );
  9545. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  9546. var normal;
  9547. if ( material.shading == THREE.FlatShading ) {
  9548. normal = element.normalModelView;
  9549. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9550. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  9551. material.wireframe === true
  9552. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9553. : fillPath( _color );
  9554. } else if ( material.shading == THREE.SmoothShading ) {
  9555. normal = element.vertexNormalsModelView[ 0 ];
  9556. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9557. normal = element.vertexNormalsModelView[ 1 ];
  9558. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9559. normal = element.vertexNormalsModelView[ 3 ];
  9560. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9561. normal = element.vertexNormalsModelView[ 2 ];
  9562. _color4.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9563. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9564. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  9565. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  9566. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  9567. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  9568. }
  9569. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  9570. _near = _camera.near;
  9571. _far = _camera.far;
  9572. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  9573. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  9574. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z * v4.positionScreen.w, _near, _far );
  9575. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  9576. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9577. // TODO: UVs are incorrect, v4->v3?
  9578. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  9579. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  9580. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  9581. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  9582. }
  9583. }
  9584. //
  9585. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  9586. _context.beginPath();
  9587. _context.moveTo( x0, y0 );
  9588. _context.lineTo( x1, y1 );
  9589. _context.lineTo( x2, y2 );
  9590. _context.closePath();
  9591. }
  9592. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  9593. _context.beginPath();
  9594. _context.moveTo( x0, y0 );
  9595. _context.lineTo( x1, y1 );
  9596. _context.lineTo( x2, y2 );
  9597. _context.lineTo( x3, y3 );
  9598. _context.closePath();
  9599. }
  9600. function strokePath( color, linewidth, linecap, linejoin ) {
  9601. setLineWidth( linewidth );
  9602. setLineCap( linecap );
  9603. setLineJoin( linejoin );
  9604. setStrokeStyle( color.getStyle() );
  9605. _context.stroke();
  9606. _elemBox.expandByScalar( linewidth * 2 );
  9607. }
  9608. function fillPath( color ) {
  9609. setFillStyle( color.getStyle() );
  9610. _context.fill();
  9611. }
  9612. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  9613. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  9614. if ( texture.needsUpdate === true ) {
  9615. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  9616. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  9617. _patterns[ texture.id ] = _context.createPattern(
  9618. texture.image, repeatX === true && repeatY === true
  9619. ? 'repeat'
  9620. : repeatX === true && repeatY === false
  9621. ? 'repeat-x'
  9622. : repeatX === false && repeatY === true
  9623. ? 'repeat-y'
  9624. : 'no-repeat'
  9625. );
  9626. texture.needsUpdate = false;
  9627. }
  9628. _patterns[ texture.id ] === undefined
  9629. ? setFillStyle( 'rgba(0,0,0,1)' )
  9630. : setFillStyle( _patterns[ texture.id ] );
  9631. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9632. var a, b, c, d, e, f, det, idet,
  9633. offsetX = texture.offset.x / texture.repeat.x,
  9634. offsetY = texture.offset.y / texture.repeat.y,
  9635. width = texture.image.width * texture.repeat.x,
  9636. height = texture.image.height * texture.repeat.y;
  9637. u0 = ( u0 + offsetX ) * width;
  9638. v0 = ( 1.0 - v0 + offsetY ) * height;
  9639. u1 = ( u1 + offsetX ) * width;
  9640. v1 = ( 1.0 - v1 + offsetY ) * height;
  9641. u2 = ( u2 + offsetX ) * width;
  9642. v2 = ( 1.0 - v2 + offsetY ) * height;
  9643. x1 -= x0; y1 -= y0;
  9644. x2 -= x0; y2 -= y0;
  9645. u1 -= u0; v1 -= v0;
  9646. u2 -= u0; v2 -= v0;
  9647. det = u1 * v2 - u2 * v1;
  9648. if ( det === 0 ) {
  9649. if ( _imagedatas[ texture.id ] === undefined ) {
  9650. var canvas = document.createElement( 'canvas' )
  9651. canvas.width = texture.image.width;
  9652. canvas.height = texture.image.height;
  9653. var context = canvas.getContext( '2d' );
  9654. context.drawImage( texture.image, 0, 0 );
  9655. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  9656. }
  9657. var data = _imagedatas[ texture.id ];
  9658. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  9659. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  9660. fillPath( _color );
  9661. return;
  9662. }
  9663. idet = 1 / det;
  9664. a = ( v2 * x1 - v1 * x2 ) * idet;
  9665. b = ( v2 * y1 - v1 * y2 ) * idet;
  9666. c = ( u1 * x2 - u2 * x1 ) * idet;
  9667. d = ( u1 * y2 - u2 * y1 ) * idet;
  9668. e = x0 - a * u0 - c * v0;
  9669. f = y0 - b * u0 - d * v0;
  9670. _context.save();
  9671. _context.transform( a, b, c, d, e, f );
  9672. _context.fill();
  9673. _context.restore();
  9674. }
  9675. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  9676. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9677. var a, b, c, d, e, f, det, idet,
  9678. width = image.width - 1,
  9679. height = image.height - 1;
  9680. u0 *= width; v0 *= height;
  9681. u1 *= width; v1 *= height;
  9682. u2 *= width; v2 *= height;
  9683. x1 -= x0; y1 -= y0;
  9684. x2 -= x0; y2 -= y0;
  9685. u1 -= u0; v1 -= v0;
  9686. u2 -= u0; v2 -= v0;
  9687. det = u1 * v2 - u2 * v1;
  9688. idet = 1 / det;
  9689. a = ( v2 * x1 - v1 * x2 ) * idet;
  9690. b = ( v2 * y1 - v1 * y2 ) * idet;
  9691. c = ( u1 * x2 - u2 * x1 ) * idet;
  9692. d = ( u1 * y2 - u2 * y1 ) * idet;
  9693. e = x0 - a * u0 - c * v0;
  9694. f = y0 - b * u0 - d * v0;
  9695. _context.save();
  9696. _context.transform( a, b, c, d, e, f );
  9697. _context.clip();
  9698. _context.drawImage( image, 0, 0 );
  9699. _context.restore();
  9700. }
  9701. function getGradientTexture( color1, color2, color3, color4 ) {
  9702. // http://mrdoob.com/blog/post/710
  9703. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  9704. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  9705. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  9706. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  9707. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  9708. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  9709. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  9710. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  9711. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  9712. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  9713. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  9714. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  9715. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  9716. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  9717. return _gradientMap;
  9718. }
  9719. // Hide anti-alias gaps
  9720. function expand( v1, v2, pixels ) {
  9721. var x = v2.x - v1.x, y = v2.y - v1.y,
  9722. det = x * x + y * y, idet;
  9723. if ( det === 0 ) return;
  9724. idet = pixels / Math.sqrt( det );
  9725. x *= idet; y *= idet;
  9726. v2.x += x; v2.y += y;
  9727. v1.x -= x; v1.y -= y;
  9728. }
  9729. // Context cached methods.
  9730. function setOpacity( value ) {
  9731. if ( _contextGlobalAlpha !== value ) {
  9732. _context.globalAlpha = value;
  9733. _contextGlobalAlpha = value;
  9734. }
  9735. }
  9736. function setBlending( value ) {
  9737. if ( _contextGlobalCompositeOperation !== value ) {
  9738. if ( value === THREE.NormalBlending ) {
  9739. _context.globalCompositeOperation = 'source-over';
  9740. } else if ( value === THREE.AdditiveBlending ) {
  9741. _context.globalCompositeOperation = 'lighter';
  9742. } else if ( value === THREE.SubtractiveBlending ) {
  9743. _context.globalCompositeOperation = 'darker';
  9744. }
  9745. _contextGlobalCompositeOperation = value;
  9746. }
  9747. }
  9748. function setLineWidth( value ) {
  9749. if ( _contextLineWidth !== value ) {
  9750. _context.lineWidth = value;
  9751. _contextLineWidth = value;
  9752. }
  9753. }
  9754. function setLineCap( value ) {
  9755. // "butt", "round", "square"
  9756. if ( _contextLineCap !== value ) {
  9757. _context.lineCap = value;
  9758. _contextLineCap = value;
  9759. }
  9760. }
  9761. function setLineJoin( value ) {
  9762. // "round", "bevel", "miter"
  9763. if ( _contextLineJoin !== value ) {
  9764. _context.lineJoin = value;
  9765. _contextLineJoin = value;
  9766. }
  9767. }
  9768. function setStrokeStyle( value ) {
  9769. if ( _contextStrokeStyle !== value ) {
  9770. _context.strokeStyle = value;
  9771. _contextStrokeStyle = value;
  9772. }
  9773. }
  9774. function setFillStyle( value ) {
  9775. if ( _contextFillStyle !== value ) {
  9776. _context.fillStyle = value;
  9777. _contextFillStyle = value;
  9778. }
  9779. }
  9780. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  9781. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  9782. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  9783. _contextDashSize = dashSizeValue;
  9784. _contextGapSize = gapSizeValue;
  9785. }
  9786. }
  9787. };
  9788. /**
  9789. * @author alteredq / http://alteredqualia.com/
  9790. * @author mrdoob / http://mrdoob.com/
  9791. * @author mikael emtinger / http://gomo.se/
  9792. */
  9793. THREE.ShaderChunk = {
  9794. // FOG
  9795. fog_pars_fragment: [
  9796. "#ifdef USE_FOG",
  9797. "uniform vec3 fogColor;",
  9798. "#ifdef FOG_EXP2",
  9799. "uniform float fogDensity;",
  9800. "#else",
  9801. "uniform float fogNear;",
  9802. "uniform float fogFar;",
  9803. "#endif",
  9804. "#endif"
  9805. ].join("\n"),
  9806. fog_fragment: [
  9807. "#ifdef USE_FOG",
  9808. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9809. "#ifdef FOG_EXP2",
  9810. "const float LOG2 = 1.442695;",
  9811. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  9812. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  9813. "#else",
  9814. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  9815. "#endif",
  9816. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  9817. "#endif"
  9818. ].join("\n"),
  9819. // ENVIRONMENT MAP
  9820. envmap_pars_fragment: [
  9821. "#ifdef USE_ENVMAP",
  9822. "uniform float reflectivity;",
  9823. "uniform samplerCube envMap;",
  9824. "uniform float flipEnvMap;",
  9825. "uniform int combine;",
  9826. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9827. "uniform bool useRefract;",
  9828. "uniform float refractionRatio;",
  9829. "#else",
  9830. "varying vec3 vReflect;",
  9831. "#endif",
  9832. "#endif"
  9833. ].join("\n"),
  9834. envmap_fragment: [
  9835. "#ifdef USE_ENVMAP",
  9836. "vec3 reflectVec;",
  9837. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9838. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  9839. "if ( useRefract ) {",
  9840. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  9841. "} else { ",
  9842. "reflectVec = reflect( cameraToVertex, normal );",
  9843. "}",
  9844. "#else",
  9845. "reflectVec = vReflect;",
  9846. "#endif",
  9847. "#ifdef DOUBLE_SIDED",
  9848. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9849. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9850. "#else",
  9851. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9852. "#endif",
  9853. "#ifdef GAMMA_INPUT",
  9854. "cubeColor.xyz *= cubeColor.xyz;",
  9855. "#endif",
  9856. "if ( combine == 1 ) {",
  9857. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  9858. "} else if ( combine == 2 ) {",
  9859. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  9860. "} else {",
  9861. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  9862. "}",
  9863. "#endif"
  9864. ].join("\n"),
  9865. envmap_pars_vertex: [
  9866. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9867. "varying vec3 vReflect;",
  9868. "uniform float refractionRatio;",
  9869. "uniform bool useRefract;",
  9870. "#endif"
  9871. ].join("\n"),
  9872. worldpos_vertex : [
  9873. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  9874. "#ifdef USE_SKINNING",
  9875. "vec4 worldPosition = modelMatrix * skinned;",
  9876. "#endif",
  9877. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9878. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  9879. "#endif",
  9880. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9881. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  9882. "#endif",
  9883. "#endif"
  9884. ].join("\n"),
  9885. envmap_vertex : [
  9886. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9887. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  9888. "worldNormal = normalize( worldNormal );",
  9889. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  9890. "if ( useRefract ) {",
  9891. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  9892. "} else {",
  9893. "vReflect = reflect( cameraToVertex, worldNormal );",
  9894. "}",
  9895. "#endif"
  9896. ].join("\n"),
  9897. // COLOR MAP (particles)
  9898. map_particle_pars_fragment: [
  9899. "#ifdef USE_MAP",
  9900. "uniform sampler2D map;",
  9901. "#endif"
  9902. ].join("\n"),
  9903. map_particle_fragment: [
  9904. "#ifdef USE_MAP",
  9905. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  9906. "#endif"
  9907. ].join("\n"),
  9908. // COLOR MAP (triangles)
  9909. map_pars_vertex: [
  9910. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9911. "varying vec2 vUv;",
  9912. "uniform vec4 offsetRepeat;",
  9913. "#endif"
  9914. ].join("\n"),
  9915. map_pars_fragment: [
  9916. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9917. "varying vec2 vUv;",
  9918. "#endif",
  9919. "#ifdef USE_MAP",
  9920. "uniform sampler2D map;",
  9921. "#endif"
  9922. ].join("\n"),
  9923. map_vertex: [
  9924. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9925. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  9926. "#endif"
  9927. ].join("\n"),
  9928. map_fragment: [
  9929. "#ifdef USE_MAP",
  9930. "vec4 texelColor = texture2D( map, vUv );",
  9931. "#ifdef GAMMA_INPUT",
  9932. "texelColor.xyz *= texelColor.xyz;",
  9933. "#endif",
  9934. "gl_FragColor = gl_FragColor * texelColor;",
  9935. "#endif"
  9936. ].join("\n"),
  9937. // LIGHT MAP
  9938. lightmap_pars_fragment: [
  9939. "#ifdef USE_LIGHTMAP",
  9940. "varying vec2 vUv2;",
  9941. "uniform sampler2D lightMap;",
  9942. "#endif"
  9943. ].join("\n"),
  9944. lightmap_pars_vertex: [
  9945. "#ifdef USE_LIGHTMAP",
  9946. "varying vec2 vUv2;",
  9947. "#endif"
  9948. ].join("\n"),
  9949. lightmap_fragment: [
  9950. "#ifdef USE_LIGHTMAP",
  9951. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  9952. "#endif"
  9953. ].join("\n"),
  9954. lightmap_vertex: [
  9955. "#ifdef USE_LIGHTMAP",
  9956. "vUv2 = uv2;",
  9957. "#endif"
  9958. ].join("\n"),
  9959. // BUMP MAP
  9960. bumpmap_pars_fragment: [
  9961. "#ifdef USE_BUMPMAP",
  9962. "uniform sampler2D bumpMap;",
  9963. "uniform float bumpScale;",
  9964. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  9965. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  9966. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  9967. "vec2 dHdxy_fwd() {",
  9968. "vec2 dSTdx = dFdx( vUv );",
  9969. "vec2 dSTdy = dFdy( vUv );",
  9970. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  9971. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  9972. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  9973. "return vec2( dBx, dBy );",
  9974. "}",
  9975. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  9976. "vec3 vSigmaX = dFdx( surf_pos );",
  9977. "vec3 vSigmaY = dFdy( surf_pos );",
  9978. "vec3 vN = surf_norm;", // normalized
  9979. "vec3 R1 = cross( vSigmaY, vN );",
  9980. "vec3 R2 = cross( vN, vSigmaX );",
  9981. "float fDet = dot( vSigmaX, R1 );",
  9982. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  9983. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  9984. "}",
  9985. "#endif"
  9986. ].join("\n"),
  9987. // NORMAL MAP
  9988. normalmap_pars_fragment: [
  9989. "#ifdef USE_NORMALMAP",
  9990. "uniform sampler2D normalMap;",
  9991. "uniform vec2 normalScale;",
  9992. // Per-Pixel Tangent Space Normal Mapping
  9993. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  9994. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  9995. "vec3 q0 = dFdx( eye_pos.xyz );",
  9996. "vec3 q1 = dFdy( eye_pos.xyz );",
  9997. "vec2 st0 = dFdx( vUv.st );",
  9998. "vec2 st1 = dFdy( vUv.st );",
  9999. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  10000. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  10001. "vec3 N = normalize( surf_norm );",
  10002. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  10003. "mapN.xy = normalScale * mapN.xy;",
  10004. "mat3 tsn = mat3( S, T, N );",
  10005. "return normalize( tsn * mapN );",
  10006. "}",
  10007. "#endif"
  10008. ].join("\n"),
  10009. // SPECULAR MAP
  10010. specularmap_pars_fragment: [
  10011. "#ifdef USE_SPECULARMAP",
  10012. "uniform sampler2D specularMap;",
  10013. "#endif"
  10014. ].join("\n"),
  10015. specularmap_fragment: [
  10016. "float specularStrength;",
  10017. "#ifdef USE_SPECULARMAP",
  10018. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  10019. "specularStrength = texelSpecular.r;",
  10020. "#else",
  10021. "specularStrength = 1.0;",
  10022. "#endif"
  10023. ].join("\n"),
  10024. // LIGHTS LAMBERT
  10025. lights_lambert_pars_vertex: [
  10026. "uniform vec3 ambient;",
  10027. "uniform vec3 diffuse;",
  10028. "uniform vec3 emissive;",
  10029. "uniform vec3 ambientLightColor;",
  10030. "#if MAX_DIR_LIGHTS > 0",
  10031. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10032. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10033. "#endif",
  10034. "#if MAX_HEMI_LIGHTS > 0",
  10035. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10036. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10037. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10038. "#endif",
  10039. "#if MAX_POINT_LIGHTS > 0",
  10040. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10041. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10042. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10043. "#endif",
  10044. "#if MAX_SPOT_LIGHTS > 0",
  10045. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10046. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10047. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10048. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10049. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10050. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10051. "#endif",
  10052. "#ifdef WRAP_AROUND",
  10053. "uniform vec3 wrapRGB;",
  10054. "#endif"
  10055. ].join("\n"),
  10056. lights_lambert_vertex: [
  10057. "vLightFront = vec3( 0.0 );",
  10058. "#ifdef DOUBLE_SIDED",
  10059. "vLightBack = vec3( 0.0 );",
  10060. "#endif",
  10061. "transformedNormal = normalize( transformedNormal );",
  10062. "#if MAX_DIR_LIGHTS > 0",
  10063. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10064. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10065. "vec3 dirVector = normalize( lDirection.xyz );",
  10066. "float dotProduct = dot( transformedNormal, dirVector );",
  10067. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10068. "#ifdef DOUBLE_SIDED",
  10069. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10070. "#ifdef WRAP_AROUND",
  10071. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10072. "#endif",
  10073. "#endif",
  10074. "#ifdef WRAP_AROUND",
  10075. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10076. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  10077. "#ifdef DOUBLE_SIDED",
  10078. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  10079. "#endif",
  10080. "#endif",
  10081. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  10082. "#ifdef DOUBLE_SIDED",
  10083. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  10084. "#endif",
  10085. "}",
  10086. "#endif",
  10087. "#if MAX_POINT_LIGHTS > 0",
  10088. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10089. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10090. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10091. "float lDistance = 1.0;",
  10092. "if ( pointLightDistance[ i ] > 0.0 )",
  10093. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10094. "lVector = normalize( lVector );",
  10095. "float dotProduct = dot( transformedNormal, lVector );",
  10096. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10097. "#ifdef DOUBLE_SIDED",
  10098. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10099. "#ifdef WRAP_AROUND",
  10100. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10101. "#endif",
  10102. "#endif",
  10103. "#ifdef WRAP_AROUND",
  10104. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10105. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  10106. "#ifdef DOUBLE_SIDED",
  10107. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  10108. "#endif",
  10109. "#endif",
  10110. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  10111. "#ifdef DOUBLE_SIDED",
  10112. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  10113. "#endif",
  10114. "}",
  10115. "#endif",
  10116. "#if MAX_SPOT_LIGHTS > 0",
  10117. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10118. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10119. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10120. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  10121. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10122. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10123. "float lDistance = 1.0;",
  10124. "if ( spotLightDistance[ i ] > 0.0 )",
  10125. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10126. "lVector = normalize( lVector );",
  10127. "float dotProduct = dot( transformedNormal, lVector );",
  10128. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10129. "#ifdef DOUBLE_SIDED",
  10130. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10131. "#ifdef WRAP_AROUND",
  10132. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10133. "#endif",
  10134. "#endif",
  10135. "#ifdef WRAP_AROUND",
  10136. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10137. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  10138. "#ifdef DOUBLE_SIDED",
  10139. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  10140. "#endif",
  10141. "#endif",
  10142. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  10143. "#ifdef DOUBLE_SIDED",
  10144. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  10145. "#endif",
  10146. "}",
  10147. "}",
  10148. "#endif",
  10149. "#if MAX_HEMI_LIGHTS > 0",
  10150. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10151. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10152. "vec3 lVector = normalize( lDirection.xyz );",
  10153. "float dotProduct = dot( transformedNormal, lVector );",
  10154. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10155. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  10156. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10157. "#ifdef DOUBLE_SIDED",
  10158. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  10159. "#endif",
  10160. "}",
  10161. "#endif",
  10162. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  10163. "#ifdef DOUBLE_SIDED",
  10164. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  10165. "#endif"
  10166. ].join("\n"),
  10167. // LIGHTS PHONG
  10168. lights_phong_pars_vertex: [
  10169. "#ifndef PHONG_PER_PIXEL",
  10170. "#if MAX_POINT_LIGHTS > 0",
  10171. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10172. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10173. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  10174. "#endif",
  10175. "#if MAX_SPOT_LIGHTS > 0",
  10176. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10177. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10178. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  10179. "#endif",
  10180. "#endif",
  10181. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10182. "varying vec3 vWorldPosition;",
  10183. "#endif"
  10184. ].join("\n"),
  10185. lights_phong_vertex: [
  10186. "#ifndef PHONG_PER_PIXEL",
  10187. "#if MAX_POINT_LIGHTS > 0",
  10188. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10189. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10190. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10191. "float lDistance = 1.0;",
  10192. "if ( pointLightDistance[ i ] > 0.0 )",
  10193. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10194. "vPointLight[ i ] = vec4( lVector, lDistance );",
  10195. "}",
  10196. "#endif",
  10197. "#if MAX_SPOT_LIGHTS > 0",
  10198. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10199. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10200. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10201. "float lDistance = 1.0;",
  10202. "if ( spotLightDistance[ i ] > 0.0 )",
  10203. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10204. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  10205. "}",
  10206. "#endif",
  10207. "#endif",
  10208. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10209. "vWorldPosition = worldPosition.xyz;",
  10210. "#endif"
  10211. ].join("\n"),
  10212. lights_phong_pars_fragment: [
  10213. "uniform vec3 ambientLightColor;",
  10214. "#if MAX_DIR_LIGHTS > 0",
  10215. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10216. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10217. "#endif",
  10218. "#if MAX_HEMI_LIGHTS > 0",
  10219. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10220. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10221. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10222. "#endif",
  10223. "#if MAX_POINT_LIGHTS > 0",
  10224. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10225. "#ifdef PHONG_PER_PIXEL",
  10226. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10227. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10228. "#else",
  10229. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  10230. "#endif",
  10231. "#endif",
  10232. "#if MAX_SPOT_LIGHTS > 0",
  10233. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10234. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10235. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10236. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10237. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10238. "#ifdef PHONG_PER_PIXEL",
  10239. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10240. "#else",
  10241. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  10242. "#endif",
  10243. "#endif",
  10244. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10245. "varying vec3 vWorldPosition;",
  10246. "#endif",
  10247. "#ifdef WRAP_AROUND",
  10248. "uniform vec3 wrapRGB;",
  10249. "#endif",
  10250. "varying vec3 vViewPosition;",
  10251. "varying vec3 vNormal;"
  10252. ].join("\n"),
  10253. lights_phong_fragment: [
  10254. "vec3 normal = normalize( vNormal );",
  10255. "vec3 viewPosition = normalize( vViewPosition );",
  10256. "#ifdef DOUBLE_SIDED",
  10257. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10258. "#endif",
  10259. "#ifdef USE_NORMALMAP",
  10260. "normal = perturbNormal2Arb( -vViewPosition, normal );",
  10261. "#elif defined( USE_BUMPMAP )",
  10262. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  10263. "#endif",
  10264. "#if MAX_POINT_LIGHTS > 0",
  10265. "vec3 pointDiffuse = vec3( 0.0 );",
  10266. "vec3 pointSpecular = vec3( 0.0 );",
  10267. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10268. "#ifdef PHONG_PER_PIXEL",
  10269. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10270. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10271. "float lDistance = 1.0;",
  10272. "if ( pointLightDistance[ i ] > 0.0 )",
  10273. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10274. "lVector = normalize( lVector );",
  10275. "#else",
  10276. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  10277. "float lDistance = vPointLight[ i ].w;",
  10278. "#endif",
  10279. // diffuse
  10280. "float dotProduct = dot( normal, lVector );",
  10281. "#ifdef WRAP_AROUND",
  10282. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  10283. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10284. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10285. "#else",
  10286. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  10287. "#endif",
  10288. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  10289. // specular
  10290. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  10291. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10292. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  10293. "#ifdef PHYSICALLY_BASED_SHADING",
  10294. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10295. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10296. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  10297. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  10298. "#else",
  10299. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  10300. "#endif",
  10301. "}",
  10302. "#endif",
  10303. "#if MAX_SPOT_LIGHTS > 0",
  10304. "vec3 spotDiffuse = vec3( 0.0 );",
  10305. "vec3 spotSpecular = vec3( 0.0 );",
  10306. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10307. "#ifdef PHONG_PER_PIXEL",
  10308. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10309. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10310. "float lDistance = 1.0;",
  10311. "if ( spotLightDistance[ i ] > 0.0 )",
  10312. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10313. "lVector = normalize( lVector );",
  10314. "#else",
  10315. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  10316. "float lDistance = vSpotLight[ i ].w;",
  10317. "#endif",
  10318. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10319. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10320. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10321. // diffuse
  10322. "float dotProduct = dot( normal, lVector );",
  10323. "#ifdef WRAP_AROUND",
  10324. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  10325. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10326. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10327. "#else",
  10328. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  10329. "#endif",
  10330. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  10331. // specular
  10332. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  10333. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10334. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  10335. "#ifdef PHYSICALLY_BASED_SHADING",
  10336. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10337. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10338. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  10339. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  10340. "#else",
  10341. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  10342. "#endif",
  10343. "}",
  10344. "}",
  10345. "#endif",
  10346. "#if MAX_DIR_LIGHTS > 0",
  10347. "vec3 dirDiffuse = vec3( 0.0 );",
  10348. "vec3 dirSpecular = vec3( 0.0 );" ,
  10349. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10350. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10351. "vec3 dirVector = normalize( lDirection.xyz );",
  10352. // diffuse
  10353. "float dotProduct = dot( normal, dirVector );",
  10354. "#ifdef WRAP_AROUND",
  10355. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  10356. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10357. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  10358. "#else",
  10359. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  10360. "#endif",
  10361. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  10362. // specular
  10363. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10364. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10365. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  10366. "#ifdef PHYSICALLY_BASED_SHADING",
  10367. /*
  10368. // fresnel term from skin shader
  10369. "const float F0 = 0.128;",
  10370. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  10371. "float exponential = pow( base, 5.0 );",
  10372. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  10373. */
  10374. /*
  10375. // fresnel term from fresnel shader
  10376. "const float mFresnelBias = 0.08;",
  10377. "const float mFresnelScale = 0.3;",
  10378. "const float mFresnelPower = 5.0;",
  10379. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  10380. */
  10381. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10382. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10383. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  10384. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  10385. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10386. "#else",
  10387. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  10388. "#endif",
  10389. "}",
  10390. "#endif",
  10391. "#if MAX_HEMI_LIGHTS > 0",
  10392. "vec3 hemiDiffuse = vec3( 0.0 );",
  10393. "vec3 hemiSpecular = vec3( 0.0 );" ,
  10394. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10395. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10396. "vec3 lVector = normalize( lDirection.xyz );",
  10397. // diffuse
  10398. "float dotProduct = dot( normal, lVector );",
  10399. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10400. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10401. "hemiDiffuse += diffuse * hemiColor;",
  10402. // specular (sky light)
  10403. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10404. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10405. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  10406. // specular (ground light)
  10407. "vec3 lVectorGround = -lVector;",
  10408. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10409. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10410. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  10411. "#ifdef PHYSICALLY_BASED_SHADING",
  10412. "float dotProductGround = dot( normal, lVectorGround );",
  10413. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10414. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10415. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  10416. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  10417. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10418. "#else",
  10419. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  10420. "#endif",
  10421. "}",
  10422. "#endif",
  10423. "vec3 totalDiffuse = vec3( 0.0 );",
  10424. "vec3 totalSpecular = vec3( 0.0 );",
  10425. "#if MAX_DIR_LIGHTS > 0",
  10426. "totalDiffuse += dirDiffuse;",
  10427. "totalSpecular += dirSpecular;",
  10428. "#endif",
  10429. "#if MAX_HEMI_LIGHTS > 0",
  10430. "totalDiffuse += hemiDiffuse;",
  10431. "totalSpecular += hemiSpecular;",
  10432. "#endif",
  10433. "#if MAX_POINT_LIGHTS > 0",
  10434. "totalDiffuse += pointDiffuse;",
  10435. "totalSpecular += pointSpecular;",
  10436. "#endif",
  10437. "#if MAX_SPOT_LIGHTS > 0",
  10438. "totalDiffuse += spotDiffuse;",
  10439. "totalSpecular += spotSpecular;",
  10440. "#endif",
  10441. "#ifdef METAL",
  10442. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  10443. "#else",
  10444. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  10445. "#endif"
  10446. ].join("\n"),
  10447. // VERTEX COLORS
  10448. color_pars_fragment: [
  10449. "#ifdef USE_COLOR",
  10450. "varying vec3 vColor;",
  10451. "#endif"
  10452. ].join("\n"),
  10453. color_fragment: [
  10454. "#ifdef USE_COLOR",
  10455. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  10456. "#endif"
  10457. ].join("\n"),
  10458. color_pars_vertex: [
  10459. "#ifdef USE_COLOR",
  10460. "varying vec3 vColor;",
  10461. "#endif"
  10462. ].join("\n"),
  10463. color_vertex: [
  10464. "#ifdef USE_COLOR",
  10465. "#ifdef GAMMA_INPUT",
  10466. "vColor = color * color;",
  10467. "#else",
  10468. "vColor = color;",
  10469. "#endif",
  10470. "#endif"
  10471. ].join("\n"),
  10472. // SKINNING
  10473. skinning_pars_vertex: [
  10474. "#ifdef USE_SKINNING",
  10475. "#ifdef BONE_TEXTURE",
  10476. "uniform sampler2D boneTexture;",
  10477. "mat4 getBoneMatrix( const in float i ) {",
  10478. "float j = i * 4.0;",
  10479. "float x = mod( j, N_BONE_PIXEL_X );",
  10480. "float y = floor( j / N_BONE_PIXEL_X );",
  10481. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  10482. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  10483. "y = dy * ( y + 0.5 );",
  10484. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  10485. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  10486. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  10487. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  10488. "mat4 bone = mat4( v1, v2, v3, v4 );",
  10489. "return bone;",
  10490. "}",
  10491. "#else",
  10492. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  10493. "mat4 getBoneMatrix( const in float i ) {",
  10494. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  10495. "return bone;",
  10496. "}",
  10497. "#endif",
  10498. "#endif"
  10499. ].join("\n"),
  10500. skinbase_vertex: [
  10501. "#ifdef USE_SKINNING",
  10502. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  10503. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  10504. "#endif"
  10505. ].join("\n"),
  10506. skinning_vertex: [
  10507. "#ifdef USE_SKINNING",
  10508. "#ifdef USE_MORPHTARGETS",
  10509. "vec4 skinVertex = vec4( morphed, 1.0 );",
  10510. "#else",
  10511. "vec4 skinVertex = vec4( position, 1.0 );",
  10512. "#endif",
  10513. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10514. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10515. "#endif"
  10516. ].join("\n"),
  10517. // MORPHING
  10518. morphtarget_pars_vertex: [
  10519. "#ifdef USE_MORPHTARGETS",
  10520. "#ifndef USE_MORPHNORMALS",
  10521. "uniform float morphTargetInfluences[ 8 ];",
  10522. "#else",
  10523. "uniform float morphTargetInfluences[ 4 ];",
  10524. "#endif",
  10525. "#endif"
  10526. ].join("\n"),
  10527. morphtarget_vertex: [
  10528. "#ifdef USE_MORPHTARGETS",
  10529. "vec3 morphed = vec3( 0.0 );",
  10530. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  10531. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  10532. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  10533. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  10534. "#ifndef USE_MORPHNORMALS",
  10535. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  10536. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  10537. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  10538. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  10539. "#endif",
  10540. "morphed += position;",
  10541. "#endif"
  10542. ].join("\n"),
  10543. default_vertex : [
  10544. "vec4 mvPosition;",
  10545. "#ifdef USE_SKINNING",
  10546. "mvPosition = modelViewMatrix * skinned;",
  10547. "#endif",
  10548. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  10549. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  10550. "#endif",
  10551. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  10552. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10553. "#endif",
  10554. "gl_Position = projectionMatrix * mvPosition;"
  10555. ].join("\n"),
  10556. morphnormal_vertex: [
  10557. "#ifdef USE_MORPHNORMALS",
  10558. "vec3 morphedNormal = vec3( 0.0 );",
  10559. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  10560. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  10561. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  10562. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  10563. "morphedNormal += normal;",
  10564. "#endif"
  10565. ].join("\n"),
  10566. skinnormal_vertex: [
  10567. "#ifdef USE_SKINNING",
  10568. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  10569. "skinMatrix += skinWeight.y * boneMatY;",
  10570. "#ifdef USE_MORPHNORMALS",
  10571. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  10572. "#else",
  10573. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  10574. "#endif",
  10575. "#endif"
  10576. ].join("\n"),
  10577. defaultnormal_vertex: [
  10578. "vec3 objectNormal;",
  10579. "#ifdef USE_SKINNING",
  10580. "objectNormal = skinnedNormal.xyz;",
  10581. "#endif",
  10582. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  10583. "objectNormal = morphedNormal;",
  10584. "#endif",
  10585. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  10586. "objectNormal = normal;",
  10587. "#endif",
  10588. "#ifdef FLIP_SIDED",
  10589. "objectNormal = -objectNormal;",
  10590. "#endif",
  10591. "vec3 transformedNormal = normalMatrix * objectNormal;"
  10592. ].join("\n"),
  10593. // SHADOW MAP
  10594. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  10595. // http://spidergl.org/example.php?id=6
  10596. // http://fabiensanglard.net/shadowmapping
  10597. shadowmap_pars_fragment: [
  10598. "#ifdef USE_SHADOWMAP",
  10599. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  10600. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  10601. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  10602. "uniform float shadowBias[ MAX_SHADOWS ];",
  10603. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10604. "float unpackDepth( const in vec4 rgba_depth ) {",
  10605. "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 );",
  10606. "float depth = dot( rgba_depth, bit_shift );",
  10607. "return depth;",
  10608. "}",
  10609. "#endif"
  10610. ].join("\n"),
  10611. shadowmap_fragment: [
  10612. "#ifdef USE_SHADOWMAP",
  10613. "#ifdef SHADOWMAP_DEBUG",
  10614. "vec3 frustumColors[3];",
  10615. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  10616. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  10617. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  10618. "#endif",
  10619. "#ifdef SHADOWMAP_CASCADE",
  10620. "int inFrustumCount = 0;",
  10621. "#endif",
  10622. "float fDepth;",
  10623. "vec3 shadowColor = vec3( 1.0 );",
  10624. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10625. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  10626. // "if ( something && something )" breaks ATI OpenGL shader compiler
  10627. // "if ( all( something, something ) )" using this instead
  10628. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  10629. "bool inFrustum = all( inFrustumVec );",
  10630. // don't shadow pixels outside of light frustum
  10631. // use just first frustum (for cascades)
  10632. // don't shadow pixels behind far plane of light frustum
  10633. "#ifdef SHADOWMAP_CASCADE",
  10634. "inFrustumCount += int( inFrustum );",
  10635. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  10636. "#else",
  10637. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  10638. "#endif",
  10639. "bool frustumTest = all( frustumTestVec );",
  10640. "if ( frustumTest ) {",
  10641. "shadowCoord.z += shadowBias[ i ];",
  10642. "#if defined( SHADOWMAP_TYPE_PCF )",
  10643. // Percentage-close filtering
  10644. // (9 pixel kernel)
  10645. // http://fabiensanglard.net/shadowmappingPCF/
  10646. "float shadow = 0.0;",
  10647. /*
  10648. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  10649. // must enroll loop manually
  10650. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  10651. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  10652. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  10653. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  10654. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  10655. "float fDepth = unpackDepth( rgbaDepth );",
  10656. "if ( fDepth < shadowCoord.z )",
  10657. "shadow += 1.0;",
  10658. "}",
  10659. "shadow /= 9.0;",
  10660. */
  10661. "const float shadowDelta = 1.0 / 9.0;",
  10662. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10663. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10664. "float dx0 = -1.25 * xPixelOffset;",
  10665. "float dy0 = -1.25 * yPixelOffset;",
  10666. "float dx1 = 1.25 * xPixelOffset;",
  10667. "float dy1 = 1.25 * yPixelOffset;",
  10668. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10669. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10670. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10671. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10672. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10673. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10674. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10675. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10676. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10677. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10678. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10679. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10680. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10681. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10682. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10683. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10684. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10685. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10686. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10687. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  10688. // Percentage-close filtering
  10689. // (9 pixel kernel)
  10690. // http://fabiensanglard.net/shadowmappingPCF/
  10691. "float shadow = 0.0;",
  10692. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10693. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10694. "float dx0 = -1.0 * xPixelOffset;",
  10695. "float dy0 = -1.0 * yPixelOffset;",
  10696. "float dx1 = 1.0 * xPixelOffset;",
  10697. "float dy1 = 1.0 * yPixelOffset;",
  10698. "mat3 shadowKernel;",
  10699. "mat3 depthKernel;",
  10700. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10701. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10702. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10703. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10704. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10705. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10706. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10707. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10708. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10709. "vec3 shadowZ = vec3( shadowCoord.z );",
  10710. "shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  10711. "shadowKernel[0] *= vec3(0.25);",
  10712. "shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  10713. "shadowKernel[1] *= vec3(0.25);",
  10714. "shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  10715. "shadowKernel[2] *= vec3(0.25);",
  10716. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  10717. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  10718. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  10719. "vec4 shadowValues;",
  10720. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  10721. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  10722. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  10723. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  10724. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  10725. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10726. "#else",
  10727. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  10728. "float fDepth = unpackDepth( rgbaDepth );",
  10729. "if ( fDepth < shadowCoord.z )",
  10730. // spot with multiple shadows is darker
  10731. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  10732. // spot with multiple shadows has the same color as single shadow spot
  10733. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  10734. "#endif",
  10735. "}",
  10736. "#ifdef SHADOWMAP_DEBUG",
  10737. "#ifdef SHADOWMAP_CASCADE",
  10738. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  10739. "#else",
  10740. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  10741. "#endif",
  10742. "#endif",
  10743. "}",
  10744. "#ifdef GAMMA_OUTPUT",
  10745. "shadowColor *= shadowColor;",
  10746. "#endif",
  10747. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  10748. "#endif"
  10749. ].join("\n"),
  10750. shadowmap_pars_vertex: [
  10751. "#ifdef USE_SHADOWMAP",
  10752. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10753. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  10754. "#endif"
  10755. ].join("\n"),
  10756. shadowmap_vertex: [
  10757. "#ifdef USE_SHADOWMAP",
  10758. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10759. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10760. "}",
  10761. "#endif"
  10762. ].join("\n"),
  10763. // ALPHATEST
  10764. alphatest_fragment: [
  10765. "#ifdef ALPHATEST",
  10766. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  10767. "#endif"
  10768. ].join("\n"),
  10769. // LINEAR SPACE
  10770. linear_to_gamma_fragment: [
  10771. "#ifdef GAMMA_OUTPUT",
  10772. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  10773. "#endif"
  10774. ].join("\n")
  10775. };
  10776. THREE.UniformsUtils = {
  10777. merge: function ( uniforms ) {
  10778. var u, p, tmp, merged = {};
  10779. for ( u = 0; u < uniforms.length; u ++ ) {
  10780. tmp = this.clone( uniforms[ u ] );
  10781. for ( p in tmp ) {
  10782. merged[ p ] = tmp[ p ];
  10783. }
  10784. }
  10785. return merged;
  10786. },
  10787. clone: function ( uniforms_src ) {
  10788. var u, p, parameter, parameter_src, uniforms_dst = {};
  10789. for ( u in uniforms_src ) {
  10790. uniforms_dst[ u ] = {};
  10791. for ( p in uniforms_src[ u ] ) {
  10792. parameter_src = uniforms_src[ u ][ p ];
  10793. if ( parameter_src instanceof THREE.Color ||
  10794. parameter_src instanceof THREE.Vector2 ||
  10795. parameter_src instanceof THREE.Vector3 ||
  10796. parameter_src instanceof THREE.Vector4 ||
  10797. parameter_src instanceof THREE.Matrix4 ||
  10798. parameter_src instanceof THREE.Texture ) {
  10799. uniforms_dst[ u ][ p ] = parameter_src.clone();
  10800. } else if ( parameter_src instanceof Array ) {
  10801. uniforms_dst[ u ][ p ] = parameter_src.slice();
  10802. } else {
  10803. uniforms_dst[ u ][ p ] = parameter_src;
  10804. }
  10805. }
  10806. }
  10807. return uniforms_dst;
  10808. }
  10809. };
  10810. THREE.UniformsLib = {
  10811. common: {
  10812. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10813. "opacity" : { type: "f", value: 1.0 },
  10814. "map" : { type: "t", value: null },
  10815. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10816. "lightMap" : { type: "t", value: null },
  10817. "specularMap" : { type: "t", value: null },
  10818. "envMap" : { type: "t", value: null },
  10819. "flipEnvMap" : { type: "f", value: -1 },
  10820. "useRefract" : { type: "i", value: 0 },
  10821. "reflectivity" : { type: "f", value: 1.0 },
  10822. "refractionRatio" : { type: "f", value: 0.98 },
  10823. "combine" : { type: "i", value: 0 },
  10824. "morphTargetInfluences" : { type: "f", value: 0 }
  10825. },
  10826. bump: {
  10827. "bumpMap" : { type: "t", value: null },
  10828. "bumpScale" : { type: "f", value: 1 }
  10829. },
  10830. normalmap: {
  10831. "normalMap" : { type: "t", value: null },
  10832. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  10833. },
  10834. fog : {
  10835. "fogDensity" : { type: "f", value: 0.00025 },
  10836. "fogNear" : { type: "f", value: 1 },
  10837. "fogFar" : { type: "f", value: 2000 },
  10838. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10839. },
  10840. lights: {
  10841. "ambientLightColor" : { type: "fv", value: [] },
  10842. "directionalLightDirection" : { type: "fv", value: [] },
  10843. "directionalLightColor" : { type: "fv", value: [] },
  10844. "hemisphereLightDirection" : { type: "fv", value: [] },
  10845. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  10846. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  10847. "pointLightColor" : { type: "fv", value: [] },
  10848. "pointLightPosition" : { type: "fv", value: [] },
  10849. "pointLightDistance" : { type: "fv1", value: [] },
  10850. "spotLightColor" : { type: "fv", value: [] },
  10851. "spotLightPosition" : { type: "fv", value: [] },
  10852. "spotLightDirection" : { type: "fv", value: [] },
  10853. "spotLightDistance" : { type: "fv1", value: [] },
  10854. "spotLightAngleCos" : { type: "fv1", value: [] },
  10855. "spotLightExponent" : { type: "fv1", value: [] }
  10856. },
  10857. particle: {
  10858. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10859. "opacity" : { type: "f", value: 1.0 },
  10860. "size" : { type: "f", value: 1.0 },
  10861. "scale" : { type: "f", value: 1.0 },
  10862. "map" : { type: "t", value: null },
  10863. "fogDensity" : { type: "f", value: 0.00025 },
  10864. "fogNear" : { type: "f", value: 1 },
  10865. "fogFar" : { type: "f", value: 2000 },
  10866. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10867. },
  10868. shadowmap: {
  10869. "shadowMap": { type: "tv", value: [] },
  10870. "shadowMapSize": { type: "v2v", value: [] },
  10871. "shadowBias" : { type: "fv1", value: [] },
  10872. "shadowDarkness": { type: "fv1", value: [] },
  10873. "shadowMatrix" : { type: "m4v", value: [] }
  10874. }
  10875. };
  10876. THREE.ShaderLib = {
  10877. 'basic': {
  10878. uniforms: THREE.UniformsUtils.merge( [
  10879. THREE.UniformsLib[ "common" ],
  10880. THREE.UniformsLib[ "fog" ],
  10881. THREE.UniformsLib[ "shadowmap" ]
  10882. ] ),
  10883. vertexShader: [
  10884. THREE.ShaderChunk[ "map_pars_vertex" ],
  10885. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10886. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10887. THREE.ShaderChunk[ "color_pars_vertex" ],
  10888. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10889. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10890. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10891. "void main() {",
  10892. THREE.ShaderChunk[ "map_vertex" ],
  10893. THREE.ShaderChunk[ "lightmap_vertex" ],
  10894. THREE.ShaderChunk[ "color_vertex" ],
  10895. THREE.ShaderChunk[ "skinbase_vertex" ],
  10896. "#ifdef USE_ENVMAP",
  10897. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10898. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10899. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10900. "#endif",
  10901. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10902. THREE.ShaderChunk[ "skinning_vertex" ],
  10903. THREE.ShaderChunk[ "default_vertex" ],
  10904. THREE.ShaderChunk[ "worldpos_vertex" ],
  10905. THREE.ShaderChunk[ "envmap_vertex" ],
  10906. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10907. "}"
  10908. ].join("\n"),
  10909. fragmentShader: [
  10910. "uniform vec3 diffuse;",
  10911. "uniform float opacity;",
  10912. THREE.ShaderChunk[ "color_pars_fragment" ],
  10913. THREE.ShaderChunk[ "map_pars_fragment" ],
  10914. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10915. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10916. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10917. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10918. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10919. "void main() {",
  10920. "gl_FragColor = vec4( diffuse, opacity );",
  10921. THREE.ShaderChunk[ "map_fragment" ],
  10922. THREE.ShaderChunk[ "alphatest_fragment" ],
  10923. THREE.ShaderChunk[ "specularmap_fragment" ],
  10924. THREE.ShaderChunk[ "lightmap_fragment" ],
  10925. THREE.ShaderChunk[ "color_fragment" ],
  10926. THREE.ShaderChunk[ "envmap_fragment" ],
  10927. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10928. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10929. THREE.ShaderChunk[ "fog_fragment" ],
  10930. "}"
  10931. ].join("\n")
  10932. },
  10933. 'lambert': {
  10934. uniforms: THREE.UniformsUtils.merge( [
  10935. THREE.UniformsLib[ "common" ],
  10936. THREE.UniformsLib[ "fog" ],
  10937. THREE.UniformsLib[ "lights" ],
  10938. THREE.UniformsLib[ "shadowmap" ],
  10939. {
  10940. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10941. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10942. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10943. }
  10944. ] ),
  10945. vertexShader: [
  10946. "#define LAMBERT",
  10947. "varying vec3 vLightFront;",
  10948. "#ifdef DOUBLE_SIDED",
  10949. "varying vec3 vLightBack;",
  10950. "#endif",
  10951. THREE.ShaderChunk[ "map_pars_vertex" ],
  10952. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10953. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10954. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  10955. THREE.ShaderChunk[ "color_pars_vertex" ],
  10956. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10957. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10958. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10959. "void main() {",
  10960. THREE.ShaderChunk[ "map_vertex" ],
  10961. THREE.ShaderChunk[ "lightmap_vertex" ],
  10962. THREE.ShaderChunk[ "color_vertex" ],
  10963. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10964. THREE.ShaderChunk[ "skinbase_vertex" ],
  10965. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10966. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10967. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10968. THREE.ShaderChunk[ "skinning_vertex" ],
  10969. THREE.ShaderChunk[ "default_vertex" ],
  10970. THREE.ShaderChunk[ "worldpos_vertex" ],
  10971. THREE.ShaderChunk[ "envmap_vertex" ],
  10972. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  10973. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10974. "}"
  10975. ].join("\n"),
  10976. fragmentShader: [
  10977. "uniform float opacity;",
  10978. "varying vec3 vLightFront;",
  10979. "#ifdef DOUBLE_SIDED",
  10980. "varying vec3 vLightBack;",
  10981. "#endif",
  10982. THREE.ShaderChunk[ "color_pars_fragment" ],
  10983. THREE.ShaderChunk[ "map_pars_fragment" ],
  10984. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10985. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10986. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10987. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10988. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10989. "void main() {",
  10990. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10991. THREE.ShaderChunk[ "map_fragment" ],
  10992. THREE.ShaderChunk[ "alphatest_fragment" ],
  10993. THREE.ShaderChunk[ "specularmap_fragment" ],
  10994. "#ifdef DOUBLE_SIDED",
  10995. //"float isFront = float( gl_FrontFacing );",
  10996. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  10997. "if ( gl_FrontFacing )",
  10998. "gl_FragColor.xyz *= vLightFront;",
  10999. "else",
  11000. "gl_FragColor.xyz *= vLightBack;",
  11001. "#else",
  11002. "gl_FragColor.xyz *= vLightFront;",
  11003. "#endif",
  11004. THREE.ShaderChunk[ "lightmap_fragment" ],
  11005. THREE.ShaderChunk[ "color_fragment" ],
  11006. THREE.ShaderChunk[ "envmap_fragment" ],
  11007. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11008. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11009. THREE.ShaderChunk[ "fog_fragment" ],
  11010. "}"
  11011. ].join("\n")
  11012. },
  11013. 'phong': {
  11014. uniforms: THREE.UniformsUtils.merge( [
  11015. THREE.UniformsLib[ "common" ],
  11016. THREE.UniformsLib[ "bump" ],
  11017. THREE.UniformsLib[ "normalmap" ],
  11018. THREE.UniformsLib[ "fog" ],
  11019. THREE.UniformsLib[ "lights" ],
  11020. THREE.UniformsLib[ "shadowmap" ],
  11021. {
  11022. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  11023. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  11024. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  11025. "shininess": { type: "f", value: 30 },
  11026. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11027. }
  11028. ] ),
  11029. vertexShader: [
  11030. "#define PHONG",
  11031. "varying vec3 vViewPosition;",
  11032. "varying vec3 vNormal;",
  11033. THREE.ShaderChunk[ "map_pars_vertex" ],
  11034. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11035. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11036. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  11037. THREE.ShaderChunk[ "color_pars_vertex" ],
  11038. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11039. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11040. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11041. "void main() {",
  11042. THREE.ShaderChunk[ "map_vertex" ],
  11043. THREE.ShaderChunk[ "lightmap_vertex" ],
  11044. THREE.ShaderChunk[ "color_vertex" ],
  11045. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11046. THREE.ShaderChunk[ "skinbase_vertex" ],
  11047. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11048. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11049. "vNormal = normalize( transformedNormal );",
  11050. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11051. THREE.ShaderChunk[ "skinning_vertex" ],
  11052. THREE.ShaderChunk[ "default_vertex" ],
  11053. "vViewPosition = -mvPosition.xyz;",
  11054. THREE.ShaderChunk[ "worldpos_vertex" ],
  11055. THREE.ShaderChunk[ "envmap_vertex" ],
  11056. THREE.ShaderChunk[ "lights_phong_vertex" ],
  11057. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11058. "}"
  11059. ].join("\n"),
  11060. fragmentShader: [
  11061. "uniform vec3 diffuse;",
  11062. "uniform float opacity;",
  11063. "uniform vec3 ambient;",
  11064. "uniform vec3 emissive;",
  11065. "uniform vec3 specular;",
  11066. "uniform float shininess;",
  11067. THREE.ShaderChunk[ "color_pars_fragment" ],
  11068. THREE.ShaderChunk[ "map_pars_fragment" ],
  11069. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11070. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11071. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11072. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  11073. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11074. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  11075. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  11076. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11077. "void main() {",
  11078. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  11079. THREE.ShaderChunk[ "map_fragment" ],
  11080. THREE.ShaderChunk[ "alphatest_fragment" ],
  11081. THREE.ShaderChunk[ "specularmap_fragment" ],
  11082. THREE.ShaderChunk[ "lights_phong_fragment" ],
  11083. THREE.ShaderChunk[ "lightmap_fragment" ],
  11084. THREE.ShaderChunk[ "color_fragment" ],
  11085. THREE.ShaderChunk[ "envmap_fragment" ],
  11086. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11087. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11088. THREE.ShaderChunk[ "fog_fragment" ],
  11089. "}"
  11090. ].join("\n")
  11091. },
  11092. 'particle_basic': {
  11093. uniforms: THREE.UniformsUtils.merge( [
  11094. THREE.UniformsLib[ "particle" ],
  11095. THREE.UniformsLib[ "shadowmap" ]
  11096. ] ),
  11097. vertexShader: [
  11098. "uniform float size;",
  11099. "uniform float scale;",
  11100. THREE.ShaderChunk[ "color_pars_vertex" ],
  11101. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11102. "void main() {",
  11103. THREE.ShaderChunk[ "color_vertex" ],
  11104. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11105. "#ifdef USE_SIZEATTENUATION",
  11106. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  11107. "#else",
  11108. "gl_PointSize = size;",
  11109. "#endif",
  11110. "gl_Position = projectionMatrix * mvPosition;",
  11111. THREE.ShaderChunk[ "worldpos_vertex" ],
  11112. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11113. "}"
  11114. ].join("\n"),
  11115. fragmentShader: [
  11116. "uniform vec3 psColor;",
  11117. "uniform float opacity;",
  11118. THREE.ShaderChunk[ "color_pars_fragment" ],
  11119. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  11120. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11121. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11122. "void main() {",
  11123. "gl_FragColor = vec4( psColor, opacity );",
  11124. THREE.ShaderChunk[ "map_particle_fragment" ],
  11125. THREE.ShaderChunk[ "alphatest_fragment" ],
  11126. THREE.ShaderChunk[ "color_fragment" ],
  11127. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11128. THREE.ShaderChunk[ "fog_fragment" ],
  11129. "}"
  11130. ].join("\n")
  11131. },
  11132. 'dashed': {
  11133. uniforms: THREE.UniformsUtils.merge( [
  11134. THREE.UniformsLib[ "common" ],
  11135. THREE.UniformsLib[ "fog" ],
  11136. {
  11137. "scale": { type: "f", value: 1 },
  11138. "dashSize": { type: "f", value: 1 },
  11139. "totalSize": { type: "f", value: 2 }
  11140. }
  11141. ] ),
  11142. vertexShader: [
  11143. "uniform float scale;",
  11144. "attribute float lineDistance;",
  11145. "varying float vLineDistance;",
  11146. THREE.ShaderChunk[ "color_pars_vertex" ],
  11147. "void main() {",
  11148. THREE.ShaderChunk[ "color_vertex" ],
  11149. "vLineDistance = scale * lineDistance;",
  11150. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11151. "gl_Position = projectionMatrix * mvPosition;",
  11152. "}"
  11153. ].join("\n"),
  11154. fragmentShader: [
  11155. "uniform vec3 diffuse;",
  11156. "uniform float opacity;",
  11157. "uniform float dashSize;",
  11158. "uniform float totalSize;",
  11159. "varying float vLineDistance;",
  11160. THREE.ShaderChunk[ "color_pars_fragment" ],
  11161. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11162. "void main() {",
  11163. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  11164. "discard;",
  11165. "}",
  11166. "gl_FragColor = vec4( diffuse, opacity );",
  11167. THREE.ShaderChunk[ "color_fragment" ],
  11168. THREE.ShaderChunk[ "fog_fragment" ],
  11169. "}"
  11170. ].join("\n")
  11171. },
  11172. 'depth': {
  11173. uniforms: {
  11174. "mNear": { type: "f", value: 1.0 },
  11175. "mFar" : { type: "f", value: 2000.0 },
  11176. "opacity" : { type: "f", value: 1.0 }
  11177. },
  11178. vertexShader: [
  11179. "void main() {",
  11180. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11181. "}"
  11182. ].join("\n"),
  11183. fragmentShader: [
  11184. "uniform float mNear;",
  11185. "uniform float mFar;",
  11186. "uniform float opacity;",
  11187. "void main() {",
  11188. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  11189. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  11190. "gl_FragColor = vec4( vec3( color ), opacity );",
  11191. "}"
  11192. ].join("\n")
  11193. },
  11194. 'normal': {
  11195. uniforms: {
  11196. "opacity" : { type: "f", value: 1.0 }
  11197. },
  11198. vertexShader: [
  11199. "varying vec3 vNormal;",
  11200. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11201. "void main() {",
  11202. "vNormal = normalize( normalMatrix * normal );",
  11203. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11204. THREE.ShaderChunk[ "default_vertex" ],
  11205. "}"
  11206. ].join("\n"),
  11207. fragmentShader: [
  11208. "uniform float opacity;",
  11209. "varying vec3 vNormal;",
  11210. "void main() {",
  11211. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  11212. "}"
  11213. ].join("\n")
  11214. },
  11215. /* -------------------------------------------------------------------------
  11216. // Normal map shader
  11217. // - Blinn-Phong
  11218. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  11219. // - point and directional lights (use with "lights: true" material option)
  11220. ------------------------------------------------------------------------- */
  11221. 'normalmap' : {
  11222. uniforms: THREE.UniformsUtils.merge( [
  11223. THREE.UniformsLib[ "fog" ],
  11224. THREE.UniformsLib[ "lights" ],
  11225. THREE.UniformsLib[ "shadowmap" ],
  11226. {
  11227. "enableAO" : { type: "i", value: 0 },
  11228. "enableDiffuse" : { type: "i", value: 0 },
  11229. "enableSpecular" : { type: "i", value: 0 },
  11230. "enableReflection": { type: "i", value: 0 },
  11231. "enableDisplacement": { type: "i", value: 0 },
  11232. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  11233. "tDiffuse" : { type: "t", value: null },
  11234. "tCube" : { type: "t", value: null },
  11235. "tNormal" : { type: "t", value: null },
  11236. "tSpecular" : { type: "t", value: null },
  11237. "tAO" : { type: "t", value: null },
  11238. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11239. "uDisplacementBias": { type: "f", value: 0.0 },
  11240. "uDisplacementScale": { type: "f", value: 1.0 },
  11241. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  11242. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  11243. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  11244. "uShininess": { type: "f", value: 30 },
  11245. "uOpacity": { type: "f", value: 1 },
  11246. "useRefract": { type: "i", value: 0 },
  11247. "uRefractionRatio": { type: "f", value: 0.98 },
  11248. "uReflectivity": { type: "f", value: 0.5 },
  11249. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  11250. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11251. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11252. }
  11253. ] ),
  11254. fragmentShader: [
  11255. "uniform vec3 uAmbientColor;",
  11256. "uniform vec3 uDiffuseColor;",
  11257. "uniform vec3 uSpecularColor;",
  11258. "uniform float uShininess;",
  11259. "uniform float uOpacity;",
  11260. "uniform bool enableDiffuse;",
  11261. "uniform bool enableSpecular;",
  11262. "uniform bool enableAO;",
  11263. "uniform bool enableReflection;",
  11264. "uniform sampler2D tDiffuse;",
  11265. "uniform sampler2D tNormal;",
  11266. "uniform sampler2D tSpecular;",
  11267. "uniform sampler2D tAO;",
  11268. "uniform samplerCube tCube;",
  11269. "uniform vec2 uNormalScale;",
  11270. "uniform bool useRefract;",
  11271. "uniform float uRefractionRatio;",
  11272. "uniform float uReflectivity;",
  11273. "varying vec3 vTangent;",
  11274. "varying vec3 vBinormal;",
  11275. "varying vec3 vNormal;",
  11276. "varying vec2 vUv;",
  11277. "uniform vec3 ambientLightColor;",
  11278. "#if MAX_DIR_LIGHTS > 0",
  11279. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11280. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11281. "#endif",
  11282. "#if MAX_HEMI_LIGHTS > 0",
  11283. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  11284. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  11285. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  11286. "#endif",
  11287. "#if MAX_POINT_LIGHTS > 0",
  11288. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11289. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11290. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11291. "#endif",
  11292. "#if MAX_SPOT_LIGHTS > 0",
  11293. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  11294. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  11295. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  11296. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  11297. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  11298. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  11299. "#endif",
  11300. "#ifdef WRAP_AROUND",
  11301. "uniform vec3 wrapRGB;",
  11302. "#endif",
  11303. "varying vec3 vWorldPosition;",
  11304. "varying vec3 vViewPosition;",
  11305. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11306. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11307. "void main() {",
  11308. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  11309. "vec3 specularTex = vec3( 1.0 );",
  11310. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  11311. "normalTex.xy *= uNormalScale;",
  11312. "normalTex = normalize( normalTex );",
  11313. "if( enableDiffuse ) {",
  11314. "#ifdef GAMMA_INPUT",
  11315. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  11316. "texelColor.xyz *= texelColor.xyz;",
  11317. "gl_FragColor = gl_FragColor * texelColor;",
  11318. "#else",
  11319. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  11320. "#endif",
  11321. "}",
  11322. "if( enableAO ) {",
  11323. "#ifdef GAMMA_INPUT",
  11324. "vec4 aoColor = texture2D( tAO, vUv );",
  11325. "aoColor.xyz *= aoColor.xyz;",
  11326. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  11327. "#else",
  11328. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  11329. "#endif",
  11330. "}",
  11331. "if( enableSpecular )",
  11332. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  11333. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  11334. "vec3 finalNormal = tsb * normalTex;",
  11335. "#ifdef FLIP_SIDED",
  11336. "finalNormal = -finalNormal;",
  11337. "#endif",
  11338. "vec3 normal = normalize( finalNormal );",
  11339. "vec3 viewPosition = normalize( vViewPosition );",
  11340. // point lights
  11341. "#if MAX_POINT_LIGHTS > 0",
  11342. "vec3 pointDiffuse = vec3( 0.0 );",
  11343. "vec3 pointSpecular = vec3( 0.0 );",
  11344. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11345. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11346. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  11347. "float pointDistance = 1.0;",
  11348. "if ( pointLightDistance[ i ] > 0.0 )",
  11349. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  11350. "pointVector = normalize( pointVector );",
  11351. // diffuse
  11352. "#ifdef WRAP_AROUND",
  11353. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  11354. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  11355. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11356. "#else",
  11357. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  11358. "#endif",
  11359. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  11360. // specular
  11361. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  11362. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11363. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  11364. "#ifdef PHYSICALLY_BASED_SHADING",
  11365. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11366. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11367. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  11368. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  11369. "#else",
  11370. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  11371. "#endif",
  11372. "}",
  11373. "#endif",
  11374. // spot lights
  11375. "#if MAX_SPOT_LIGHTS > 0",
  11376. "vec3 spotDiffuse = vec3( 0.0 );",
  11377. "vec3 spotSpecular = vec3( 0.0 );",
  11378. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  11379. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  11380. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  11381. "float spotDistance = 1.0;",
  11382. "if ( spotLightDistance[ i ] > 0.0 )",
  11383. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  11384. "spotVector = normalize( spotVector );",
  11385. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  11386. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  11387. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  11388. // diffuse
  11389. "#ifdef WRAP_AROUND",
  11390. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  11391. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  11392. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  11393. "#else",
  11394. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  11395. "#endif",
  11396. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  11397. // specular
  11398. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  11399. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  11400. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  11401. "#ifdef PHYSICALLY_BASED_SHADING",
  11402. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11403. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11404. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  11405. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  11406. "#else",
  11407. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  11408. "#endif",
  11409. "}",
  11410. "}",
  11411. "#endif",
  11412. // directional lights
  11413. "#if MAX_DIR_LIGHTS > 0",
  11414. "vec3 dirDiffuse = vec3( 0.0 );",
  11415. "vec3 dirSpecular = vec3( 0.0 );",
  11416. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  11417. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11418. "vec3 dirVector = normalize( lDirection.xyz );",
  11419. // diffuse
  11420. "#ifdef WRAP_AROUND",
  11421. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  11422. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  11423. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  11424. "#else",
  11425. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  11426. "#endif",
  11427. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  11428. // specular
  11429. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11430. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11431. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  11432. "#ifdef PHYSICALLY_BASED_SHADING",
  11433. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11434. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11435. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  11436. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11437. "#else",
  11438. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  11439. "#endif",
  11440. "}",
  11441. "#endif",
  11442. // hemisphere lights
  11443. "#if MAX_HEMI_LIGHTS > 0",
  11444. "vec3 hemiDiffuse = vec3( 0.0 );",
  11445. "vec3 hemiSpecular = vec3( 0.0 );" ,
  11446. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  11447. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  11448. "vec3 lVector = normalize( lDirection.xyz );",
  11449. // diffuse
  11450. "float dotProduct = dot( normal, lVector );",
  11451. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  11452. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  11453. "hemiDiffuse += uDiffuseColor * hemiColor;",
  11454. // specular (sky light)
  11455. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  11456. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  11457. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  11458. // specular (ground light)
  11459. "vec3 lVectorGround = -lVector;",
  11460. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  11461. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  11462. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  11463. "#ifdef PHYSICALLY_BASED_SHADING",
  11464. "float dotProductGround = dot( normal, lVectorGround );",
  11465. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11466. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11467. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  11468. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  11469. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  11470. "#else",
  11471. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  11472. "#endif",
  11473. "}",
  11474. "#endif",
  11475. // all lights contribution summation
  11476. "vec3 totalDiffuse = vec3( 0.0 );",
  11477. "vec3 totalSpecular = vec3( 0.0 );",
  11478. "#if MAX_DIR_LIGHTS > 0",
  11479. "totalDiffuse += dirDiffuse;",
  11480. "totalSpecular += dirSpecular;",
  11481. "#endif",
  11482. "#if MAX_HEMI_LIGHTS > 0",
  11483. "totalDiffuse += hemiDiffuse;",
  11484. "totalSpecular += hemiSpecular;",
  11485. "#endif",
  11486. "#if MAX_POINT_LIGHTS > 0",
  11487. "totalDiffuse += pointDiffuse;",
  11488. "totalSpecular += pointSpecular;",
  11489. "#endif",
  11490. "#if MAX_SPOT_LIGHTS > 0",
  11491. "totalDiffuse += spotDiffuse;",
  11492. "totalSpecular += spotSpecular;",
  11493. "#endif",
  11494. "#ifdef METAL",
  11495. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  11496. "#else",
  11497. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  11498. "#endif",
  11499. "if ( enableReflection ) {",
  11500. "vec3 vReflect;",
  11501. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  11502. "if ( useRefract ) {",
  11503. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  11504. "} else {",
  11505. "vReflect = reflect( cameraToVertex, normal );",
  11506. "}",
  11507. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  11508. "#ifdef GAMMA_INPUT",
  11509. "cubeColor.xyz *= cubeColor.xyz;",
  11510. "#endif",
  11511. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  11512. "}",
  11513. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11514. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11515. THREE.ShaderChunk[ "fog_fragment" ],
  11516. "}"
  11517. ].join("\n"),
  11518. vertexShader: [
  11519. "attribute vec4 tangent;",
  11520. "uniform vec2 uOffset;",
  11521. "uniform vec2 uRepeat;",
  11522. "uniform bool enableDisplacement;",
  11523. "#ifdef VERTEX_TEXTURES",
  11524. "uniform sampler2D tDisplacement;",
  11525. "uniform float uDisplacementScale;",
  11526. "uniform float uDisplacementBias;",
  11527. "#endif",
  11528. "varying vec3 vTangent;",
  11529. "varying vec3 vBinormal;",
  11530. "varying vec3 vNormal;",
  11531. "varying vec2 vUv;",
  11532. "varying vec3 vWorldPosition;",
  11533. "varying vec3 vViewPosition;",
  11534. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11535. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11536. "void main() {",
  11537. THREE.ShaderChunk[ "skinbase_vertex" ],
  11538. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11539. // normal, tangent and binormal vectors
  11540. "#ifdef USE_SKINNING",
  11541. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  11542. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  11543. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  11544. "#else",
  11545. "vNormal = normalize( normalMatrix * normal );",
  11546. "vTangent = normalize( normalMatrix * tangent.xyz );",
  11547. "#endif",
  11548. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  11549. "vUv = uv * uRepeat + uOffset;",
  11550. // displacement mapping
  11551. "vec3 displacedPosition;",
  11552. "#ifdef VERTEX_TEXTURES",
  11553. "if ( enableDisplacement ) {",
  11554. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  11555. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  11556. "displacedPosition = position + normalize( normal ) * df;",
  11557. "} else {",
  11558. "#ifdef USE_SKINNING",
  11559. "vec4 skinVertex = vec4( position, 1.0 );",
  11560. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11561. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11562. "displacedPosition = skinned.xyz;",
  11563. "#else",
  11564. "displacedPosition = position;",
  11565. "#endif",
  11566. "}",
  11567. "#else",
  11568. "#ifdef USE_SKINNING",
  11569. "vec4 skinVertex = vec4( position, 1.0 );",
  11570. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11571. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11572. "displacedPosition = skinned.xyz;",
  11573. "#else",
  11574. "displacedPosition = position;",
  11575. "#endif",
  11576. "#endif",
  11577. //
  11578. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  11579. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  11580. "gl_Position = projectionMatrix * mvPosition;",
  11581. //
  11582. "vWorldPosition = worldPosition.xyz;",
  11583. "vViewPosition = -mvPosition.xyz;",
  11584. // shadows
  11585. "#ifdef USE_SHADOWMAP",
  11586. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11587. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11588. "}",
  11589. "#endif",
  11590. "}"
  11591. ].join("\n")
  11592. },
  11593. /* -------------------------------------------------------------------------
  11594. // Cube map shader
  11595. ------------------------------------------------------------------------- */
  11596. 'cube': {
  11597. uniforms: { "tCube": { type: "t", value: null },
  11598. "tFlip": { type: "f", value: -1 } },
  11599. vertexShader: [
  11600. "varying vec3 vWorldPosition;",
  11601. "void main() {",
  11602. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  11603. "vWorldPosition = worldPosition.xyz;",
  11604. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11605. "}"
  11606. ].join("\n"),
  11607. fragmentShader: [
  11608. "uniform samplerCube tCube;",
  11609. "uniform float tFlip;",
  11610. "varying vec3 vWorldPosition;",
  11611. "void main() {",
  11612. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  11613. "}"
  11614. ].join("\n")
  11615. },
  11616. // Depth encoding into RGBA texture
  11617. // based on SpiderGL shadow map example
  11618. // http://spidergl.org/example.php?id=6
  11619. // originally from
  11620. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  11621. // see also here:
  11622. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  11623. 'depthRGBA': {
  11624. uniforms: {},
  11625. vertexShader: [
  11626. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11627. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11628. "void main() {",
  11629. THREE.ShaderChunk[ "skinbase_vertex" ],
  11630. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11631. THREE.ShaderChunk[ "skinning_vertex" ],
  11632. THREE.ShaderChunk[ "default_vertex" ],
  11633. "}"
  11634. ].join("\n"),
  11635. fragmentShader: [
  11636. "vec4 pack_depth( const in float depth ) {",
  11637. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  11638. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  11639. "vec4 res = fract( depth * bit_shift );",
  11640. "res -= res.xxyz * bit_mask;",
  11641. "return res;",
  11642. "}",
  11643. "void main() {",
  11644. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  11645. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  11646. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  11647. //"gl_FragData[ 0 ] = pack_depth( z );",
  11648. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  11649. "}"
  11650. ].join("\n")
  11651. }
  11652. };
  11653. /**
  11654. * @author supereggbert / http://www.paulbrunt.co.uk/
  11655. * @author mrdoob / http://mrdoob.com/
  11656. * @author alteredq / http://alteredqualia.com/
  11657. * @author szimek / https://github.com/szimek/
  11658. */
  11659. THREE.WebGLRenderer = function ( parameters ) {
  11660. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  11661. parameters = parameters || {};
  11662. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  11663. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  11664. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  11665. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11666. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11667. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11668. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  11669. _clearColor = new THREE.Color( 0x000000 ),
  11670. _clearAlpha = 0;
  11671. if ( parameters.clearColor !== undefined ) {
  11672. console.warn( 'DEPRECATED: clearColor in WebGLRenderer constructor parameters is being removed. Use .setClearColor() instead.' );
  11673. _clearColor.setHex( parameters.clearColor );
  11674. }
  11675. if ( parameters.clearAlpha !== undefined ) {
  11676. console.warn( 'DEPRECATED: clearAlpha in WebGLRenderer constructor parameters is being removed. Use .setClearColor() instead.' );
  11677. _clearAlpha = parameters.clearAlpha;
  11678. }
  11679. // public properties
  11680. this.domElement = _canvas;
  11681. this.context = null;
  11682. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  11683. ? parameters.devicePixelRatio
  11684. : window.devicePixelRatio !== undefined
  11685. ? window.devicePixelRatio
  11686. : 1;
  11687. // clearing
  11688. this.autoClear = true;
  11689. this.autoClearColor = true;
  11690. this.autoClearDepth = true;
  11691. this.autoClearStencil = true;
  11692. // scene graph
  11693. this.sortObjects = true;
  11694. this.autoUpdateObjects = true;
  11695. // physically based shading
  11696. this.gammaInput = false;
  11697. this.gammaOutput = false;
  11698. this.physicallyBasedShading = false;
  11699. // shadow map
  11700. this.shadowMapEnabled = false;
  11701. this.shadowMapAutoUpdate = true;
  11702. this.shadowMapType = THREE.PCFShadowMap;
  11703. this.shadowMapCullFace = THREE.CullFaceFront;
  11704. this.shadowMapDebug = false;
  11705. this.shadowMapCascade = false;
  11706. // morphs
  11707. this.maxMorphTargets = 8;
  11708. this.maxMorphNormals = 4;
  11709. // flags
  11710. this.autoScaleCubemaps = true;
  11711. // custom render plugins
  11712. this.renderPluginsPre = [];
  11713. this.renderPluginsPost = [];
  11714. // info
  11715. this.info = {
  11716. memory: {
  11717. programs: 0,
  11718. geometries: 0,
  11719. textures: 0
  11720. },
  11721. render: {
  11722. calls: 0,
  11723. vertices: 0,
  11724. faces: 0,
  11725. points: 0
  11726. }
  11727. };
  11728. // internal properties
  11729. var _this = this,
  11730. _programs = [],
  11731. _programs_counter = 0,
  11732. // internal state cache
  11733. _currentProgram = null,
  11734. _currentFramebuffer = null,
  11735. _currentMaterialId = -1,
  11736. _currentGeometryGroupHash = null,
  11737. _currentCamera = null,
  11738. _geometryGroupCounter = 0,
  11739. _usedTextureUnits = 0,
  11740. // GL state cache
  11741. _oldDoubleSided = -1,
  11742. _oldFlipSided = -1,
  11743. _oldBlending = -1,
  11744. _oldBlendEquation = -1,
  11745. _oldBlendSrc = -1,
  11746. _oldBlendDst = -1,
  11747. _oldDepthTest = -1,
  11748. _oldDepthWrite = -1,
  11749. _oldPolygonOffset = null,
  11750. _oldPolygonOffsetFactor = null,
  11751. _oldPolygonOffsetUnits = null,
  11752. _oldLineWidth = null,
  11753. _viewportX = 0,
  11754. _viewportY = 0,
  11755. _viewportWidth = 0,
  11756. _viewportHeight = 0,
  11757. _currentWidth = 0,
  11758. _currentHeight = 0,
  11759. _enabledAttributes = {},
  11760. // frustum
  11761. _frustum = new THREE.Frustum(),
  11762. // camera matrices cache
  11763. _projScreenMatrix = new THREE.Matrix4(),
  11764. _projScreenMatrixPS = new THREE.Matrix4(),
  11765. _vector3 = new THREE.Vector3(),
  11766. // light arrays cache
  11767. _direction = new THREE.Vector3(),
  11768. _lightsNeedUpdate = true,
  11769. _lights = {
  11770. ambient: [ 0, 0, 0 ],
  11771. directional: { length: 0, colors: new Array(), positions: new Array() },
  11772. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  11773. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  11774. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  11775. };
  11776. // initialize
  11777. var _gl;
  11778. var _glExtensionTextureFloat;
  11779. var _glExtensionTextureFloatLinear;
  11780. var _glExtensionStandardDerivatives;
  11781. var _glExtensionTextureFilterAnisotropic;
  11782. var _glExtensionCompressedTextureS3TC;
  11783. initGL();
  11784. setDefaultGLState();
  11785. this.context = _gl;
  11786. // GPU capabilities
  11787. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  11788. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11789. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  11790. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11791. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  11792. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  11793. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  11794. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  11795. //
  11796. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  11797. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  11798. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  11799. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  11800. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  11801. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  11802. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  11803. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  11804. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  11805. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  11806. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  11807. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  11808. // clamp precision to maximum available
  11809. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  11810. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  11811. if ( _precision === "highp" && ! highpAvailable ) {
  11812. if ( mediumpAvailable ) {
  11813. _precision = "mediump";
  11814. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  11815. } else {
  11816. _precision = "lowp";
  11817. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  11818. }
  11819. }
  11820. if ( _precision === "mediump" && ! mediumpAvailable ) {
  11821. _precision = "lowp";
  11822. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  11823. }
  11824. // API
  11825. this.getContext = function () {
  11826. return _gl;
  11827. };
  11828. this.supportsVertexTextures = function () {
  11829. return _supportsVertexTextures;
  11830. };
  11831. this.supportsFloatTextures = function () {
  11832. return _glExtensionTextureFloat;
  11833. };
  11834. this.supportsStandardDerivatives = function () {
  11835. return _glExtensionStandardDerivatives;
  11836. };
  11837. this.supportsCompressedTextureS3TC = function () {
  11838. return _glExtensionCompressedTextureS3TC;
  11839. };
  11840. this.getMaxAnisotropy = function () {
  11841. return _maxAnisotropy;
  11842. };
  11843. this.getPrecision = function () {
  11844. return _precision;
  11845. };
  11846. this.setSize = function ( width, height, updateStyle ) {
  11847. _canvas.width = width * this.devicePixelRatio;
  11848. _canvas.height = height * this.devicePixelRatio;
  11849. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  11850. _canvas.style.width = width + 'px';
  11851. _canvas.style.height = height + 'px';
  11852. }
  11853. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  11854. };
  11855. this.setViewport = function ( x, y, width, height ) {
  11856. _viewportX = x !== undefined ? x : 0;
  11857. _viewportY = y !== undefined ? y : 0;
  11858. _viewportWidth = width !== undefined ? width : _canvas.width;
  11859. _viewportHeight = height !== undefined ? height : _canvas.height;
  11860. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  11861. };
  11862. this.setScissor = function ( x, y, width, height ) {
  11863. _gl.scissor( x, y, width, height );
  11864. };
  11865. this.enableScissorTest = function ( enable ) {
  11866. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  11867. };
  11868. // Clearing
  11869. this.setClearColor = function ( color, alpha ) {
  11870. _clearColor.set( color );
  11871. _clearAlpha = alpha !== undefined ? alpha : 1;
  11872. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11873. };
  11874. this.setClearColorHex = function ( hex, alpha ) {
  11875. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  11876. this.setClearColor( hex, alpha );
  11877. };
  11878. this.getClearColor = function () {
  11879. return _clearColor;
  11880. };
  11881. this.getClearAlpha = function () {
  11882. return _clearAlpha;
  11883. };
  11884. this.clear = function ( color, depth, stencil ) {
  11885. var bits = 0;
  11886. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11887. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11888. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11889. _gl.clear( bits );
  11890. };
  11891. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11892. this.setRenderTarget( renderTarget );
  11893. this.clear( color, depth, stencil );
  11894. };
  11895. // Plugins
  11896. this.addPostPlugin = function ( plugin ) {
  11897. plugin.init( this );
  11898. this.renderPluginsPost.push( plugin );
  11899. };
  11900. this.addPrePlugin = function ( plugin ) {
  11901. plugin.init( this );
  11902. this.renderPluginsPre.push( plugin );
  11903. };
  11904. // Rendering
  11905. this.updateShadowMap = function ( scene, camera ) {
  11906. _currentProgram = null;
  11907. _oldBlending = -1;
  11908. _oldDepthTest = -1;
  11909. _oldDepthWrite = -1;
  11910. _currentGeometryGroupHash = -1;
  11911. _currentMaterialId = -1;
  11912. _lightsNeedUpdate = true;
  11913. _oldDoubleSided = -1;
  11914. _oldFlipSided = -1;
  11915. this.shadowMapPlugin.update( scene, camera );
  11916. };
  11917. // Internal functions
  11918. // Buffer allocation
  11919. function createParticleBuffers ( geometry ) {
  11920. geometry.__webglVertexBuffer = _gl.createBuffer();
  11921. geometry.__webglColorBuffer = _gl.createBuffer();
  11922. _this.info.memory.geometries ++;
  11923. };
  11924. function createLineBuffers ( geometry ) {
  11925. geometry.__webglVertexBuffer = _gl.createBuffer();
  11926. geometry.__webglColorBuffer = _gl.createBuffer();
  11927. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  11928. _this.info.memory.geometries ++;
  11929. };
  11930. function createRibbonBuffers ( geometry ) {
  11931. geometry.__webglVertexBuffer = _gl.createBuffer();
  11932. geometry.__webglColorBuffer = _gl.createBuffer();
  11933. geometry.__webglNormalBuffer = _gl.createBuffer();
  11934. _this.info.memory.geometries ++;
  11935. };
  11936. function createMeshBuffers ( geometryGroup ) {
  11937. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  11938. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  11939. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  11940. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  11941. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  11942. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  11943. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  11944. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  11945. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  11946. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  11947. var m, ml;
  11948. if ( geometryGroup.numMorphTargets ) {
  11949. geometryGroup.__webglMorphTargetsBuffers = [];
  11950. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11951. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  11952. }
  11953. }
  11954. if ( geometryGroup.numMorphNormals ) {
  11955. geometryGroup.__webglMorphNormalsBuffers = [];
  11956. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11957. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  11958. }
  11959. }
  11960. _this.info.memory.geometries ++;
  11961. };
  11962. // Events
  11963. var onGeometryDispose = function ( event ) {
  11964. var geometry = event.target;
  11965. geometry.removeEventListener( 'dispose', onGeometryDispose );
  11966. deallocateGeometry( geometry );
  11967. _this.info.memory.geometries --;
  11968. };
  11969. var onTextureDispose = function ( event ) {
  11970. var texture = event.target;
  11971. texture.removeEventListener( 'dispose', onTextureDispose );
  11972. deallocateTexture( texture );
  11973. _this.info.memory.textures --;
  11974. };
  11975. var onRenderTargetDispose = function ( event ) {
  11976. var renderTarget = event.target;
  11977. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  11978. deallocateRenderTarget( renderTarget );
  11979. _this.info.memory.textures --;
  11980. };
  11981. var onMaterialDispose = function ( event ) {
  11982. var material = event.target;
  11983. material.removeEventListener( 'dispose', onMaterialDispose );
  11984. deallocateMaterial( material );
  11985. };
  11986. // Buffer deallocation
  11987. var deallocateGeometry = function ( geometry ) {
  11988. geometry.__webglInit = undefined;
  11989. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11990. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  11991. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  11992. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  11993. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  11994. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  11995. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  11996. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  11997. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  11998. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  11999. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  12000. // geometry groups
  12001. if ( geometry.geometryGroups !== undefined ) {
  12002. for ( var g in geometry.geometryGroups ) {
  12003. var geometryGroup = geometry.geometryGroups[ g ];
  12004. if ( geometryGroup.numMorphTargets !== undefined ) {
  12005. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12006. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  12007. }
  12008. }
  12009. if ( geometryGroup.numMorphNormals !== undefined ) {
  12010. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12011. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  12012. }
  12013. }
  12014. deleteCustomAttributesBuffers( geometryGroup );
  12015. }
  12016. }
  12017. deleteCustomAttributesBuffers( geometry );
  12018. };
  12019. var deallocateTexture = function ( texture ) {
  12020. if ( texture.image && texture.image.__webglTextureCube ) {
  12021. // cube texture
  12022. _gl.deleteTexture( texture.image.__webglTextureCube );
  12023. } else {
  12024. // 2D texture
  12025. if ( ! texture.__webglInit ) return;
  12026. texture.__webglInit = false;
  12027. _gl.deleteTexture( texture.__webglTexture );
  12028. }
  12029. };
  12030. var deallocateRenderTarget = function ( renderTarget ) {
  12031. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  12032. _gl.deleteTexture( renderTarget.__webglTexture );
  12033. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  12034. for ( var i = 0; i < 6; i ++ ) {
  12035. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  12036. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  12037. }
  12038. } else {
  12039. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  12040. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  12041. }
  12042. };
  12043. var deallocateMaterial = function ( material ) {
  12044. var program = material.program;
  12045. if ( program === undefined ) return;
  12046. material.program = undefined;
  12047. // only deallocate GL program if this was the last use of shared program
  12048. // assumed there is only single copy of any program in the _programs list
  12049. // (that's how it's constructed)
  12050. var i, il, programInfo;
  12051. var deleteProgram = false;
  12052. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12053. programInfo = _programs[ i ];
  12054. if ( programInfo.program === program ) {
  12055. programInfo.usedTimes --;
  12056. if ( programInfo.usedTimes === 0 ) {
  12057. deleteProgram = true;
  12058. }
  12059. break;
  12060. }
  12061. }
  12062. if ( deleteProgram === true ) {
  12063. // avoid using array.splice, this is costlier than creating new array from scratch
  12064. var newPrograms = [];
  12065. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12066. programInfo = _programs[ i ];
  12067. if ( programInfo.program !== program ) {
  12068. newPrograms.push( programInfo );
  12069. }
  12070. }
  12071. _programs = newPrograms;
  12072. _gl.deleteProgram( program );
  12073. _this.info.memory.programs --;
  12074. }
  12075. };
  12076. //
  12077. function deleteCustomAttributesBuffers( geometry ) {
  12078. if ( geometry.__webglCustomAttributesList ) {
  12079. for ( var id in geometry.__webglCustomAttributesList ) {
  12080. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  12081. }
  12082. }
  12083. };
  12084. // Buffer initialization
  12085. function initCustomAttributes ( geometry, object ) {
  12086. var nvertices = geometry.vertices.length;
  12087. var material = object.material;
  12088. if ( material.attributes ) {
  12089. if ( geometry.__webglCustomAttributesList === undefined ) {
  12090. geometry.__webglCustomAttributesList = [];
  12091. }
  12092. for ( var a in material.attributes ) {
  12093. var attribute = material.attributes[ a ];
  12094. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12095. attribute.__webglInitialized = true;
  12096. var size = 1; // "f" and "i"
  12097. if ( attribute.type === "v2" ) size = 2;
  12098. else if ( attribute.type === "v3" ) size = 3;
  12099. else if ( attribute.type === "v4" ) size = 4;
  12100. else if ( attribute.type === "c" ) size = 3;
  12101. attribute.size = size;
  12102. attribute.array = new Float32Array( nvertices * size );
  12103. attribute.buffer = _gl.createBuffer();
  12104. attribute.buffer.belongsToAttribute = a;
  12105. attribute.needsUpdate = true;
  12106. }
  12107. geometry.__webglCustomAttributesList.push( attribute );
  12108. }
  12109. }
  12110. };
  12111. function initParticleBuffers ( geometry, object ) {
  12112. var nvertices = geometry.vertices.length;
  12113. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12114. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12115. geometry.__sortArray = [];
  12116. geometry.__webglParticleCount = nvertices;
  12117. initCustomAttributes ( geometry, object );
  12118. };
  12119. function initLineBuffers ( geometry, object ) {
  12120. var nvertices = geometry.vertices.length;
  12121. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12122. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12123. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  12124. geometry.__webglLineCount = nvertices;
  12125. initCustomAttributes ( geometry, object );
  12126. };
  12127. function initRibbonBuffers ( geometry, object ) {
  12128. var nvertices = geometry.vertices.length;
  12129. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12130. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12131. geometry.__normalArray = new Float32Array( nvertices * 3 );
  12132. geometry.__webglVertexCount = nvertices;
  12133. initCustomAttributes ( geometry, object );
  12134. };
  12135. function initMeshBuffers ( geometryGroup, object ) {
  12136. var geometry = object.geometry,
  12137. faces3 = geometryGroup.faces3,
  12138. faces4 = geometryGroup.faces4,
  12139. nvertices = faces3.length * 3 + faces4.length * 4,
  12140. ntris = faces3.length * 1 + faces4.length * 2,
  12141. nlines = faces3.length * 3 + faces4.length * 4,
  12142. material = getBufferMaterial( object, geometryGroup ),
  12143. uvType = bufferGuessUVType( material ),
  12144. normalType = bufferGuessNormalType( material ),
  12145. vertexColorType = bufferGuessVertexColorType( material );
  12146. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  12147. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  12148. if ( normalType ) {
  12149. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  12150. }
  12151. if ( geometry.hasTangents ) {
  12152. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  12153. }
  12154. if ( vertexColorType ) {
  12155. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  12156. }
  12157. if ( uvType ) {
  12158. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  12159. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  12160. }
  12161. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  12162. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  12163. }
  12164. }
  12165. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  12166. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  12167. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  12168. }
  12169. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  12170. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  12171. var m, ml;
  12172. if ( geometryGroup.numMorphTargets ) {
  12173. geometryGroup.__morphTargetsArrays = [];
  12174. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12175. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  12176. }
  12177. }
  12178. if ( geometryGroup.numMorphNormals ) {
  12179. geometryGroup.__morphNormalsArrays = [];
  12180. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12181. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  12182. }
  12183. }
  12184. geometryGroup.__webglFaceCount = ntris * 3;
  12185. geometryGroup.__webglLineCount = nlines * 2;
  12186. // custom attributes
  12187. if ( material.attributes ) {
  12188. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  12189. geometryGroup.__webglCustomAttributesList = [];
  12190. }
  12191. for ( var a in material.attributes ) {
  12192. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  12193. // attribute buffers which are correctly indexed in the setMeshBuffers function
  12194. var originalAttribute = material.attributes[ a ];
  12195. var attribute = {};
  12196. for ( var property in originalAttribute ) {
  12197. attribute[ property ] = originalAttribute[ property ];
  12198. }
  12199. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12200. attribute.__webglInitialized = true;
  12201. var size = 1; // "f" and "i"
  12202. if( attribute.type === "v2" ) size = 2;
  12203. else if( attribute.type === "v3" ) size = 3;
  12204. else if( attribute.type === "v4" ) size = 4;
  12205. else if( attribute.type === "c" ) size = 3;
  12206. attribute.size = size;
  12207. attribute.array = new Float32Array( nvertices * size );
  12208. attribute.buffer = _gl.createBuffer();
  12209. attribute.buffer.belongsToAttribute = a;
  12210. originalAttribute.needsUpdate = true;
  12211. attribute.__original = originalAttribute;
  12212. }
  12213. geometryGroup.__webglCustomAttributesList.push( attribute );
  12214. }
  12215. }
  12216. geometryGroup.__inittedArrays = true;
  12217. };
  12218. function getBufferMaterial( object, geometryGroup ) {
  12219. return object.material instanceof THREE.MeshFaceMaterial
  12220. ? object.material.materials[ geometryGroup.materialIndex ]
  12221. : object.material;
  12222. };
  12223. function materialNeedsSmoothNormals ( material ) {
  12224. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  12225. };
  12226. function bufferGuessNormalType ( material ) {
  12227. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  12228. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  12229. return false;
  12230. }
  12231. if ( materialNeedsSmoothNormals( material ) ) {
  12232. return THREE.SmoothShading;
  12233. } else {
  12234. return THREE.FlatShading;
  12235. }
  12236. };
  12237. function bufferGuessVertexColorType( material ) {
  12238. if ( material.vertexColors ) {
  12239. return material.vertexColors;
  12240. }
  12241. return false;
  12242. };
  12243. function bufferGuessUVType( material ) {
  12244. // material must use some texture to require uvs
  12245. if ( material.map ||
  12246. material.lightMap ||
  12247. material.bumpMap ||
  12248. material.normalMap ||
  12249. material.specularMap ||
  12250. material instanceof THREE.ShaderMaterial ) {
  12251. return true;
  12252. }
  12253. return false;
  12254. };
  12255. //
  12256. function initDirectBuffers( geometry ) {
  12257. var a, attribute, type;
  12258. for ( a in geometry.attributes ) {
  12259. if ( a === "index" ) {
  12260. type = _gl.ELEMENT_ARRAY_BUFFER;
  12261. } else {
  12262. type = _gl.ARRAY_BUFFER;
  12263. }
  12264. attribute = geometry.attributes[ a ];
  12265. if ( attribute.numItems === undefined ) {
  12266. attribute.numItems = attribute.array.length;
  12267. }
  12268. attribute.buffer = _gl.createBuffer();
  12269. _gl.bindBuffer( type, attribute.buffer );
  12270. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  12271. }
  12272. };
  12273. // Buffer setting
  12274. function setParticleBuffers ( geometry, hint, object ) {
  12275. var v, c, vertex, offset, index, color,
  12276. vertices = geometry.vertices,
  12277. vl = vertices.length,
  12278. colors = geometry.colors,
  12279. cl = colors.length,
  12280. vertexArray = geometry.__vertexArray,
  12281. colorArray = geometry.__colorArray,
  12282. sortArray = geometry.__sortArray,
  12283. dirtyVertices = geometry.verticesNeedUpdate,
  12284. dirtyElements = geometry.elementsNeedUpdate,
  12285. dirtyColors = geometry.colorsNeedUpdate,
  12286. customAttributes = geometry.__webglCustomAttributesList,
  12287. i, il,
  12288. a, ca, cal, value,
  12289. customAttribute;
  12290. if ( object.sortParticles ) {
  12291. _projScreenMatrixPS.copy( _projScreenMatrix );
  12292. _projScreenMatrixPS.multiply( object.matrixWorld );
  12293. for ( v = 0; v < vl; v ++ ) {
  12294. vertex = vertices[ v ];
  12295. _vector3.copy( vertex );
  12296. _vector3.applyProjection( _projScreenMatrixPS );
  12297. sortArray[ v ] = [ _vector3.z, v ];
  12298. }
  12299. sortArray.sort( numericalSort );
  12300. for ( v = 0; v < vl; v ++ ) {
  12301. vertex = vertices[ sortArray[v][1] ];
  12302. offset = v * 3;
  12303. vertexArray[ offset ] = vertex.x;
  12304. vertexArray[ offset + 1 ] = vertex.y;
  12305. vertexArray[ offset + 2 ] = vertex.z;
  12306. }
  12307. for ( c = 0; c < cl; c ++ ) {
  12308. offset = c * 3;
  12309. color = colors[ sortArray[c][1] ];
  12310. colorArray[ offset ] = color.r;
  12311. colorArray[ offset + 1 ] = color.g;
  12312. colorArray[ offset + 2 ] = color.b;
  12313. }
  12314. if ( customAttributes ) {
  12315. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12316. customAttribute = customAttributes[ i ];
  12317. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  12318. offset = 0;
  12319. cal = customAttribute.value.length;
  12320. if ( customAttribute.size === 1 ) {
  12321. for ( ca = 0; ca < cal; ca ++ ) {
  12322. index = sortArray[ ca ][ 1 ];
  12323. customAttribute.array[ ca ] = customAttribute.value[ index ];
  12324. }
  12325. } else if ( customAttribute.size === 2 ) {
  12326. for ( ca = 0; ca < cal; ca ++ ) {
  12327. index = sortArray[ ca ][ 1 ];
  12328. value = customAttribute.value[ index ];
  12329. customAttribute.array[ offset ] = value.x;
  12330. customAttribute.array[ offset + 1 ] = value.y;
  12331. offset += 2;
  12332. }
  12333. } else if ( customAttribute.size === 3 ) {
  12334. if ( customAttribute.type === "c" ) {
  12335. for ( ca = 0; ca < cal; ca ++ ) {
  12336. index = sortArray[ ca ][ 1 ];
  12337. value = customAttribute.value[ index ];
  12338. customAttribute.array[ offset ] = value.r;
  12339. customAttribute.array[ offset + 1 ] = value.g;
  12340. customAttribute.array[ offset + 2 ] = value.b;
  12341. offset += 3;
  12342. }
  12343. } else {
  12344. for ( ca = 0; ca < cal; ca ++ ) {
  12345. index = sortArray[ ca ][ 1 ];
  12346. value = customAttribute.value[ index ];
  12347. customAttribute.array[ offset ] = value.x;
  12348. customAttribute.array[ offset + 1 ] = value.y;
  12349. customAttribute.array[ offset + 2 ] = value.z;
  12350. offset += 3;
  12351. }
  12352. }
  12353. } else if ( customAttribute.size === 4 ) {
  12354. for ( ca = 0; ca < cal; ca ++ ) {
  12355. index = sortArray[ ca ][ 1 ];
  12356. value = customAttribute.value[ index ];
  12357. customAttribute.array[ offset ] = value.x;
  12358. customAttribute.array[ offset + 1 ] = value.y;
  12359. customAttribute.array[ offset + 2 ] = value.z;
  12360. customAttribute.array[ offset + 3 ] = value.w;
  12361. offset += 4;
  12362. }
  12363. }
  12364. }
  12365. }
  12366. } else {
  12367. if ( dirtyVertices ) {
  12368. for ( v = 0; v < vl; v ++ ) {
  12369. vertex = vertices[ v ];
  12370. offset = v * 3;
  12371. vertexArray[ offset ] = vertex.x;
  12372. vertexArray[ offset + 1 ] = vertex.y;
  12373. vertexArray[ offset + 2 ] = vertex.z;
  12374. }
  12375. }
  12376. if ( dirtyColors ) {
  12377. for ( c = 0; c < cl; c ++ ) {
  12378. color = colors[ c ];
  12379. offset = c * 3;
  12380. colorArray[ offset ] = color.r;
  12381. colorArray[ offset + 1 ] = color.g;
  12382. colorArray[ offset + 2 ] = color.b;
  12383. }
  12384. }
  12385. if ( customAttributes ) {
  12386. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12387. customAttribute = customAttributes[ i ];
  12388. if ( customAttribute.needsUpdate &&
  12389. ( customAttribute.boundTo === undefined ||
  12390. customAttribute.boundTo === "vertices") ) {
  12391. cal = customAttribute.value.length;
  12392. offset = 0;
  12393. if ( customAttribute.size === 1 ) {
  12394. for ( ca = 0; ca < cal; ca ++ ) {
  12395. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12396. }
  12397. } else if ( customAttribute.size === 2 ) {
  12398. for ( ca = 0; ca < cal; ca ++ ) {
  12399. value = customAttribute.value[ ca ];
  12400. customAttribute.array[ offset ] = value.x;
  12401. customAttribute.array[ offset + 1 ] = value.y;
  12402. offset += 2;
  12403. }
  12404. } else if ( customAttribute.size === 3 ) {
  12405. if ( customAttribute.type === "c" ) {
  12406. for ( ca = 0; ca < cal; ca ++ ) {
  12407. value = customAttribute.value[ ca ];
  12408. customAttribute.array[ offset ] = value.r;
  12409. customAttribute.array[ offset + 1 ] = value.g;
  12410. customAttribute.array[ offset + 2 ] = value.b;
  12411. offset += 3;
  12412. }
  12413. } else {
  12414. for ( ca = 0; ca < cal; ca ++ ) {
  12415. value = customAttribute.value[ ca ];
  12416. customAttribute.array[ offset ] = value.x;
  12417. customAttribute.array[ offset + 1 ] = value.y;
  12418. customAttribute.array[ offset + 2 ] = value.z;
  12419. offset += 3;
  12420. }
  12421. }
  12422. } else if ( customAttribute.size === 4 ) {
  12423. for ( ca = 0; ca < cal; ca ++ ) {
  12424. value = customAttribute.value[ ca ];
  12425. customAttribute.array[ offset ] = value.x;
  12426. customAttribute.array[ offset + 1 ] = value.y;
  12427. customAttribute.array[ offset + 2 ] = value.z;
  12428. customAttribute.array[ offset + 3 ] = value.w;
  12429. offset += 4;
  12430. }
  12431. }
  12432. }
  12433. }
  12434. }
  12435. }
  12436. if ( dirtyVertices || object.sortParticles ) {
  12437. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12438. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12439. }
  12440. if ( dirtyColors || object.sortParticles ) {
  12441. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12442. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12443. }
  12444. if ( customAttributes ) {
  12445. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12446. customAttribute = customAttributes[ i ];
  12447. if ( customAttribute.needsUpdate || object.sortParticles ) {
  12448. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12449. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12450. }
  12451. }
  12452. }
  12453. };
  12454. function setLineBuffers ( geometry, hint ) {
  12455. var v, c, d, vertex, offset, color,
  12456. vertices = geometry.vertices,
  12457. colors = geometry.colors,
  12458. lineDistances = geometry.lineDistances,
  12459. vl = vertices.length,
  12460. cl = colors.length,
  12461. dl = lineDistances.length,
  12462. vertexArray = geometry.__vertexArray,
  12463. colorArray = geometry.__colorArray,
  12464. lineDistanceArray = geometry.__lineDistanceArray,
  12465. dirtyVertices = geometry.verticesNeedUpdate,
  12466. dirtyColors = geometry.colorsNeedUpdate,
  12467. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  12468. customAttributes = geometry.__webglCustomAttributesList,
  12469. i, il,
  12470. a, ca, cal, value,
  12471. customAttribute;
  12472. if ( dirtyVertices ) {
  12473. for ( v = 0; v < vl; v ++ ) {
  12474. vertex = vertices[ v ];
  12475. offset = v * 3;
  12476. vertexArray[ offset ] = vertex.x;
  12477. vertexArray[ offset + 1 ] = vertex.y;
  12478. vertexArray[ offset + 2 ] = vertex.z;
  12479. }
  12480. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12481. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12482. }
  12483. if ( dirtyColors ) {
  12484. for ( c = 0; c < cl; c ++ ) {
  12485. color = colors[ c ];
  12486. offset = c * 3;
  12487. colorArray[ offset ] = color.r;
  12488. colorArray[ offset + 1 ] = color.g;
  12489. colorArray[ offset + 2 ] = color.b;
  12490. }
  12491. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12492. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12493. }
  12494. if ( dirtyLineDistances ) {
  12495. for ( d = 0; d < dl; d ++ ) {
  12496. lineDistanceArray[ d ] = lineDistances[ d ];
  12497. }
  12498. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  12499. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  12500. }
  12501. if ( customAttributes ) {
  12502. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12503. customAttribute = customAttributes[ i ];
  12504. if ( customAttribute.needsUpdate &&
  12505. ( customAttribute.boundTo === undefined ||
  12506. customAttribute.boundTo === "vertices" ) ) {
  12507. offset = 0;
  12508. cal = customAttribute.value.length;
  12509. if ( customAttribute.size === 1 ) {
  12510. for ( ca = 0; ca < cal; ca ++ ) {
  12511. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12512. }
  12513. } else if ( customAttribute.size === 2 ) {
  12514. for ( ca = 0; ca < cal; ca ++ ) {
  12515. value = customAttribute.value[ ca ];
  12516. customAttribute.array[ offset ] = value.x;
  12517. customAttribute.array[ offset + 1 ] = value.y;
  12518. offset += 2;
  12519. }
  12520. } else if ( customAttribute.size === 3 ) {
  12521. if ( customAttribute.type === "c" ) {
  12522. for ( ca = 0; ca < cal; ca ++ ) {
  12523. value = customAttribute.value[ ca ];
  12524. customAttribute.array[ offset ] = value.r;
  12525. customAttribute.array[ offset + 1 ] = value.g;
  12526. customAttribute.array[ offset + 2 ] = value.b;
  12527. offset += 3;
  12528. }
  12529. } else {
  12530. for ( ca = 0; ca < cal; ca ++ ) {
  12531. value = customAttribute.value[ ca ];
  12532. customAttribute.array[ offset ] = value.x;
  12533. customAttribute.array[ offset + 1 ] = value.y;
  12534. customAttribute.array[ offset + 2 ] = value.z;
  12535. offset += 3;
  12536. }
  12537. }
  12538. } else if ( customAttribute.size === 4 ) {
  12539. for ( ca = 0; ca < cal; ca ++ ) {
  12540. value = customAttribute.value[ ca ];
  12541. customAttribute.array[ offset ] = value.x;
  12542. customAttribute.array[ offset + 1 ] = value.y;
  12543. customAttribute.array[ offset + 2 ] = value.z;
  12544. customAttribute.array[ offset + 3 ] = value.w;
  12545. offset += 4;
  12546. }
  12547. }
  12548. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12549. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12550. }
  12551. }
  12552. }
  12553. };
  12554. function setRibbonBuffers ( geometry, hint ) {
  12555. var v, c, n, vertex, offset, color, normal,
  12556. i, il, ca, cal, customAttribute, value,
  12557. vertices = geometry.vertices,
  12558. colors = geometry.colors,
  12559. normals = geometry.normals,
  12560. vl = vertices.length,
  12561. cl = colors.length,
  12562. nl = normals.length,
  12563. vertexArray = geometry.__vertexArray,
  12564. colorArray = geometry.__colorArray,
  12565. normalArray = geometry.__normalArray,
  12566. dirtyVertices = geometry.verticesNeedUpdate,
  12567. dirtyColors = geometry.colorsNeedUpdate,
  12568. dirtyNormals = geometry.normalsNeedUpdate,
  12569. customAttributes = geometry.__webglCustomAttributesList;
  12570. if ( dirtyVertices ) {
  12571. for ( v = 0; v < vl; v ++ ) {
  12572. vertex = vertices[ v ];
  12573. offset = v * 3;
  12574. vertexArray[ offset ] = vertex.x;
  12575. vertexArray[ offset + 1 ] = vertex.y;
  12576. vertexArray[ offset + 2 ] = vertex.z;
  12577. }
  12578. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12579. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12580. }
  12581. if ( dirtyColors ) {
  12582. for ( c = 0; c < cl; c ++ ) {
  12583. color = colors[ c ];
  12584. offset = c * 3;
  12585. colorArray[ offset ] = color.r;
  12586. colorArray[ offset + 1 ] = color.g;
  12587. colorArray[ offset + 2 ] = color.b;
  12588. }
  12589. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12590. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12591. }
  12592. if ( dirtyNormals ) {
  12593. for ( n = 0; n < nl; n ++ ) {
  12594. normal = normals[ n ];
  12595. offset = n * 3;
  12596. normalArray[ offset ] = normal.x;
  12597. normalArray[ offset + 1 ] = normal.y;
  12598. normalArray[ offset + 2 ] = normal.z;
  12599. }
  12600. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  12601. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12602. }
  12603. if ( customAttributes ) {
  12604. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12605. customAttribute = customAttributes[ i ];
  12606. if ( customAttribute.needsUpdate &&
  12607. ( customAttribute.boundTo === undefined ||
  12608. customAttribute.boundTo === "vertices" ) ) {
  12609. offset = 0;
  12610. cal = customAttribute.value.length;
  12611. if ( customAttribute.size === 1 ) {
  12612. for ( ca = 0; ca < cal; ca ++ ) {
  12613. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12614. }
  12615. } else if ( customAttribute.size === 2 ) {
  12616. for ( ca = 0; ca < cal; ca ++ ) {
  12617. value = customAttribute.value[ ca ];
  12618. customAttribute.array[ offset ] = value.x;
  12619. customAttribute.array[ offset + 1 ] = value.y;
  12620. offset += 2;
  12621. }
  12622. } else if ( customAttribute.size === 3 ) {
  12623. if ( customAttribute.type === "c" ) {
  12624. for ( ca = 0; ca < cal; ca ++ ) {
  12625. value = customAttribute.value[ ca ];
  12626. customAttribute.array[ offset ] = value.r;
  12627. customAttribute.array[ offset + 1 ] = value.g;
  12628. customAttribute.array[ offset + 2 ] = value.b;
  12629. offset += 3;
  12630. }
  12631. } else {
  12632. for ( ca = 0; ca < cal; ca ++ ) {
  12633. value = customAttribute.value[ ca ];
  12634. customAttribute.array[ offset ] = value.x;
  12635. customAttribute.array[ offset + 1 ] = value.y;
  12636. customAttribute.array[ offset + 2 ] = value.z;
  12637. offset += 3;
  12638. }
  12639. }
  12640. } else if ( customAttribute.size === 4 ) {
  12641. for ( ca = 0; ca < cal; ca ++ ) {
  12642. value = customAttribute.value[ ca ];
  12643. customAttribute.array[ offset ] = value.x;
  12644. customAttribute.array[ offset + 1 ] = value.y;
  12645. customAttribute.array[ offset + 2 ] = value.z;
  12646. customAttribute.array[ offset + 3 ] = value.w;
  12647. offset += 4;
  12648. }
  12649. }
  12650. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12651. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12652. }
  12653. }
  12654. }
  12655. };
  12656. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  12657. if ( ! geometryGroup.__inittedArrays ) {
  12658. return;
  12659. }
  12660. var normalType = bufferGuessNormalType( material ),
  12661. vertexColorType = bufferGuessVertexColorType( material ),
  12662. uvType = bufferGuessUVType( material ),
  12663. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  12664. var f, fl, fi, face,
  12665. vertexNormals, faceNormal, normal,
  12666. vertexColors, faceColor,
  12667. vertexTangents,
  12668. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  12669. c1, c2, c3, c4,
  12670. sw1, sw2, sw3, sw4,
  12671. si1, si2, si3, si4,
  12672. sa1, sa2, sa3, sa4,
  12673. sb1, sb2, sb3, sb4,
  12674. m, ml, i, il,
  12675. vn, uvi, uv2i,
  12676. vk, vkl, vka,
  12677. nka, chf, faceVertexNormals,
  12678. a,
  12679. vertexIndex = 0,
  12680. offset = 0,
  12681. offset_uv = 0,
  12682. offset_uv2 = 0,
  12683. offset_face = 0,
  12684. offset_normal = 0,
  12685. offset_tangent = 0,
  12686. offset_line = 0,
  12687. offset_color = 0,
  12688. offset_skin = 0,
  12689. offset_morphTarget = 0,
  12690. offset_custom = 0,
  12691. offset_customSrc = 0,
  12692. value,
  12693. vertexArray = geometryGroup.__vertexArray,
  12694. uvArray = geometryGroup.__uvArray,
  12695. uv2Array = geometryGroup.__uv2Array,
  12696. normalArray = geometryGroup.__normalArray,
  12697. tangentArray = geometryGroup.__tangentArray,
  12698. colorArray = geometryGroup.__colorArray,
  12699. skinIndexArray = geometryGroup.__skinIndexArray,
  12700. skinWeightArray = geometryGroup.__skinWeightArray,
  12701. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  12702. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  12703. customAttributes = geometryGroup.__webglCustomAttributesList,
  12704. customAttribute,
  12705. faceArray = geometryGroup.__faceArray,
  12706. lineArray = geometryGroup.__lineArray,
  12707. geometry = object.geometry, // this is shared for all chunks
  12708. dirtyVertices = geometry.verticesNeedUpdate,
  12709. dirtyElements = geometry.elementsNeedUpdate,
  12710. dirtyUvs = geometry.uvsNeedUpdate,
  12711. dirtyNormals = geometry.normalsNeedUpdate,
  12712. dirtyTangents = geometry.tangentsNeedUpdate,
  12713. dirtyColors = geometry.colorsNeedUpdate,
  12714. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  12715. vertices = geometry.vertices,
  12716. chunk_faces3 = geometryGroup.faces3,
  12717. chunk_faces4 = geometryGroup.faces4,
  12718. obj_faces = geometry.faces,
  12719. obj_uvs = geometry.faceVertexUvs[ 0 ],
  12720. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  12721. obj_colors = geometry.colors,
  12722. obj_skinIndices = geometry.skinIndices,
  12723. obj_skinWeights = geometry.skinWeights,
  12724. morphTargets = geometry.morphTargets,
  12725. morphNormals = geometry.morphNormals;
  12726. if ( dirtyVertices ) {
  12727. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12728. face = obj_faces[ chunk_faces3[ f ] ];
  12729. v1 = vertices[ face.a ];
  12730. v2 = vertices[ face.b ];
  12731. v3 = vertices[ face.c ];
  12732. vertexArray[ offset ] = v1.x;
  12733. vertexArray[ offset + 1 ] = v1.y;
  12734. vertexArray[ offset + 2 ] = v1.z;
  12735. vertexArray[ offset + 3 ] = v2.x;
  12736. vertexArray[ offset + 4 ] = v2.y;
  12737. vertexArray[ offset + 5 ] = v2.z;
  12738. vertexArray[ offset + 6 ] = v3.x;
  12739. vertexArray[ offset + 7 ] = v3.y;
  12740. vertexArray[ offset + 8 ] = v3.z;
  12741. offset += 9;
  12742. }
  12743. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12744. face = obj_faces[ chunk_faces4[ f ] ];
  12745. v1 = vertices[ face.a ];
  12746. v2 = vertices[ face.b ];
  12747. v3 = vertices[ face.c ];
  12748. v4 = vertices[ face.d ];
  12749. vertexArray[ offset ] = v1.x;
  12750. vertexArray[ offset + 1 ] = v1.y;
  12751. vertexArray[ offset + 2 ] = v1.z;
  12752. vertexArray[ offset + 3 ] = v2.x;
  12753. vertexArray[ offset + 4 ] = v2.y;
  12754. vertexArray[ offset + 5 ] = v2.z;
  12755. vertexArray[ offset + 6 ] = v3.x;
  12756. vertexArray[ offset + 7 ] = v3.y;
  12757. vertexArray[ offset + 8 ] = v3.z;
  12758. vertexArray[ offset + 9 ] = v4.x;
  12759. vertexArray[ offset + 10 ] = v4.y;
  12760. vertexArray[ offset + 11 ] = v4.z;
  12761. offset += 12;
  12762. }
  12763. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12764. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12765. }
  12766. if ( dirtyMorphTargets ) {
  12767. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  12768. offset_morphTarget = 0;
  12769. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12770. chf = chunk_faces3[ f ];
  12771. face = obj_faces[ chf ];
  12772. // morph positions
  12773. v1 = morphTargets[ vk ].vertices[ face.a ];
  12774. v2 = morphTargets[ vk ].vertices[ face.b ];
  12775. v3 = morphTargets[ vk ].vertices[ face.c ];
  12776. vka = morphTargetsArrays[ vk ];
  12777. vka[ offset_morphTarget ] = v1.x;
  12778. vka[ offset_morphTarget + 1 ] = v1.y;
  12779. vka[ offset_morphTarget + 2 ] = v1.z;
  12780. vka[ offset_morphTarget + 3 ] = v2.x;
  12781. vka[ offset_morphTarget + 4 ] = v2.y;
  12782. vka[ offset_morphTarget + 5 ] = v2.z;
  12783. vka[ offset_morphTarget + 6 ] = v3.x;
  12784. vka[ offset_morphTarget + 7 ] = v3.y;
  12785. vka[ offset_morphTarget + 8 ] = v3.z;
  12786. // morph normals
  12787. if ( material.morphNormals ) {
  12788. if ( needsSmoothNormals ) {
  12789. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12790. n1 = faceVertexNormals.a;
  12791. n2 = faceVertexNormals.b;
  12792. n3 = faceVertexNormals.c;
  12793. } else {
  12794. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12795. n2 = n1;
  12796. n3 = n1;
  12797. }
  12798. nka = morphNormalsArrays[ vk ];
  12799. nka[ offset_morphTarget ] = n1.x;
  12800. nka[ offset_morphTarget + 1 ] = n1.y;
  12801. nka[ offset_morphTarget + 2 ] = n1.z;
  12802. nka[ offset_morphTarget + 3 ] = n2.x;
  12803. nka[ offset_morphTarget + 4 ] = n2.y;
  12804. nka[ offset_morphTarget + 5 ] = n2.z;
  12805. nka[ offset_morphTarget + 6 ] = n3.x;
  12806. nka[ offset_morphTarget + 7 ] = n3.y;
  12807. nka[ offset_morphTarget + 8 ] = n3.z;
  12808. }
  12809. //
  12810. offset_morphTarget += 9;
  12811. }
  12812. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12813. chf = chunk_faces4[ f ];
  12814. face = obj_faces[ chf ];
  12815. // morph positions
  12816. v1 = morphTargets[ vk ].vertices[ face.a ];
  12817. v2 = morphTargets[ vk ].vertices[ face.b ];
  12818. v3 = morphTargets[ vk ].vertices[ face.c ];
  12819. v4 = morphTargets[ vk ].vertices[ face.d ];
  12820. vka = morphTargetsArrays[ vk ];
  12821. vka[ offset_morphTarget ] = v1.x;
  12822. vka[ offset_morphTarget + 1 ] = v1.y;
  12823. vka[ offset_morphTarget + 2 ] = v1.z;
  12824. vka[ offset_morphTarget + 3 ] = v2.x;
  12825. vka[ offset_morphTarget + 4 ] = v2.y;
  12826. vka[ offset_morphTarget + 5 ] = v2.z;
  12827. vka[ offset_morphTarget + 6 ] = v3.x;
  12828. vka[ offset_morphTarget + 7 ] = v3.y;
  12829. vka[ offset_morphTarget + 8 ] = v3.z;
  12830. vka[ offset_morphTarget + 9 ] = v4.x;
  12831. vka[ offset_morphTarget + 10 ] = v4.y;
  12832. vka[ offset_morphTarget + 11 ] = v4.z;
  12833. // morph normals
  12834. if ( material.morphNormals ) {
  12835. if ( needsSmoothNormals ) {
  12836. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12837. n1 = faceVertexNormals.a;
  12838. n2 = faceVertexNormals.b;
  12839. n3 = faceVertexNormals.c;
  12840. n4 = faceVertexNormals.d;
  12841. } else {
  12842. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12843. n2 = n1;
  12844. n3 = n1;
  12845. n4 = n1;
  12846. }
  12847. nka = morphNormalsArrays[ vk ];
  12848. nka[ offset_morphTarget ] = n1.x;
  12849. nka[ offset_morphTarget + 1 ] = n1.y;
  12850. nka[ offset_morphTarget + 2 ] = n1.z;
  12851. nka[ offset_morphTarget + 3 ] = n2.x;
  12852. nka[ offset_morphTarget + 4 ] = n2.y;
  12853. nka[ offset_morphTarget + 5 ] = n2.z;
  12854. nka[ offset_morphTarget + 6 ] = n3.x;
  12855. nka[ offset_morphTarget + 7 ] = n3.y;
  12856. nka[ offset_morphTarget + 8 ] = n3.z;
  12857. nka[ offset_morphTarget + 9 ] = n4.x;
  12858. nka[ offset_morphTarget + 10 ] = n4.y;
  12859. nka[ offset_morphTarget + 11 ] = n4.z;
  12860. }
  12861. //
  12862. offset_morphTarget += 12;
  12863. }
  12864. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  12865. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  12866. if ( material.morphNormals ) {
  12867. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  12868. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  12869. }
  12870. }
  12871. }
  12872. if ( obj_skinWeights.length ) {
  12873. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12874. face = obj_faces[ chunk_faces3[ f ] ];
  12875. // weights
  12876. sw1 = obj_skinWeights[ face.a ];
  12877. sw2 = obj_skinWeights[ face.b ];
  12878. sw3 = obj_skinWeights[ face.c ];
  12879. skinWeightArray[ offset_skin ] = sw1.x;
  12880. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12881. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12882. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12883. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12884. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12885. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12886. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12887. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12888. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12889. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12890. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12891. // indices
  12892. si1 = obj_skinIndices[ face.a ];
  12893. si2 = obj_skinIndices[ face.b ];
  12894. si3 = obj_skinIndices[ face.c ];
  12895. skinIndexArray[ offset_skin ] = si1.x;
  12896. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12897. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12898. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12899. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12900. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12901. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12902. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12903. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12904. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12905. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12906. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12907. offset_skin += 12;
  12908. }
  12909. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12910. face = obj_faces[ chunk_faces4[ f ] ];
  12911. // weights
  12912. sw1 = obj_skinWeights[ face.a ];
  12913. sw2 = obj_skinWeights[ face.b ];
  12914. sw3 = obj_skinWeights[ face.c ];
  12915. sw4 = obj_skinWeights[ face.d ];
  12916. skinWeightArray[ offset_skin ] = sw1.x;
  12917. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12918. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12919. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12920. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12921. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12922. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12923. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12924. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12925. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12926. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12927. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12928. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  12929. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  12930. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  12931. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  12932. // indices
  12933. si1 = obj_skinIndices[ face.a ];
  12934. si2 = obj_skinIndices[ face.b ];
  12935. si3 = obj_skinIndices[ face.c ];
  12936. si4 = obj_skinIndices[ face.d ];
  12937. skinIndexArray[ offset_skin ] = si1.x;
  12938. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12939. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12940. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12941. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12942. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12943. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12944. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12945. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12946. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12947. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12948. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12949. skinIndexArray[ offset_skin + 12 ] = si4.x;
  12950. skinIndexArray[ offset_skin + 13 ] = si4.y;
  12951. skinIndexArray[ offset_skin + 14 ] = si4.z;
  12952. skinIndexArray[ offset_skin + 15 ] = si4.w;
  12953. offset_skin += 16;
  12954. }
  12955. if ( offset_skin > 0 ) {
  12956. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12957. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  12958. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12959. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  12960. }
  12961. }
  12962. if ( dirtyColors && vertexColorType ) {
  12963. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12964. face = obj_faces[ chunk_faces3[ f ] ];
  12965. vertexColors = face.vertexColors;
  12966. faceColor = face.color;
  12967. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  12968. c1 = vertexColors[ 0 ];
  12969. c2 = vertexColors[ 1 ];
  12970. c3 = vertexColors[ 2 ];
  12971. } else {
  12972. c1 = faceColor;
  12973. c2 = faceColor;
  12974. c3 = faceColor;
  12975. }
  12976. colorArray[ offset_color ] = c1.r;
  12977. colorArray[ offset_color + 1 ] = c1.g;
  12978. colorArray[ offset_color + 2 ] = c1.b;
  12979. colorArray[ offset_color + 3 ] = c2.r;
  12980. colorArray[ offset_color + 4 ] = c2.g;
  12981. colorArray[ offset_color + 5 ] = c2.b;
  12982. colorArray[ offset_color + 6 ] = c3.r;
  12983. colorArray[ offset_color + 7 ] = c3.g;
  12984. colorArray[ offset_color + 8 ] = c3.b;
  12985. offset_color += 9;
  12986. }
  12987. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12988. face = obj_faces[ chunk_faces4[ f ] ];
  12989. vertexColors = face.vertexColors;
  12990. faceColor = face.color;
  12991. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  12992. c1 = vertexColors[ 0 ];
  12993. c2 = vertexColors[ 1 ];
  12994. c3 = vertexColors[ 2 ];
  12995. c4 = vertexColors[ 3 ];
  12996. } else {
  12997. c1 = faceColor;
  12998. c2 = faceColor;
  12999. c3 = faceColor;
  13000. c4 = faceColor;
  13001. }
  13002. colorArray[ offset_color ] = c1.r;
  13003. colorArray[ offset_color + 1 ] = c1.g;
  13004. colorArray[ offset_color + 2 ] = c1.b;
  13005. colorArray[ offset_color + 3 ] = c2.r;
  13006. colorArray[ offset_color + 4 ] = c2.g;
  13007. colorArray[ offset_color + 5 ] = c2.b;
  13008. colorArray[ offset_color + 6 ] = c3.r;
  13009. colorArray[ offset_color + 7 ] = c3.g;
  13010. colorArray[ offset_color + 8 ] = c3.b;
  13011. colorArray[ offset_color + 9 ] = c4.r;
  13012. colorArray[ offset_color + 10 ] = c4.g;
  13013. colorArray[ offset_color + 11 ] = c4.b;
  13014. offset_color += 12;
  13015. }
  13016. if ( offset_color > 0 ) {
  13017. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13018. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  13019. }
  13020. }
  13021. if ( dirtyTangents && geometry.hasTangents ) {
  13022. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13023. face = obj_faces[ chunk_faces3[ f ] ];
  13024. vertexTangents = face.vertexTangents;
  13025. t1 = vertexTangents[ 0 ];
  13026. t2 = vertexTangents[ 1 ];
  13027. t3 = vertexTangents[ 2 ];
  13028. tangentArray[ offset_tangent ] = t1.x;
  13029. tangentArray[ offset_tangent + 1 ] = t1.y;
  13030. tangentArray[ offset_tangent + 2 ] = t1.z;
  13031. tangentArray[ offset_tangent + 3 ] = t1.w;
  13032. tangentArray[ offset_tangent + 4 ] = t2.x;
  13033. tangentArray[ offset_tangent + 5 ] = t2.y;
  13034. tangentArray[ offset_tangent + 6 ] = t2.z;
  13035. tangentArray[ offset_tangent + 7 ] = t2.w;
  13036. tangentArray[ offset_tangent + 8 ] = t3.x;
  13037. tangentArray[ offset_tangent + 9 ] = t3.y;
  13038. tangentArray[ offset_tangent + 10 ] = t3.z;
  13039. tangentArray[ offset_tangent + 11 ] = t3.w;
  13040. offset_tangent += 12;
  13041. }
  13042. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13043. face = obj_faces[ chunk_faces4[ f ] ];
  13044. vertexTangents = face.vertexTangents;
  13045. t1 = vertexTangents[ 0 ];
  13046. t2 = vertexTangents[ 1 ];
  13047. t3 = vertexTangents[ 2 ];
  13048. t4 = vertexTangents[ 3 ];
  13049. tangentArray[ offset_tangent ] = t1.x;
  13050. tangentArray[ offset_tangent + 1 ] = t1.y;
  13051. tangentArray[ offset_tangent + 2 ] = t1.z;
  13052. tangentArray[ offset_tangent + 3 ] = t1.w;
  13053. tangentArray[ offset_tangent + 4 ] = t2.x;
  13054. tangentArray[ offset_tangent + 5 ] = t2.y;
  13055. tangentArray[ offset_tangent + 6 ] = t2.z;
  13056. tangentArray[ offset_tangent + 7 ] = t2.w;
  13057. tangentArray[ offset_tangent + 8 ] = t3.x;
  13058. tangentArray[ offset_tangent + 9 ] = t3.y;
  13059. tangentArray[ offset_tangent + 10 ] = t3.z;
  13060. tangentArray[ offset_tangent + 11 ] = t3.w;
  13061. tangentArray[ offset_tangent + 12 ] = t4.x;
  13062. tangentArray[ offset_tangent + 13 ] = t4.y;
  13063. tangentArray[ offset_tangent + 14 ] = t4.z;
  13064. tangentArray[ offset_tangent + 15 ] = t4.w;
  13065. offset_tangent += 16;
  13066. }
  13067. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13068. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  13069. }
  13070. if ( dirtyNormals && normalType ) {
  13071. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13072. face = obj_faces[ chunk_faces3[ f ] ];
  13073. vertexNormals = face.vertexNormals;
  13074. faceNormal = face.normal;
  13075. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  13076. for ( i = 0; i < 3; i ++ ) {
  13077. vn = vertexNormals[ i ];
  13078. normalArray[ offset_normal ] = vn.x;
  13079. normalArray[ offset_normal + 1 ] = vn.y;
  13080. normalArray[ offset_normal + 2 ] = vn.z;
  13081. offset_normal += 3;
  13082. }
  13083. } else {
  13084. for ( i = 0; i < 3; i ++ ) {
  13085. normalArray[ offset_normal ] = faceNormal.x;
  13086. normalArray[ offset_normal + 1 ] = faceNormal.y;
  13087. normalArray[ offset_normal + 2 ] = faceNormal.z;
  13088. offset_normal += 3;
  13089. }
  13090. }
  13091. }
  13092. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13093. face = obj_faces[ chunk_faces4[ f ] ];
  13094. vertexNormals = face.vertexNormals;
  13095. faceNormal = face.normal;
  13096. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  13097. for ( i = 0; i < 4; i ++ ) {
  13098. vn = vertexNormals[ i ];
  13099. normalArray[ offset_normal ] = vn.x;
  13100. normalArray[ offset_normal + 1 ] = vn.y;
  13101. normalArray[ offset_normal + 2 ] = vn.z;
  13102. offset_normal += 3;
  13103. }
  13104. } else {
  13105. for ( i = 0; i < 4; i ++ ) {
  13106. normalArray[ offset_normal ] = faceNormal.x;
  13107. normalArray[ offset_normal + 1 ] = faceNormal.y;
  13108. normalArray[ offset_normal + 2 ] = faceNormal.z;
  13109. offset_normal += 3;
  13110. }
  13111. }
  13112. }
  13113. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13114. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  13115. }
  13116. if ( dirtyUvs && obj_uvs && uvType ) {
  13117. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13118. fi = chunk_faces3[ f ];
  13119. uv = obj_uvs[ fi ];
  13120. if ( uv === undefined ) continue;
  13121. for ( i = 0; i < 3; i ++ ) {
  13122. uvi = uv[ i ];
  13123. uvArray[ offset_uv ] = uvi.x;
  13124. uvArray[ offset_uv + 1 ] = uvi.y;
  13125. offset_uv += 2;
  13126. }
  13127. }
  13128. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13129. fi = chunk_faces4[ f ];
  13130. uv = obj_uvs[ fi ];
  13131. if ( uv === undefined ) continue;
  13132. for ( i = 0; i < 4; i ++ ) {
  13133. uvi = uv[ i ];
  13134. uvArray[ offset_uv ] = uvi.x;
  13135. uvArray[ offset_uv + 1 ] = uvi.y;
  13136. offset_uv += 2;
  13137. }
  13138. }
  13139. if ( offset_uv > 0 ) {
  13140. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13141. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  13142. }
  13143. }
  13144. if ( dirtyUvs && obj_uvs2 && uvType ) {
  13145. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13146. fi = chunk_faces3[ f ];
  13147. uv2 = obj_uvs2[ fi ];
  13148. if ( uv2 === undefined ) continue;
  13149. for ( i = 0; i < 3; i ++ ) {
  13150. uv2i = uv2[ i ];
  13151. uv2Array[ offset_uv2 ] = uv2i.x;
  13152. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  13153. offset_uv2 += 2;
  13154. }
  13155. }
  13156. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13157. fi = chunk_faces4[ f ];
  13158. uv2 = obj_uvs2[ fi ];
  13159. if ( uv2 === undefined ) continue;
  13160. for ( i = 0; i < 4; i ++ ) {
  13161. uv2i = uv2[ i ];
  13162. uv2Array[ offset_uv2 ] = uv2i.x;
  13163. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  13164. offset_uv2 += 2;
  13165. }
  13166. }
  13167. if ( offset_uv2 > 0 ) {
  13168. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13169. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  13170. }
  13171. }
  13172. if ( dirtyElements ) {
  13173. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13174. faceArray[ offset_face ] = vertexIndex;
  13175. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  13176. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  13177. offset_face += 3;
  13178. lineArray[ offset_line ] = vertexIndex;
  13179. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  13180. lineArray[ offset_line + 2 ] = vertexIndex;
  13181. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  13182. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  13183. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  13184. offset_line += 6;
  13185. vertexIndex += 3;
  13186. }
  13187. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13188. faceArray[ offset_face ] = vertexIndex;
  13189. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  13190. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  13191. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  13192. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  13193. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  13194. offset_face += 6;
  13195. lineArray[ offset_line ] = vertexIndex;
  13196. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  13197. lineArray[ offset_line + 2 ] = vertexIndex;
  13198. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  13199. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  13200. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  13201. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  13202. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  13203. offset_line += 8;
  13204. vertexIndex += 4;
  13205. }
  13206. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13207. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  13208. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13209. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  13210. }
  13211. if ( customAttributes ) {
  13212. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13213. customAttribute = customAttributes[ i ];
  13214. if ( ! customAttribute.__original.needsUpdate ) continue;
  13215. offset_custom = 0;
  13216. offset_customSrc = 0;
  13217. if ( customAttribute.size === 1 ) {
  13218. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13219. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13220. face = obj_faces[ chunk_faces3[ f ] ];
  13221. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  13222. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  13223. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  13224. offset_custom += 3;
  13225. }
  13226. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13227. face = obj_faces[ chunk_faces4[ f ] ];
  13228. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  13229. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  13230. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  13231. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  13232. offset_custom += 4;
  13233. }
  13234. } else if ( customAttribute.boundTo === "faces" ) {
  13235. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13236. value = customAttribute.value[ chunk_faces3[ f ] ];
  13237. customAttribute.array[ offset_custom ] = value;
  13238. customAttribute.array[ offset_custom + 1 ] = value;
  13239. customAttribute.array[ offset_custom + 2 ] = value;
  13240. offset_custom += 3;
  13241. }
  13242. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13243. value = customAttribute.value[ chunk_faces4[ f ] ];
  13244. customAttribute.array[ offset_custom ] = value;
  13245. customAttribute.array[ offset_custom + 1 ] = value;
  13246. customAttribute.array[ offset_custom + 2 ] = value;
  13247. customAttribute.array[ offset_custom + 3 ] = value;
  13248. offset_custom += 4;
  13249. }
  13250. }
  13251. } else if ( customAttribute.size === 2 ) {
  13252. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13253. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13254. face = obj_faces[ chunk_faces3[ f ] ];
  13255. v1 = customAttribute.value[ face.a ];
  13256. v2 = customAttribute.value[ face.b ];
  13257. v3 = customAttribute.value[ face.c ];
  13258. customAttribute.array[ offset_custom ] = v1.x;
  13259. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13260. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13261. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13262. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13263. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13264. offset_custom += 6;
  13265. }
  13266. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13267. face = obj_faces[ chunk_faces4[ f ] ];
  13268. v1 = customAttribute.value[ face.a ];
  13269. v2 = customAttribute.value[ face.b ];
  13270. v3 = customAttribute.value[ face.c ];
  13271. v4 = customAttribute.value[ face.d ];
  13272. customAttribute.array[ offset_custom ] = v1.x;
  13273. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13274. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13275. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13276. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13277. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13278. customAttribute.array[ offset_custom + 6 ] = v4.x;
  13279. customAttribute.array[ offset_custom + 7 ] = v4.y;
  13280. offset_custom += 8;
  13281. }
  13282. } else if ( customAttribute.boundTo === "faces" ) {
  13283. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13284. value = customAttribute.value[ chunk_faces3[ f ] ];
  13285. v1 = value;
  13286. v2 = value;
  13287. v3 = value;
  13288. customAttribute.array[ offset_custom ] = v1.x;
  13289. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13290. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13291. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13292. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13293. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13294. offset_custom += 6;
  13295. }
  13296. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13297. value = customAttribute.value[ chunk_faces4[ f ] ];
  13298. v1 = value;
  13299. v2 = value;
  13300. v3 = value;
  13301. v4 = value;
  13302. customAttribute.array[ offset_custom ] = v1.x;
  13303. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13304. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13305. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13306. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13307. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13308. customAttribute.array[ offset_custom + 6 ] = v4.x;
  13309. customAttribute.array[ offset_custom + 7 ] = v4.y;
  13310. offset_custom += 8;
  13311. }
  13312. }
  13313. } else if ( customAttribute.size === 3 ) {
  13314. var pp;
  13315. if ( customAttribute.type === "c" ) {
  13316. pp = [ "r", "g", "b" ];
  13317. } else {
  13318. pp = [ "x", "y", "z" ];
  13319. }
  13320. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13321. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13322. face = obj_faces[ chunk_faces3[ f ] ];
  13323. v1 = customAttribute.value[ face.a ];
  13324. v2 = customAttribute.value[ face.b ];
  13325. v3 = customAttribute.value[ face.c ];
  13326. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13327. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13328. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13329. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13330. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13331. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13332. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13333. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13334. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13335. offset_custom += 9;
  13336. }
  13337. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13338. face = obj_faces[ chunk_faces4[ f ] ];
  13339. v1 = customAttribute.value[ face.a ];
  13340. v2 = customAttribute.value[ face.b ];
  13341. v3 = customAttribute.value[ face.c ];
  13342. v4 = customAttribute.value[ face.d ];
  13343. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13344. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13345. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13346. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13347. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13348. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13349. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13350. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13351. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13352. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  13353. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  13354. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  13355. offset_custom += 12;
  13356. }
  13357. } else if ( customAttribute.boundTo === "faces" ) {
  13358. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13359. value = customAttribute.value[ chunk_faces3[ f ] ];
  13360. v1 = value;
  13361. v2 = value;
  13362. v3 = value;
  13363. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13364. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13365. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13366. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13367. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13368. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13369. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13370. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13371. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13372. offset_custom += 9;
  13373. }
  13374. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13375. value = customAttribute.value[ chunk_faces4[ f ] ];
  13376. v1 = value;
  13377. v2 = value;
  13378. v3 = value;
  13379. v4 = value;
  13380. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13381. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13382. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13383. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13384. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13385. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13386. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13387. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13388. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13389. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  13390. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  13391. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  13392. offset_custom += 12;
  13393. }
  13394. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13395. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13396. value = customAttribute.value[ chunk_faces3[ f ] ];
  13397. v1 = value[ 0 ];
  13398. v2 = value[ 1 ];
  13399. v3 = value[ 2 ];
  13400. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13401. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13402. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13403. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13404. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13405. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13406. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13407. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13408. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13409. offset_custom += 9;
  13410. }
  13411. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13412. value = customAttribute.value[ chunk_faces4[ f ] ];
  13413. v1 = value[ 0 ];
  13414. v2 = value[ 1 ];
  13415. v3 = value[ 2 ];
  13416. v4 = value[ 3 ];
  13417. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13418. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13419. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13420. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13421. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13422. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13423. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13424. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13425. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13426. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  13427. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  13428. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  13429. offset_custom += 12;
  13430. }
  13431. }
  13432. } else if ( customAttribute.size === 4 ) {
  13433. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13434. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13435. face = obj_faces[ chunk_faces3[ f ] ];
  13436. v1 = customAttribute.value[ face.a ];
  13437. v2 = customAttribute.value[ face.b ];
  13438. v3 = customAttribute.value[ face.c ];
  13439. customAttribute.array[ offset_custom ] = v1.x;
  13440. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13441. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13442. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13443. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13444. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13445. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13446. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13447. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13448. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13449. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13450. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13451. offset_custom += 12;
  13452. }
  13453. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13454. face = obj_faces[ chunk_faces4[ f ] ];
  13455. v1 = customAttribute.value[ face.a ];
  13456. v2 = customAttribute.value[ face.b ];
  13457. v3 = customAttribute.value[ face.c ];
  13458. v4 = customAttribute.value[ face.d ];
  13459. customAttribute.array[ offset_custom ] = v1.x;
  13460. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13461. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13462. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13463. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13464. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13465. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13466. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13467. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13468. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13469. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13470. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13471. customAttribute.array[ offset_custom + 12 ] = v4.x;
  13472. customAttribute.array[ offset_custom + 13 ] = v4.y;
  13473. customAttribute.array[ offset_custom + 14 ] = v4.z;
  13474. customAttribute.array[ offset_custom + 15 ] = v4.w;
  13475. offset_custom += 16;
  13476. }
  13477. } else if ( customAttribute.boundTo === "faces" ) {
  13478. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13479. value = customAttribute.value[ chunk_faces3[ f ] ];
  13480. v1 = value;
  13481. v2 = value;
  13482. v3 = value;
  13483. customAttribute.array[ offset_custom ] = v1.x;
  13484. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13485. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13486. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13487. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13488. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13489. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13490. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13491. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13492. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13493. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13494. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13495. offset_custom += 12;
  13496. }
  13497. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13498. value = customAttribute.value[ chunk_faces4[ f ] ];
  13499. v1 = value;
  13500. v2 = value;
  13501. v3 = value;
  13502. v4 = value;
  13503. customAttribute.array[ offset_custom ] = v1.x;
  13504. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13505. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13506. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13507. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13508. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13509. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13510. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13511. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13512. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13513. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13514. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13515. customAttribute.array[ offset_custom + 12 ] = v4.x;
  13516. customAttribute.array[ offset_custom + 13 ] = v4.y;
  13517. customAttribute.array[ offset_custom + 14 ] = v4.z;
  13518. customAttribute.array[ offset_custom + 15 ] = v4.w;
  13519. offset_custom += 16;
  13520. }
  13521. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13522. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13523. value = customAttribute.value[ chunk_faces3[ f ] ];
  13524. v1 = value[ 0 ];
  13525. v2 = value[ 1 ];
  13526. v3 = value[ 2 ];
  13527. customAttribute.array[ offset_custom ] = v1.x;
  13528. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13529. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13530. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13531. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13532. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13533. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13534. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13535. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13536. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13537. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13538. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13539. offset_custom += 12;
  13540. }
  13541. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13542. value = customAttribute.value[ chunk_faces4[ f ] ];
  13543. v1 = value[ 0 ];
  13544. v2 = value[ 1 ];
  13545. v3 = value[ 2 ];
  13546. v4 = value[ 3 ];
  13547. customAttribute.array[ offset_custom ] = v1.x;
  13548. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13549. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13550. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13551. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13552. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13553. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13554. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13555. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13556. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13557. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13558. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13559. customAttribute.array[ offset_custom + 12 ] = v4.x;
  13560. customAttribute.array[ offset_custom + 13 ] = v4.y;
  13561. customAttribute.array[ offset_custom + 14 ] = v4.z;
  13562. customAttribute.array[ offset_custom + 15 ] = v4.w;
  13563. offset_custom += 16;
  13564. }
  13565. }
  13566. }
  13567. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  13568. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  13569. }
  13570. }
  13571. if ( dispose ) {
  13572. delete geometryGroup.__inittedArrays;
  13573. delete geometryGroup.__colorArray;
  13574. delete geometryGroup.__normalArray;
  13575. delete geometryGroup.__tangentArray;
  13576. delete geometryGroup.__uvArray;
  13577. delete geometryGroup.__uv2Array;
  13578. delete geometryGroup.__faceArray;
  13579. delete geometryGroup.__vertexArray;
  13580. delete geometryGroup.__lineArray;
  13581. delete geometryGroup.__skinIndexArray;
  13582. delete geometryGroup.__skinWeightArray;
  13583. }
  13584. };
  13585. function setDirectBuffers ( geometry, hint, dispose ) {
  13586. var attributes = geometry.attributes;
  13587. var attributeName, attributeItem;
  13588. for ( attributeName in attributes ) {
  13589. attributeItem = attributes[ attributeName ];
  13590. if ( attributeItem.needsUpdate ) {
  13591. if ( attributeName === 'index' ) {
  13592. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  13593. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  13594. } else {
  13595. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13596. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  13597. }
  13598. attributeItem.needsUpdate = false;
  13599. }
  13600. if ( dispose && ! attributeItem.dynamic ) {
  13601. attributeItem.array = null;
  13602. }
  13603. }
  13604. };
  13605. // Buffer rendering
  13606. this.renderBufferImmediate = function ( object, program, material ) {
  13607. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  13608. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  13609. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  13610. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  13611. if ( object.hasPositions ) {
  13612. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  13613. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  13614. _gl.enableVertexAttribArray( program.attributes.position );
  13615. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13616. }
  13617. if ( object.hasNormals ) {
  13618. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  13619. if ( material.shading === THREE.FlatShading ) {
  13620. var nx, ny, nz,
  13621. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  13622. normalArray,
  13623. i, il = object.count * 3;
  13624. for( i = 0; i < il; i += 9 ) {
  13625. normalArray = object.normalArray;
  13626. nax = normalArray[ i ];
  13627. nay = normalArray[ i + 1 ];
  13628. naz = normalArray[ i + 2 ];
  13629. nbx = normalArray[ i + 3 ];
  13630. nby = normalArray[ i + 4 ];
  13631. nbz = normalArray[ i + 5 ];
  13632. ncx = normalArray[ i + 6 ];
  13633. ncy = normalArray[ i + 7 ];
  13634. ncz = normalArray[ i + 8 ];
  13635. nx = ( nax + nbx + ncx ) / 3;
  13636. ny = ( nay + nby + ncy ) / 3;
  13637. nz = ( naz + nbz + ncz ) / 3;
  13638. normalArray[ i ] = nx;
  13639. normalArray[ i + 1 ] = ny;
  13640. normalArray[ i + 2 ] = nz;
  13641. normalArray[ i + 3 ] = nx;
  13642. normalArray[ i + 4 ] = ny;
  13643. normalArray[ i + 5 ] = nz;
  13644. normalArray[ i + 6 ] = nx;
  13645. normalArray[ i + 7 ] = ny;
  13646. normalArray[ i + 8 ] = nz;
  13647. }
  13648. }
  13649. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13650. _gl.enableVertexAttribArray( program.attributes.normal );
  13651. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13652. }
  13653. if ( object.hasUvs && material.map ) {
  13654. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13655. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13656. _gl.enableVertexAttribArray( program.attributes.uv );
  13657. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13658. }
  13659. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13660. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13661. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13662. _gl.enableVertexAttribArray( program.attributes.color );
  13663. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13664. }
  13665. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13666. object.count = 0;
  13667. };
  13668. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  13669. if ( material.visible === false ) return;
  13670. var linewidth, a, attribute;
  13671. var attributeItem, attributeName, attributePointer, attributeSize;
  13672. var program = setProgram( camera, lights, fog, material, object );
  13673. var programAttributes = program.attributes;
  13674. var geometryAttributes = geometry.attributes;
  13675. var updateBuffers = false,
  13676. wireframeBit = material.wireframe ? 1 : 0,
  13677. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13678. if ( geometryHash !== _currentGeometryGroupHash ) {
  13679. _currentGeometryGroupHash = geometryHash;
  13680. updateBuffers = true;
  13681. }
  13682. if ( updateBuffers ) {
  13683. disableAttributes();
  13684. }
  13685. // render mesh
  13686. if ( object instanceof THREE.Mesh ) {
  13687. var index = geometryAttributes[ "index" ];
  13688. // indexed triangles
  13689. if ( index ) {
  13690. var offsets = geometry.offsets;
  13691. // if there is more than 1 chunk
  13692. // must set attribute pointers to use new offsets for each chunk
  13693. // even if geometry and materials didn't change
  13694. if ( offsets.length > 1 ) updateBuffers = true;
  13695. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13696. var startIndex = offsets[ i ].index;
  13697. if ( updateBuffers ) {
  13698. for ( attributeName in geometryAttributes ) {
  13699. if ( attributeName === 'index' ) continue;
  13700. attributePointer = programAttributes[ attributeName ];
  13701. attributeItem = geometryAttributes[ attributeName ];
  13702. attributeSize = attributeItem.itemSize;
  13703. if ( attributePointer >= 0 ) {
  13704. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13705. enableAttribute( attributePointer );
  13706. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13707. }
  13708. }
  13709. // indices
  13710. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13711. }
  13712. // render indexed triangles
  13713. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  13714. _this.info.render.calls ++;
  13715. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13716. _this.info.render.faces += offsets[ i ].count / 3;
  13717. }
  13718. // non-indexed triangles
  13719. } else {
  13720. if ( updateBuffers ) {
  13721. for ( attributeName in geometryAttributes ) {
  13722. if ( attributeName === 'index') continue;
  13723. attributePointer = programAttributes[ attributeName ];
  13724. attributeItem = geometryAttributes[ attributeName ];
  13725. attributeSize = attributeItem.itemSize;
  13726. if ( attributePointer >= 0 ) {
  13727. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13728. enableAttribute( attributePointer );
  13729. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13730. }
  13731. }
  13732. }
  13733. var position = geometry.attributes[ "position" ];
  13734. // render non-indexed triangles
  13735. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  13736. _this.info.render.calls ++;
  13737. _this.info.render.vertices += position.numItems / 3;
  13738. _this.info.render.faces += position.numItems / 3 / 3;
  13739. }
  13740. // render particles
  13741. } else if ( object instanceof THREE.ParticleSystem ) {
  13742. if ( updateBuffers ) {
  13743. for ( attributeName in geometryAttributes ) {
  13744. attributePointer = programAttributes[ attributeName ];
  13745. attributeItem = geometryAttributes[ attributeName ];
  13746. attributeSize = attributeItem.itemSize;
  13747. if ( attributePointer >= 0 ) {
  13748. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13749. enableAttribute( attributePointer );
  13750. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13751. }
  13752. }
  13753. var position = geometryAttributes[ "position" ];
  13754. // render particles
  13755. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  13756. _this.info.render.calls ++;
  13757. _this.info.render.points += position.numItems / 3;
  13758. }
  13759. } else if ( object instanceof THREE.Line ) {
  13760. if ( updateBuffers ) {
  13761. for ( attributeName in geometryAttributes ) {
  13762. attributePointer = programAttributes[ attributeName ];
  13763. attributeItem = geometryAttributes[ attributeName ];
  13764. attributeSize = attributeItem.itemSize;
  13765. if ( attributePointer >= 0 ) {
  13766. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13767. enableAttribute( attributePointer );
  13768. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13769. }
  13770. }
  13771. // render lines
  13772. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13773. setLineWidth( material.linewidth );
  13774. var position = geometryAttributes[ "position" ];
  13775. _gl.drawArrays( primitives, 0, position.numItems / 3 );
  13776. _this.info.render.calls ++;
  13777. _this.info.render.points += position.numItems;
  13778. }
  13779. }
  13780. };
  13781. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  13782. if ( material.visible === false ) return;
  13783. var linewidth, a, attribute, i, il;
  13784. var program = setProgram( camera, lights, fog, material, object );
  13785. var attributes = program.attributes;
  13786. var updateBuffers = false,
  13787. wireframeBit = material.wireframe ? 1 : 0,
  13788. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13789. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  13790. _currentGeometryGroupHash = geometryGroupHash;
  13791. updateBuffers = true;
  13792. }
  13793. if ( updateBuffers ) {
  13794. disableAttributes();
  13795. }
  13796. // vertices
  13797. if ( !material.morphTargets && attributes.position >= 0 ) {
  13798. if ( updateBuffers ) {
  13799. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13800. enableAttribute( attributes.position );
  13801. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13802. }
  13803. } else {
  13804. if ( object.morphTargetBase ) {
  13805. setupMorphTargets( material, geometryGroup, object );
  13806. }
  13807. }
  13808. if ( updateBuffers ) {
  13809. // custom attributes
  13810. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  13811. if ( geometryGroup.__webglCustomAttributesList ) {
  13812. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  13813. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  13814. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  13815. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  13816. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  13817. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  13818. }
  13819. }
  13820. }
  13821. // colors
  13822. if ( attributes.color >= 0 ) {
  13823. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13824. enableAttribute( attributes.color );
  13825. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13826. }
  13827. // normals
  13828. if ( attributes.normal >= 0 ) {
  13829. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13830. enableAttribute( attributes.normal );
  13831. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13832. }
  13833. // tangents
  13834. if ( attributes.tangent >= 0 ) {
  13835. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13836. enableAttribute( attributes.tangent );
  13837. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  13838. }
  13839. // uvs
  13840. if ( attributes.uv >= 0 ) {
  13841. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13842. enableAttribute( attributes.uv );
  13843. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13844. }
  13845. if ( attributes.uv2 >= 0 ) {
  13846. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13847. enableAttribute( attributes.uv2 );
  13848. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  13849. }
  13850. if ( material.skinning &&
  13851. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  13852. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13853. enableAttribute( attributes.skinIndex );
  13854. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  13855. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13856. enableAttribute( attributes.skinWeight );
  13857. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  13858. }
  13859. // line distances
  13860. if ( attributes.lineDistance >= 0 ) {
  13861. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  13862. enableAttribute( attributes.lineDistance );
  13863. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  13864. }
  13865. }
  13866. // render mesh
  13867. if ( object instanceof THREE.Mesh ) {
  13868. // wireframe
  13869. if ( material.wireframe ) {
  13870. setLineWidth( material.wireframeLinewidth );
  13871. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13872. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  13873. // triangles
  13874. } else {
  13875. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13876. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  13877. }
  13878. _this.info.render.calls ++;
  13879. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  13880. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  13881. // render lines
  13882. } else if ( object instanceof THREE.Line ) {
  13883. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13884. setLineWidth( material.linewidth );
  13885. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  13886. _this.info.render.calls ++;
  13887. // render particles
  13888. } else if ( object instanceof THREE.ParticleSystem ) {
  13889. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  13890. _this.info.render.calls ++;
  13891. _this.info.render.points += geometryGroup.__webglParticleCount;
  13892. // render ribbon
  13893. } else if ( object instanceof THREE.Ribbon ) {
  13894. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  13895. _this.info.render.calls ++;
  13896. }
  13897. };
  13898. function enableAttribute( attribute ) {
  13899. if ( ! _enabledAttributes[ attribute ] ) {
  13900. _gl.enableVertexAttribArray( attribute );
  13901. _enabledAttributes[ attribute ] = true;
  13902. }
  13903. };
  13904. function disableAttributes() {
  13905. for ( var attribute in _enabledAttributes ) {
  13906. if ( _enabledAttributes[ attribute ] ) {
  13907. _gl.disableVertexAttribArray( attribute );
  13908. _enabledAttributes[ attribute ] = false;
  13909. }
  13910. }
  13911. };
  13912. function setupMorphTargets ( material, geometryGroup, object ) {
  13913. // set base
  13914. var attributes = material.program.attributes;
  13915. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  13916. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13917. enableAttribute( attributes.position );
  13918. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13919. } else if ( attributes.position >= 0 ) {
  13920. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13921. enableAttribute( attributes.position );
  13922. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13923. }
  13924. if ( object.morphTargetForcedOrder.length ) {
  13925. // set forced order
  13926. var m = 0;
  13927. var order = object.morphTargetForcedOrder;
  13928. var influences = object.morphTargetInfluences;
  13929. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13930. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13931. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13932. enableAttribute( attributes[ "morphTarget" + m ] );
  13933. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13934. }
  13935. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13936. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13937. enableAttribute( attributes[ "morphNormal" + m ] );
  13938. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13939. }
  13940. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13941. m ++;
  13942. }
  13943. } else {
  13944. // find the most influencing
  13945. var influence, activeInfluenceIndices = [];
  13946. var influences = object.morphTargetInfluences;
  13947. var i, il = influences.length;
  13948. for ( i = 0; i < il; i ++ ) {
  13949. influence = influences[ i ];
  13950. if ( influence > 0 ) {
  13951. activeInfluenceIndices.push( [ influence, i ] );
  13952. }
  13953. }
  13954. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13955. activeInfluenceIndices.sort( numericalSort );
  13956. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13957. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13958. activeInfluenceIndices.sort( numericalSort );
  13959. } else if ( activeInfluenceIndices.length === 0 ) {
  13960. activeInfluenceIndices.push( [ 0, 0 ] );
  13961. };
  13962. var influenceIndex, m = 0;
  13963. while ( m < material.numSupportedMorphTargets ) {
  13964. if ( activeInfluenceIndices[ m ] ) {
  13965. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13966. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13967. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13968. enableAttribute( attributes[ "morphTarget" + m ] );
  13969. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13970. }
  13971. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13972. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13973. enableAttribute( attributes[ "morphNormal" + m ] );
  13974. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13975. }
  13976. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13977. } else {
  13978. /*
  13979. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13980. if ( material.morphNormals ) {
  13981. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13982. }
  13983. */
  13984. object.__webglMorphTargetInfluences[ m ] = 0;
  13985. }
  13986. m ++;
  13987. }
  13988. }
  13989. // load updated influences uniform
  13990. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13991. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13992. }
  13993. };
  13994. // Sorting
  13995. function painterSortStable ( a, b ) {
  13996. if ( a.z !== b.z ) {
  13997. return b.z - a.z;
  13998. } else {
  13999. return a.id - b.id;
  14000. }
  14001. };
  14002. function numericalSort ( a, b ) {
  14003. return b[ 0 ] - a[ 0 ];
  14004. };
  14005. // Rendering
  14006. this.render = function ( scene, camera, renderTarget, forceClear ) {
  14007. if ( camera instanceof THREE.Camera === false ) {
  14008. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  14009. return;
  14010. }
  14011. var i, il,
  14012. webglObject, object,
  14013. renderList,
  14014. lights = scene.__lights,
  14015. fog = scene.fog;
  14016. // reset caching for this frame
  14017. _currentMaterialId = -1;
  14018. _lightsNeedUpdate = true;
  14019. // update scene graph
  14020. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  14021. // update camera matrices and frustum
  14022. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  14023. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  14024. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  14025. _frustum.setFromMatrix( _projScreenMatrix );
  14026. // update WebGL objects
  14027. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  14028. // custom render plugins (pre pass)
  14029. renderPlugins( this.renderPluginsPre, scene, camera );
  14030. //
  14031. _this.info.render.calls = 0;
  14032. _this.info.render.vertices = 0;
  14033. _this.info.render.faces = 0;
  14034. _this.info.render.points = 0;
  14035. this.setRenderTarget( renderTarget );
  14036. if ( this.autoClear || forceClear ) {
  14037. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  14038. }
  14039. // set matrices for regular objects (frustum culled)
  14040. renderList = scene.__webglObjects;
  14041. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  14042. webglObject = renderList[ i ];
  14043. object = webglObject.object;
  14044. webglObject.id = i;
  14045. webglObject.render = false;
  14046. if ( object.visible ) {
  14047. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  14048. setupMatrices( object, camera );
  14049. unrollBufferMaterial( webglObject );
  14050. webglObject.render = true;
  14051. if ( this.sortObjects === true ) {
  14052. if ( object.renderDepth !== null ) {
  14053. webglObject.z = object.renderDepth;
  14054. } else {
  14055. _vector3.getPositionFromMatrix( object.matrixWorld );
  14056. _vector3.applyProjection( _projScreenMatrix );
  14057. webglObject.z = _vector3.z;
  14058. }
  14059. }
  14060. }
  14061. }
  14062. }
  14063. if ( this.sortObjects ) {
  14064. renderList.sort( painterSortStable );
  14065. }
  14066. // set matrices for immediate objects
  14067. renderList = scene.__webglObjectsImmediate;
  14068. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  14069. webglObject = renderList[ i ];
  14070. object = webglObject.object;
  14071. if ( object.visible ) {
  14072. setupMatrices( object, camera );
  14073. unrollImmediateBufferMaterial( webglObject );
  14074. }
  14075. }
  14076. if ( scene.overrideMaterial ) {
  14077. var material = scene.overrideMaterial;
  14078. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  14079. this.setDepthTest( material.depthTest );
  14080. this.setDepthWrite( material.depthWrite );
  14081. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14082. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  14083. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  14084. } else {
  14085. var material = null;
  14086. // opaque pass (front-to-back order)
  14087. this.setBlending( THREE.NoBlending );
  14088. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  14089. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  14090. // transparent pass (back-to-front order)
  14091. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  14092. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  14093. }
  14094. // custom render plugins (post pass)
  14095. renderPlugins( this.renderPluginsPost, scene, camera );
  14096. // Generate mipmap if we're using any kind of mipmap filtering
  14097. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  14098. updateRenderTargetMipmap( renderTarget );
  14099. }
  14100. // Ensure depth buffer writing is enabled so it can be cleared on next render
  14101. this.setDepthTest( true );
  14102. this.setDepthWrite( true );
  14103. // _gl.finish();
  14104. };
  14105. function renderPlugins( plugins, scene, camera ) {
  14106. if ( ! plugins.length ) return;
  14107. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  14108. // reset state for plugin (to start from clean slate)
  14109. _currentProgram = null;
  14110. _currentCamera = null;
  14111. _oldBlending = -1;
  14112. _oldDepthTest = -1;
  14113. _oldDepthWrite = -1;
  14114. _oldDoubleSided = -1;
  14115. _oldFlipSided = -1;
  14116. _currentGeometryGroupHash = -1;
  14117. _currentMaterialId = -1;
  14118. _lightsNeedUpdate = true;
  14119. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  14120. // reset state after plugin (anything could have changed)
  14121. _currentProgram = null;
  14122. _currentCamera = null;
  14123. _oldBlending = -1;
  14124. _oldDepthTest = -1;
  14125. _oldDepthWrite = -1;
  14126. _oldDoubleSided = -1;
  14127. _oldFlipSided = -1;
  14128. _currentGeometryGroupHash = -1;
  14129. _currentMaterialId = -1;
  14130. _lightsNeedUpdate = true;
  14131. }
  14132. };
  14133. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  14134. var webglObject, object, buffer, material, start, end, delta;
  14135. if ( reverse ) {
  14136. start = renderList.length - 1;
  14137. end = -1;
  14138. delta = -1;
  14139. } else {
  14140. start = 0;
  14141. end = renderList.length;
  14142. delta = 1;
  14143. }
  14144. for ( var i = start; i !== end; i += delta ) {
  14145. webglObject = renderList[ i ];
  14146. if ( webglObject.render ) {
  14147. object = webglObject.object;
  14148. buffer = webglObject.buffer;
  14149. if ( overrideMaterial ) {
  14150. material = overrideMaterial;
  14151. } else {
  14152. material = webglObject[ materialType ];
  14153. if ( ! material ) continue;
  14154. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  14155. _this.setDepthTest( material.depthTest );
  14156. _this.setDepthWrite( material.depthWrite );
  14157. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14158. }
  14159. _this.setMaterialFaces( material );
  14160. if ( buffer instanceof THREE.BufferGeometry ) {
  14161. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  14162. } else {
  14163. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  14164. }
  14165. }
  14166. }
  14167. };
  14168. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  14169. var webglObject, object, material, program;
  14170. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  14171. webglObject = renderList[ i ];
  14172. object = webglObject.object;
  14173. if ( object.visible ) {
  14174. if ( overrideMaterial ) {
  14175. material = overrideMaterial;
  14176. } else {
  14177. material = webglObject[ materialType ];
  14178. if ( ! material ) continue;
  14179. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  14180. _this.setDepthTest( material.depthTest );
  14181. _this.setDepthWrite( material.depthWrite );
  14182. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14183. }
  14184. _this.renderImmediateObject( camera, lights, fog, material, object );
  14185. }
  14186. }
  14187. };
  14188. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  14189. var program = setProgram( camera, lights, fog, material, object );
  14190. _currentGeometryGroupHash = -1;
  14191. _this.setMaterialFaces( material );
  14192. if ( object.immediateRenderCallback ) {
  14193. object.immediateRenderCallback( program, _gl, _frustum );
  14194. } else {
  14195. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  14196. }
  14197. };
  14198. function unrollImmediateBufferMaterial ( globject ) {
  14199. var object = globject.object,
  14200. material = object.material;
  14201. if ( material.transparent ) {
  14202. globject.transparent = material;
  14203. globject.opaque = null;
  14204. } else {
  14205. globject.opaque = material;
  14206. globject.transparent = null;
  14207. }
  14208. };
  14209. function unrollBufferMaterial ( globject ) {
  14210. var object = globject.object,
  14211. buffer = globject.buffer,
  14212. material, materialIndex, meshMaterial;
  14213. meshMaterial = object.material;
  14214. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  14215. materialIndex = buffer.materialIndex;
  14216. material = meshMaterial.materials[ materialIndex ];
  14217. if ( material.transparent ) {
  14218. globject.transparent = material;
  14219. globject.opaque = null;
  14220. } else {
  14221. globject.opaque = material;
  14222. globject.transparent = null;
  14223. }
  14224. } else {
  14225. material = meshMaterial;
  14226. if ( material ) {
  14227. if ( material.transparent ) {
  14228. globject.transparent = material;
  14229. globject.opaque = null;
  14230. } else {
  14231. globject.opaque = material;
  14232. globject.transparent = null;
  14233. }
  14234. }
  14235. }
  14236. };
  14237. // Geometry splitting
  14238. function sortFacesByMaterial ( geometry, material ) {
  14239. var f, fl, face, materialIndex, vertices,
  14240. groupHash, hash_map = {};
  14241. var numMorphTargets = geometry.morphTargets.length;
  14242. var numMorphNormals = geometry.morphNormals.length;
  14243. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  14244. geometry.geometryGroups = {};
  14245. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  14246. face = geometry.faces[ f ];
  14247. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  14248. if ( hash_map[ materialIndex ] === undefined ) {
  14249. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  14250. }
  14251. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  14252. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  14253. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  14254. }
  14255. vertices = face instanceof THREE.Face3 ? 3 : 4;
  14256. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  14257. hash_map[ materialIndex ].counter += 1;
  14258. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  14259. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  14260. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  14261. }
  14262. }
  14263. if ( face instanceof THREE.Face3 ) {
  14264. geometry.geometryGroups[ groupHash ].faces3.push( f );
  14265. } else {
  14266. geometry.geometryGroups[ groupHash ].faces4.push( f );
  14267. }
  14268. geometry.geometryGroups[ groupHash ].vertices += vertices;
  14269. }
  14270. geometry.geometryGroupsList = [];
  14271. for ( var g in geometry.geometryGroups ) {
  14272. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  14273. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  14274. }
  14275. };
  14276. // Objects refresh
  14277. this.initWebGLObjects = function ( scene ) {
  14278. if ( !scene.__webglObjects ) {
  14279. scene.__webglObjects = [];
  14280. scene.__webglObjectsImmediate = [];
  14281. scene.__webglSprites = [];
  14282. scene.__webglFlares = [];
  14283. }
  14284. while ( scene.__objectsAdded.length ) {
  14285. addObject( scene.__objectsAdded[ 0 ], scene );
  14286. scene.__objectsAdded.splice( 0, 1 );
  14287. }
  14288. while ( scene.__objectsRemoved.length ) {
  14289. removeObject( scene.__objectsRemoved[ 0 ], scene );
  14290. scene.__objectsRemoved.splice( 0, 1 );
  14291. }
  14292. // update must be called after objects adding / removal
  14293. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  14294. var object = scene.__webglObjects[ o ].object;
  14295. // TODO: Remove this hack (WebGLRenderer refactoring)
  14296. if ( object.__webglInit === undefined ) {
  14297. if ( object.__webglActive !== undefined ) {
  14298. removeObject( object, scene );
  14299. }
  14300. addObject( object, scene );
  14301. }
  14302. updateObject( object );
  14303. }
  14304. };
  14305. // Objects adding
  14306. function addObject( object, scene ) {
  14307. var g, geometry, material, geometryGroup;
  14308. if ( object.__webglInit === undefined ) {
  14309. object.__webglInit = true;
  14310. object._modelViewMatrix = new THREE.Matrix4();
  14311. object._normalMatrix = new THREE.Matrix3();
  14312. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  14313. object.geometry.__webglInit = true;
  14314. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  14315. }
  14316. geometry = object.geometry;
  14317. if ( geometry === undefined ) {
  14318. // fail silently for now
  14319. } else if ( geometry instanceof THREE.BufferGeometry ) {
  14320. initDirectBuffers( geometry );
  14321. } else if ( object instanceof THREE.Mesh ) {
  14322. material = object.material;
  14323. if ( geometry.geometryGroups === undefined ) {
  14324. sortFacesByMaterial( geometry, material );
  14325. }
  14326. // create separate VBOs per geometry chunk
  14327. for ( g in geometry.geometryGroups ) {
  14328. geometryGroup = geometry.geometryGroups[ g ];
  14329. // initialise VBO on the first access
  14330. if ( ! geometryGroup.__webglVertexBuffer ) {
  14331. createMeshBuffers( geometryGroup );
  14332. initMeshBuffers( geometryGroup, object );
  14333. geometry.verticesNeedUpdate = true;
  14334. geometry.morphTargetsNeedUpdate = true;
  14335. geometry.elementsNeedUpdate = true;
  14336. geometry.uvsNeedUpdate = true;
  14337. geometry.normalsNeedUpdate = true;
  14338. geometry.tangentsNeedUpdate = true;
  14339. geometry.colorsNeedUpdate = true;
  14340. }
  14341. }
  14342. } else if ( object instanceof THREE.Ribbon ) {
  14343. if ( ! geometry.__webglVertexBuffer ) {
  14344. createRibbonBuffers( geometry );
  14345. initRibbonBuffers( geometry, object );
  14346. geometry.verticesNeedUpdate = true;
  14347. geometry.colorsNeedUpdate = true;
  14348. geometry.normalsNeedUpdate = true;
  14349. }
  14350. } else if ( object instanceof THREE.Line ) {
  14351. if ( ! geometry.__webglVertexBuffer ) {
  14352. createLineBuffers( geometry );
  14353. initLineBuffers( geometry, object );
  14354. geometry.verticesNeedUpdate = true;
  14355. geometry.colorsNeedUpdate = true;
  14356. geometry.lineDistancesNeedUpdate = true;
  14357. }
  14358. } else if ( object instanceof THREE.ParticleSystem ) {
  14359. if ( ! geometry.__webglVertexBuffer ) {
  14360. createParticleBuffers( geometry );
  14361. initParticleBuffers( geometry, object );
  14362. geometry.verticesNeedUpdate = true;
  14363. geometry.colorsNeedUpdate = true;
  14364. }
  14365. }
  14366. }
  14367. if ( object.__webglActive === undefined ) {
  14368. if ( object instanceof THREE.Mesh ) {
  14369. geometry = object.geometry;
  14370. if ( geometry instanceof THREE.BufferGeometry ) {
  14371. addBuffer( scene.__webglObjects, geometry, object );
  14372. } else if ( geometry instanceof THREE.Geometry ) {
  14373. for ( g in geometry.geometryGroups ) {
  14374. geometryGroup = geometry.geometryGroups[ g ];
  14375. addBuffer( scene.__webglObjects, geometryGroup, object );
  14376. }
  14377. }
  14378. } else if ( object instanceof THREE.Ribbon ||
  14379. object instanceof THREE.Line ||
  14380. object instanceof THREE.ParticleSystem ) {
  14381. geometry = object.geometry;
  14382. addBuffer( scene.__webglObjects, geometry, object );
  14383. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14384. addBufferImmediate( scene.__webglObjectsImmediate, object );
  14385. } else if ( object instanceof THREE.Sprite ) {
  14386. scene.__webglSprites.push( object );
  14387. } else if ( object instanceof THREE.LensFlare ) {
  14388. scene.__webglFlares.push( object );
  14389. }
  14390. object.__webglActive = true;
  14391. }
  14392. };
  14393. function addBuffer( objlist, buffer, object ) {
  14394. objlist.push(
  14395. {
  14396. id: null,
  14397. buffer: buffer,
  14398. object: object,
  14399. opaque: null,
  14400. transparent: null,
  14401. z: 0
  14402. }
  14403. );
  14404. };
  14405. function addBufferImmediate( objlist, object ) {
  14406. objlist.push(
  14407. {
  14408. id: null,
  14409. object: object,
  14410. opaque: null,
  14411. transparent: null,
  14412. z: 0
  14413. }
  14414. );
  14415. };
  14416. // Objects updates
  14417. function updateObject( object ) {
  14418. var geometry = object.geometry,
  14419. geometryGroup, customAttributesDirty, material;
  14420. if ( geometry instanceof THREE.BufferGeometry ) {
  14421. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  14422. } else if ( object instanceof THREE.Mesh ) {
  14423. // check all geometry groups
  14424. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  14425. geometryGroup = geometry.geometryGroupsList[ i ];
  14426. material = getBufferMaterial( object, geometryGroup );
  14427. if ( geometry.buffersNeedUpdate ) {
  14428. initMeshBuffers( geometryGroup, object );
  14429. }
  14430. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14431. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  14432. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  14433. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  14434. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  14435. }
  14436. }
  14437. geometry.verticesNeedUpdate = false;
  14438. geometry.morphTargetsNeedUpdate = false;
  14439. geometry.elementsNeedUpdate = false;
  14440. geometry.uvsNeedUpdate = false;
  14441. geometry.normalsNeedUpdate = false;
  14442. geometry.colorsNeedUpdate = false;
  14443. geometry.tangentsNeedUpdate = false;
  14444. geometry.buffersNeedUpdate = false;
  14445. material.attributes && clearCustomAttributes( material );
  14446. } else if ( object instanceof THREE.Ribbon ) {
  14447. material = getBufferMaterial( object, geometry );
  14448. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14449. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  14450. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  14451. }
  14452. geometry.verticesNeedUpdate = false;
  14453. geometry.colorsNeedUpdate = false;
  14454. geometry.normalsNeedUpdate = false;
  14455. material.attributes && clearCustomAttributes( material );
  14456. } else if ( object instanceof THREE.Line ) {
  14457. material = getBufferMaterial( object, geometry );
  14458. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14459. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  14460. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  14461. }
  14462. geometry.verticesNeedUpdate = false;
  14463. geometry.colorsNeedUpdate = false;
  14464. geometry.lineDistancesNeedUpdate = false;
  14465. material.attributes && clearCustomAttributes( material );
  14466. } else if ( object instanceof THREE.ParticleSystem ) {
  14467. material = getBufferMaterial( object, geometry );
  14468. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14469. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  14470. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  14471. }
  14472. geometry.verticesNeedUpdate = false;
  14473. geometry.colorsNeedUpdate = false;
  14474. material.attributes && clearCustomAttributes( material );
  14475. }
  14476. };
  14477. // Objects updates - custom attributes check
  14478. function areCustomAttributesDirty( material ) {
  14479. for ( var a in material.attributes ) {
  14480. if ( material.attributes[ a ].needsUpdate ) return true;
  14481. }
  14482. return false;
  14483. };
  14484. function clearCustomAttributes( material ) {
  14485. for ( var a in material.attributes ) {
  14486. material.attributes[ a ].needsUpdate = false;
  14487. }
  14488. };
  14489. // Objects removal
  14490. function removeObject( object, scene ) {
  14491. if ( object instanceof THREE.Mesh ||
  14492. object instanceof THREE.ParticleSystem ||
  14493. object instanceof THREE.Ribbon ||
  14494. object instanceof THREE.Line ) {
  14495. removeInstances( scene.__webglObjects, object );
  14496. } else if ( object instanceof THREE.Sprite ) {
  14497. removeInstancesDirect( scene.__webglSprites, object );
  14498. } else if ( object instanceof THREE.LensFlare ) {
  14499. removeInstancesDirect( scene.__webglFlares, object );
  14500. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14501. removeInstances( scene.__webglObjectsImmediate, object );
  14502. }
  14503. delete object.__webglActive;
  14504. };
  14505. function removeInstances( objlist, object ) {
  14506. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14507. if ( objlist[ o ].object === object ) {
  14508. objlist.splice( o, 1 );
  14509. }
  14510. }
  14511. };
  14512. function removeInstancesDirect( objlist, object ) {
  14513. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14514. if ( objlist[ o ] === object ) {
  14515. objlist.splice( o, 1 );
  14516. }
  14517. }
  14518. };
  14519. // Materials
  14520. this.initMaterial = function ( material, lights, fog, object ) {
  14521. material.addEventListener( 'dispose', onMaterialDispose );
  14522. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  14523. if ( material instanceof THREE.MeshDepthMaterial ) {
  14524. shaderID = 'depth';
  14525. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14526. shaderID = 'normal';
  14527. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  14528. shaderID = 'basic';
  14529. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14530. shaderID = 'lambert';
  14531. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14532. shaderID = 'phong';
  14533. } else if ( material instanceof THREE.LineBasicMaterial ) {
  14534. shaderID = 'basic';
  14535. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14536. shaderID = 'dashed';
  14537. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  14538. shaderID = 'particle_basic';
  14539. }
  14540. if ( shaderID ) {
  14541. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  14542. }
  14543. // heuristics to create shader parameters according to lights in the scene
  14544. // (not to blow over maxLights budget)
  14545. maxLightCount = allocateLights( lights );
  14546. maxShadows = allocateShadows( lights );
  14547. maxBones = allocateBones( object );
  14548. parameters = {
  14549. map: !!material.map,
  14550. envMap: !!material.envMap,
  14551. lightMap: !!material.lightMap,
  14552. bumpMap: !!material.bumpMap,
  14553. normalMap: !!material.normalMap,
  14554. specularMap: !!material.specularMap,
  14555. vertexColors: material.vertexColors,
  14556. fog: fog,
  14557. useFog: material.fog,
  14558. fogExp: fog instanceof THREE.FogExp2,
  14559. sizeAttenuation: material.sizeAttenuation,
  14560. skinning: material.skinning,
  14561. maxBones: maxBones,
  14562. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  14563. boneTextureWidth: object && object.boneTextureWidth,
  14564. boneTextureHeight: object && object.boneTextureHeight,
  14565. morphTargets: material.morphTargets,
  14566. morphNormals: material.morphNormals,
  14567. maxMorphTargets: this.maxMorphTargets,
  14568. maxMorphNormals: this.maxMorphNormals,
  14569. maxDirLights: maxLightCount.directional,
  14570. maxPointLights: maxLightCount.point,
  14571. maxSpotLights: maxLightCount.spot,
  14572. maxHemiLights: maxLightCount.hemi,
  14573. maxShadows: maxShadows,
  14574. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  14575. shadowMapType: this.shadowMapType,
  14576. shadowMapDebug: this.shadowMapDebug,
  14577. shadowMapCascade: this.shadowMapCascade,
  14578. alphaTest: material.alphaTest,
  14579. metal: material.metal,
  14580. perPixel: material.perPixel,
  14581. wrapAround: material.wrapAround,
  14582. doubleSided: material.side === THREE.DoubleSide,
  14583. flipSided: material.side === THREE.BackSide
  14584. };
  14585. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  14586. var attributes = material.program.attributes;
  14587. if ( material.morphTargets ) {
  14588. material.numSupportedMorphTargets = 0;
  14589. var id, base = "morphTarget";
  14590. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  14591. id = base + i;
  14592. if ( attributes[ id ] >= 0 ) {
  14593. material.numSupportedMorphTargets ++;
  14594. }
  14595. }
  14596. }
  14597. if ( material.morphNormals ) {
  14598. material.numSupportedMorphNormals = 0;
  14599. var id, base = "morphNormal";
  14600. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  14601. id = base + i;
  14602. if ( attributes[ id ] >= 0 ) {
  14603. material.numSupportedMorphNormals ++;
  14604. }
  14605. }
  14606. }
  14607. material.uniformsList = [];
  14608. for ( u in material.uniforms ) {
  14609. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  14610. }
  14611. };
  14612. function setMaterialShaders( material, shaders ) {
  14613. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  14614. material.vertexShader = shaders.vertexShader;
  14615. material.fragmentShader = shaders.fragmentShader;
  14616. };
  14617. function setProgram( camera, lights, fog, material, object ) {
  14618. _usedTextureUnits = 0;
  14619. if ( material.needsUpdate ) {
  14620. if ( material.program ) deallocateMaterial( material );
  14621. _this.initMaterial( material, lights, fog, object );
  14622. material.needsUpdate = false;
  14623. }
  14624. if ( material.morphTargets ) {
  14625. if ( ! object.__webglMorphTargetInfluences ) {
  14626. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  14627. }
  14628. }
  14629. var refreshMaterial = false;
  14630. var program = material.program,
  14631. p_uniforms = program.uniforms,
  14632. m_uniforms = material.uniforms;
  14633. if ( program !== _currentProgram ) {
  14634. _gl.useProgram( program );
  14635. _currentProgram = program;
  14636. refreshMaterial = true;
  14637. }
  14638. if ( material.id !== _currentMaterialId ) {
  14639. _currentMaterialId = material.id;
  14640. refreshMaterial = true;
  14641. }
  14642. if ( refreshMaterial || camera !== _currentCamera ) {
  14643. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  14644. if ( camera !== _currentCamera ) _currentCamera = camera;
  14645. }
  14646. // skinning uniforms must be set even if material didn't change
  14647. // auto-setting of texture unit for bone texture must go before other textures
  14648. // not sure why, but otherwise weird things happen
  14649. if ( material.skinning ) {
  14650. if ( _supportsBoneTextures && object.useVertexTexture ) {
  14651. if ( p_uniforms.boneTexture !== null ) {
  14652. var textureUnit = getTextureUnit();
  14653. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  14654. _this.setTexture( object.boneTexture, textureUnit );
  14655. }
  14656. } else {
  14657. if ( p_uniforms.boneGlobalMatrices !== null ) {
  14658. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  14659. }
  14660. }
  14661. }
  14662. if ( refreshMaterial ) {
  14663. // refresh uniforms common to several materials
  14664. if ( fog && material.fog ) {
  14665. refreshUniformsFog( m_uniforms, fog );
  14666. }
  14667. if ( material instanceof THREE.MeshPhongMaterial ||
  14668. material instanceof THREE.MeshLambertMaterial ||
  14669. material.lights ) {
  14670. if ( _lightsNeedUpdate ) {
  14671. setupLights( program, lights );
  14672. _lightsNeedUpdate = false;
  14673. }
  14674. refreshUniformsLights( m_uniforms, _lights );
  14675. }
  14676. if ( material instanceof THREE.MeshBasicMaterial ||
  14677. material instanceof THREE.MeshLambertMaterial ||
  14678. material instanceof THREE.MeshPhongMaterial ) {
  14679. refreshUniformsCommon( m_uniforms, material );
  14680. }
  14681. // refresh single material specific uniforms
  14682. if ( material instanceof THREE.LineBasicMaterial ) {
  14683. refreshUniformsLine( m_uniforms, material );
  14684. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14685. refreshUniformsLine( m_uniforms, material );
  14686. refreshUniformsDash( m_uniforms, material );
  14687. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  14688. refreshUniformsParticle( m_uniforms, material );
  14689. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14690. refreshUniformsPhong( m_uniforms, material );
  14691. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14692. refreshUniformsLambert( m_uniforms, material );
  14693. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  14694. m_uniforms.mNear.value = camera.near;
  14695. m_uniforms.mFar.value = camera.far;
  14696. m_uniforms.opacity.value = material.opacity;
  14697. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14698. m_uniforms.opacity.value = material.opacity;
  14699. }
  14700. if ( object.receiveShadow && ! material._shadowPass ) {
  14701. refreshUniformsShadow( m_uniforms, lights );
  14702. }
  14703. // load common uniforms
  14704. loadUniformsGeneric( program, material.uniformsList );
  14705. // load material specific uniforms
  14706. // (shader material also gets them for the sake of genericity)
  14707. if ( material instanceof THREE.ShaderMaterial ||
  14708. material instanceof THREE.MeshPhongMaterial ||
  14709. material.envMap ) {
  14710. if ( p_uniforms.cameraPosition !== null ) {
  14711. _vector3.getPositionFromMatrix( camera.matrixWorld );
  14712. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  14713. }
  14714. }
  14715. if ( material instanceof THREE.MeshPhongMaterial ||
  14716. material instanceof THREE.MeshLambertMaterial ||
  14717. material instanceof THREE.ShaderMaterial ||
  14718. material.skinning ) {
  14719. if ( p_uniforms.viewMatrix !== null ) {
  14720. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  14721. }
  14722. }
  14723. }
  14724. loadUniformsMatrices( p_uniforms, object );
  14725. if ( p_uniforms.modelMatrix !== null ) {
  14726. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  14727. }
  14728. return program;
  14729. };
  14730. // Uniforms (refresh uniforms objects)
  14731. function refreshUniformsCommon ( uniforms, material ) {
  14732. uniforms.opacity.value = material.opacity;
  14733. if ( _this.gammaInput ) {
  14734. uniforms.diffuse.value.copyGammaToLinear( material.color );
  14735. } else {
  14736. uniforms.diffuse.value = material.color;
  14737. }
  14738. uniforms.map.value = material.map;
  14739. uniforms.lightMap.value = material.lightMap;
  14740. uniforms.specularMap.value = material.specularMap;
  14741. if ( material.bumpMap ) {
  14742. uniforms.bumpMap.value = material.bumpMap;
  14743. uniforms.bumpScale.value = material.bumpScale;
  14744. }
  14745. if ( material.normalMap ) {
  14746. uniforms.normalMap.value = material.normalMap;
  14747. uniforms.normalScale.value.copy( material.normalScale );
  14748. }
  14749. // uv repeat and offset setting priorities
  14750. // 1. color map
  14751. // 2. specular map
  14752. // 3. normal map
  14753. // 4. bump map
  14754. var uvScaleMap;
  14755. if ( material.map ) {
  14756. uvScaleMap = material.map;
  14757. } else if ( material.specularMap ) {
  14758. uvScaleMap = material.specularMap;
  14759. } else if ( material.normalMap ) {
  14760. uvScaleMap = material.normalMap;
  14761. } else if ( material.bumpMap ) {
  14762. uvScaleMap = material.bumpMap;
  14763. }
  14764. if ( uvScaleMap !== undefined ) {
  14765. var offset = uvScaleMap.offset;
  14766. var repeat = uvScaleMap.repeat;
  14767. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  14768. }
  14769. uniforms.envMap.value = material.envMap;
  14770. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  14771. if ( _this.gammaInput ) {
  14772. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  14773. uniforms.reflectivity.value = material.reflectivity;
  14774. } else {
  14775. uniforms.reflectivity.value = material.reflectivity;
  14776. }
  14777. uniforms.refractionRatio.value = material.refractionRatio;
  14778. uniforms.combine.value = material.combine;
  14779. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  14780. };
  14781. function refreshUniformsLine ( uniforms, material ) {
  14782. uniforms.diffuse.value = material.color;
  14783. uniforms.opacity.value = material.opacity;
  14784. };
  14785. function refreshUniformsDash ( uniforms, material ) {
  14786. uniforms.dashSize.value = material.dashSize;
  14787. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14788. uniforms.scale.value = material.scale;
  14789. };
  14790. function refreshUniformsParticle ( uniforms, material ) {
  14791. uniforms.psColor.value = material.color;
  14792. uniforms.opacity.value = material.opacity;
  14793. uniforms.size.value = material.size;
  14794. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  14795. uniforms.map.value = material.map;
  14796. };
  14797. function refreshUniformsFog ( uniforms, fog ) {
  14798. uniforms.fogColor.value = fog.color;
  14799. if ( fog instanceof THREE.Fog ) {
  14800. uniforms.fogNear.value = fog.near;
  14801. uniforms.fogFar.value = fog.far;
  14802. } else if ( fog instanceof THREE.FogExp2 ) {
  14803. uniforms.fogDensity.value = fog.density;
  14804. }
  14805. };
  14806. function refreshUniformsPhong ( uniforms, material ) {
  14807. uniforms.shininess.value = material.shininess;
  14808. if ( _this.gammaInput ) {
  14809. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14810. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14811. uniforms.specular.value.copyGammaToLinear( material.specular );
  14812. } else {
  14813. uniforms.ambient.value = material.ambient;
  14814. uniforms.emissive.value = material.emissive;
  14815. uniforms.specular.value = material.specular;
  14816. }
  14817. if ( material.wrapAround ) {
  14818. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14819. }
  14820. };
  14821. function refreshUniformsLambert ( uniforms, material ) {
  14822. if ( _this.gammaInput ) {
  14823. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14824. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14825. } else {
  14826. uniforms.ambient.value = material.ambient;
  14827. uniforms.emissive.value = material.emissive;
  14828. }
  14829. if ( material.wrapAround ) {
  14830. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14831. }
  14832. };
  14833. function refreshUniformsLights ( uniforms, lights ) {
  14834. uniforms.ambientLightColor.value = lights.ambient;
  14835. uniforms.directionalLightColor.value = lights.directional.colors;
  14836. uniforms.directionalLightDirection.value = lights.directional.positions;
  14837. uniforms.pointLightColor.value = lights.point.colors;
  14838. uniforms.pointLightPosition.value = lights.point.positions;
  14839. uniforms.pointLightDistance.value = lights.point.distances;
  14840. uniforms.spotLightColor.value = lights.spot.colors;
  14841. uniforms.spotLightPosition.value = lights.spot.positions;
  14842. uniforms.spotLightDistance.value = lights.spot.distances;
  14843. uniforms.spotLightDirection.value = lights.spot.directions;
  14844. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  14845. uniforms.spotLightExponent.value = lights.spot.exponents;
  14846. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  14847. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  14848. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  14849. };
  14850. function refreshUniformsShadow ( uniforms, lights ) {
  14851. if ( uniforms.shadowMatrix ) {
  14852. var j = 0;
  14853. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14854. var light = lights[ i ];
  14855. if ( ! light.castShadow ) continue;
  14856. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  14857. uniforms.shadowMap.value[ j ] = light.shadowMap;
  14858. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  14859. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  14860. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  14861. uniforms.shadowBias.value[ j ] = light.shadowBias;
  14862. j ++;
  14863. }
  14864. }
  14865. }
  14866. };
  14867. // Uniforms (load to GPU)
  14868. function loadUniformsMatrices ( uniforms, object ) {
  14869. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14870. if ( uniforms.normalMatrix ) {
  14871. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14872. }
  14873. };
  14874. function getTextureUnit() {
  14875. var textureUnit = _usedTextureUnits;
  14876. if ( textureUnit >= _maxTextures ) {
  14877. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  14878. }
  14879. _usedTextureUnits += 1;
  14880. return textureUnit;
  14881. };
  14882. function loadUniformsGeneric ( program, uniforms ) {
  14883. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  14884. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14885. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14886. if ( !location ) continue;
  14887. uniform = uniforms[ j ][ 0 ];
  14888. type = uniform.type;
  14889. value = uniform.value;
  14890. if ( type === "i" ) { // single integer
  14891. _gl.uniform1i( location, value );
  14892. } else if ( type === "f" ) { // single float
  14893. _gl.uniform1f( location, value );
  14894. } else if ( type === "v2" ) { // single THREE.Vector2
  14895. _gl.uniform2f( location, value.x, value.y );
  14896. } else if ( type === "v3" ) { // single THREE.Vector3
  14897. _gl.uniform3f( location, value.x, value.y, value.z );
  14898. } else if ( type === "v4" ) { // single THREE.Vector4
  14899. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14900. } else if ( type === "c" ) { // single THREE.Color
  14901. _gl.uniform3f( location, value.r, value.g, value.b );
  14902. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  14903. _gl.uniform1iv( location, value );
  14904. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  14905. _gl.uniform3iv( location, value );
  14906. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  14907. _gl.uniform1fv( location, value );
  14908. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  14909. _gl.uniform3fv( location, value );
  14910. } else if ( type === "v2v" ) { // array of THREE.Vector2
  14911. if ( uniform._array === undefined ) {
  14912. uniform._array = new Float32Array( 2 * value.length );
  14913. }
  14914. for ( i = 0, il = value.length; i < il; i ++ ) {
  14915. offset = i * 2;
  14916. uniform._array[ offset ] = value[ i ].x;
  14917. uniform._array[ offset + 1 ] = value[ i ].y;
  14918. }
  14919. _gl.uniform2fv( location, uniform._array );
  14920. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14921. if ( uniform._array === undefined ) {
  14922. uniform._array = new Float32Array( 3 * value.length );
  14923. }
  14924. for ( i = 0, il = value.length; i < il; i ++ ) {
  14925. offset = i * 3;
  14926. uniform._array[ offset ] = value[ i ].x;
  14927. uniform._array[ offset + 1 ] = value[ i ].y;
  14928. uniform._array[ offset + 2 ] = value[ i ].z;
  14929. }
  14930. _gl.uniform3fv( location, uniform._array );
  14931. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14932. if ( uniform._array === undefined ) {
  14933. uniform._array = new Float32Array( 4 * value.length );
  14934. }
  14935. for ( i = 0, il = value.length; i < il; i ++ ) {
  14936. offset = i * 4;
  14937. uniform._array[ offset ] = value[ i ].x;
  14938. uniform._array[ offset + 1 ] = value[ i ].y;
  14939. uniform._array[ offset + 2 ] = value[ i ].z;
  14940. uniform._array[ offset + 3 ] = value[ i ].w;
  14941. }
  14942. _gl.uniform4fv( location, uniform._array );
  14943. } else if ( type === "m4") { // single THREE.Matrix4
  14944. if ( uniform._array === undefined ) {
  14945. uniform._array = new Float32Array( 16 );
  14946. }
  14947. value.flattenToArray( uniform._array );
  14948. _gl.uniformMatrix4fv( location, false, uniform._array );
  14949. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14950. if ( uniform._array === undefined ) {
  14951. uniform._array = new Float32Array( 16 * value.length );
  14952. }
  14953. for ( i = 0, il = value.length; i < il; i ++ ) {
  14954. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14955. }
  14956. _gl.uniformMatrix4fv( location, false, uniform._array );
  14957. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14958. texture = value;
  14959. textureUnit = getTextureUnit();
  14960. _gl.uniform1i( location, textureUnit );
  14961. if ( !texture ) continue;
  14962. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  14963. setCubeTexture( texture, textureUnit );
  14964. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14965. setCubeTextureDynamic( texture, textureUnit );
  14966. } else {
  14967. _this.setTexture( texture, textureUnit );
  14968. }
  14969. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  14970. if ( uniform._array === undefined ) {
  14971. uniform._array = [];
  14972. }
  14973. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14974. uniform._array[ i ] = getTextureUnit();
  14975. }
  14976. _gl.uniform1iv( location, uniform._array );
  14977. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14978. texture = uniform.value[ i ];
  14979. textureUnit = uniform._array[ i ];
  14980. if ( !texture ) continue;
  14981. _this.setTexture( texture, textureUnit );
  14982. }
  14983. } else {
  14984. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  14985. }
  14986. }
  14987. };
  14988. function setupMatrices ( object, camera ) {
  14989. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14990. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  14991. };
  14992. //
  14993. function setColorGamma( array, offset, color, intensitySq ) {
  14994. array[ offset ] = color.r * color.r * intensitySq;
  14995. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14996. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14997. };
  14998. function setColorLinear( array, offset, color, intensity ) {
  14999. array[ offset ] = color.r * intensity;
  15000. array[ offset + 1 ] = color.g * intensity;
  15001. array[ offset + 2 ] = color.b * intensity;
  15002. };
  15003. function setupLights ( program, lights ) {
  15004. var l, ll, light, n,
  15005. r = 0, g = 0, b = 0,
  15006. color, skyColor, groundColor,
  15007. intensity, intensitySq,
  15008. position,
  15009. distance,
  15010. zlights = _lights,
  15011. dirColors = zlights.directional.colors,
  15012. dirPositions = zlights.directional.positions,
  15013. pointColors = zlights.point.colors,
  15014. pointPositions = zlights.point.positions,
  15015. pointDistances = zlights.point.distances,
  15016. spotColors = zlights.spot.colors,
  15017. spotPositions = zlights.spot.positions,
  15018. spotDistances = zlights.spot.distances,
  15019. spotDirections = zlights.spot.directions,
  15020. spotAnglesCos = zlights.spot.anglesCos,
  15021. spotExponents = zlights.spot.exponents,
  15022. hemiSkyColors = zlights.hemi.skyColors,
  15023. hemiGroundColors = zlights.hemi.groundColors,
  15024. hemiPositions = zlights.hemi.positions,
  15025. dirLength = 0,
  15026. pointLength = 0,
  15027. spotLength = 0,
  15028. hemiLength = 0,
  15029. dirCount = 0,
  15030. pointCount = 0,
  15031. spotCount = 0,
  15032. hemiCount = 0,
  15033. dirOffset = 0,
  15034. pointOffset = 0,
  15035. spotOffset = 0,
  15036. hemiOffset = 0;
  15037. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  15038. light = lights[ l ];
  15039. if ( light.onlyShadow ) continue;
  15040. color = light.color;
  15041. intensity = light.intensity;
  15042. distance = light.distance;
  15043. if ( light instanceof THREE.AmbientLight ) {
  15044. if ( ! light.visible ) continue;
  15045. if ( _this.gammaInput ) {
  15046. r += color.r * color.r;
  15047. g += color.g * color.g;
  15048. b += color.b * color.b;
  15049. } else {
  15050. r += color.r;
  15051. g += color.g;
  15052. b += color.b;
  15053. }
  15054. } else if ( light instanceof THREE.DirectionalLight ) {
  15055. dirCount += 1;
  15056. if ( ! light.visible ) continue;
  15057. _direction.getPositionFromMatrix( light.matrixWorld );
  15058. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  15059. _direction.sub( _vector3 );
  15060. _direction.normalize();
  15061. // skip lights with undefined direction
  15062. // these create troubles in OpenGL (making pixel black)
  15063. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  15064. dirOffset = dirLength * 3;
  15065. dirPositions[ dirOffset ] = _direction.x;
  15066. dirPositions[ dirOffset + 1 ] = _direction.y;
  15067. dirPositions[ dirOffset + 2 ] = _direction.z;
  15068. if ( _this.gammaInput ) {
  15069. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  15070. } else {
  15071. setColorLinear( dirColors, dirOffset, color, intensity );
  15072. }
  15073. dirLength += 1;
  15074. } else if ( light instanceof THREE.PointLight ) {
  15075. pointCount += 1;
  15076. if ( ! light.visible ) continue;
  15077. pointOffset = pointLength * 3;
  15078. if ( _this.gammaInput ) {
  15079. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  15080. } else {
  15081. setColorLinear( pointColors, pointOffset, color, intensity );
  15082. }
  15083. _vector3.getPositionFromMatrix( light.matrixWorld );
  15084. pointPositions[ pointOffset ] = _vector3.x;
  15085. pointPositions[ pointOffset + 1 ] = _vector3.y;
  15086. pointPositions[ pointOffset + 2 ] = _vector3.z;
  15087. pointDistances[ pointLength ] = distance;
  15088. pointLength += 1;
  15089. } else if ( light instanceof THREE.SpotLight ) {
  15090. spotCount += 1;
  15091. if ( ! light.visible ) continue;
  15092. spotOffset = spotLength * 3;
  15093. if ( _this.gammaInput ) {
  15094. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  15095. } else {
  15096. setColorLinear( spotColors, spotOffset, color, intensity );
  15097. }
  15098. _vector3.getPositionFromMatrix( light.matrixWorld );
  15099. spotPositions[ spotOffset ] = _vector3.x;
  15100. spotPositions[ spotOffset + 1 ] = _vector3.y;
  15101. spotPositions[ spotOffset + 2 ] = _vector3.z;
  15102. spotDistances[ spotLength ] = distance;
  15103. _direction.copy( _vector3 );
  15104. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  15105. _direction.sub( _vector3 );
  15106. _direction.normalize();
  15107. spotDirections[ spotOffset ] = _direction.x;
  15108. spotDirections[ spotOffset + 1 ] = _direction.y;
  15109. spotDirections[ spotOffset + 2 ] = _direction.z;
  15110. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  15111. spotExponents[ spotLength ] = light.exponent;
  15112. spotLength += 1;
  15113. } else if ( light instanceof THREE.HemisphereLight ) {
  15114. hemiCount += 1;
  15115. if ( ! light.visible ) continue;
  15116. _direction.getPositionFromMatrix( light.matrixWorld );
  15117. _direction.normalize();
  15118. // skip lights with undefined direction
  15119. // these create troubles in OpenGL (making pixel black)
  15120. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  15121. hemiOffset = hemiLength * 3;
  15122. hemiPositions[ hemiOffset ] = _direction.x;
  15123. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  15124. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  15125. skyColor = light.color;
  15126. groundColor = light.groundColor;
  15127. if ( _this.gammaInput ) {
  15128. intensitySq = intensity * intensity;
  15129. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  15130. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  15131. } else {
  15132. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  15133. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  15134. }
  15135. hemiLength += 1;
  15136. }
  15137. }
  15138. // null eventual remains from removed lights
  15139. // (this is to avoid if in shader)
  15140. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  15141. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  15142. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  15143. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  15144. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  15145. zlights.directional.length = dirLength;
  15146. zlights.point.length = pointLength;
  15147. zlights.spot.length = spotLength;
  15148. zlights.hemi.length = hemiLength;
  15149. zlights.ambient[ 0 ] = r;
  15150. zlights.ambient[ 1 ] = g;
  15151. zlights.ambient[ 2 ] = b;
  15152. };
  15153. // GL state setting
  15154. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  15155. if ( cullFace === THREE.CullFaceNone ) {
  15156. _gl.disable( _gl.CULL_FACE );
  15157. } else {
  15158. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  15159. _gl.frontFace( _gl.CW );
  15160. } else {
  15161. _gl.frontFace( _gl.CCW );
  15162. }
  15163. if ( cullFace === THREE.CullFaceBack ) {
  15164. _gl.cullFace( _gl.BACK );
  15165. } else if ( cullFace === THREE.CullFaceFront ) {
  15166. _gl.cullFace( _gl.FRONT );
  15167. } else {
  15168. _gl.cullFace( _gl.FRONT_AND_BACK );
  15169. }
  15170. _gl.enable( _gl.CULL_FACE );
  15171. }
  15172. };
  15173. this.setMaterialFaces = function ( material ) {
  15174. var doubleSided = material.side === THREE.DoubleSide;
  15175. var flipSided = material.side === THREE.BackSide;
  15176. if ( _oldDoubleSided !== doubleSided ) {
  15177. if ( doubleSided ) {
  15178. _gl.disable( _gl.CULL_FACE );
  15179. } else {
  15180. _gl.enable( _gl.CULL_FACE );
  15181. }
  15182. _oldDoubleSided = doubleSided;
  15183. }
  15184. if ( _oldFlipSided !== flipSided ) {
  15185. if ( flipSided ) {
  15186. _gl.frontFace( _gl.CW );
  15187. } else {
  15188. _gl.frontFace( _gl.CCW );
  15189. }
  15190. _oldFlipSided = flipSided;
  15191. }
  15192. };
  15193. this.setDepthTest = function ( depthTest ) {
  15194. if ( _oldDepthTest !== depthTest ) {
  15195. if ( depthTest ) {
  15196. _gl.enable( _gl.DEPTH_TEST );
  15197. } else {
  15198. _gl.disable( _gl.DEPTH_TEST );
  15199. }
  15200. _oldDepthTest = depthTest;
  15201. }
  15202. };
  15203. this.setDepthWrite = function ( depthWrite ) {
  15204. if ( _oldDepthWrite !== depthWrite ) {
  15205. _gl.depthMask( depthWrite );
  15206. _oldDepthWrite = depthWrite;
  15207. }
  15208. };
  15209. function setLineWidth ( width ) {
  15210. if ( width !== _oldLineWidth ) {
  15211. _gl.lineWidth( width );
  15212. _oldLineWidth = width;
  15213. }
  15214. };
  15215. function setPolygonOffset ( polygonoffset, factor, units ) {
  15216. if ( _oldPolygonOffset !== polygonoffset ) {
  15217. if ( polygonoffset ) {
  15218. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  15219. } else {
  15220. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  15221. }
  15222. _oldPolygonOffset = polygonoffset;
  15223. }
  15224. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  15225. _gl.polygonOffset( factor, units );
  15226. _oldPolygonOffsetFactor = factor;
  15227. _oldPolygonOffsetUnits = units;
  15228. }
  15229. };
  15230. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  15231. if ( blending !== _oldBlending ) {
  15232. if ( blending === THREE.NoBlending ) {
  15233. _gl.disable( _gl.BLEND );
  15234. } else if ( blending === THREE.AdditiveBlending ) {
  15235. _gl.enable( _gl.BLEND );
  15236. _gl.blendEquation( _gl.FUNC_ADD );
  15237. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  15238. } else if ( blending === THREE.SubtractiveBlending ) {
  15239. // TODO: Find blendFuncSeparate() combination
  15240. _gl.enable( _gl.BLEND );
  15241. _gl.blendEquation( _gl.FUNC_ADD );
  15242. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  15243. } else if ( blending === THREE.MultiplyBlending ) {
  15244. // TODO: Find blendFuncSeparate() combination
  15245. _gl.enable( _gl.BLEND );
  15246. _gl.blendEquation( _gl.FUNC_ADD );
  15247. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  15248. } else if ( blending === THREE.CustomBlending ) {
  15249. _gl.enable( _gl.BLEND );
  15250. } else {
  15251. _gl.enable( _gl.BLEND );
  15252. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  15253. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  15254. }
  15255. _oldBlending = blending;
  15256. }
  15257. if ( blending === THREE.CustomBlending ) {
  15258. if ( blendEquation !== _oldBlendEquation ) {
  15259. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  15260. _oldBlendEquation = blendEquation;
  15261. }
  15262. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  15263. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  15264. _oldBlendSrc = blendSrc;
  15265. _oldBlendDst = blendDst;
  15266. }
  15267. } else {
  15268. _oldBlendEquation = null;
  15269. _oldBlendSrc = null;
  15270. _oldBlendDst = null;
  15271. }
  15272. };
  15273. // Defines
  15274. function generateDefines ( defines ) {
  15275. var value, chunk, chunks = [];
  15276. for ( var d in defines ) {
  15277. value = defines[ d ];
  15278. if ( value === false ) continue;
  15279. chunk = "#define " + d + " " + value;
  15280. chunks.push( chunk );
  15281. }
  15282. return chunks.join( "\n" );
  15283. };
  15284. // Shaders
  15285. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  15286. var p, pl, d, program, code;
  15287. var chunks = [];
  15288. // Generate code
  15289. if ( shaderID ) {
  15290. chunks.push( shaderID );
  15291. } else {
  15292. chunks.push( fragmentShader );
  15293. chunks.push( vertexShader );
  15294. }
  15295. for ( d in defines ) {
  15296. chunks.push( d );
  15297. chunks.push( defines[ d ] );
  15298. }
  15299. for ( p in parameters ) {
  15300. chunks.push( p );
  15301. chunks.push( parameters[ p ] );
  15302. }
  15303. code = chunks.join();
  15304. // Check if code has been already compiled
  15305. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  15306. var programInfo = _programs[ p ];
  15307. if ( programInfo.code === code ) {
  15308. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  15309. programInfo.usedTimes ++;
  15310. return programInfo.program;
  15311. }
  15312. }
  15313. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  15314. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  15315. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  15316. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  15317. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  15318. }
  15319. // console.log( "building new program " );
  15320. //
  15321. var customDefines = generateDefines( defines );
  15322. //
  15323. program = _gl.createProgram();
  15324. var prefix_vertex = [
  15325. "precision " + _precision + " float;",
  15326. customDefines,
  15327. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  15328. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15329. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15330. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  15331. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15332. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15333. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15334. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15335. "#define MAX_SHADOWS " + parameters.maxShadows,
  15336. "#define MAX_BONES " + parameters.maxBones,
  15337. parameters.map ? "#define USE_MAP" : "",
  15338. parameters.envMap ? "#define USE_ENVMAP" : "",
  15339. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15340. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15341. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15342. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15343. parameters.vertexColors ? "#define USE_COLOR" : "",
  15344. parameters.skinning ? "#define USE_SKINNING" : "",
  15345. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  15346. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  15347. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  15348. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  15349. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  15350. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  15351. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15352. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15353. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15354. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15355. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15356. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15357. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15358. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  15359. "uniform mat4 modelMatrix;",
  15360. "uniform mat4 modelViewMatrix;",
  15361. "uniform mat4 projectionMatrix;",
  15362. "uniform mat4 viewMatrix;",
  15363. "uniform mat3 normalMatrix;",
  15364. "uniform vec3 cameraPosition;",
  15365. "attribute vec3 position;",
  15366. "attribute vec3 normal;",
  15367. "attribute vec2 uv;",
  15368. "attribute vec2 uv2;",
  15369. "#ifdef USE_COLOR",
  15370. "attribute vec3 color;",
  15371. "#endif",
  15372. "#ifdef USE_MORPHTARGETS",
  15373. "attribute vec3 morphTarget0;",
  15374. "attribute vec3 morphTarget1;",
  15375. "attribute vec3 morphTarget2;",
  15376. "attribute vec3 morphTarget3;",
  15377. "#ifdef USE_MORPHNORMALS",
  15378. "attribute vec3 morphNormal0;",
  15379. "attribute vec3 morphNormal1;",
  15380. "attribute vec3 morphNormal2;",
  15381. "attribute vec3 morphNormal3;",
  15382. "#else",
  15383. "attribute vec3 morphTarget4;",
  15384. "attribute vec3 morphTarget5;",
  15385. "attribute vec3 morphTarget6;",
  15386. "attribute vec3 morphTarget7;",
  15387. "#endif",
  15388. "#endif",
  15389. "#ifdef USE_SKINNING",
  15390. "attribute vec4 skinIndex;",
  15391. "attribute vec4 skinWeight;",
  15392. "#endif",
  15393. ""
  15394. ].join("\n");
  15395. var prefix_fragment = [
  15396. "precision " + _precision + " float;",
  15397. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  15398. customDefines,
  15399. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15400. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15401. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15402. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15403. "#define MAX_SHADOWS " + parameters.maxShadows,
  15404. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  15405. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15406. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15407. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  15408. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  15409. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  15410. parameters.map ? "#define USE_MAP" : "",
  15411. parameters.envMap ? "#define USE_ENVMAP" : "",
  15412. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15413. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15414. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15415. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15416. parameters.vertexColors ? "#define USE_COLOR" : "",
  15417. parameters.metal ? "#define METAL" : "",
  15418. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  15419. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15420. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15421. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15422. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15423. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15424. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15425. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15426. "uniform mat4 viewMatrix;",
  15427. "uniform vec3 cameraPosition;",
  15428. ""
  15429. ].join("\n");
  15430. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  15431. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  15432. _gl.attachShader( program, glVertexShader );
  15433. _gl.attachShader( program, glFragmentShader );
  15434. _gl.linkProgram( program );
  15435. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  15436. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  15437. }
  15438. // clean up
  15439. _gl.deleteShader( glFragmentShader );
  15440. _gl.deleteShader( glVertexShader );
  15441. // console.log( prefix_fragment + fragmentShader );
  15442. // console.log( prefix_vertex + vertexShader );
  15443. program.uniforms = {};
  15444. program.attributes = {};
  15445. var identifiers, u, a, i;
  15446. // cache uniform locations
  15447. identifiers = [
  15448. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  15449. 'morphTargetInfluences'
  15450. ];
  15451. if ( parameters.useVertexTexture ) {
  15452. identifiers.push( 'boneTexture' );
  15453. } else {
  15454. identifiers.push( 'boneGlobalMatrices' );
  15455. }
  15456. for ( u in uniforms ) {
  15457. identifiers.push( u );
  15458. }
  15459. cacheUniformLocations( program, identifiers );
  15460. // cache attributes locations
  15461. identifiers = [
  15462. "position", "normal", "uv", "uv2", "tangent", "color",
  15463. "skinIndex", "skinWeight", "lineDistance"
  15464. ];
  15465. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  15466. identifiers.push( "morphTarget" + i );
  15467. }
  15468. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  15469. identifiers.push( "morphNormal" + i );
  15470. }
  15471. for ( a in attributes ) {
  15472. identifiers.push( a );
  15473. }
  15474. cacheAttributeLocations( program, identifiers );
  15475. program.id = _programs_counter ++;
  15476. _programs.push( { program: program, code: code, usedTimes: 1 } );
  15477. _this.info.memory.programs = _programs.length;
  15478. return program;
  15479. };
  15480. // Shader parameters cache
  15481. function cacheUniformLocations ( program, identifiers ) {
  15482. var i, l, id;
  15483. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  15484. id = identifiers[ i ];
  15485. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  15486. }
  15487. };
  15488. function cacheAttributeLocations ( program, identifiers ) {
  15489. var i, l, id;
  15490. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  15491. id = identifiers[ i ];
  15492. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  15493. }
  15494. };
  15495. function addLineNumbers ( string ) {
  15496. var chunks = string.split( "\n" );
  15497. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  15498. // Chrome reports shader errors on lines
  15499. // starting counting from 1
  15500. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  15501. }
  15502. return chunks.join( "\n" );
  15503. };
  15504. function getShader ( type, string ) {
  15505. var shader;
  15506. if ( type === "fragment" ) {
  15507. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  15508. } else if ( type === "vertex" ) {
  15509. shader = _gl.createShader( _gl.VERTEX_SHADER );
  15510. }
  15511. _gl.shaderSource( shader, string );
  15512. _gl.compileShader( shader );
  15513. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  15514. console.error( _gl.getShaderInfoLog( shader ) );
  15515. console.error( addLineNumbers( string ) );
  15516. return null;
  15517. }
  15518. return shader;
  15519. };
  15520. // Textures
  15521. function isPowerOfTwo ( value ) {
  15522. return ( value & ( value - 1 ) ) === 0;
  15523. };
  15524. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  15525. if ( isImagePowerOfTwo ) {
  15526. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  15527. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  15528. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  15529. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  15530. } else {
  15531. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  15532. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  15533. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  15534. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  15535. }
  15536. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  15537. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  15538. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  15539. texture.__oldAnisotropy = texture.anisotropy;
  15540. }
  15541. }
  15542. };
  15543. this.setTexture = function ( texture, slot ) {
  15544. if ( texture.needsUpdate ) {
  15545. if ( ! texture.__webglInit ) {
  15546. texture.__webglInit = true;
  15547. texture.addEventListener( 'dispose', onTextureDispose );
  15548. texture.__webglTexture = _gl.createTexture();
  15549. _this.info.memory.textures ++;
  15550. }
  15551. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15552. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15553. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15554. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  15555. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  15556. var image = texture.image,
  15557. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  15558. glFormat = paramThreeToGL( texture.format ),
  15559. glType = paramThreeToGL( texture.type );
  15560. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  15561. var mipmap, mipmaps = texture.mipmaps;
  15562. if ( texture instanceof THREE.DataTexture ) {
  15563. // use manually created mipmaps if available
  15564. // if there are no manual mipmaps
  15565. // set 0 level mipmap and then use GL to generate other mipmap levels
  15566. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15567. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15568. mipmap = mipmaps[ i ];
  15569. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15570. }
  15571. texture.generateMipmaps = false;
  15572. } else {
  15573. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  15574. }
  15575. } else if ( texture instanceof THREE.CompressedTexture ) {
  15576. // compressed textures can only use manually created mipmaps
  15577. // WebGL can't generate mipmaps for DDS textures
  15578. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15579. mipmap = mipmaps[ i ];
  15580. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15581. }
  15582. } else { // regular Texture (image, video, canvas)
  15583. // use manually created mipmaps if available
  15584. // if there are no manual mipmaps
  15585. // set 0 level mipmap and then use GL to generate other mipmap levels
  15586. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15587. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15588. mipmap = mipmaps[ i ];
  15589. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  15590. }
  15591. texture.generateMipmaps = false;
  15592. } else {
  15593. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  15594. }
  15595. }
  15596. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15597. texture.needsUpdate = false;
  15598. if ( texture.onUpdate ) texture.onUpdate();
  15599. } else {
  15600. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15601. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15602. }
  15603. };
  15604. function clampToMaxSize ( image, maxSize ) {
  15605. if ( image.width <= maxSize && image.height <= maxSize ) {
  15606. return image;
  15607. }
  15608. // Warning: Scaling through the canvas will only work with images that use
  15609. // premultiplied alpha.
  15610. var maxDimension = Math.max( image.width, image.height );
  15611. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  15612. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  15613. var canvas = document.createElement( 'canvas' );
  15614. canvas.width = newWidth;
  15615. canvas.height = newHeight;
  15616. var ctx = canvas.getContext( "2d" );
  15617. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  15618. return canvas;
  15619. }
  15620. function setCubeTexture ( texture, slot ) {
  15621. if ( texture.image.length === 6 ) {
  15622. if ( texture.needsUpdate ) {
  15623. if ( ! texture.image.__webglTextureCube ) {
  15624. texture.addEventListener( 'dispose', onTextureDispose );
  15625. texture.image.__webglTextureCube = _gl.createTexture();
  15626. _this.info.memory.textures ++;
  15627. }
  15628. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15629. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15630. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15631. var isCompressed = texture instanceof THREE.CompressedTexture;
  15632. var cubeImage = [];
  15633. for ( var i = 0; i < 6; i ++ ) {
  15634. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  15635. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  15636. } else {
  15637. cubeImage[ i ] = texture.image[ i ];
  15638. }
  15639. }
  15640. var image = cubeImage[ 0 ],
  15641. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  15642. glFormat = paramThreeToGL( texture.format ),
  15643. glType = paramThreeToGL( texture.type );
  15644. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  15645. for ( var i = 0; i < 6; i ++ ) {
  15646. if ( isCompressed ) {
  15647. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15648. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15649. mipmap = mipmaps[ j ];
  15650. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15651. }
  15652. } else {
  15653. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15654. }
  15655. }
  15656. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  15657. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15658. }
  15659. texture.needsUpdate = false;
  15660. if ( texture.onUpdate ) texture.onUpdate();
  15661. } else {
  15662. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15663. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15664. }
  15665. }
  15666. };
  15667. function setCubeTextureDynamic ( texture, slot ) {
  15668. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15669. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  15670. };
  15671. // Render targets
  15672. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  15673. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15674. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  15675. };
  15676. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  15677. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15678. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15679. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15680. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15681. /* For some reason this is not working. Defaulting to RGBA4.
  15682. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15683. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  15684. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15685. */
  15686. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15687. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15688. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15689. } else {
  15690. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15691. }
  15692. };
  15693. this.setRenderTarget = function ( renderTarget ) {
  15694. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  15695. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  15696. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  15697. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  15698. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15699. renderTarget.__webglTexture = _gl.createTexture();
  15700. _this.info.memory.textures ++;
  15701. // Setup texture, create render and frame buffers
  15702. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  15703. glFormat = paramThreeToGL( renderTarget.format ),
  15704. glType = paramThreeToGL( renderTarget.type );
  15705. if ( isCube ) {
  15706. renderTarget.__webglFramebuffer = [];
  15707. renderTarget.__webglRenderbuffer = [];
  15708. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15709. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  15710. for ( var i = 0; i < 6; i ++ ) {
  15711. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15712. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  15713. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15714. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15715. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  15716. }
  15717. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15718. } else {
  15719. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  15720. if ( renderTarget.shareDepthFrom ) {
  15721. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  15722. } else {
  15723. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  15724. }
  15725. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15726. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  15727. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15728. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  15729. if ( renderTarget.shareDepthFrom ) {
  15730. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15731. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15732. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15733. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15734. }
  15735. } else {
  15736. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15737. }
  15738. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15739. }
  15740. // Release everything
  15741. if ( isCube ) {
  15742. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15743. } else {
  15744. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15745. }
  15746. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15747. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15748. }
  15749. var framebuffer, width, height, vx, vy;
  15750. if ( renderTarget ) {
  15751. if ( isCube ) {
  15752. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15753. } else {
  15754. framebuffer = renderTarget.__webglFramebuffer;
  15755. }
  15756. width = renderTarget.width;
  15757. height = renderTarget.height;
  15758. vx = 0;
  15759. vy = 0;
  15760. } else {
  15761. framebuffer = null;
  15762. width = _viewportWidth;
  15763. height = _viewportHeight;
  15764. vx = _viewportX;
  15765. vy = _viewportY;
  15766. }
  15767. if ( framebuffer !== _currentFramebuffer ) {
  15768. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15769. _gl.viewport( vx, vy, width, height );
  15770. _currentFramebuffer = framebuffer;
  15771. }
  15772. _currentWidth = width;
  15773. _currentHeight = height;
  15774. };
  15775. function updateRenderTargetMipmap ( renderTarget ) {
  15776. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15777. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15778. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15779. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15780. } else {
  15781. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15782. _gl.generateMipmap( _gl.TEXTURE_2D );
  15783. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15784. }
  15785. };
  15786. // Fallback filters for non-power-of-2 textures
  15787. function filterFallback ( f ) {
  15788. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15789. return _gl.NEAREST;
  15790. }
  15791. return _gl.LINEAR;
  15792. };
  15793. // Map three.js constants to WebGL constants
  15794. function paramThreeToGL ( p ) {
  15795. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15796. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15797. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15798. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15799. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15800. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15801. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15802. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15803. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15804. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15805. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15806. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15807. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15808. if ( p === THREE.ByteType ) return _gl.BYTE;
  15809. if ( p === THREE.ShortType ) return _gl.SHORT;
  15810. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15811. if ( p === THREE.IntType ) return _gl.INT;
  15812. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15813. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15814. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15815. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15816. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15817. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15818. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15819. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15820. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15821. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15822. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15823. if ( p === THREE.OneFactor ) return _gl.ONE;
  15824. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15825. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15826. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15827. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15828. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15829. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15830. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15831. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15832. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15833. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15834. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15835. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15836. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15837. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15838. }
  15839. return 0;
  15840. };
  15841. // Allocations
  15842. function allocateBones ( object ) {
  15843. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  15844. return 1024;
  15845. } else {
  15846. // default for when object is not specified
  15847. // ( for example when prebuilding shader
  15848. // to be used with multiple objects )
  15849. //
  15850. // - leave some extra space for other uniforms
  15851. // - limit here is ANGLE's 254 max uniform vectors
  15852. // (up to 54 should be safe)
  15853. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15854. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15855. var maxBones = nVertexMatrices;
  15856. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15857. maxBones = Math.min( object.bones.length, maxBones );
  15858. if ( maxBones < object.bones.length ) {
  15859. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  15860. }
  15861. }
  15862. return maxBones;
  15863. }
  15864. };
  15865. function allocateLights( lights ) {
  15866. var dirLights = 0;
  15867. var pointLights = 0;
  15868. var spotLights = 0;
  15869. var hemiLights = 0;
  15870. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15871. var light = lights[ l ];
  15872. if ( light.onlyShadow ) continue;
  15873. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15874. if ( light instanceof THREE.PointLight ) pointLights ++;
  15875. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15876. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15877. }
  15878. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15879. };
  15880. function allocateShadows( lights ) {
  15881. var maxShadows = 0;
  15882. for ( var l = 0, ll = lights.length; l < ll; l++ ) {
  15883. var light = lights[ l ];
  15884. if ( ! light.castShadow ) continue;
  15885. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15886. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15887. }
  15888. return maxShadows;
  15889. };
  15890. // Initialization
  15891. function initGL() {
  15892. try {
  15893. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  15894. throw 'Error creating WebGL context.';
  15895. }
  15896. } catch ( error ) {
  15897. console.error( error );
  15898. }
  15899. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15900. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  15901. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15902. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15903. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15904. if ( ! _glExtensionTextureFloat ) {
  15905. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15906. }
  15907. if ( ! _glExtensionStandardDerivatives ) {
  15908. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15909. }
  15910. if ( ! _glExtensionTextureFilterAnisotropic ) {
  15911. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15912. }
  15913. if ( ! _glExtensionCompressedTextureS3TC ) {
  15914. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15915. }
  15916. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15917. _gl.getShaderPrecisionFormat = function() {
  15918. return {
  15919. "rangeMin" : 1,
  15920. "rangeMax" : 1,
  15921. "precision" : 1
  15922. };
  15923. }
  15924. }
  15925. };
  15926. function setDefaultGLState () {
  15927. _gl.clearColor( 0, 0, 0, 1 );
  15928. _gl.clearDepth( 1 );
  15929. _gl.clearStencil( 0 );
  15930. _gl.enable( _gl.DEPTH_TEST );
  15931. _gl.depthFunc( _gl.LEQUAL );
  15932. _gl.frontFace( _gl.CCW );
  15933. _gl.cullFace( _gl.BACK );
  15934. _gl.enable( _gl.CULL_FACE );
  15935. _gl.enable( _gl.BLEND );
  15936. _gl.blendEquation( _gl.FUNC_ADD );
  15937. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15938. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15939. };
  15940. // default plugins (order is important)
  15941. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15942. this.addPrePlugin( this.shadowMapPlugin );
  15943. this.addPostPlugin( new THREE.SpritePlugin() );
  15944. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15945. };
  15946. /**
  15947. * @author szimek / https://github.com/szimek/
  15948. * @author alteredq / http://alteredqualia.com/
  15949. */
  15950. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15951. this.width = width;
  15952. this.height = height;
  15953. options = options || {};
  15954. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15955. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15956. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15957. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15958. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15959. this.offset = new THREE.Vector2( 0, 0 );
  15960. this.repeat = new THREE.Vector2( 1, 1 );
  15961. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15962. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15963. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15964. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15965. this.generateMipmaps = true;
  15966. this.shareDepthFrom = null;
  15967. };
  15968. THREE.WebGLRenderTarget.prototype = {
  15969. constructor: THREE.WebGLRenderTarget,
  15970. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  15971. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  15972. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  15973. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  15974. clone: function () {
  15975. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15976. tmp.wrapS = this.wrapS;
  15977. tmp.wrapT = this.wrapT;
  15978. tmp.magFilter = this.magFilter;
  15979. tmp.minFilter = this.minFilter;
  15980. tmp.anisotropy = this.anisotropy;
  15981. tmp.offset.copy( this.offset );
  15982. tmp.repeat.copy( this.repeat );
  15983. tmp.format = this.format;
  15984. tmp.type = this.type;
  15985. tmp.depthBuffer = this.depthBuffer;
  15986. tmp.stencilBuffer = this.stencilBuffer;
  15987. tmp.generateMipmaps = this.generateMipmaps;
  15988. tmp.shareDepthFrom = this.shareDepthFrom;
  15989. return tmp;
  15990. },
  15991. dispose: function () {
  15992. this.dispatchEvent( { type: 'dispose' } );
  15993. }
  15994. };
  15995. /**
  15996. * @author alteredq / http://alteredqualia.com
  15997. */
  15998. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15999. THREE.WebGLRenderTarget.call( this, width, height, options );
  16000. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  16001. };
  16002. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  16003. /**
  16004. * @author mrdoob / http://mrdoob.com/
  16005. */
  16006. THREE.RenderableVertex = function () {
  16007. this.positionWorld = new THREE.Vector3();
  16008. this.positionScreen = new THREE.Vector4();
  16009. this.visible = true;
  16010. };
  16011. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  16012. this.positionWorld.copy( vertex.positionWorld );
  16013. this.positionScreen.copy( vertex.positionScreen );
  16014. };
  16015. /**
  16016. * @author mrdoob / http://mrdoob.com/
  16017. */
  16018. THREE.RenderableFace3 = function () {
  16019. this.id = 0;
  16020. this.v1 = new THREE.RenderableVertex();
  16021. this.v2 = new THREE.RenderableVertex();
  16022. this.v3 = new THREE.RenderableVertex();
  16023. this.centroidModel = new THREE.Vector3();
  16024. this.normalModel = new THREE.Vector3();
  16025. this.normalModelView = new THREE.Vector3();
  16026. this.vertexNormalsLength = 0;
  16027. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  16028. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  16029. this.color = null;
  16030. this.material = null;
  16031. this.uvs = [[]];
  16032. this.z = 0;
  16033. };
  16034. /**
  16035. * @author mrdoob / http://mrdoob.com/
  16036. */
  16037. THREE.RenderableFace4 = function () {
  16038. this.id = 0;
  16039. this.v1 = new THREE.RenderableVertex();
  16040. this.v2 = new THREE.RenderableVertex();
  16041. this.v3 = new THREE.RenderableVertex();
  16042. this.v4 = new THREE.RenderableVertex();
  16043. this.centroidModel = new THREE.Vector3();
  16044. this.normalModel = new THREE.Vector3();
  16045. this.normalModelView = new THREE.Vector3();
  16046. this.vertexNormalsLength = 0;
  16047. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  16048. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  16049. this.color = null;
  16050. this.material = null;
  16051. this.uvs = [[]];
  16052. this.z = 0;
  16053. };
  16054. /**
  16055. * @author mrdoob / http://mrdoob.com/
  16056. */
  16057. THREE.RenderableObject = function () {
  16058. this.id = 0;
  16059. this.object = null;
  16060. this.z = 0;
  16061. };
  16062. /**
  16063. * @author mrdoob / http://mrdoob.com/
  16064. */
  16065. THREE.RenderableParticle = function () {
  16066. this.id = 0;
  16067. this.object = null;
  16068. this.x = 0;
  16069. this.y = 0;
  16070. this.z = 0;
  16071. this.rotation = null;
  16072. this.scale = new THREE.Vector2();
  16073. this.material = null;
  16074. };
  16075. /**
  16076. * @author mrdoob / http://mrdoob.com/
  16077. */
  16078. THREE.RenderableLine = function () {
  16079. this.id = 0;
  16080. this.v1 = new THREE.RenderableVertex();
  16081. this.v2 = new THREE.RenderableVertex();
  16082. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  16083. this.material = null;
  16084. this.z = 0;
  16085. };
  16086. /**
  16087. * @author mrdoob / http://mrdoob.com/
  16088. * @author alteredq / http://alteredqualia.com/
  16089. */
  16090. THREE.GeometryUtils = {
  16091. // Merge two geometries or geometry and geometry from object (using object's transform)
  16092. merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) {
  16093. var matrix, normalMatrix,
  16094. vertexOffset = geometry1.vertices.length,
  16095. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  16096. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  16097. vertices1 = geometry1.vertices,
  16098. vertices2 = geometry2.vertices,
  16099. faces1 = geometry1.faces,
  16100. faces2 = geometry2.faces,
  16101. uvs1 = geometry1.faceVertexUvs[ 0 ],
  16102. uvs2 = geometry2.faceVertexUvs[ 0 ];
  16103. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  16104. if ( object2 instanceof THREE.Mesh ) {
  16105. object2.matrixAutoUpdate && object2.updateMatrix();
  16106. matrix = object2.matrix;
  16107. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  16108. }
  16109. // vertices
  16110. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  16111. var vertex = vertices2[ i ];
  16112. var vertexCopy = vertex.clone();
  16113. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  16114. vertices1.push( vertexCopy );
  16115. }
  16116. // faces
  16117. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  16118. var face = faces2[ i ], faceCopy, normal, color,
  16119. faceVertexNormals = face.vertexNormals,
  16120. faceVertexColors = face.vertexColors;
  16121. if ( face instanceof THREE.Face3 ) {
  16122. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  16123. } else if ( face instanceof THREE.Face4 ) {
  16124. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  16125. }
  16126. faceCopy.normal.copy( face.normal );
  16127. if ( normalMatrix ) {
  16128. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  16129. }
  16130. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  16131. normal = faceVertexNormals[ j ].clone();
  16132. if ( normalMatrix ) {
  16133. normal.applyMatrix3( normalMatrix ).normalize();
  16134. }
  16135. faceCopy.vertexNormals.push( normal );
  16136. }
  16137. faceCopy.color.copy( face.color );
  16138. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  16139. color = faceVertexColors[ j ];
  16140. faceCopy.vertexColors.push( color.clone() );
  16141. }
  16142. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  16143. faceCopy.centroid.copy( face.centroid );
  16144. if ( matrix ) {
  16145. faceCopy.centroid.applyMatrix4( matrix );
  16146. }
  16147. faces1.push( faceCopy );
  16148. }
  16149. // uvs
  16150. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  16151. var uv = uvs2[ i ], uvCopy = [];
  16152. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  16153. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  16154. }
  16155. uvs1.push( uvCopy );
  16156. }
  16157. },
  16158. removeMaterials: function ( geometry, materialIndexArray ) {
  16159. var materialIndexMap = {};
  16160. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  16161. materialIndexMap[ materialIndexArray[i] ] = true;
  16162. }
  16163. var face, newFaces = [];
  16164. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  16165. face = geometry.faces[ i ];
  16166. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  16167. }
  16168. geometry.faces = newFaces;
  16169. },
  16170. // Get random point in triangle (via barycentric coordinates)
  16171. // (uniform distribution)
  16172. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  16173. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  16174. var a, b, c,
  16175. point = new THREE.Vector3(),
  16176. tmp = THREE.GeometryUtils.__v1;
  16177. a = THREE.GeometryUtils.random();
  16178. b = THREE.GeometryUtils.random();
  16179. if ( ( a + b ) > 1 ) {
  16180. a = 1 - a;
  16181. b = 1 - b;
  16182. }
  16183. c = 1 - a - b;
  16184. point.copy( vectorA );
  16185. point.multiplyScalar( a );
  16186. tmp.copy( vectorB );
  16187. tmp.multiplyScalar( b );
  16188. point.add( tmp );
  16189. tmp.copy( vectorC );
  16190. tmp.multiplyScalar( c );
  16191. point.add( tmp );
  16192. return point;
  16193. },
  16194. // Get random point in face (triangle / quad)
  16195. // (uniform distribution)
  16196. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  16197. var vA, vB, vC, vD;
  16198. if ( face instanceof THREE.Face3 ) {
  16199. vA = geometry.vertices[ face.a ];
  16200. vB = geometry.vertices[ face.b ];
  16201. vC = geometry.vertices[ face.c ];
  16202. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  16203. } else if ( face instanceof THREE.Face4 ) {
  16204. vA = geometry.vertices[ face.a ];
  16205. vB = geometry.vertices[ face.b ];
  16206. vC = geometry.vertices[ face.c ];
  16207. vD = geometry.vertices[ face.d ];
  16208. var area1, area2;
  16209. if ( useCachedAreas ) {
  16210. if ( face._area1 && face._area2 ) {
  16211. area1 = face._area1;
  16212. area2 = face._area2;
  16213. } else {
  16214. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  16215. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  16216. face._area1 = area1;
  16217. face._area2 = area2;
  16218. }
  16219. } else {
  16220. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  16221. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  16222. }
  16223. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  16224. if ( r < area1 ) {
  16225. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  16226. } else {
  16227. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  16228. }
  16229. }
  16230. },
  16231. // Get uniformly distributed random points in mesh
  16232. // - create array with cumulative sums of face areas
  16233. // - pick random number from 0 to total area
  16234. // - find corresponding place in area array by binary search
  16235. // - get random point in face
  16236. randomPointsInGeometry: function ( geometry, n ) {
  16237. var face, i,
  16238. faces = geometry.faces,
  16239. vertices = geometry.vertices,
  16240. il = faces.length,
  16241. totalArea = 0,
  16242. cumulativeAreas = [],
  16243. vA, vB, vC, vD;
  16244. // precompute face areas
  16245. for ( i = 0; i < il; i ++ ) {
  16246. face = faces[ i ];
  16247. if ( face instanceof THREE.Face3 ) {
  16248. vA = vertices[ face.a ];
  16249. vB = vertices[ face.b ];
  16250. vC = vertices[ face.c ];
  16251. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  16252. } else if ( face instanceof THREE.Face4 ) {
  16253. vA = vertices[ face.a ];
  16254. vB = vertices[ face.b ];
  16255. vC = vertices[ face.c ];
  16256. vD = vertices[ face.d ];
  16257. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  16258. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  16259. face._area = face._area1 + face._area2;
  16260. }
  16261. totalArea += face._area;
  16262. cumulativeAreas[ i ] = totalArea;
  16263. }
  16264. // binary search cumulative areas array
  16265. function binarySearchIndices( value ) {
  16266. function binarySearch( start, end ) {
  16267. // return closest larger index
  16268. // if exact number is not found
  16269. if ( end < start )
  16270. return start;
  16271. var mid = start + Math.floor( ( end - start ) / 2 );
  16272. if ( cumulativeAreas[ mid ] > value ) {
  16273. return binarySearch( start, mid - 1 );
  16274. } else if ( cumulativeAreas[ mid ] < value ) {
  16275. return binarySearch( mid + 1, end );
  16276. } else {
  16277. return mid;
  16278. }
  16279. }
  16280. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  16281. return result;
  16282. }
  16283. // pick random face weighted by face area
  16284. var r, index,
  16285. result = [];
  16286. var stats = {};
  16287. for ( i = 0; i < n; i ++ ) {
  16288. r = THREE.GeometryUtils.random() * totalArea;
  16289. index = binarySearchIndices( r );
  16290. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  16291. if ( ! stats[ index ] ) {
  16292. stats[ index ] = 1;
  16293. } else {
  16294. stats[ index ] += 1;
  16295. }
  16296. }
  16297. return result;
  16298. },
  16299. // Get triangle area (half of parallelogram)
  16300. // http://mathworld.wolfram.com/TriangleArea.html
  16301. triangleArea: function ( vectorA, vectorB, vectorC ) {
  16302. var tmp1 = THREE.GeometryUtils.__v1,
  16303. tmp2 = THREE.GeometryUtils.__v2;
  16304. tmp1.subVectors( vectorB, vectorA );
  16305. tmp2.subVectors( vectorC, vectorA );
  16306. tmp1.cross( tmp2 );
  16307. return 0.5 * tmp1.length();
  16308. },
  16309. // Center geometry so that 0,0,0 is in center of bounding box
  16310. center: function ( geometry ) {
  16311. geometry.computeBoundingBox();
  16312. var bb = geometry.boundingBox;
  16313. var offset = new THREE.Vector3();
  16314. offset.addVectors( bb.min, bb.max );
  16315. offset.multiplyScalar( -0.5 );
  16316. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  16317. geometry.computeBoundingBox();
  16318. return offset;
  16319. },
  16320. // Normalize UVs to be from <0,1>
  16321. // (for now just the first set of UVs)
  16322. normalizeUVs: function ( geometry ) {
  16323. var uvSet = geometry.faceVertexUvs[ 0 ];
  16324. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  16325. var uvs = uvSet[ i ];
  16326. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  16327. // texture repeat
  16328. if( uvs[ j ].x !== 1.0 ) uvs[ j ].x = uvs[ j ].x - Math.floor( uvs[ j ].x );
  16329. if( uvs[ j ].y !== 1.0 ) uvs[ j ].y = uvs[ j ].y - Math.floor( uvs[ j ].y );
  16330. }
  16331. }
  16332. },
  16333. triangulateQuads: function ( geometry ) {
  16334. var i, il, j, jl;
  16335. var faces = [];
  16336. var faceUvs = [];
  16337. var faceVertexUvs = [];
  16338. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  16339. faceUvs[ i ] = [];
  16340. }
  16341. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  16342. faceVertexUvs[ i ] = [];
  16343. }
  16344. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  16345. var face = geometry.faces[ i ];
  16346. if ( face instanceof THREE.Face4 ) {
  16347. var a = face.a;
  16348. var b = face.b;
  16349. var c = face.c;
  16350. var d = face.d;
  16351. var triA = new THREE.Face3();
  16352. var triB = new THREE.Face3();
  16353. triA.color.copy( face.color );
  16354. triB.color.copy( face.color );
  16355. triA.materialIndex = face.materialIndex;
  16356. triB.materialIndex = face.materialIndex;
  16357. triA.a = a;
  16358. triA.b = b;
  16359. triA.c = d;
  16360. triB.a = b;
  16361. triB.b = c;
  16362. triB.c = d;
  16363. if ( face.vertexColors.length === 4 ) {
  16364. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  16365. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  16366. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  16367. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  16368. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  16369. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  16370. }
  16371. faces.push( triA, triB );
  16372. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  16373. if ( geometry.faceVertexUvs[ j ].length ) {
  16374. var uvs = geometry.faceVertexUvs[ j ][ i ];
  16375. var uvA = uvs[ 0 ];
  16376. var uvB = uvs[ 1 ];
  16377. var uvC = uvs[ 2 ];
  16378. var uvD = uvs[ 3 ];
  16379. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  16380. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  16381. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  16382. }
  16383. }
  16384. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  16385. if ( geometry.faceUvs[ j ].length ) {
  16386. var faceUv = geometry.faceUvs[ j ][ i ];
  16387. faceUvs[ j ].push( faceUv, faceUv );
  16388. }
  16389. }
  16390. } else {
  16391. faces.push( face );
  16392. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  16393. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  16394. }
  16395. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  16396. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  16397. }
  16398. }
  16399. }
  16400. geometry.faces = faces;
  16401. geometry.faceUvs = faceUvs;
  16402. geometry.faceVertexUvs = faceVertexUvs;
  16403. geometry.computeCentroids();
  16404. geometry.computeFaceNormals();
  16405. geometry.computeVertexNormals();
  16406. if ( geometry.hasTangents ) geometry.computeTangents();
  16407. },
  16408. setMaterialIndex: function ( geometry, index, startFace, endFace ){
  16409. var faces = geometry.faces;
  16410. var start = startFace || 0;
  16411. var end = endFace || faces.length - 1;
  16412. for ( var i = start; i <= end; i ++ ) {
  16413. faces[i].materialIndex = index;
  16414. }
  16415. }
  16416. };
  16417. THREE.GeometryUtils.random = THREE.Math.random16;
  16418. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  16419. THREE.GeometryUtils.__v2 = new THREE.Vector3();
  16420. /**
  16421. * @author alteredq / http://alteredqualia.com/
  16422. * @author mrdoob / http://mrdoob.com/
  16423. */
  16424. THREE.ImageUtils = {
  16425. crossOrigin: 'anonymous',
  16426. loadTexture: function ( url, mapping, onLoad, onError ) {
  16427. var image = new Image();
  16428. var texture = new THREE.Texture( image, mapping );
  16429. var loader = new THREE.ImageLoader();
  16430. loader.crossOrigin = this.crossOrigin;
  16431. loader.load( url, function ( image ) {
  16432. texture.image = image;
  16433. texture.needsUpdate = true;
  16434. if ( onLoad ) onLoad( texture );
  16435. } );
  16436. texture.sourceFile = url;
  16437. return texture;
  16438. },
  16439. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  16440. var texture = new THREE.CompressedTexture();
  16441. texture.mapping = mapping;
  16442. var request = new XMLHttpRequest();
  16443. request.onload = function () {
  16444. var buffer = request.response;
  16445. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16446. texture.format = dds.format;
  16447. texture.mipmaps = dds.mipmaps;
  16448. texture.image.width = dds.width;
  16449. texture.image.height = dds.height;
  16450. // gl.generateMipmap fails for compressed textures
  16451. // mipmaps must be embedded in the DDS file
  16452. // or texture filters must not use mipmapping
  16453. texture.generateMipmaps = false;
  16454. texture.needsUpdate = true;
  16455. if ( onLoad ) onLoad( texture );
  16456. }
  16457. request.onerror = onError;
  16458. request.open( 'GET', url, true );
  16459. request.responseType = "arraybuffer";
  16460. request.send( null );
  16461. return texture;
  16462. },
  16463. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  16464. var images = [];
  16465. images.loadCount = 0;
  16466. var texture = new THREE.Texture();
  16467. texture.image = images;
  16468. if ( mapping !== undefined ) texture.mapping = mapping;
  16469. // no flipping needed for cube textures
  16470. texture.flipY = false;
  16471. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16472. var cubeImage = new Image();
  16473. images[ i ] = cubeImage;
  16474. cubeImage.onload = function () {
  16475. images.loadCount += 1;
  16476. if ( images.loadCount === 6 ) {
  16477. texture.needsUpdate = true;
  16478. if ( onLoad ) onLoad( texture );
  16479. }
  16480. };
  16481. cubeImage.onerror = onError;
  16482. cubeImage.crossOrigin = this.crossOrigin;
  16483. cubeImage.src = array[ i ];
  16484. }
  16485. return texture;
  16486. },
  16487. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  16488. var images = [];
  16489. images.loadCount = 0;
  16490. var texture = new THREE.CompressedTexture();
  16491. texture.image = images;
  16492. if ( mapping !== undefined ) texture.mapping = mapping;
  16493. // no flipping for cube textures
  16494. // (also flipping doesn't work for compressed textures )
  16495. texture.flipY = false;
  16496. // can't generate mipmaps for compressed textures
  16497. // mips must be embedded in DDS files
  16498. texture.generateMipmaps = false;
  16499. var generateCubeFaceCallback = function ( rq, img ) {
  16500. return function () {
  16501. var buffer = rq.response;
  16502. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16503. img.format = dds.format;
  16504. img.mipmaps = dds.mipmaps;
  16505. img.width = dds.width;
  16506. img.height = dds.height;
  16507. images.loadCount += 1;
  16508. if ( images.loadCount === 6 ) {
  16509. texture.format = dds.format;
  16510. texture.needsUpdate = true;
  16511. if ( onLoad ) onLoad( texture );
  16512. }
  16513. }
  16514. }
  16515. // compressed cubemap textures as 6 separate DDS files
  16516. if ( array instanceof Array ) {
  16517. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16518. var cubeImage = {};
  16519. images[ i ] = cubeImage;
  16520. var request = new XMLHttpRequest();
  16521. request.onload = generateCubeFaceCallback( request, cubeImage );
  16522. request.onerror = onError;
  16523. var url = array[ i ];
  16524. request.open( 'GET', url, true );
  16525. request.responseType = "arraybuffer";
  16526. request.send( null );
  16527. }
  16528. // compressed cubemap texture stored in a single DDS file
  16529. } else {
  16530. var url = array;
  16531. var request = new XMLHttpRequest();
  16532. request.onload = function( ) {
  16533. var buffer = request.response;
  16534. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16535. if ( dds.isCubemap ) {
  16536. var faces = dds.mipmaps.length / dds.mipmapCount;
  16537. for ( var f = 0; f < faces; f ++ ) {
  16538. images[ f ] = { mipmaps : [] };
  16539. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16540. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  16541. images[ f ].format = dds.format;
  16542. images[ f ].width = dds.width;
  16543. images[ f ].height = dds.height;
  16544. }
  16545. }
  16546. texture.format = dds.format;
  16547. texture.needsUpdate = true;
  16548. if ( onLoad ) onLoad( texture );
  16549. }
  16550. }
  16551. request.onerror = onError;
  16552. request.open( 'GET', url, true );
  16553. request.responseType = "arraybuffer";
  16554. request.send( null );
  16555. }
  16556. return texture;
  16557. },
  16558. parseDDS: function ( buffer, loadMipmaps ) {
  16559. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  16560. // Adapted from @toji's DDS utils
  16561. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  16562. // All values and structures referenced from:
  16563. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  16564. var DDS_MAGIC = 0x20534444;
  16565. var DDSD_CAPS = 0x1,
  16566. DDSD_HEIGHT = 0x2,
  16567. DDSD_WIDTH = 0x4,
  16568. DDSD_PITCH = 0x8,
  16569. DDSD_PIXELFORMAT = 0x1000,
  16570. DDSD_MIPMAPCOUNT = 0x20000,
  16571. DDSD_LINEARSIZE = 0x80000,
  16572. DDSD_DEPTH = 0x800000;
  16573. var DDSCAPS_COMPLEX = 0x8,
  16574. DDSCAPS_MIPMAP = 0x400000,
  16575. DDSCAPS_TEXTURE = 0x1000;
  16576. var DDSCAPS2_CUBEMAP = 0x200,
  16577. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  16578. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  16579. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  16580. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  16581. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  16582. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  16583. DDSCAPS2_VOLUME = 0x200000;
  16584. var DDPF_ALPHAPIXELS = 0x1,
  16585. DDPF_ALPHA = 0x2,
  16586. DDPF_FOURCC = 0x4,
  16587. DDPF_RGB = 0x40,
  16588. DDPF_YUV = 0x200,
  16589. DDPF_LUMINANCE = 0x20000;
  16590. function fourCCToInt32( value ) {
  16591. return value.charCodeAt(0) +
  16592. (value.charCodeAt(1) << 8) +
  16593. (value.charCodeAt(2) << 16) +
  16594. (value.charCodeAt(3) << 24);
  16595. }
  16596. function int32ToFourCC( value ) {
  16597. return String.fromCharCode(
  16598. value & 0xff,
  16599. (value >> 8) & 0xff,
  16600. (value >> 16) & 0xff,
  16601. (value >> 24) & 0xff
  16602. );
  16603. }
  16604. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  16605. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  16606. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  16607. var headerLengthInt = 31; // The header length in 32 bit ints
  16608. // Offsets into the header array
  16609. var off_magic = 0;
  16610. var off_size = 1;
  16611. var off_flags = 2;
  16612. var off_height = 3;
  16613. var off_width = 4;
  16614. var off_mipmapCount = 7;
  16615. var off_pfFlags = 20;
  16616. var off_pfFourCC = 21;
  16617. var off_caps = 27;
  16618. var off_caps2 = 28;
  16619. var off_caps3 = 29;
  16620. var off_caps4 = 30;
  16621. // Parse header
  16622. var header = new Int32Array( buffer, 0, headerLengthInt );
  16623. if ( header[ off_magic ] !== DDS_MAGIC ) {
  16624. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  16625. return dds;
  16626. }
  16627. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  16628. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  16629. return dds;
  16630. }
  16631. var blockBytes;
  16632. var fourCC = header[ off_pfFourCC ];
  16633. switch ( fourCC ) {
  16634. case FOURCC_DXT1:
  16635. blockBytes = 8;
  16636. dds.format = THREE.RGB_S3TC_DXT1_Format;
  16637. break;
  16638. case FOURCC_DXT3:
  16639. blockBytes = 16;
  16640. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  16641. break;
  16642. case FOURCC_DXT5:
  16643. blockBytes = 16;
  16644. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  16645. break;
  16646. default:
  16647. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  16648. return dds;
  16649. }
  16650. dds.mipmapCount = 1;
  16651. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  16652. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  16653. }
  16654. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  16655. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  16656. dds.width = header[ off_width ];
  16657. dds.height = header[ off_height ];
  16658. var dataOffset = header[ off_size ] + 4;
  16659. // Extract mipmaps buffers
  16660. var width = dds.width;
  16661. var height = dds.height;
  16662. var faces = dds.isCubemap ? 6 : 1;
  16663. for ( var face = 0; face < faces; face ++ ) {
  16664. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16665. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  16666. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  16667. var mipmap = { "data": byteArray, "width": width, "height": height };
  16668. dds.mipmaps.push( mipmap );
  16669. dataOffset += dataLength;
  16670. width = Math.max( width * 0.5, 1 );
  16671. height = Math.max( height * 0.5, 1 );
  16672. }
  16673. width = dds.width;
  16674. height = dds.height;
  16675. }
  16676. return dds;
  16677. },
  16678. getNormalMap: function ( image, depth ) {
  16679. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  16680. var cross = function ( a, b ) {
  16681. 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 ] ];
  16682. }
  16683. var subtract = function ( a, b ) {
  16684. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  16685. }
  16686. var normalize = function ( a ) {
  16687. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  16688. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  16689. }
  16690. depth = depth | 1;
  16691. var width = image.width;
  16692. var height = image.height;
  16693. var canvas = document.createElement( 'canvas' );
  16694. canvas.width = width;
  16695. canvas.height = height;
  16696. var context = canvas.getContext( '2d' );
  16697. context.drawImage( image, 0, 0 );
  16698. var data = context.getImageData( 0, 0, width, height ).data;
  16699. var imageData = context.createImageData( width, height );
  16700. var output = imageData.data;
  16701. for ( var x = 0; x < width; x ++ ) {
  16702. for ( var y = 0; y < height; y ++ ) {
  16703. var ly = y - 1 < 0 ? 0 : y - 1;
  16704. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  16705. var lx = x - 1 < 0 ? 0 : x - 1;
  16706. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  16707. var points = [];
  16708. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  16709. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  16710. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  16711. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  16712. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  16713. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  16714. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  16715. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  16716. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  16717. var normals = [];
  16718. var num_points = points.length;
  16719. for ( var i = 0; i < num_points; i ++ ) {
  16720. var v1 = points[ i ];
  16721. var v2 = points[ ( i + 1 ) % num_points ];
  16722. v1 = subtract( v1, origin );
  16723. v2 = subtract( v2, origin );
  16724. normals.push( normalize( cross( v1, v2 ) ) );
  16725. }
  16726. var normal = [ 0, 0, 0 ];
  16727. for ( var i = 0; i < normals.length; i ++ ) {
  16728. normal[ 0 ] += normals[ i ][ 0 ];
  16729. normal[ 1 ] += normals[ i ][ 1 ];
  16730. normal[ 2 ] += normals[ i ][ 2 ];
  16731. }
  16732. normal[ 0 ] /= normals.length;
  16733. normal[ 1 ] /= normals.length;
  16734. normal[ 2 ] /= normals.length;
  16735. var idx = ( y * width + x ) * 4;
  16736. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16737. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16738. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  16739. output[ idx + 3 ] = 255;
  16740. }
  16741. }
  16742. context.putImageData( imageData, 0, 0 );
  16743. return canvas;
  16744. },
  16745. generateDataTexture: function ( width, height, color ) {
  16746. var size = width * height;
  16747. var data = new Uint8Array( 3 * size );
  16748. var r = Math.floor( color.r * 255 );
  16749. var g = Math.floor( color.g * 255 );
  16750. var b = Math.floor( color.b * 255 );
  16751. for ( var i = 0; i < size; i ++ ) {
  16752. data[ i * 3 ] = r;
  16753. data[ i * 3 + 1 ] = g;
  16754. data[ i * 3 + 2 ] = b;
  16755. }
  16756. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16757. texture.needsUpdate = true;
  16758. return texture;
  16759. }
  16760. };
  16761. /**
  16762. * @author alteredq / http://alteredqualia.com/
  16763. */
  16764. THREE.SceneUtils = {
  16765. createMultiMaterialObject: function ( geometry, materials ) {
  16766. var group = new THREE.Object3D();
  16767. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16768. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16769. }
  16770. return group;
  16771. },
  16772. detach : function ( child, parent, scene ) {
  16773. child.applyMatrix( parent.matrixWorld );
  16774. parent.remove( child );
  16775. scene.add( child );
  16776. },
  16777. attach: function ( child, scene, parent ) {
  16778. var matrixWorldInverse = new THREE.Matrix4();
  16779. matrixWorldInverse.getInverse( parent.matrixWorld );
  16780. child.applyMatrix( matrixWorldInverse );
  16781. scene.remove( child );
  16782. parent.add( child );
  16783. }
  16784. };
  16785. /**
  16786. * @author zz85 / http://www.lab4games.net/zz85/blog
  16787. * @author alteredq / http://alteredqualia.com/
  16788. *
  16789. * For Text operations in three.js (See TextGeometry)
  16790. *
  16791. * It uses techniques used in:
  16792. *
  16793. * typeface.js and canvastext
  16794. * For converting fonts and rendering with javascript
  16795. * http://typeface.neocracy.org
  16796. *
  16797. * Triangulation ported from AS3
  16798. * Simple Polygon Triangulation
  16799. * http://actionsnippet.com/?p=1462
  16800. *
  16801. * A Method to triangulate shapes with holes
  16802. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16803. *
  16804. */
  16805. THREE.FontUtils = {
  16806. faces : {},
  16807. // Just for now. face[weight][style]
  16808. face : "helvetiker",
  16809. weight: "normal",
  16810. style : "normal",
  16811. size : 150,
  16812. divisions : 10,
  16813. getFace : function() {
  16814. return this.faces[ this.face ][ this.weight ][ this.style ];
  16815. },
  16816. loadFace : function( data ) {
  16817. var family = data.familyName.toLowerCase();
  16818. var ThreeFont = this;
  16819. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16820. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16821. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16822. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16823. return data;
  16824. },
  16825. drawText : function( text ) {
  16826. var characterPts = [], allPts = [];
  16827. // RenderText
  16828. var i, p,
  16829. face = this.getFace(),
  16830. scale = this.size / face.resolution,
  16831. offset = 0,
  16832. chars = String( text ).split( '' ),
  16833. length = chars.length;
  16834. var fontPaths = [];
  16835. for ( i = 0; i < length; i ++ ) {
  16836. var path = new THREE.Path();
  16837. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16838. offset += ret.offset;
  16839. fontPaths.push( ret.path );
  16840. }
  16841. // get the width
  16842. var width = offset / 2;
  16843. //
  16844. // for ( p = 0; p < allPts.length; p++ ) {
  16845. //
  16846. // allPts[ p ].x -= width;
  16847. //
  16848. // }
  16849. //var extract = this.extractPoints( allPts, characterPts );
  16850. //extract.contour = allPts;
  16851. //extract.paths = fontPaths;
  16852. //extract.offset = width;
  16853. return { paths : fontPaths, offset : width };
  16854. },
  16855. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16856. var pts = [];
  16857. var i, i2, divisions,
  16858. outline, action, length,
  16859. scaleX, scaleY,
  16860. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16861. laste,
  16862. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16863. if ( !glyph ) return;
  16864. if ( glyph.o ) {
  16865. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16866. length = outline.length;
  16867. scaleX = scale;
  16868. scaleY = scale;
  16869. for ( i = 0; i < length; ) {
  16870. action = outline[ i ++ ];
  16871. //console.log( action );
  16872. switch( action ) {
  16873. case 'm':
  16874. // Move To
  16875. x = outline[ i++ ] * scaleX + offset;
  16876. y = outline[ i++ ] * scaleY;
  16877. path.moveTo( x, y );
  16878. break;
  16879. case 'l':
  16880. // Line To
  16881. x = outline[ i++ ] * scaleX + offset;
  16882. y = outline[ i++ ] * scaleY;
  16883. path.lineTo(x,y);
  16884. break;
  16885. case 'q':
  16886. // QuadraticCurveTo
  16887. cpx = outline[ i++ ] * scaleX + offset;
  16888. cpy = outline[ i++ ] * scaleY;
  16889. cpx1 = outline[ i++ ] * scaleX + offset;
  16890. cpy1 = outline[ i++ ] * scaleY;
  16891. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16892. laste = pts[ pts.length - 1 ];
  16893. if ( laste ) {
  16894. cpx0 = laste.x;
  16895. cpy0 = laste.y;
  16896. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16897. var t = i2 / divisions;
  16898. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16899. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16900. }
  16901. }
  16902. break;
  16903. case 'b':
  16904. // Cubic Bezier Curve
  16905. cpx = outline[ i++ ] * scaleX + offset;
  16906. cpy = outline[ i++ ] * scaleY;
  16907. cpx1 = outline[ i++ ] * scaleX + offset;
  16908. cpy1 = outline[ i++ ] * -scaleY;
  16909. cpx2 = outline[ i++ ] * scaleX + offset;
  16910. cpy2 = outline[ i++ ] * -scaleY;
  16911. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16912. laste = pts[ pts.length - 1 ];
  16913. if ( laste ) {
  16914. cpx0 = laste.x;
  16915. cpy0 = laste.y;
  16916. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16917. var t = i2 / divisions;
  16918. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16919. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16920. }
  16921. }
  16922. break;
  16923. }
  16924. }
  16925. }
  16926. return { offset: glyph.ha*scale, path:path};
  16927. }
  16928. };
  16929. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16930. // Parameters
  16931. parameters = parameters || {};
  16932. var size = parameters.size !== undefined ? parameters.size : 100;
  16933. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16934. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16935. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16936. var style = parameters.style !== undefined ? parameters.style : "normal";
  16937. THREE.FontUtils.size = size;
  16938. THREE.FontUtils.divisions = curveSegments;
  16939. THREE.FontUtils.face = font;
  16940. THREE.FontUtils.weight = weight;
  16941. THREE.FontUtils.style = style;
  16942. // Get a Font data json object
  16943. var data = THREE.FontUtils.drawText( text );
  16944. var paths = data.paths;
  16945. var shapes = [];
  16946. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16947. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16948. }
  16949. return shapes;
  16950. };
  16951. /**
  16952. * This code is a quick port of code written in C++ which was submitted to
  16953. * flipcode.com by John W. Ratcliff // July 22, 2000
  16954. * See original code and more information here:
  16955. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16956. *
  16957. * ported to actionscript by Zevan Rosser
  16958. * www.actionsnippet.com
  16959. *
  16960. * ported to javascript by Joshua Koo
  16961. * http://www.lab4games.net/zz85/blog
  16962. *
  16963. */
  16964. ( function( namespace ) {
  16965. var EPSILON = 0.0000000001;
  16966. // takes in an contour array and returns
  16967. var process = function( contour, indices ) {
  16968. var n = contour.length;
  16969. if ( n < 3 ) return null;
  16970. var result = [],
  16971. verts = [],
  16972. vertIndices = [];
  16973. /* we want a counter-clockwise polygon in verts */
  16974. var u, v, w;
  16975. if ( area( contour ) > 0.0 ) {
  16976. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16977. } else {
  16978. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16979. }
  16980. var nv = n;
  16981. /* remove nv - 2 vertices, creating 1 triangle every time */
  16982. var count = 2 * nv; /* error detection */
  16983. for( v = nv - 1; nv > 2; ) {
  16984. /* if we loop, it is probably a non-simple polygon */
  16985. if ( ( count-- ) <= 0 ) {
  16986. //** Triangulate: ERROR - probable bad polygon!
  16987. //throw ( "Warning, unable to triangulate polygon!" );
  16988. //return null;
  16989. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16990. console.log( "Warning, unable to triangulate polygon!" );
  16991. if ( indices ) return vertIndices;
  16992. return result;
  16993. }
  16994. /* three consecutive vertices in current polygon, <u,v,w> */
  16995. u = v; if ( nv <= u ) u = 0; /* previous */
  16996. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16997. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16998. if ( snip( contour, u, v, w, nv, verts ) ) {
  16999. var a, b, c, s, t;
  17000. /* true names of the vertices */
  17001. a = verts[ u ];
  17002. b = verts[ v ];
  17003. c = verts[ w ];
  17004. /* output Triangle */
  17005. result.push( [ contour[ a ],
  17006. contour[ b ],
  17007. contour[ c ] ] );
  17008. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  17009. /* remove v from the remaining polygon */
  17010. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  17011. verts[ s ] = verts[ t ];
  17012. }
  17013. nv--;
  17014. /* reset error detection counter */
  17015. count = 2 * nv;
  17016. }
  17017. }
  17018. if ( indices ) return vertIndices;
  17019. return result;
  17020. };
  17021. // calculate area of the contour polygon
  17022. var area = function ( contour ) {
  17023. var n = contour.length;
  17024. var a = 0.0;
  17025. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  17026. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  17027. }
  17028. return a * 0.5;
  17029. };
  17030. var snip = function ( contour, u, v, w, n, verts ) {
  17031. var p;
  17032. var ax, ay, bx, by;
  17033. var cx, cy, px, py;
  17034. ax = contour[ verts[ u ] ].x;
  17035. ay = contour[ verts[ u ] ].y;
  17036. bx = contour[ verts[ v ] ].x;
  17037. by = contour[ verts[ v ] ].y;
  17038. cx = contour[ verts[ w ] ].x;
  17039. cy = contour[ verts[ w ] ].y;
  17040. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  17041. var aX, aY, bX, bY, cX, cY;
  17042. var apx, apy, bpx, bpy, cpx, cpy;
  17043. var cCROSSap, bCROSScp, aCROSSbp;
  17044. aX = cx - bx; aY = cy - by;
  17045. bX = ax - cx; bY = ay - cy;
  17046. cX = bx - ax; cY = by - ay;
  17047. for ( p = 0; p < n; p++ ) {
  17048. if( (p === u) || (p === v) || (p === w) ) continue;
  17049. px = contour[ verts[ p ] ].x
  17050. py = contour[ verts[ p ] ].y
  17051. apx = px - ax; apy = py - ay;
  17052. bpx = px - bx; bpy = py - by;
  17053. cpx = px - cx; cpy = py - cy;
  17054. // see if p is inside triangle abc
  17055. aCROSSbp = aX*bpy - aY*bpx;
  17056. cCROSSap = cX*apy - cY*apx;
  17057. bCROSScp = bX*cpy - bY*cpx;
  17058. if ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) ) return false;
  17059. }
  17060. return true;
  17061. };
  17062. namespace.Triangulate = process;
  17063. namespace.Triangulate.area = area;
  17064. return namespace;
  17065. })(THREE.FontUtils);
  17066. // To use the typeface.js face files, hook up the API
  17067. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  17068. THREE.typeface_js = self._typeface_js;
  17069. /**
  17070. * @author zz85 / http://www.lab4games.net/zz85/blog
  17071. * Extensible curve object
  17072. *
  17073. * Some common of Curve methods
  17074. * .getPoint(t), getTangent(t)
  17075. * .getPointAt(u), getTagentAt(u)
  17076. * .getPoints(), .getSpacedPoints()
  17077. * .getLength()
  17078. * .updateArcLengths()
  17079. *
  17080. * This following classes subclasses THREE.Curve:
  17081. *
  17082. * -- 2d classes --
  17083. * THREE.LineCurve
  17084. * THREE.QuadraticBezierCurve
  17085. * THREE.CubicBezierCurve
  17086. * THREE.SplineCurve
  17087. * THREE.ArcCurve
  17088. * THREE.EllipseCurve
  17089. *
  17090. * -- 3d classes --
  17091. * THREE.LineCurve3
  17092. * THREE.QuadraticBezierCurve3
  17093. * THREE.CubicBezierCurve3
  17094. * THREE.SplineCurve3
  17095. * THREE.ClosedSplineCurve3
  17096. *
  17097. * A series of curves can be represented as a THREE.CurvePath
  17098. *
  17099. **/
  17100. /**************************************************************
  17101. * Abstract Curve base class
  17102. **************************************************************/
  17103. THREE.Curve = function () {
  17104. };
  17105. // Virtual base class method to overwrite and implement in subclasses
  17106. // - t [0 .. 1]
  17107. THREE.Curve.prototype.getPoint = function ( t ) {
  17108. console.log( "Warning, getPoint() not implemented!" );
  17109. return null;
  17110. };
  17111. // Get point at relative position in curve according to arc length
  17112. // - u [0 .. 1]
  17113. THREE.Curve.prototype.getPointAt = function ( u ) {
  17114. var t = this.getUtoTmapping( u );
  17115. return this.getPoint( t );
  17116. };
  17117. // Get sequence of points using getPoint( t )
  17118. THREE.Curve.prototype.getPoints = function ( divisions ) {
  17119. if ( !divisions ) divisions = 5;
  17120. var d, pts = [];
  17121. for ( d = 0; d <= divisions; d ++ ) {
  17122. pts.push( this.getPoint( d / divisions ) );
  17123. }
  17124. return pts;
  17125. };
  17126. // Get sequence of points using getPointAt( u )
  17127. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  17128. if ( !divisions ) divisions = 5;
  17129. var d, pts = [];
  17130. for ( d = 0; d <= divisions; d ++ ) {
  17131. pts.push( this.getPointAt( d / divisions ) );
  17132. }
  17133. return pts;
  17134. };
  17135. // Get total curve arc length
  17136. THREE.Curve.prototype.getLength = function () {
  17137. var lengths = this.getLengths();
  17138. return lengths[ lengths.length - 1 ];
  17139. };
  17140. // Get list of cumulative segment lengths
  17141. THREE.Curve.prototype.getLengths = function ( divisions ) {
  17142. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  17143. if ( this.cacheArcLengths
  17144. && ( this.cacheArcLengths.length == divisions + 1 )
  17145. && !this.needsUpdate) {
  17146. //console.log( "cached", this.cacheArcLengths );
  17147. return this.cacheArcLengths;
  17148. }
  17149. this.needsUpdate = false;
  17150. var cache = [];
  17151. var current, last = this.getPoint( 0 );
  17152. var p, sum = 0;
  17153. cache.push( 0 );
  17154. for ( p = 1; p <= divisions; p ++ ) {
  17155. current = this.getPoint ( p / divisions );
  17156. sum += current.distanceTo( last );
  17157. cache.push( sum );
  17158. last = current;
  17159. }
  17160. this.cacheArcLengths = cache;
  17161. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  17162. };
  17163. THREE.Curve.prototype.updateArcLengths = function() {
  17164. this.needsUpdate = true;
  17165. this.getLengths();
  17166. };
  17167. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  17168. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  17169. var arcLengths = this.getLengths();
  17170. var i = 0, il = arcLengths.length;
  17171. var targetArcLength; // The targeted u distance value to get
  17172. if ( distance ) {
  17173. targetArcLength = distance;
  17174. } else {
  17175. targetArcLength = u * arcLengths[ il - 1 ];
  17176. }
  17177. //var time = Date.now();
  17178. // binary search for the index with largest value smaller than target u distance
  17179. var low = 0, high = il - 1, comparison;
  17180. while ( low <= high ) {
  17181. 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
  17182. comparison = arcLengths[ i ] - targetArcLength;
  17183. if ( comparison < 0 ) {
  17184. low = i + 1;
  17185. continue;
  17186. } else if ( comparison > 0 ) {
  17187. high = i - 1;
  17188. continue;
  17189. } else {
  17190. high = i;
  17191. break;
  17192. // DONE
  17193. }
  17194. }
  17195. i = high;
  17196. //console.log('b' , i, low, high, Date.now()- time);
  17197. if ( arcLengths[ i ] == targetArcLength ) {
  17198. var t = i / ( il - 1 );
  17199. return t;
  17200. }
  17201. // we could get finer grain at lengths, or use simple interpolatation between two points
  17202. var lengthBefore = arcLengths[ i ];
  17203. var lengthAfter = arcLengths[ i + 1 ];
  17204. var segmentLength = lengthAfter - lengthBefore;
  17205. // determine where we are between the 'before' and 'after' points
  17206. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  17207. // add that fractional amount to t
  17208. var t = ( i + segmentFraction ) / ( il -1 );
  17209. return t;
  17210. };
  17211. // Returns a unit vector tangent at t
  17212. // In case any sub curve does not implement its tangent derivation,
  17213. // 2 points a small delta apart will be used to find its gradient
  17214. // which seems to give a reasonable approximation
  17215. THREE.Curve.prototype.getTangent = function( t ) {
  17216. var delta = 0.0001;
  17217. var t1 = t - delta;
  17218. var t2 = t + delta;
  17219. // Capping in case of danger
  17220. if ( t1 < 0 ) t1 = 0;
  17221. if ( t2 > 1 ) t2 = 1;
  17222. var pt1 = this.getPoint( t1 );
  17223. var pt2 = this.getPoint( t2 );
  17224. var vec = pt2.clone().sub(pt1);
  17225. return vec.normalize();
  17226. };
  17227. THREE.Curve.prototype.getTangentAt = function ( u ) {
  17228. var t = this.getUtoTmapping( u );
  17229. return this.getTangent( t );
  17230. };
  17231. /**************************************************************
  17232. * Utils
  17233. **************************************************************/
  17234. THREE.Curve.Utils = {
  17235. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  17236. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  17237. },
  17238. // Puay Bing, thanks for helping with this derivative!
  17239. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  17240. return -3 * p0 * (1 - t) * (1 - t) +
  17241. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  17242. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  17243. 3 * t * t * p3;
  17244. },
  17245. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  17246. // To check if my formulas are correct
  17247. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  17248. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  17249. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  17250. var h11 = 3 * t * t - 2 * t; // t3 − t2
  17251. return h00 + h10 + h01 + h11;
  17252. },
  17253. // Catmull-Rom
  17254. interpolate: function( p0, p1, p2, p3, t ) {
  17255. var v0 = ( p2 - p0 ) * 0.5;
  17256. var v1 = ( p3 - p1 ) * 0.5;
  17257. var t2 = t * t;
  17258. var t3 = t * t2;
  17259. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17260. }
  17261. };
  17262. // TODO: Transformation for Curves?
  17263. /**************************************************************
  17264. * 3D Curves
  17265. **************************************************************/
  17266. // A Factory method for creating new curve subclasses
  17267. THREE.Curve.create = function ( constructor, getPointFunc ) {
  17268. constructor.prototype = Object.create( THREE.Curve.prototype );
  17269. constructor.prototype.getPoint = getPointFunc;
  17270. return constructor;
  17271. };
  17272. /**
  17273. * @author zz85 / http://www.lab4games.net/zz85/blog
  17274. *
  17275. **/
  17276. /**************************************************************
  17277. * Curved Path - a curve path is simply a array of connected
  17278. * curves, but retains the api of a curve
  17279. **************************************************************/
  17280. THREE.CurvePath = function () {
  17281. this.curves = [];
  17282. this.bends = [];
  17283. this.autoClose = false; // Automatically closes the path
  17284. };
  17285. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  17286. THREE.CurvePath.prototype.add = function ( curve ) {
  17287. this.curves.push( curve );
  17288. };
  17289. THREE.CurvePath.prototype.checkConnection = function() {
  17290. // TODO
  17291. // If the ending of curve is not connected to the starting
  17292. // or the next curve, then, this is not a real path
  17293. };
  17294. THREE.CurvePath.prototype.closePath = function() {
  17295. // TODO Test
  17296. // and verify for vector3 (needs to implement equals)
  17297. // Add a line curve if start and end of lines are not connected
  17298. var startPoint = this.curves[0].getPoint(0);
  17299. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  17300. if (!startPoint.equals(endPoint)) {
  17301. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  17302. }
  17303. };
  17304. // To get accurate point with reference to
  17305. // entire path distance at time t,
  17306. // following has to be done:
  17307. // 1. Length of each sub path have to be known
  17308. // 2. Locate and identify type of curve
  17309. // 3. Get t for the curve
  17310. // 4. Return curve.getPointAt(t')
  17311. THREE.CurvePath.prototype.getPoint = function( t ) {
  17312. var d = t * this.getLength();
  17313. var curveLengths = this.getCurveLengths();
  17314. var i = 0, diff, curve;
  17315. // To think about boundaries points.
  17316. while ( i < curveLengths.length ) {
  17317. if ( curveLengths[ i ] >= d ) {
  17318. diff = curveLengths[ i ] - d;
  17319. curve = this.curves[ i ];
  17320. var u = 1 - diff / curve.getLength();
  17321. return curve.getPointAt( u );
  17322. break;
  17323. }
  17324. i ++;
  17325. }
  17326. return null;
  17327. // loop where sum != 0, sum > d , sum+1 <d
  17328. };
  17329. /*
  17330. THREE.CurvePath.prototype.getTangent = function( t ) {
  17331. };*/
  17332. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  17333. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  17334. // getPoint() depends on getLength
  17335. THREE.CurvePath.prototype.getLength = function() {
  17336. var lens = this.getCurveLengths();
  17337. return lens[ lens.length - 1 ];
  17338. };
  17339. // Compute lengths and cache them
  17340. // We cannot overwrite getLengths() because UtoT mapping uses it.
  17341. THREE.CurvePath.prototype.getCurveLengths = function() {
  17342. // We use cache values if curves and cache array are same length
  17343. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  17344. return this.cacheLengths;
  17345. };
  17346. // Get length of subsurve
  17347. // Push sums into cached array
  17348. var lengths = [], sums = 0;
  17349. var i, il = this.curves.length;
  17350. for ( i = 0; i < il; i ++ ) {
  17351. sums += this.curves[ i ].getLength();
  17352. lengths.push( sums );
  17353. }
  17354. this.cacheLengths = lengths;
  17355. return lengths;
  17356. };
  17357. // Returns min and max coordinates, as well as centroid
  17358. THREE.CurvePath.prototype.getBoundingBox = function () {
  17359. var points = this.getPoints();
  17360. var maxX, maxY, maxZ;
  17361. var minX, minY, minZ;
  17362. maxX = maxY = Number.NEGATIVE_INFINITY;
  17363. minX = minY = Number.POSITIVE_INFINITY;
  17364. var p, i, il, sum;
  17365. var v3 = points[0] instanceof THREE.Vector3;
  17366. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  17367. for ( i = 0, il = points.length; i < il; i ++ ) {
  17368. p = points[ i ];
  17369. if ( p.x > maxX ) maxX = p.x;
  17370. else if ( p.x < minX ) minX = p.x;
  17371. if ( p.y > maxY ) maxY = p.y;
  17372. else if ( p.y < minY ) minY = p.y;
  17373. if ( v3 ) {
  17374. if ( p.z > maxZ ) maxZ = p.z;
  17375. else if ( p.z < minZ ) minZ = p.z;
  17376. }
  17377. sum.add( p );
  17378. }
  17379. var ret = {
  17380. minX: minX,
  17381. minY: minY,
  17382. maxX: maxX,
  17383. maxY: maxY,
  17384. centroid: sum.divideScalar( il )
  17385. };
  17386. if ( v3 ) {
  17387. ret.maxZ = maxZ;
  17388. ret.minZ = minZ;
  17389. }
  17390. return ret;
  17391. };
  17392. /**************************************************************
  17393. * Create Geometries Helpers
  17394. **************************************************************/
  17395. /// Generate geometry from path points (for Line or ParticleSystem objects)
  17396. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  17397. var pts = this.getPoints( divisions, true );
  17398. return this.createGeometry( pts );
  17399. };
  17400. // Generate geometry from equidistance sampling along the path
  17401. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  17402. var pts = this.getSpacedPoints( divisions, true );
  17403. return this.createGeometry( pts );
  17404. };
  17405. THREE.CurvePath.prototype.createGeometry = function( points ) {
  17406. var geometry = new THREE.Geometry();
  17407. for ( var i = 0; i < points.length; i ++ ) {
  17408. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  17409. }
  17410. return geometry;
  17411. };
  17412. /**************************************************************
  17413. * Bend / Wrap Helper Methods
  17414. **************************************************************/
  17415. // Wrap path / Bend modifiers?
  17416. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  17417. this.bends.push( bendpath );
  17418. };
  17419. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  17420. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  17421. var i, il;
  17422. if ( !bends ) {
  17423. bends = this.bends;
  17424. }
  17425. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17426. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17427. }
  17428. return oldPts;
  17429. };
  17430. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  17431. var oldPts = this.getSpacedPoints( segments );
  17432. var i, il;
  17433. if ( !bends ) {
  17434. bends = this.bends;
  17435. }
  17436. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17437. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17438. }
  17439. return oldPts;
  17440. };
  17441. // This returns getPoints() bend/wrapped around the contour of a path.
  17442. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  17443. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  17444. var bounds = this.getBoundingBox();
  17445. var i, il, p, oldX, oldY, xNorm;
  17446. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  17447. p = oldPts[ i ];
  17448. oldX = p.x;
  17449. oldY = p.y;
  17450. xNorm = oldX / bounds.maxX;
  17451. // If using actual distance, for length > path, requires line extrusions
  17452. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  17453. xNorm = path.getUtoTmapping( xNorm, oldX );
  17454. // check for out of bounds?
  17455. var pathPt = path.getPoint( xNorm );
  17456. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  17457. p.x = pathPt.x + normal.x;
  17458. p.y = pathPt.y + normal.y;
  17459. }
  17460. return oldPts;
  17461. };
  17462. /**
  17463. * @author alteredq / http://alteredqualia.com/
  17464. */
  17465. THREE.Gyroscope = function () {
  17466. THREE.Object3D.call( this );
  17467. };
  17468. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  17469. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  17470. this.matrixAutoUpdate && this.updateMatrix();
  17471. // update matrixWorld
  17472. if ( this.matrixWorldNeedsUpdate || force ) {
  17473. if ( this.parent ) {
  17474. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  17475. this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld );
  17476. this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject );
  17477. this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld );
  17478. } else {
  17479. this.matrixWorld.copy( this.matrix );
  17480. }
  17481. this.matrixWorldNeedsUpdate = false;
  17482. force = true;
  17483. }
  17484. // update children
  17485. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  17486. this.children[ i ].updateMatrixWorld( force );
  17487. }
  17488. };
  17489. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  17490. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  17491. THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion();
  17492. THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion();
  17493. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  17494. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  17495. /**
  17496. * @author zz85 / http://www.lab4games.net/zz85/blog
  17497. * Creates free form 2d path using series of points, lines or curves.
  17498. *
  17499. **/
  17500. THREE.Path = function ( points ) {
  17501. THREE.CurvePath.call(this);
  17502. this.actions = [];
  17503. if ( points ) {
  17504. this.fromPoints( points );
  17505. }
  17506. };
  17507. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  17508. THREE.PathActions = {
  17509. MOVE_TO: 'moveTo',
  17510. LINE_TO: 'lineTo',
  17511. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  17512. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  17513. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  17514. ARC: 'arc', // Circle
  17515. ELLIPSE: 'ellipse'
  17516. };
  17517. // TODO Clean up PATH API
  17518. // Create path using straight lines to connect all points
  17519. // - vectors: array of Vector2
  17520. THREE.Path.prototype.fromPoints = function ( vectors ) {
  17521. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  17522. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  17523. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  17524. };
  17525. };
  17526. // startPath() endPath()?
  17527. THREE.Path.prototype.moveTo = function ( x, y ) {
  17528. var args = Array.prototype.slice.call( arguments );
  17529. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  17530. };
  17531. THREE.Path.prototype.lineTo = function ( x, y ) {
  17532. var args = Array.prototype.slice.call( arguments );
  17533. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17534. var x0 = lastargs[ lastargs.length - 2 ];
  17535. var y0 = lastargs[ lastargs.length - 1 ];
  17536. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  17537. this.curves.push( curve );
  17538. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  17539. };
  17540. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  17541. var args = Array.prototype.slice.call( arguments );
  17542. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17543. var x0 = lastargs[ lastargs.length - 2 ];
  17544. var y0 = lastargs[ lastargs.length - 1 ];
  17545. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  17546. new THREE.Vector2( aCPx, aCPy ),
  17547. new THREE.Vector2( aX, aY ) );
  17548. this.curves.push( curve );
  17549. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  17550. };
  17551. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  17552. aCP2x, aCP2y,
  17553. aX, aY ) {
  17554. var args = Array.prototype.slice.call( arguments );
  17555. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17556. var x0 = lastargs[ lastargs.length - 2 ];
  17557. var y0 = lastargs[ lastargs.length - 1 ];
  17558. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  17559. new THREE.Vector2( aCP1x, aCP1y ),
  17560. new THREE.Vector2( aCP2x, aCP2y ),
  17561. new THREE.Vector2( aX, aY ) );
  17562. this.curves.push( curve );
  17563. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  17564. };
  17565. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  17566. var args = Array.prototype.slice.call( arguments );
  17567. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17568. var x0 = lastargs[ lastargs.length - 2 ];
  17569. var y0 = lastargs[ lastargs.length - 1 ];
  17570. //---
  17571. var npts = [ new THREE.Vector2( x0, y0 ) ];
  17572. Array.prototype.push.apply( npts, pts );
  17573. var curve = new THREE.SplineCurve( npts );
  17574. this.curves.push( curve );
  17575. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  17576. };
  17577. // FUTURE: Change the API or follow canvas API?
  17578. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  17579. aStartAngle, aEndAngle, aClockwise ) {
  17580. var lastargs = this.actions[ this.actions.length - 1].args;
  17581. var x0 = lastargs[ lastargs.length - 2 ];
  17582. var y0 = lastargs[ lastargs.length - 1 ];
  17583. this.absarc(aX + x0, aY + y0, aRadius,
  17584. aStartAngle, aEndAngle, aClockwise );
  17585. };
  17586. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  17587. aStartAngle, aEndAngle, aClockwise ) {
  17588. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17589. };
  17590. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  17591. aStartAngle, aEndAngle, aClockwise ) {
  17592. var lastargs = this.actions[ this.actions.length - 1].args;
  17593. var x0 = lastargs[ lastargs.length - 2 ];
  17594. var y0 = lastargs[ lastargs.length - 1 ];
  17595. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  17596. aStartAngle, aEndAngle, aClockwise );
  17597. };
  17598. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  17599. aStartAngle, aEndAngle, aClockwise ) {
  17600. var args = Array.prototype.slice.call( arguments );
  17601. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  17602. aStartAngle, aEndAngle, aClockwise );
  17603. this.curves.push( curve );
  17604. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  17605. args.push(lastPoint.x);
  17606. args.push(lastPoint.y);
  17607. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17608. };
  17609. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17610. if ( ! divisions ) divisions = 40;
  17611. var points = [];
  17612. for ( var i = 0; i < divisions; i ++ ) {
  17613. points.push( this.getPoint( i / divisions ) );
  17614. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17615. }
  17616. // if ( closedPath ) {
  17617. //
  17618. // points.push( points[ 0 ] );
  17619. //
  17620. // }
  17621. return points;
  17622. };
  17623. /* Return an array of vectors based on contour of the path */
  17624. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17625. if (this.useSpacedPoints) {
  17626. console.log('tata');
  17627. return this.getSpacedPoints( divisions, closedPath );
  17628. }
  17629. divisions = divisions || 12;
  17630. var points = [];
  17631. var i, il, item, action, args;
  17632. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17633. laste, j,
  17634. t, tx, ty;
  17635. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17636. item = this.actions[ i ];
  17637. action = item.action;
  17638. args = item.args;
  17639. switch( action ) {
  17640. case THREE.PathActions.MOVE_TO:
  17641. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17642. break;
  17643. case THREE.PathActions.LINE_TO:
  17644. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17645. break;
  17646. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17647. cpx = args[ 2 ];
  17648. cpy = args[ 3 ];
  17649. cpx1 = args[ 0 ];
  17650. cpy1 = args[ 1 ];
  17651. if ( points.length > 0 ) {
  17652. laste = points[ points.length - 1 ];
  17653. cpx0 = laste.x;
  17654. cpy0 = laste.y;
  17655. } else {
  17656. laste = this.actions[ i - 1 ].args;
  17657. cpx0 = laste[ laste.length - 2 ];
  17658. cpy0 = laste[ laste.length - 1 ];
  17659. }
  17660. for ( j = 1; j <= divisions; j ++ ) {
  17661. t = j / divisions;
  17662. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17663. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17664. points.push( new THREE.Vector2( tx, ty ) );
  17665. }
  17666. break;
  17667. case THREE.PathActions.BEZIER_CURVE_TO:
  17668. cpx = args[ 4 ];
  17669. cpy = args[ 5 ];
  17670. cpx1 = args[ 0 ];
  17671. cpy1 = args[ 1 ];
  17672. cpx2 = args[ 2 ];
  17673. cpy2 = args[ 3 ];
  17674. if ( points.length > 0 ) {
  17675. laste = points[ points.length - 1 ];
  17676. cpx0 = laste.x;
  17677. cpy0 = laste.y;
  17678. } else {
  17679. laste = this.actions[ i - 1 ].args;
  17680. cpx0 = laste[ laste.length - 2 ];
  17681. cpy0 = laste[ laste.length - 1 ];
  17682. }
  17683. for ( j = 1; j <= divisions; j ++ ) {
  17684. t = j / divisions;
  17685. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17686. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17687. points.push( new THREE.Vector2( tx, ty ) );
  17688. }
  17689. break;
  17690. case THREE.PathActions.CSPLINE_THRU:
  17691. laste = this.actions[ i - 1 ].args;
  17692. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17693. var spts = [ last ];
  17694. var n = divisions * args[ 0 ].length;
  17695. spts = spts.concat( args[ 0 ] );
  17696. var spline = new THREE.SplineCurve( spts );
  17697. for ( j = 1; j <= n; j ++ ) {
  17698. points.push( spline.getPointAt( j / n ) ) ;
  17699. }
  17700. break;
  17701. case THREE.PathActions.ARC:
  17702. var aX = args[ 0 ], aY = args[ 1 ],
  17703. aRadius = args[ 2 ],
  17704. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17705. aClockwise = !!args[ 5 ];
  17706. var deltaAngle = aEndAngle - aStartAngle;
  17707. var angle;
  17708. var tdivisions = divisions * 2;
  17709. for ( j = 1; j <= tdivisions; j ++ ) {
  17710. t = j / tdivisions;
  17711. if ( ! aClockwise ) {
  17712. t = 1 - t;
  17713. }
  17714. angle = aStartAngle + t * deltaAngle;
  17715. tx = aX + aRadius * Math.cos( angle );
  17716. ty = aY + aRadius * Math.sin( angle );
  17717. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17718. points.push( new THREE.Vector2( tx, ty ) );
  17719. }
  17720. //console.log(points);
  17721. break;
  17722. case THREE.PathActions.ELLIPSE:
  17723. var aX = args[ 0 ], aY = args[ 1 ],
  17724. xRadius = args[ 2 ],
  17725. yRadius = args[ 3 ],
  17726. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17727. aClockwise = !!args[ 6 ];
  17728. var deltaAngle = aEndAngle - aStartAngle;
  17729. var angle;
  17730. var tdivisions = divisions * 2;
  17731. for ( j = 1; j <= tdivisions; j ++ ) {
  17732. t = j / tdivisions;
  17733. if ( ! aClockwise ) {
  17734. t = 1 - t;
  17735. }
  17736. angle = aStartAngle + t * deltaAngle;
  17737. tx = aX + xRadius * Math.cos( angle );
  17738. ty = aY + yRadius * Math.sin( angle );
  17739. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17740. points.push( new THREE.Vector2( tx, ty ) );
  17741. }
  17742. //console.log(points);
  17743. break;
  17744. } // end switch
  17745. }
  17746. // Normalize to remove the closing point by default.
  17747. var lastPoint = points[ points.length - 1];
  17748. var EPSILON = 0.0000000001;
  17749. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17750. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17751. points.splice( points.length - 1, 1);
  17752. if ( closedPath ) {
  17753. points.push( points[ 0 ] );
  17754. }
  17755. return points;
  17756. };
  17757. // Breaks path into shapes
  17758. THREE.Path.prototype.toShapes = function( isCCW ) {
  17759. var i, il, item, action, args;
  17760. var subPaths = [], lastPath = new THREE.Path();
  17761. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17762. item = this.actions[ i ];
  17763. args = item.args;
  17764. action = item.action;
  17765. if ( action == THREE.PathActions.MOVE_TO ) {
  17766. if ( lastPath.actions.length != 0 ) {
  17767. subPaths.push( lastPath );
  17768. lastPath = new THREE.Path();
  17769. }
  17770. }
  17771. lastPath[ action ].apply( lastPath, args );
  17772. }
  17773. if ( lastPath.actions.length != 0 ) {
  17774. subPaths.push( lastPath );
  17775. }
  17776. // console.log(subPaths);
  17777. if ( subPaths.length == 0 ) return [];
  17778. var solid, tmpPath, tmpShape, shapes = [];
  17779. if ( subPaths.length == 1) {
  17780. tmpPath = subPaths[0];
  17781. tmpShape = new THREE.Shape();
  17782. tmpShape.actions = tmpPath.actions;
  17783. tmpShape.curves = tmpPath.curves;
  17784. shapes.push( tmpShape );
  17785. return shapes;
  17786. }
  17787. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17788. holesFirst = isCCW ? !holesFirst : holesFirst;
  17789. // console.log("Holes first", holesFirst);
  17790. if ( holesFirst ) {
  17791. tmpShape = new THREE.Shape();
  17792. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17793. tmpPath = subPaths[ i ];
  17794. solid = THREE.Shape.Utils.isClockWise( tmpPath.getPoints() );
  17795. solid = isCCW ? !solid : solid;
  17796. if ( solid ) {
  17797. tmpShape.actions = tmpPath.actions;
  17798. tmpShape.curves = tmpPath.curves;
  17799. shapes.push( tmpShape );
  17800. tmpShape = new THREE.Shape();
  17801. //console.log('cw', i);
  17802. } else {
  17803. tmpShape.holes.push( tmpPath );
  17804. //console.log('ccw', i);
  17805. }
  17806. }
  17807. } else {
  17808. // Shapes first
  17809. tmpShape = undefined;
  17810. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17811. tmpPath = subPaths[ i ];
  17812. solid = THREE.Shape.Utils.isClockWise( tmpPath.getPoints() );
  17813. solid = isCCW ? !solid : solid;
  17814. if ( solid ) {
  17815. if ( tmpShape ) shapes.push( tmpShape );
  17816. tmpShape = new THREE.Shape();
  17817. tmpShape.actions = tmpPath.actions;
  17818. tmpShape.curves = tmpPath.curves;
  17819. } else {
  17820. tmpShape.holes.push( tmpPath );
  17821. }
  17822. }
  17823. shapes.push( tmpShape );
  17824. }
  17825. //console.log("shape", shapes);
  17826. return shapes;
  17827. };
  17828. /**
  17829. * @author zz85 / http://www.lab4games.net/zz85/blog
  17830. * Defines a 2d shape plane using paths.
  17831. **/
  17832. // STEP 1 Create a path.
  17833. // STEP 2 Turn path into shape.
  17834. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17835. // STEP 3a - Extract points from each shape, turn to vertices
  17836. // STEP 3b - Triangulate each shape, add faces.
  17837. THREE.Shape = function () {
  17838. THREE.Path.apply( this, arguments );
  17839. this.holes = [];
  17840. };
  17841. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17842. // Convenience method to return ExtrudeGeometry
  17843. THREE.Shape.prototype.extrude = function ( options ) {
  17844. var extruded = new THREE.ExtrudeGeometry( this, options );
  17845. return extruded;
  17846. };
  17847. // Convenience method to return ShapeGeometry
  17848. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17849. var geometry = new THREE.ShapeGeometry( this, options );
  17850. return geometry;
  17851. };
  17852. // Get points of holes
  17853. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17854. var i, il = this.holes.length, holesPts = [];
  17855. for ( i = 0; i < il; i ++ ) {
  17856. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17857. }
  17858. return holesPts;
  17859. };
  17860. // Get points of holes (spaced by regular distance)
  17861. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17862. var i, il = this.holes.length, holesPts = [];
  17863. for ( i = 0; i < il; i ++ ) {
  17864. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17865. }
  17866. return holesPts;
  17867. };
  17868. // Get points of shape and holes (keypoints based on segments parameter)
  17869. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17870. return {
  17871. shape: this.getTransformedPoints( divisions ),
  17872. holes: this.getPointsHoles( divisions )
  17873. };
  17874. };
  17875. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17876. if (this.useSpacedPoints) {
  17877. return this.extractAllSpacedPoints(divisions);
  17878. }
  17879. return this.extractAllPoints(divisions);
  17880. };
  17881. //
  17882. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17883. //
  17884. // return {
  17885. //
  17886. // shape: this.transform( bend, divisions ),
  17887. // holes: this.getPointsHoles( divisions, bend )
  17888. //
  17889. // };
  17890. //
  17891. // };
  17892. // Get points of shape and holes (spaced by regular distance)
  17893. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17894. return {
  17895. shape: this.getTransformedSpacedPoints( divisions ),
  17896. holes: this.getSpacedPointsHoles( divisions )
  17897. };
  17898. };
  17899. /**************************************************************
  17900. * Utils
  17901. **************************************************************/
  17902. THREE.Shape.Utils = {
  17903. /*
  17904. contour - array of vector2 for contour
  17905. holes - array of array of vector2
  17906. */
  17907. removeHoles: function ( contour, holes ) {
  17908. var shape = contour.concat(); // work on this shape
  17909. var allpoints = shape.concat();
  17910. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17911. var prevShapeVert, nextShapeVert,
  17912. prevHoleVert, nextHoleVert,
  17913. holeIndex, shapeIndex,
  17914. shapeId, shapeGroup,
  17915. h, h2,
  17916. hole, shortest, d,
  17917. p, pts1, pts2,
  17918. tmpShape1, tmpShape2,
  17919. tmpHole1, tmpHole2,
  17920. verts = [];
  17921. for ( h = 0; h < holes.length; h ++ ) {
  17922. hole = holes[ h ];
  17923. /*
  17924. shapeholes[ h ].concat(); // preserves original
  17925. holes.push( hole );
  17926. */
  17927. Array.prototype.push.apply( allpoints, hole );
  17928. shortest = Number.POSITIVE_INFINITY;
  17929. // Find the shortest pair of pts between shape and hole
  17930. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17931. // Using distanceToSquared() intead of distanceTo() should speed a little
  17932. // since running square roots operations are reduced.
  17933. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17934. pts1 = hole[ h2 ];
  17935. var dist = [];
  17936. for ( p = 0; p < shape.length; p++ ) {
  17937. pts2 = shape[ p ];
  17938. d = pts1.distanceToSquared( pts2 );
  17939. dist.push( d );
  17940. if ( d < shortest ) {
  17941. shortest = d;
  17942. holeIndex = h2;
  17943. shapeIndex = p;
  17944. }
  17945. }
  17946. }
  17947. //console.log("shortest", shortest, dist);
  17948. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17949. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17950. var areaapts = [
  17951. hole[ holeIndex ],
  17952. shape[ shapeIndex ],
  17953. shape[ prevShapeVert ]
  17954. ];
  17955. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17956. var areabpts = [
  17957. hole[ holeIndex ],
  17958. hole[ prevHoleVert ],
  17959. shape[ shapeIndex ]
  17960. ];
  17961. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17962. var shapeOffset = 1;
  17963. var holeOffset = -1;
  17964. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17965. shapeIndex += shapeOffset;
  17966. holeIndex += holeOffset;
  17967. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17968. shapeIndex %= shape.length;
  17969. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17970. holeIndex %= hole.length;
  17971. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17972. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17973. areaapts = [
  17974. hole[ holeIndex ],
  17975. shape[ shapeIndex ],
  17976. shape[ prevShapeVert ]
  17977. ];
  17978. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17979. areabpts = [
  17980. hole[ holeIndex ],
  17981. hole[ prevHoleVert ],
  17982. shape[ shapeIndex ]
  17983. ];
  17984. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17985. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17986. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17987. // In case areas are not correct.
  17988. //console.log("USE THIS");
  17989. shapeIndex = oldShapeIndex;
  17990. holeIndex = oldHoleIndex ;
  17991. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17992. shapeIndex %= shape.length;
  17993. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17994. holeIndex %= hole.length;
  17995. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17996. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17997. } else {
  17998. //console.log("USE THAT ")
  17999. }
  18000. tmpShape1 = shape.slice( 0, shapeIndex );
  18001. tmpShape2 = shape.slice( shapeIndex );
  18002. tmpHole1 = hole.slice( holeIndex );
  18003. tmpHole2 = hole.slice( 0, holeIndex );
  18004. // Should check orders here again?
  18005. var trianglea = [
  18006. hole[ holeIndex ],
  18007. shape[ shapeIndex ],
  18008. shape[ prevShapeVert ]
  18009. ];
  18010. var triangleb = [
  18011. hole[ holeIndex ] ,
  18012. hole[ prevHoleVert ],
  18013. shape[ shapeIndex ]
  18014. ];
  18015. verts.push( trianglea );
  18016. verts.push( triangleb );
  18017. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  18018. }
  18019. return {
  18020. shape:shape, /* shape with no holes */
  18021. isolatedPts: verts, /* isolated faces */
  18022. allpoints: allpoints
  18023. }
  18024. },
  18025. triangulateShape: function ( contour, holes ) {
  18026. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  18027. var shape = shapeWithoutHoles.shape,
  18028. allpoints = shapeWithoutHoles.allpoints,
  18029. isolatedPts = shapeWithoutHoles.isolatedPts;
  18030. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  18031. // 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.
  18032. //console.log( "triangles",triangles, triangles.length );
  18033. //console.log( "allpoints",allpoints, allpoints.length );
  18034. var i, il, f, face,
  18035. key, index,
  18036. allPointsMap = {},
  18037. isolatedPointsMap = {};
  18038. // prepare all points map
  18039. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  18040. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  18041. if ( allPointsMap[ key ] !== undefined ) {
  18042. console.log( "Duplicate point", key );
  18043. }
  18044. allPointsMap[ key ] = i;
  18045. }
  18046. // check all face vertices against all points map
  18047. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  18048. face = triangles[ i ];
  18049. for ( f = 0; f < 3; f ++ ) {
  18050. key = face[ f ].x + ":" + face[ f ].y;
  18051. index = allPointsMap[ key ];
  18052. if ( index !== undefined ) {
  18053. face[ f ] = index;
  18054. }
  18055. }
  18056. }
  18057. // check isolated points vertices against all points map
  18058. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  18059. face = isolatedPts[ i ];
  18060. for ( f = 0; f < 3; f ++ ) {
  18061. key = face[ f ].x + ":" + face[ f ].y;
  18062. index = allPointsMap[ key ];
  18063. if ( index !== undefined ) {
  18064. face[ f ] = index;
  18065. }
  18066. }
  18067. }
  18068. return triangles.concat( isolatedPts );
  18069. }, // end triangulate shapes
  18070. /*
  18071. triangulate2 : function( pts, holes ) {
  18072. // For use with Poly2Tri.js
  18073. var allpts = pts.concat();
  18074. var shape = [];
  18075. for (var p in pts) {
  18076. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  18077. }
  18078. var swctx = new js.poly2tri.SweepContext(shape);
  18079. for (var h in holes) {
  18080. var aHole = holes[h];
  18081. var newHole = []
  18082. for (i in aHole) {
  18083. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  18084. allpts.push(aHole[i]);
  18085. }
  18086. swctx.AddHole(newHole);
  18087. }
  18088. var find;
  18089. var findIndexForPt = function (pt) {
  18090. find = new THREE.Vector2(pt.x, pt.y);
  18091. var p;
  18092. for (p=0, pl = allpts.length; p<pl; p++) {
  18093. if (allpts[p].equals(find)) return p;
  18094. }
  18095. return -1;
  18096. };
  18097. // triangulate
  18098. js.poly2tri.sweep.Triangulate(swctx);
  18099. var triangles = swctx.GetTriangles();
  18100. var tr ;
  18101. var facesPts = [];
  18102. for (var t in triangles) {
  18103. tr = triangles[t];
  18104. facesPts.push([
  18105. findIndexForPt(tr.GetPoint(0)),
  18106. findIndexForPt(tr.GetPoint(1)),
  18107. findIndexForPt(tr.GetPoint(2))
  18108. ]);
  18109. }
  18110. // console.log(facesPts);
  18111. // console.log("triangles", triangles.length, triangles);
  18112. // Returns array of faces with 3 element each
  18113. return facesPts;
  18114. },
  18115. */
  18116. isClockWise: function ( pts ) {
  18117. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  18118. },
  18119. // Bezier Curves formulas obtained from
  18120. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  18121. // Quad Bezier Functions
  18122. b2p0: function ( t, p ) {
  18123. var k = 1 - t;
  18124. return k * k * p;
  18125. },
  18126. b2p1: function ( t, p ) {
  18127. return 2 * ( 1 - t ) * t * p;
  18128. },
  18129. b2p2: function ( t, p ) {
  18130. return t * t * p;
  18131. },
  18132. b2: function ( t, p0, p1, p2 ) {
  18133. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  18134. },
  18135. // Cubic Bezier Functions
  18136. b3p0: function ( t, p ) {
  18137. var k = 1 - t;
  18138. return k * k * k * p;
  18139. },
  18140. b3p1: function ( t, p ) {
  18141. var k = 1 - t;
  18142. return 3 * k * k * t * p;
  18143. },
  18144. b3p2: function ( t, p ) {
  18145. var k = 1 - t;
  18146. return 3 * k * t * t * p;
  18147. },
  18148. b3p3: function ( t, p ) {
  18149. return t * t * t * p;
  18150. },
  18151. b3: function ( t, p0, p1, p2, p3 ) {
  18152. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  18153. }
  18154. };
  18155. /**************************************************************
  18156. * Line
  18157. **************************************************************/
  18158. THREE.LineCurve = function ( v1, v2 ) {
  18159. this.v1 = v1;
  18160. this.v2 = v2;
  18161. };
  18162. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  18163. THREE.LineCurve.prototype.getPoint = function ( t ) {
  18164. var point = this.v2.clone().sub(this.v1);
  18165. point.multiplyScalar( t ).add( this.v1 );
  18166. return point;
  18167. };
  18168. // Line curve is linear, so we can overwrite default getPointAt
  18169. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  18170. return this.getPoint( u );
  18171. };
  18172. THREE.LineCurve.prototype.getTangent = function( t ) {
  18173. var tangent = this.v2.clone().sub(this.v1);
  18174. return tangent.normalize();
  18175. };
  18176. /**************************************************************
  18177. * Quadratic Bezier curve
  18178. **************************************************************/
  18179. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  18180. this.v0 = v0;
  18181. this.v1 = v1;
  18182. this.v2 = v2;
  18183. };
  18184. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  18185. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  18186. var tx, ty;
  18187. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  18188. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  18189. return new THREE.Vector2( tx, ty );
  18190. };
  18191. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  18192. var tx, ty;
  18193. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  18194. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  18195. // returns unit vector
  18196. var tangent = new THREE.Vector2( tx, ty );
  18197. tangent.normalize();
  18198. return tangent;
  18199. };
  18200. /**************************************************************
  18201. * Cubic Bezier curve
  18202. **************************************************************/
  18203. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  18204. this.v0 = v0;
  18205. this.v1 = v1;
  18206. this.v2 = v2;
  18207. this.v3 = v3;
  18208. };
  18209. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  18210. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  18211. var tx, ty;
  18212. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18213. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18214. return new THREE.Vector2( tx, ty );
  18215. };
  18216. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  18217. var tx, ty;
  18218. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18219. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18220. var tangent = new THREE.Vector2( tx, ty );
  18221. tangent.normalize();
  18222. return tangent;
  18223. };
  18224. /**************************************************************
  18225. * Spline curve
  18226. **************************************************************/
  18227. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  18228. this.points = (points == undefined) ? [] : points;
  18229. };
  18230. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  18231. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  18232. var v = new THREE.Vector2();
  18233. var c = [];
  18234. var points = this.points, point, intPoint, weight;
  18235. point = ( points.length - 1 ) * t;
  18236. intPoint = Math.floor( point );
  18237. weight = point - intPoint;
  18238. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18239. c[ 1 ] = intPoint;
  18240. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  18241. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  18242. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  18243. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  18244. return v;
  18245. };
  18246. /**************************************************************
  18247. * Ellipse curve
  18248. **************************************************************/
  18249. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  18250. aStartAngle, aEndAngle,
  18251. aClockwise ) {
  18252. this.aX = aX;
  18253. this.aY = aY;
  18254. this.xRadius = xRadius;
  18255. this.yRadius = yRadius;
  18256. this.aStartAngle = aStartAngle;
  18257. this.aEndAngle = aEndAngle;
  18258. this.aClockwise = aClockwise;
  18259. };
  18260. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  18261. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  18262. var deltaAngle = this.aEndAngle - this.aStartAngle;
  18263. if ( !this.aClockwise ) {
  18264. t = 1 - t;
  18265. }
  18266. var angle = this.aStartAngle + t * deltaAngle;
  18267. var tx = this.aX + this.xRadius * Math.cos( angle );
  18268. var ty = this.aY + this.yRadius * Math.sin( angle );
  18269. return new THREE.Vector2( tx, ty );
  18270. };
  18271. /**************************************************************
  18272. * Arc curve
  18273. **************************************************************/
  18274. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18275. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18276. };
  18277. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  18278. /**************************************************************
  18279. * Line3D
  18280. **************************************************************/
  18281. THREE.LineCurve3 = THREE.Curve.create(
  18282. function ( v1, v2 ) {
  18283. this.v1 = v1;
  18284. this.v2 = v2;
  18285. },
  18286. function ( t ) {
  18287. var r = new THREE.Vector3();
  18288. r.subVectors( this.v2, this.v1 ); // diff
  18289. r.multiplyScalar( t );
  18290. r.add( this.v1 );
  18291. return r;
  18292. }
  18293. );
  18294. /**************************************************************
  18295. * Quadratic Bezier 3D curve
  18296. **************************************************************/
  18297. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  18298. function ( v0, v1, v2 ) {
  18299. this.v0 = v0;
  18300. this.v1 = v1;
  18301. this.v2 = v2;
  18302. },
  18303. function ( t ) {
  18304. var tx, ty, tz;
  18305. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  18306. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  18307. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  18308. return new THREE.Vector3( tx, ty, tz );
  18309. }
  18310. );
  18311. /**************************************************************
  18312. * Cubic Bezier 3D curve
  18313. **************************************************************/
  18314. THREE.CubicBezierCurve3 = THREE.Curve.create(
  18315. function ( v0, v1, v2, v3 ) {
  18316. this.v0 = v0;
  18317. this.v1 = v1;
  18318. this.v2 = v2;
  18319. this.v3 = v3;
  18320. },
  18321. function ( t ) {
  18322. var tx, ty, tz;
  18323. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18324. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18325. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  18326. return new THREE.Vector3( tx, ty, tz );
  18327. }
  18328. );
  18329. /**************************************************************
  18330. * Spline 3D curve
  18331. **************************************************************/
  18332. THREE.SplineCurve3 = THREE.Curve.create(
  18333. function ( points /* array of Vector3 */) {
  18334. this.points = (points == undefined) ? [] : points;
  18335. },
  18336. function ( t ) {
  18337. var v = new THREE.Vector3();
  18338. var c = [];
  18339. var points = this.points, point, intPoint, weight;
  18340. point = ( points.length - 1 ) * t;
  18341. intPoint = Math.floor( point );
  18342. weight = point - intPoint;
  18343. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18344. c[ 1 ] = intPoint;
  18345. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18346. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18347. var pt0 = points[ c[0] ],
  18348. pt1 = points[ c[1] ],
  18349. pt2 = points[ c[2] ],
  18350. pt3 = points[ c[3] ];
  18351. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  18352. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  18353. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  18354. return v;
  18355. }
  18356. );
  18357. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  18358. // var v = new THREE.Vector3();
  18359. // var c = [];
  18360. // var points = this.points, point, intPoint, weight;
  18361. // point = ( points.length - 1 ) * t;
  18362. // intPoint = Math.floor( point );
  18363. // weight = point - intPoint;
  18364. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18365. // c[ 1 ] = intPoint;
  18366. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18367. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18368. // var pt0 = points[ c[0] ],
  18369. // pt1 = points[ c[1] ],
  18370. // pt2 = points[ c[2] ],
  18371. // pt3 = points[ c[3] ];
  18372. // // t = weight;
  18373. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  18374. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  18375. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  18376. // return v;
  18377. // }
  18378. /**************************************************************
  18379. * Closed Spline 3D curve
  18380. **************************************************************/
  18381. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  18382. function ( points /* array of Vector3 */) {
  18383. this.points = (points == undefined) ? [] : points;
  18384. },
  18385. function ( t ) {
  18386. var v = new THREE.Vector3();
  18387. var c = [];
  18388. var points = this.points, point, intPoint, weight;
  18389. point = ( points.length - 0 ) * t;
  18390. // This needs to be from 0-length +1
  18391. intPoint = Math.floor( point );
  18392. weight = point - intPoint;
  18393. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  18394. c[ 0 ] = ( intPoint - 1 ) % points.length;
  18395. c[ 1 ] = ( intPoint ) % points.length;
  18396. c[ 2 ] = ( intPoint + 1 ) % points.length;
  18397. c[ 3 ] = ( intPoint + 2 ) % points.length;
  18398. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  18399. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  18400. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  18401. return v;
  18402. }
  18403. );
  18404. /**
  18405. * @author mikael emtinger / http://gomo.se/
  18406. */
  18407. THREE.AnimationHandler = (function() {
  18408. var playing = [];
  18409. var library = {};
  18410. var that = {};
  18411. //--- update ---
  18412. that.update = function( deltaTimeMS ) {
  18413. for( var i = 0; i < playing.length; i ++ )
  18414. playing[ i ].update( deltaTimeMS );
  18415. };
  18416. //--- add ---
  18417. that.addToUpdate = function( animation ) {
  18418. if ( playing.indexOf( animation ) === -1 )
  18419. playing.push( animation );
  18420. };
  18421. //--- remove ---
  18422. that.removeFromUpdate = function( animation ) {
  18423. var index = playing.indexOf( animation );
  18424. if( index !== -1 )
  18425. playing.splice( index, 1 );
  18426. };
  18427. //--- add ---
  18428. that.add = function( data ) {
  18429. if ( library[ data.name ] !== undefined )
  18430. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  18431. library[ data.name ] = data;
  18432. initData( data );
  18433. };
  18434. //--- get ---
  18435. that.get = function( name ) {
  18436. if ( typeof name === "string" ) {
  18437. if ( library[ name ] ) {
  18438. return library[ name ];
  18439. } else {
  18440. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  18441. return null;
  18442. }
  18443. } else {
  18444. // todo: add simple tween library
  18445. }
  18446. };
  18447. //--- parse ---
  18448. that.parse = function( root ) {
  18449. // setup hierarchy
  18450. var hierarchy = [];
  18451. if ( root instanceof THREE.SkinnedMesh ) {
  18452. for( var b = 0; b < root.bones.length; b++ ) {
  18453. hierarchy.push( root.bones[ b ] );
  18454. }
  18455. } else {
  18456. parseRecurseHierarchy( root, hierarchy );
  18457. }
  18458. return hierarchy;
  18459. };
  18460. var parseRecurseHierarchy = function( root, hierarchy ) {
  18461. hierarchy.push( root );
  18462. for( var c = 0; c < root.children.length; c++ )
  18463. parseRecurseHierarchy( root.children[ c ], hierarchy );
  18464. }
  18465. //--- init data ---
  18466. var initData = function( data ) {
  18467. if( data.initialized === true )
  18468. return;
  18469. // loop through all keys
  18470. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  18471. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18472. // remove minus times
  18473. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  18474. data.hierarchy[ h ].keys[ k ].time = 0;
  18475. // create quaternions
  18476. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  18477. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  18478. var quat = data.hierarchy[ h ].keys[ k ].rot;
  18479. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  18480. }
  18481. }
  18482. // prepare morph target keys
  18483. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  18484. // get all used
  18485. var usedMorphTargets = {};
  18486. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18487. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18488. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  18489. usedMorphTargets[ morphTargetName ] = -1;
  18490. }
  18491. }
  18492. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  18493. // set all used on all frames
  18494. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18495. var influences = {};
  18496. for ( var morphTargetName in usedMorphTargets ) {
  18497. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18498. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  18499. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  18500. break;
  18501. }
  18502. }
  18503. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  18504. influences[ morphTargetName ] = 0;
  18505. }
  18506. }
  18507. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  18508. }
  18509. }
  18510. // remove all keys that are on the same time
  18511. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18512. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  18513. data.hierarchy[ h ].keys.splice( k, 1 );
  18514. k --;
  18515. }
  18516. }
  18517. // set index
  18518. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18519. data.hierarchy[ h ].keys[ k ].index = k;
  18520. }
  18521. }
  18522. // JIT
  18523. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  18524. data.JIT = {};
  18525. data.JIT.hierarchy = [];
  18526. for( var h = 0; h < data.hierarchy.length; h ++ )
  18527. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  18528. // done
  18529. data.initialized = true;
  18530. };
  18531. // interpolation types
  18532. that.LINEAR = 0;
  18533. that.CATMULLROM = 1;
  18534. that.CATMULLROM_FORWARD = 2;
  18535. return that;
  18536. }());
  18537. /**
  18538. * @author mikael emtinger / http://gomo.se/
  18539. * @author mrdoob / http://mrdoob.com/
  18540. * @author alteredq / http://alteredqualia.com/
  18541. */
  18542. THREE.Animation = function ( root, name, interpolationType ) {
  18543. this.root = root;
  18544. this.data = THREE.AnimationHandler.get( name );
  18545. this.hierarchy = THREE.AnimationHandler.parse( root );
  18546. this.currentTime = 0;
  18547. this.timeScale = 1;
  18548. this.isPlaying = false;
  18549. this.isPaused = true;
  18550. this.loop = true;
  18551. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  18552. this.points = [];
  18553. this.target = new THREE.Vector3();
  18554. };
  18555. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  18556. if ( this.isPlaying === false ) {
  18557. this.isPlaying = true;
  18558. this.loop = loop !== undefined ? loop : true;
  18559. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18560. // reset key cache
  18561. var h, hl = this.hierarchy.length,
  18562. object;
  18563. for ( h = 0; h < hl; h ++ ) {
  18564. object = this.hierarchy[ h ];
  18565. object.matrixAutoUpdate = true;
  18566. if ( object.animationCache === undefined ) {
  18567. object.animationCache = {};
  18568. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  18569. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  18570. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18571. }
  18572. var prevKey = object.animationCache.prevKey;
  18573. var nextKey = object.animationCache.nextKey;
  18574. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  18575. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  18576. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  18577. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  18578. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  18579. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  18580. }
  18581. this.update( 0 );
  18582. }
  18583. this.isPaused = false;
  18584. THREE.AnimationHandler.addToUpdate( this );
  18585. };
  18586. THREE.Animation.prototype.pause = function() {
  18587. if ( this.isPaused === true ) {
  18588. THREE.AnimationHandler.addToUpdate( this );
  18589. } else {
  18590. THREE.AnimationHandler.removeFromUpdate( this );
  18591. }
  18592. this.isPaused = !this.isPaused;
  18593. };
  18594. THREE.Animation.prototype.stop = function() {
  18595. this.isPlaying = false;
  18596. this.isPaused = false;
  18597. THREE.AnimationHandler.removeFromUpdate( this );
  18598. };
  18599. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  18600. // early out
  18601. if ( this.isPlaying === false ) return;
  18602. // vars
  18603. var types = [ "pos", "rot", "scl" ];
  18604. var type;
  18605. var scale;
  18606. var vector;
  18607. var prevXYZ, nextXYZ;
  18608. var prevKey, nextKey;
  18609. var object;
  18610. var animationCache;
  18611. var frame;
  18612. var JIThierarchy = this.data.JIT.hierarchy;
  18613. var currentTime, unloopedCurrentTime;
  18614. var currentPoint, forwardPoint, angle;
  18615. this.currentTime += deltaTimeMS * this.timeScale;
  18616. unloopedCurrentTime = this.currentTime;
  18617. currentTime = this.currentTime = this.currentTime % this.data.length;
  18618. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18619. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18620. object = this.hierarchy[ h ];
  18621. animationCache = object.animationCache;
  18622. // loop through pos/rot/scl
  18623. for ( var t = 0; t < 3; t ++ ) {
  18624. // get keys
  18625. type = types[ t ];
  18626. prevKey = animationCache.prevKey[ type ];
  18627. nextKey = animationCache.nextKey[ type ];
  18628. // switch keys?
  18629. if ( nextKey.time <= unloopedCurrentTime ) {
  18630. // did we loop?
  18631. if ( currentTime < unloopedCurrentTime ) {
  18632. if ( this.loop ) {
  18633. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18634. nextKey = this.getNextKeyWith( type, h, 1 );
  18635. while( nextKey.time < currentTime ) {
  18636. prevKey = nextKey;
  18637. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18638. }
  18639. } else {
  18640. this.stop();
  18641. return;
  18642. }
  18643. } else {
  18644. do {
  18645. prevKey = nextKey;
  18646. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18647. } while( nextKey.time < currentTime )
  18648. }
  18649. animationCache.prevKey[ type ] = prevKey;
  18650. animationCache.nextKey[ type ] = nextKey;
  18651. }
  18652. object.matrixAutoUpdate = true;
  18653. object.matrixWorldNeedsUpdate = true;
  18654. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18655. prevXYZ = prevKey[ type ];
  18656. nextXYZ = nextKey[ type ];
  18657. // check scale error
  18658. if ( scale < 0 || scale > 1 ) {
  18659. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  18660. scale = scale < 0 ? 0 : 1;
  18661. }
  18662. // interpolate
  18663. if ( type === "pos" ) {
  18664. vector = object.position;
  18665. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18666. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18667. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18668. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18669. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18670. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18671. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18672. this.points[ 1 ] = prevXYZ;
  18673. this.points[ 2 ] = nextXYZ;
  18674. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18675. scale = scale * 0.33 + 0.33;
  18676. currentPoint = this.interpolateCatmullRom( this.points, scale );
  18677. vector.x = currentPoint[ 0 ];
  18678. vector.y = currentPoint[ 1 ];
  18679. vector.z = currentPoint[ 2 ];
  18680. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18681. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  18682. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18683. this.target.sub( vector );
  18684. this.target.y = 0;
  18685. this.target.normalize();
  18686. angle = Math.atan2( this.target.x, this.target.z );
  18687. object.rotation.set( 0, angle, 0 );
  18688. }
  18689. }
  18690. } else if ( type === "rot" ) {
  18691. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  18692. } else if ( type === "scl" ) {
  18693. vector = object.scale;
  18694. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18695. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18696. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18697. }
  18698. }
  18699. }
  18700. };
  18701. // Catmull-Rom spline
  18702. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  18703. var c = [], v3 = [],
  18704. point, intPoint, weight, w2, w3,
  18705. pa, pb, pc, pd;
  18706. point = ( points.length - 1 ) * scale;
  18707. intPoint = Math.floor( point );
  18708. weight = point - intPoint;
  18709. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18710. c[ 1 ] = intPoint;
  18711. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18712. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18713. pa = points[ c[ 0 ] ];
  18714. pb = points[ c[ 1 ] ];
  18715. pc = points[ c[ 2 ] ];
  18716. pd = points[ c[ 3 ] ];
  18717. w2 = weight * weight;
  18718. w3 = weight * w2;
  18719. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18720. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18721. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18722. return v3;
  18723. };
  18724. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18725. var v0 = ( p2 - p0 ) * 0.5,
  18726. v1 = ( p3 - p1 ) * 0.5;
  18727. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18728. };
  18729. // Get next key with
  18730. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18731. var keys = this.data.hierarchy[ h ].keys;
  18732. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18733. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18734. key = key < keys.length - 1 ? key : keys.length - 1;
  18735. } else {
  18736. key = key % keys.length;
  18737. }
  18738. for ( ; key < keys.length; key++ ) {
  18739. if ( keys[ key ][ type ] !== undefined ) {
  18740. return keys[ key ];
  18741. }
  18742. }
  18743. return this.data.hierarchy[ h ].keys[ 0 ];
  18744. };
  18745. // Get previous key with
  18746. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18747. var keys = this.data.hierarchy[ h ].keys;
  18748. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18749. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18750. key = key > 0 ? key : 0;
  18751. } else {
  18752. key = key >= 0 ? key : key + keys.length;
  18753. }
  18754. for ( ; key >= 0; key -- ) {
  18755. if ( keys[ key ][ type ] !== undefined ) {
  18756. return keys[ key ];
  18757. }
  18758. }
  18759. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18760. };
  18761. /**
  18762. * @author mikael emtinger / http://gomo.se/
  18763. * @author mrdoob / http://mrdoob.com/
  18764. * @author alteredq / http://alteredqualia.com/
  18765. * @author khang duong
  18766. * @author erik kitson
  18767. */
  18768. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  18769. this.root = root;
  18770. this.data = THREE.AnimationHandler.get( data );
  18771. this.hierarchy = THREE.AnimationHandler.parse( root );
  18772. this.currentTime = 0;
  18773. this.timeScale = 0.001;
  18774. this.isPlaying = false;
  18775. this.isPaused = true;
  18776. this.loop = true;
  18777. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  18778. // initialize to first keyframes
  18779. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18780. var keys = this.data.hierarchy[h].keys,
  18781. sids = this.data.hierarchy[h].sids,
  18782. obj = this.hierarchy[h];
  18783. if ( keys.length && sids ) {
  18784. for ( var s = 0; s < sids.length; s++ ) {
  18785. var sid = sids[ s ],
  18786. next = this.getNextKeyWith( sid, h, 0 );
  18787. if ( next ) {
  18788. next.apply( sid );
  18789. }
  18790. }
  18791. obj.matrixAutoUpdate = false;
  18792. this.data.hierarchy[h].node.updateMatrix();
  18793. obj.matrixWorldNeedsUpdate = true;
  18794. }
  18795. }
  18796. };
  18797. // Play
  18798. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  18799. if( !this.isPlaying ) {
  18800. this.isPlaying = true;
  18801. this.loop = loop !== undefined ? loop : true;
  18802. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18803. this.startTimeMs = startTimeMS;
  18804. this.startTime = 10000000;
  18805. this.endTime = -this.startTime;
  18806. // reset key cache
  18807. var h, hl = this.hierarchy.length,
  18808. object,
  18809. node;
  18810. for ( h = 0; h < hl; h++ ) {
  18811. object = this.hierarchy[ h ];
  18812. node = this.data.hierarchy[ h ];
  18813. if ( node.animationCache === undefined ) {
  18814. node.animationCache = {};
  18815. node.animationCache.prevKey = null;
  18816. node.animationCache.nextKey = null;
  18817. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18818. }
  18819. var keys = this.data.hierarchy[h].keys;
  18820. if (keys.length) {
  18821. node.animationCache.prevKey = keys[ 0 ];
  18822. node.animationCache.nextKey = keys[ 1 ];
  18823. this.startTime = Math.min( keys[0].time, this.startTime );
  18824. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18825. }
  18826. }
  18827. this.update( 0 );
  18828. }
  18829. this.isPaused = false;
  18830. THREE.AnimationHandler.addToUpdate( this );
  18831. };
  18832. // Pause
  18833. THREE.KeyFrameAnimation.prototype.pause = function() {
  18834. if( this.isPaused ) {
  18835. THREE.AnimationHandler.addToUpdate( this );
  18836. } else {
  18837. THREE.AnimationHandler.removeFromUpdate( this );
  18838. }
  18839. this.isPaused = !this.isPaused;
  18840. };
  18841. // Stop
  18842. THREE.KeyFrameAnimation.prototype.stop = function() {
  18843. this.isPlaying = false;
  18844. this.isPaused = false;
  18845. THREE.AnimationHandler.removeFromUpdate( this );
  18846. // reset JIT matrix and remove cache
  18847. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18848. var obj = this.hierarchy[ h ];
  18849. var node = this.data.hierarchy[ h ];
  18850. if ( node.animationCache !== undefined ) {
  18851. var original = node.animationCache.originalMatrix;
  18852. if( obj instanceof THREE.Bone ) {
  18853. original.copy( obj.skinMatrix );
  18854. obj.skinMatrix = original;
  18855. } else {
  18856. original.copy( obj.matrix );
  18857. obj.matrix = original;
  18858. }
  18859. delete node.animationCache;
  18860. }
  18861. }
  18862. };
  18863. // Update
  18864. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  18865. // early out
  18866. if( !this.isPlaying ) return;
  18867. // vars
  18868. var prevKey, nextKey;
  18869. var object;
  18870. var node;
  18871. var frame;
  18872. var JIThierarchy = this.data.JIT.hierarchy;
  18873. var currentTime, unloopedCurrentTime;
  18874. var looped;
  18875. // update
  18876. this.currentTime += deltaTimeMS * this.timeScale;
  18877. unloopedCurrentTime = this.currentTime;
  18878. currentTime = this.currentTime = this.currentTime % this.data.length;
  18879. // if looped around, the current time should be based on the startTime
  18880. if ( currentTime < this.startTimeMs ) {
  18881. currentTime = this.currentTime = this.startTimeMs + currentTime;
  18882. }
  18883. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18884. looped = currentTime < unloopedCurrentTime;
  18885. if ( looped && !this.loop ) {
  18886. // Set the animation to the last keyframes and stop
  18887. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18888. var keys = this.data.hierarchy[h].keys,
  18889. sids = this.data.hierarchy[h].sids,
  18890. end = keys.length-1,
  18891. obj = this.hierarchy[h];
  18892. if ( keys.length ) {
  18893. for ( var s = 0; s < sids.length; s++ ) {
  18894. var sid = sids[ s ],
  18895. prev = this.getPrevKeyWith( sid, h, end );
  18896. if ( prev ) {
  18897. prev.apply( sid );
  18898. }
  18899. }
  18900. this.data.hierarchy[h].node.updateMatrix();
  18901. obj.matrixWorldNeedsUpdate = true;
  18902. }
  18903. }
  18904. this.stop();
  18905. return;
  18906. }
  18907. // check pre-infinity
  18908. if ( currentTime < this.startTime ) {
  18909. return;
  18910. }
  18911. // update
  18912. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18913. object = this.hierarchy[ h ];
  18914. node = this.data.hierarchy[ h ];
  18915. var keys = node.keys,
  18916. animationCache = node.animationCache;
  18917. // use JIT?
  18918. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  18919. if( object instanceof THREE.Bone ) {
  18920. object.skinMatrix = JIThierarchy[ h ][ frame ];
  18921. object.matrixWorldNeedsUpdate = false;
  18922. } else {
  18923. object.matrix = JIThierarchy[ h ][ frame ];
  18924. object.matrixWorldNeedsUpdate = true;
  18925. }
  18926. // use interpolation
  18927. } else if ( keys.length ) {
  18928. // make sure so original matrix and not JIT matrix is set
  18929. if ( this.JITCompile && animationCache ) {
  18930. if( object instanceof THREE.Bone ) {
  18931. object.skinMatrix = animationCache.originalMatrix;
  18932. } else {
  18933. object.matrix = animationCache.originalMatrix;
  18934. }
  18935. }
  18936. prevKey = animationCache.prevKey;
  18937. nextKey = animationCache.nextKey;
  18938. if ( prevKey && nextKey ) {
  18939. // switch keys?
  18940. if ( nextKey.time <= unloopedCurrentTime ) {
  18941. // did we loop?
  18942. if ( looped && this.loop ) {
  18943. prevKey = keys[ 0 ];
  18944. nextKey = keys[ 1 ];
  18945. while ( nextKey.time < currentTime ) {
  18946. prevKey = nextKey;
  18947. nextKey = keys[ prevKey.index + 1 ];
  18948. }
  18949. } else if ( !looped ) {
  18950. var lastIndex = keys.length - 1;
  18951. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18952. prevKey = nextKey;
  18953. nextKey = keys[ prevKey.index + 1 ];
  18954. }
  18955. }
  18956. animationCache.prevKey = prevKey;
  18957. animationCache.nextKey = nextKey;
  18958. }
  18959. if(nextKey.time >= currentTime)
  18960. prevKey.interpolate( nextKey, currentTime );
  18961. else
  18962. prevKey.interpolate( nextKey, nextKey.time);
  18963. }
  18964. this.data.hierarchy[h].node.updateMatrix();
  18965. object.matrixWorldNeedsUpdate = true;
  18966. }
  18967. }
  18968. // update JIT?
  18969. if ( this.JITCompile ) {
  18970. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18971. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18972. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18973. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18974. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18975. } else {
  18976. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18977. }
  18978. }
  18979. }
  18980. }
  18981. };
  18982. // Get next key with
  18983. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18984. var keys = this.data.hierarchy[ h ].keys;
  18985. key = key % keys.length;
  18986. for ( ; key < keys.length; key++ ) {
  18987. if ( keys[ key ].hasTarget( sid ) ) {
  18988. return keys[ key ];
  18989. }
  18990. }
  18991. return keys[ 0 ];
  18992. };
  18993. // Get previous key with
  18994. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18995. var keys = this.data.hierarchy[ h ].keys;
  18996. key = key >= 0 ? key : key + keys.length;
  18997. for ( ; key >= 0; key-- ) {
  18998. if ( keys[ key ].hasTarget( sid ) ) {
  18999. return keys[ key ];
  19000. }
  19001. }
  19002. return keys[ keys.length - 1 ];
  19003. };
  19004. /**
  19005. * Camera for rendering cube maps
  19006. * - renders scene into axis-aligned cube
  19007. *
  19008. * @author alteredq / http://alteredqualia.com/
  19009. */
  19010. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  19011. THREE.Object3D.call( this );
  19012. var fov = 90, aspect = 1;
  19013. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19014. cameraPX.up.set( 0, -1, 0 );
  19015. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  19016. this.add( cameraPX );
  19017. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19018. cameraNX.up.set( 0, -1, 0 );
  19019. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  19020. this.add( cameraNX );
  19021. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19022. cameraPY.up.set( 0, 0, 1 );
  19023. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  19024. this.add( cameraPY );
  19025. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19026. cameraNY.up.set( 0, 0, -1 );
  19027. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  19028. this.add( cameraNY );
  19029. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19030. cameraPZ.up.set( 0, -1, 0 );
  19031. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  19032. this.add( cameraPZ );
  19033. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19034. cameraNZ.up.set( 0, -1, 0 );
  19035. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  19036. this.add( cameraNZ );
  19037. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  19038. this.updateCubeMap = function ( renderer, scene ) {
  19039. var renderTarget = this.renderTarget;
  19040. var generateMipmaps = renderTarget.generateMipmaps;
  19041. renderTarget.generateMipmaps = false;
  19042. renderTarget.activeCubeFace = 0;
  19043. renderer.render( scene, cameraPX, renderTarget );
  19044. renderTarget.activeCubeFace = 1;
  19045. renderer.render( scene, cameraNX, renderTarget );
  19046. renderTarget.activeCubeFace = 2;
  19047. renderer.render( scene, cameraPY, renderTarget );
  19048. renderTarget.activeCubeFace = 3;
  19049. renderer.render( scene, cameraNY, renderTarget );
  19050. renderTarget.activeCubeFace = 4;
  19051. renderer.render( scene, cameraPZ, renderTarget );
  19052. renderTarget.generateMipmaps = generateMipmaps;
  19053. renderTarget.activeCubeFace = 5;
  19054. renderer.render( scene, cameraNZ, renderTarget );
  19055. };
  19056. };
  19057. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  19058. /*
  19059. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  19060. *
  19061. * A general perpose camera, for setting FOV, Lens Focal Length,
  19062. * and switching between perspective and orthographic views easily.
  19063. * Use this only if you do not wish to manage
  19064. * both a Orthographic and Perspective Camera
  19065. *
  19066. */
  19067. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  19068. THREE.Camera.call( this );
  19069. this.fov = fov;
  19070. this.left = -width / 2;
  19071. this.right = width / 2
  19072. this.top = height / 2;
  19073. this.bottom = -height / 2;
  19074. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  19075. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  19076. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  19077. this.zoom = 1;
  19078. this.toPerspective();
  19079. var aspect = width/height;
  19080. };
  19081. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  19082. THREE.CombinedCamera.prototype.toPerspective = function () {
  19083. // Switches to the Perspective Camera
  19084. this.near = this.cameraP.near;
  19085. this.far = this.cameraP.far;
  19086. this.cameraP.fov = this.fov / this.zoom ;
  19087. this.cameraP.updateProjectionMatrix();
  19088. this.projectionMatrix = this.cameraP.projectionMatrix;
  19089. this.inPerspectiveMode = true;
  19090. this.inOrthographicMode = false;
  19091. };
  19092. THREE.CombinedCamera.prototype.toOrthographic = function () {
  19093. // Switches to the Orthographic camera estimating viewport from Perspective
  19094. var fov = this.fov;
  19095. var aspect = this.cameraP.aspect;
  19096. var near = this.cameraP.near;
  19097. var far = this.cameraP.far;
  19098. // The size that we set is the mid plane of the viewing frustum
  19099. var hyperfocus = ( near + far ) / 2;
  19100. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  19101. var planeHeight = 2 * halfHeight;
  19102. var planeWidth = planeHeight * aspect;
  19103. var halfWidth = planeWidth / 2;
  19104. halfHeight /= this.zoom;
  19105. halfWidth /= this.zoom;
  19106. this.cameraO.left = -halfWidth;
  19107. this.cameraO.right = halfWidth;
  19108. this.cameraO.top = halfHeight;
  19109. this.cameraO.bottom = -halfHeight;
  19110. // this.cameraO.left = -farHalfWidth;
  19111. // this.cameraO.right = farHalfWidth;
  19112. // this.cameraO.top = farHalfHeight;
  19113. // this.cameraO.bottom = -farHalfHeight;
  19114. // this.cameraO.left = this.left / this.zoom;
  19115. // this.cameraO.right = this.right / this.zoom;
  19116. // this.cameraO.top = this.top / this.zoom;
  19117. // this.cameraO.bottom = this.bottom / this.zoom;
  19118. this.cameraO.updateProjectionMatrix();
  19119. this.near = this.cameraO.near;
  19120. this.far = this.cameraO.far;
  19121. this.projectionMatrix = this.cameraO.projectionMatrix;
  19122. this.inPerspectiveMode = false;
  19123. this.inOrthographicMode = true;
  19124. };
  19125. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  19126. this.cameraP.aspect = width / height;
  19127. this.left = -width / 2;
  19128. this.right = width / 2
  19129. this.top = height / 2;
  19130. this.bottom = -height / 2;
  19131. };
  19132. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  19133. this.fov = fov;
  19134. if ( this.inPerspectiveMode ) {
  19135. this.toPerspective();
  19136. } else {
  19137. this.toOrthographic();
  19138. }
  19139. };
  19140. // For mantaining similar API with PerspectiveCamera
  19141. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  19142. if ( this.inPerspectiveMode ) {
  19143. this.toPerspective();
  19144. } else {
  19145. this.toPerspective();
  19146. this.toOrthographic();
  19147. }
  19148. };
  19149. /*
  19150. * Uses Focal Length (in mm) to estimate and set FOV
  19151. * 35mm (fullframe) camera is used if frame size is not specified;
  19152. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  19153. */
  19154. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  19155. if ( frameHeight === undefined ) frameHeight = 24;
  19156. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  19157. this.setFov( fov );
  19158. return fov;
  19159. };
  19160. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  19161. this.zoom = zoom;
  19162. if ( this.inPerspectiveMode ) {
  19163. this.toPerspective();
  19164. } else {
  19165. this.toOrthographic();
  19166. }
  19167. };
  19168. THREE.CombinedCamera.prototype.toFrontView = function() {
  19169. this.rotation.x = 0;
  19170. this.rotation.y = 0;
  19171. this.rotation.z = 0;
  19172. // should we be modifing the matrix instead?
  19173. this.rotationAutoUpdate = false;
  19174. };
  19175. THREE.CombinedCamera.prototype.toBackView = function() {
  19176. this.rotation.x = 0;
  19177. this.rotation.y = Math.PI;
  19178. this.rotation.z = 0;
  19179. this.rotationAutoUpdate = false;
  19180. };
  19181. THREE.CombinedCamera.prototype.toLeftView = function() {
  19182. this.rotation.x = 0;
  19183. this.rotation.y = - Math.PI / 2;
  19184. this.rotation.z = 0;
  19185. this.rotationAutoUpdate = false;
  19186. };
  19187. THREE.CombinedCamera.prototype.toRightView = function() {
  19188. this.rotation.x = 0;
  19189. this.rotation.y = Math.PI / 2;
  19190. this.rotation.z = 0;
  19191. this.rotationAutoUpdate = false;
  19192. };
  19193. THREE.CombinedCamera.prototype.toTopView = function() {
  19194. this.rotation.x = - Math.PI / 2;
  19195. this.rotation.y = 0;
  19196. this.rotation.z = 0;
  19197. this.rotationAutoUpdate = false;
  19198. };
  19199. THREE.CombinedCamera.prototype.toBottomView = function() {
  19200. this.rotation.x = Math.PI / 2;
  19201. this.rotation.y = 0;
  19202. this.rotation.z = 0;
  19203. this.rotationAutoUpdate = false;
  19204. };
  19205. /**
  19206. * @author hughes
  19207. */
  19208. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  19209. THREE.Geometry.call( this );
  19210. radius = radius || 50;
  19211. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19212. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19213. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  19214. var i, uvs = [],
  19215. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  19216. this.vertices.push(center);
  19217. uvs.push( centerUV );
  19218. for ( i = 0; i <= segments; i ++ ) {
  19219. var vertex = new THREE.Vector3();
  19220. var segment = thetaStart + i / segments * thetaLength;
  19221. vertex.x = radius * Math.cos( segment );
  19222. vertex.y = radius * Math.sin( segment );
  19223. this.vertices.push( vertex );
  19224. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  19225. }
  19226. var n = new THREE.Vector3( 0, 0, 1 );
  19227. for ( i = 1; i <= segments; i ++ ) {
  19228. var v1 = i;
  19229. var v2 = i + 1 ;
  19230. var v3 = 0;
  19231. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19232. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  19233. }
  19234. this.computeCentroids();
  19235. this.computeFaceNormals();
  19236. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19237. };
  19238. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19239. /**
  19240. * @author mrdoob / http://mrdoob.com/
  19241. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  19242. */
  19243. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  19244. THREE.Geometry.call( this );
  19245. var scope = this;
  19246. this.width = width;
  19247. this.height = height;
  19248. this.depth = depth;
  19249. this.widthSegments = widthSegments || 1;
  19250. this.heightSegments = heightSegments || 1;
  19251. this.depthSegments = depthSegments || 1;
  19252. var width_half = this.width / 2;
  19253. var height_half = this.height / 2;
  19254. var depth_half = this.depth / 2;
  19255. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  19256. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  19257. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  19258. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  19259. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  19260. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  19261. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  19262. var w, ix, iy,
  19263. gridX = scope.widthSegments,
  19264. gridY = scope.heightSegments,
  19265. width_half = width / 2,
  19266. height_half = height / 2,
  19267. offset = scope.vertices.length;
  19268. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  19269. w = 'z';
  19270. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  19271. w = 'y';
  19272. gridY = scope.depthSegments;
  19273. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  19274. w = 'x';
  19275. gridX = scope.depthSegments;
  19276. }
  19277. var gridX1 = gridX + 1,
  19278. gridY1 = gridY + 1,
  19279. segment_width = width / gridX,
  19280. segment_height = height / gridY,
  19281. normal = new THREE.Vector3();
  19282. normal[ w ] = depth > 0 ? 1 : - 1;
  19283. for ( iy = 0; iy < gridY1; iy ++ ) {
  19284. for ( ix = 0; ix < gridX1; ix ++ ) {
  19285. var vector = new THREE.Vector3();
  19286. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  19287. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  19288. vector[ w ] = depth;
  19289. scope.vertices.push( vector );
  19290. }
  19291. }
  19292. for ( iy = 0; iy < gridY; iy++ ) {
  19293. for ( ix = 0; ix < gridX; ix++ ) {
  19294. var a = ix + gridX1 * iy;
  19295. var b = ix + gridX1 * ( iy + 1 );
  19296. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  19297. var d = ( ix + 1 ) + gridX1 * iy;
  19298. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  19299. face.normal.copy( normal );
  19300. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19301. face.materialIndex = materialIndex;
  19302. scope.faces.push( face );
  19303. scope.faceVertexUvs[ 0 ].push( [
  19304. new THREE.Vector2( ix / gridX, 1 - iy / gridY ),
  19305. new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  19306. new THREE.Vector2( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  19307. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY )
  19308. ] );
  19309. }
  19310. }
  19311. }
  19312. this.computeCentroids();
  19313. this.mergeVertices();
  19314. };
  19315. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19316. /**
  19317. * @author mrdoob / http://mrdoob.com/
  19318. */
  19319. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
  19320. THREE.Geometry.call( this );
  19321. this.radiusTop = radiusTop = radiusTop !== undefined ? radiusTop : 20;
  19322. this.radiusBottom = radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  19323. this.height = height = height !== undefined ? height : 100;
  19324. this.radialSegments = radialSegments = radialSegments || 8;
  19325. this.heightSegments = heightSegments = heightSegments || 1;
  19326. this.openEnded = openEnded = openEnded !== undefined ? openEnded : false;
  19327. var heightHalf = height / 2;
  19328. var x, y, vertices = [], uvs = [];
  19329. for ( y = 0; y <= heightSegments; y ++ ) {
  19330. var verticesRow = [];
  19331. var uvsRow = [];
  19332. var v = y / heightSegments;
  19333. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  19334. for ( x = 0; x <= radialSegments; x ++ ) {
  19335. var u = x / radialSegments;
  19336. var vertex = new THREE.Vector3();
  19337. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  19338. vertex.y = - v * height + heightHalf;
  19339. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  19340. this.vertices.push( vertex );
  19341. verticesRow.push( this.vertices.length - 1 );
  19342. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19343. }
  19344. vertices.push( verticesRow );
  19345. uvs.push( uvsRow );
  19346. }
  19347. var tanTheta = ( radiusBottom - radiusTop ) / height;
  19348. var na, nb;
  19349. for ( x = 0; x < radialSegments; x ++ ) {
  19350. if ( radiusTop !== 0 ) {
  19351. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  19352. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  19353. } else {
  19354. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  19355. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  19356. }
  19357. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  19358. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  19359. for ( y = 0; y < heightSegments; y ++ ) {
  19360. var v1 = vertices[ y ][ x ];
  19361. var v2 = vertices[ y + 1 ][ x ];
  19362. var v3 = vertices[ y + 1 ][ x + 1 ];
  19363. var v4 = vertices[ y ][ x + 1 ];
  19364. var n1 = na.clone();
  19365. var n2 = na.clone();
  19366. var n3 = nb.clone();
  19367. var n4 = nb.clone();
  19368. var uv1 = uvs[ y ][ x ].clone();
  19369. var uv2 = uvs[ y + 1 ][ x ].clone();
  19370. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  19371. var uv4 = uvs[ y ][ x + 1 ].clone();
  19372. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19373. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19374. }
  19375. }
  19376. // top cap
  19377. if ( openEnded === false && radiusTop > 0 ) {
  19378. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  19379. for ( x = 0; x < radialSegments; x ++ ) {
  19380. var v1 = vertices[ 0 ][ x ];
  19381. var v2 = vertices[ 0 ][ x + 1 ];
  19382. var v3 = this.vertices.length - 1;
  19383. var n1 = new THREE.Vector3( 0, 1, 0 );
  19384. var n2 = new THREE.Vector3( 0, 1, 0 );
  19385. var n3 = new THREE.Vector3( 0, 1, 0 );
  19386. var uv1 = uvs[ 0 ][ x ].clone();
  19387. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  19388. var uv3 = new THREE.Vector2( uv2.u, 0 );
  19389. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19390. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19391. }
  19392. }
  19393. // bottom cap
  19394. if ( openEnded === false && radiusBottom > 0 ) {
  19395. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  19396. for ( x = 0; x < radialSegments; x ++ ) {
  19397. var v1 = vertices[ y ][ x + 1 ];
  19398. var v2 = vertices[ y ][ x ];
  19399. var v3 = this.vertices.length - 1;
  19400. var n1 = new THREE.Vector3( 0, - 1, 0 );
  19401. var n2 = new THREE.Vector3( 0, - 1, 0 );
  19402. var n3 = new THREE.Vector3( 0, - 1, 0 );
  19403. var uv1 = uvs[ y ][ x + 1 ].clone();
  19404. var uv2 = uvs[ y ][ x ].clone();
  19405. var uv3 = new THREE.Vector2( uv2.u, 1 );
  19406. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19407. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19408. }
  19409. }
  19410. this.computeCentroids();
  19411. this.computeFaceNormals();
  19412. }
  19413. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19414. /**
  19415. * @author zz85 / http://www.lab4games.net/zz85/blog
  19416. *
  19417. * Creates extruded geometry from a path shape.
  19418. *
  19419. * parameters = {
  19420. *
  19421. * size: <float>, // size of the text
  19422. * height: <float>, // thickness to extrude text
  19423. * curveSegments: <int>, // number of points on the curves
  19424. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  19425. * amount: <int>, // Amount
  19426. *
  19427. * bevelEnabled: <bool>, // turn on bevel
  19428. * bevelThickness: <float>, // how deep into text bevel goes
  19429. * bevelSize: <float>, // how far from text outline is bevel
  19430. * bevelSegments: <int>, // number of bevel layers
  19431. *
  19432. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  19433. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  19434. *
  19435. * material: <int> // material index for front and back faces
  19436. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  19437. * uvGenerator: <Object> // object that provides UV generator functions
  19438. *
  19439. * }
  19440. **/
  19441. THREE.ExtrudeGeometry = function ( shapes, options ) {
  19442. if ( typeof( shapes ) === "undefined" ) {
  19443. shapes = [];
  19444. return;
  19445. }
  19446. THREE.Geometry.call( this );
  19447. shapes = shapes instanceof Array ? shapes : [ shapes ];
  19448. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19449. this.addShapeList( shapes, options );
  19450. this.computeCentroids();
  19451. this.computeFaceNormals();
  19452. // can't really use automatic vertex normals
  19453. // as then front and back sides get smoothed too
  19454. // should do separate smoothing just for sides
  19455. //this.computeVertexNormals();
  19456. //console.log( "took", ( Date.now() - startTime ) );
  19457. };
  19458. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19459. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19460. var sl = shapes.length;
  19461. for ( var s = 0; s < sl; s ++ ) {
  19462. var shape = shapes[ s ];
  19463. this.addShape( shape, options );
  19464. }
  19465. };
  19466. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  19467. var amount = options.amount !== undefined ? options.amount : 100;
  19468. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  19469. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  19470. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19471. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  19472. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19473. var steps = options.steps !== undefined ? options.steps : 1;
  19474. var extrudePath = options.extrudePath;
  19475. var extrudePts, extrudeByPath = false;
  19476. var material = options.material;
  19477. var extrudeMaterial = options.extrudeMaterial;
  19478. // Use default WorldUVGenerator if no UV generators are specified.
  19479. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  19480. var shapebb = this.shapebb;
  19481. //shapebb = shape.getBoundingBox();
  19482. var splineTube, binormal, normal, position2;
  19483. if ( extrudePath ) {
  19484. extrudePts = extrudePath.getSpacedPoints( steps );
  19485. extrudeByPath = true;
  19486. bevelEnabled = false; // bevels not supported for path extrusion
  19487. // SETUP TNB variables
  19488. // Reuse TNB from TubeGeomtry for now.
  19489. // TODO1 - have a .isClosed in spline?
  19490. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  19491. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19492. binormal = new THREE.Vector3();
  19493. normal = new THREE.Vector3();
  19494. position2 = new THREE.Vector3();
  19495. }
  19496. // Safeguards if bevels are not enabled
  19497. if ( ! bevelEnabled ) {
  19498. bevelSegments = 0;
  19499. bevelThickness = 0;
  19500. bevelSize = 0;
  19501. }
  19502. // Variables initalization
  19503. var ahole, h, hl; // looping of holes
  19504. var scope = this;
  19505. var bevelPoints = [];
  19506. var shapesOffset = this.vertices.length;
  19507. var shapePoints = shape.extractPoints( curveSegments );
  19508. var vertices = shapePoints.shape;
  19509. var holes = shapePoints.holes;
  19510. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  19511. if ( reverse ) {
  19512. vertices = vertices.reverse();
  19513. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19514. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19515. ahole = holes[ h ];
  19516. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  19517. holes[ h ] = ahole.reverse();
  19518. }
  19519. }
  19520. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  19521. }
  19522. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  19523. /* Vertices */
  19524. var contour = vertices; // vertices has all points but contour has only points of circumference
  19525. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19526. ahole = holes[ h ];
  19527. vertices = vertices.concat( ahole );
  19528. }
  19529. function scalePt2 ( pt, vec, size ) {
  19530. if ( !vec ) console.log( "die" );
  19531. return vec.clone().multiplyScalar( size ).add( pt );
  19532. }
  19533. var b, bs, t, z,
  19534. vert, vlen = vertices.length,
  19535. face, flen = faces.length,
  19536. cont, clen = contour.length;
  19537. // Find directions for point movement
  19538. var RAD_TO_DEGREES = 180 / Math.PI;
  19539. function getBevelVec( pt_i, pt_j, pt_k ) {
  19540. // Algorithm 2
  19541. return getBevelVec2( pt_i, pt_j, pt_k );
  19542. }
  19543. function getBevelVec1( pt_i, pt_j, pt_k ) {
  19544. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  19545. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  19546. if ( anglea > angleb ) {
  19547. angleb += Math.PI * 2;
  19548. }
  19549. var anglec = ( anglea + angleb ) / 2;
  19550. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  19551. var x = - Math.cos( anglec );
  19552. var y = - Math.sin( anglec );
  19553. var vec = new THREE.Vector2( x, y ); //.normalize();
  19554. return vec;
  19555. }
  19556. function getBevelVec2( pt_i, pt_j, pt_k ) {
  19557. var a = THREE.ExtrudeGeometry.__v1,
  19558. b = THREE.ExtrudeGeometry.__v2,
  19559. v_hat = THREE.ExtrudeGeometry.__v3,
  19560. w_hat = THREE.ExtrudeGeometry.__v4,
  19561. p = THREE.ExtrudeGeometry.__v5,
  19562. q = THREE.ExtrudeGeometry.__v6,
  19563. v, w,
  19564. v_dot_w_hat, q_sub_p_dot_w_hat,
  19565. s, intersection;
  19566. // good reading for line-line intersection
  19567. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  19568. // define a as vector j->i
  19569. // define b as vectot k->i
  19570. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  19571. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  19572. // get unit vectors
  19573. v = a.normalize();
  19574. w = b.normalize();
  19575. // normals from pt i
  19576. v_hat.set( -v.y, v.x );
  19577. w_hat.set( w.y, -w.x );
  19578. // pts from i
  19579. p.copy( pt_i ).add( v_hat );
  19580. q.copy( pt_i ).add( w_hat );
  19581. if ( p.equals( q ) ) {
  19582. //console.log("Warning: lines are straight");
  19583. return w_hat.clone();
  19584. }
  19585. // Points from j, k. helps prevents points cross overover most of the time
  19586. p.copy( pt_j ).add( v_hat );
  19587. q.copy( pt_k ).add( w_hat );
  19588. v_dot_w_hat = v.dot( w_hat );
  19589. q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
  19590. // We should not reach these conditions
  19591. if ( v_dot_w_hat === 0 ) {
  19592. console.log( "Either infinite or no solutions!" );
  19593. if ( q_sub_p_dot_w_hat === 0 ) {
  19594. console.log( "Its finite solutions." );
  19595. } else {
  19596. console.log( "Too bad, no solutions." );
  19597. }
  19598. }
  19599. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  19600. if ( s < 0 ) {
  19601. // in case of emergecy, revert to algorithm 1.
  19602. return getBevelVec1( pt_i, pt_j, pt_k );
  19603. }
  19604. intersection = v.multiplyScalar( s ).add( p );
  19605. return intersection.sub( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  19606. }
  19607. var contourMovements = [];
  19608. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19609. if ( j === il ) j = 0;
  19610. if ( k === il ) k = 0;
  19611. // (j)---(i)---(k)
  19612. // console.log('i,j,k', i, j , k)
  19613. var pt_i = contour[ i ];
  19614. var pt_j = contour[ j ];
  19615. var pt_k = contour[ k ];
  19616. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19617. }
  19618. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  19619. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19620. ahole = holes[ h ];
  19621. oneHoleMovements = [];
  19622. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19623. if ( j === il ) j = 0;
  19624. if ( k === il ) k = 0;
  19625. // (j)---(i)---(k)
  19626. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19627. }
  19628. holesMovements.push( oneHoleMovements );
  19629. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19630. }
  19631. // Loop bevelSegments, 1 for the front, 1 for the back
  19632. for ( b = 0; b < bevelSegments; b ++ ) {
  19633. //for ( b = bevelSegments; b > 0; b -- ) {
  19634. t = b / bevelSegments;
  19635. z = bevelThickness * ( 1 - t );
  19636. //z = bevelThickness * t;
  19637. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  19638. //bs = bevelSize * t ; // linear
  19639. // contract shape
  19640. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19641. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19642. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  19643. v( vert.x, vert.y, - z );
  19644. }
  19645. // expand holes
  19646. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  19647. ahole = holes[ h ];
  19648. oneHoleMovements = holesMovements[ h ];
  19649. for ( i = 0, il = ahole.length; i < il; i++ ) {
  19650. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19651. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  19652. v( vert.x, vert.y, -z );
  19653. }
  19654. }
  19655. }
  19656. bs = bevelSize;
  19657. // Back facing vertices
  19658. for ( i = 0; i < vlen; i ++ ) {
  19659. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19660. if ( !extrudeByPath ) {
  19661. v( vert.x, vert.y, 0 );
  19662. } else {
  19663. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19664. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  19665. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  19666. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  19667. v( position2.x, position2.y, position2.z );
  19668. }
  19669. }
  19670. // Add stepped vertices...
  19671. // Including front facing vertices
  19672. var s;
  19673. for ( s = 1; s <= steps; s ++ ) {
  19674. for ( i = 0; i < vlen; i ++ ) {
  19675. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19676. if ( !extrudeByPath ) {
  19677. v( vert.x, vert.y, amount / steps * s );
  19678. } else {
  19679. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19680. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19681. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19682. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  19683. v( position2.x, position2.y, position2.z );
  19684. }
  19685. }
  19686. }
  19687. // Add bevel segments planes
  19688. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19689. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19690. t = b / bevelSegments;
  19691. z = bevelThickness * ( 1 - t );
  19692. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19693. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19694. // contract shape
  19695. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19696. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19697. v( vert.x, vert.y, amount + z );
  19698. }
  19699. // expand holes
  19700. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19701. ahole = holes[ h ];
  19702. oneHoleMovements = holesMovements[ h ];
  19703. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19704. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19705. if ( !extrudeByPath ) {
  19706. v( vert.x, vert.y, amount + z );
  19707. } else {
  19708. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19709. }
  19710. }
  19711. }
  19712. }
  19713. /* Faces */
  19714. // Top and bottom faces
  19715. buildLidFaces();
  19716. // Sides faces
  19717. buildSideFaces();
  19718. ///// Internal functions
  19719. function buildLidFaces() {
  19720. if ( bevelEnabled ) {
  19721. var layer = 0 ; // steps + 1
  19722. var offset = vlen * layer;
  19723. // Bottom faces
  19724. for ( i = 0; i < flen; i ++ ) {
  19725. face = faces[ i ];
  19726. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19727. }
  19728. layer = steps + bevelSegments * 2;
  19729. offset = vlen * layer;
  19730. // Top faces
  19731. for ( i = 0; i < flen; i ++ ) {
  19732. face = faces[ i ];
  19733. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19734. }
  19735. } else {
  19736. // Bottom faces
  19737. for ( i = 0; i < flen; i++ ) {
  19738. face = faces[ i ];
  19739. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19740. }
  19741. // Top faces
  19742. for ( i = 0; i < flen; i ++ ) {
  19743. face = faces[ i ];
  19744. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19745. }
  19746. }
  19747. }
  19748. // Create faces for the z-sides of the shape
  19749. function buildSideFaces() {
  19750. var layeroffset = 0;
  19751. sidewalls( contour, layeroffset );
  19752. layeroffset += contour.length;
  19753. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19754. ahole = holes[ h ];
  19755. sidewalls( ahole, layeroffset );
  19756. //, true
  19757. layeroffset += ahole.length;
  19758. }
  19759. }
  19760. function sidewalls( contour, layeroffset ) {
  19761. var j, k;
  19762. i = contour.length;
  19763. while ( --i >= 0 ) {
  19764. j = i;
  19765. k = i - 1;
  19766. if ( k < 0 ) k = contour.length - 1;
  19767. //console.log('b', i,j, i-1, k,vertices.length);
  19768. var s = 0, sl = steps + bevelSegments * 2;
  19769. for ( s = 0; s < sl; s ++ ) {
  19770. var slen1 = vlen * s;
  19771. var slen2 = vlen * ( s + 1 );
  19772. var a = layeroffset + j + slen1,
  19773. b = layeroffset + k + slen1,
  19774. c = layeroffset + k + slen2,
  19775. d = layeroffset + j + slen2;
  19776. f4( a, b, c, d, contour, s, sl, j, k );
  19777. }
  19778. }
  19779. }
  19780. function v( x, y, z ) {
  19781. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19782. }
  19783. function f3( a, b, c, isBottom ) {
  19784. a += shapesOffset;
  19785. b += shapesOffset;
  19786. c += shapesOffset;
  19787. // normal, color, material
  19788. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19789. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19790. scope.faceVertexUvs[ 0 ].push( uvs );
  19791. }
  19792. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19793. a += shapesOffset;
  19794. b += shapesOffset;
  19795. c += shapesOffset;
  19796. d += shapesOffset;
  19797. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  19798. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19799. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19800. scope.faceVertexUvs[ 0 ].push( uvs );
  19801. }
  19802. };
  19803. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19804. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19805. var ax = geometry.vertices[ indexA ].x,
  19806. ay = geometry.vertices[ indexA ].y,
  19807. bx = geometry.vertices[ indexB ].x,
  19808. by = geometry.vertices[ indexB ].y,
  19809. cx = geometry.vertices[ indexC ].x,
  19810. cy = geometry.vertices[ indexC ].y;
  19811. return [
  19812. new THREE.Vector2( ax, ay ),
  19813. new THREE.Vector2( bx, by ),
  19814. new THREE.Vector2( cx, cy )
  19815. ];
  19816. },
  19817. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19818. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19819. },
  19820. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19821. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19822. contourIndex1, contourIndex2 ) {
  19823. var ax = geometry.vertices[ indexA ].x,
  19824. ay = geometry.vertices[ indexA ].y,
  19825. az = geometry.vertices[ indexA ].z,
  19826. bx = geometry.vertices[ indexB ].x,
  19827. by = geometry.vertices[ indexB ].y,
  19828. bz = geometry.vertices[ indexB ].z,
  19829. cx = geometry.vertices[ indexC ].x,
  19830. cy = geometry.vertices[ indexC ].y,
  19831. cz = geometry.vertices[ indexC ].z,
  19832. dx = geometry.vertices[ indexD ].x,
  19833. dy = geometry.vertices[ indexD ].y,
  19834. dz = geometry.vertices[ indexD ].z;
  19835. if ( Math.abs( ay - by ) < 0.01 ) {
  19836. return [
  19837. new THREE.Vector2( ax, 1 - az ),
  19838. new THREE.Vector2( bx, 1 - bz ),
  19839. new THREE.Vector2( cx, 1 - cz ),
  19840. new THREE.Vector2( dx, 1 - dz )
  19841. ];
  19842. } else {
  19843. return [
  19844. new THREE.Vector2( ay, 1 - az ),
  19845. new THREE.Vector2( by, 1 - bz ),
  19846. new THREE.Vector2( cy, 1 - cz ),
  19847. new THREE.Vector2( dy, 1 - dz )
  19848. ];
  19849. }
  19850. }
  19851. };
  19852. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19853. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19854. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19855. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19856. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19857. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19858. /**
  19859. * @author jonobr1 / http://jonobr1.com
  19860. *
  19861. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19862. * ExtrudeGeometry.
  19863. *
  19864. * parameters = {
  19865. *
  19866. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19867. *
  19868. * material: <int> // material index for front and back faces
  19869. * uvGenerator: <Object> // object that provides UV generator functions
  19870. *
  19871. * }
  19872. **/
  19873. THREE.ShapeGeometry = function ( shapes, options ) {
  19874. THREE.Geometry.call( this );
  19875. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19876. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19877. this.addShapeList( shapes, options );
  19878. this.computeCentroids();
  19879. this.computeFaceNormals();
  19880. };
  19881. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19882. /**
  19883. * Add an array of shapes to THREE.ShapeGeometry.
  19884. */
  19885. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19886. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19887. this.addShape( shapes[ i ], options );
  19888. }
  19889. return this;
  19890. };
  19891. /**
  19892. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19893. */
  19894. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19895. if ( options === undefined ) options = {};
  19896. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19897. var material = options.material;
  19898. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19899. var shapebb = this.shapebb;
  19900. //
  19901. var i, l, hole, s;
  19902. var shapesOffset = this.vertices.length;
  19903. var shapePoints = shape.extractPoints( curveSegments );
  19904. var vertices = shapePoints.shape;
  19905. var holes = shapePoints.holes;
  19906. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19907. if ( reverse ) {
  19908. vertices = vertices.reverse();
  19909. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19910. for ( i = 0, l = holes.length; i < l; i++ ) {
  19911. hole = holes[ i ];
  19912. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19913. holes[ i ] = hole.reverse();
  19914. }
  19915. }
  19916. reverse = false;
  19917. }
  19918. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19919. // Vertices
  19920. var contour = vertices;
  19921. for ( i = 0, l = holes.length; i < l; i++ ) {
  19922. hole = holes[ i ];
  19923. vertices = vertices.concat( hole );
  19924. }
  19925. //
  19926. var vert, vlen = vertices.length;
  19927. var face, flen = faces.length;
  19928. var cont, clen = contour.length;
  19929. for ( i = 0; i < vlen; i++ ) {
  19930. vert = vertices[ i ];
  19931. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19932. }
  19933. for ( i = 0; i < flen; i++ ) {
  19934. face = faces[ i ];
  19935. var a = face[ 0 ] + shapesOffset;
  19936. var b = face[ 1 ] + shapesOffset;
  19937. var c = face[ 2 ] + shapesOffset;
  19938. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19939. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19940. }
  19941. };
  19942. /**
  19943. * @author astrodud / http://astrodud.isgreat.org/
  19944. * @author zz85 / https://github.com/zz85
  19945. * @author bhouston / http://exocortex.com
  19946. */
  19947. // points - to create a closed torus, one must use a set of points
  19948. // like so: [ a, b, c, d, a ], see first is the same as last.
  19949. // segments - the number of circumference segments to create
  19950. // phiStart - the starting radian
  19951. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19952. // 2*pi is a closed lathe, less than 2PI is a portion.
  19953. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19954. THREE.Geometry.call( this );
  19955. segments = segments || 12;
  19956. phiStart = phiStart || 0;
  19957. phiLength = phiLength || 2 * Math.PI;
  19958. var inversePointLength = 1.0 / ( points.length - 1 );
  19959. var inverseSegments = 1.0 / segments;
  19960. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19961. var phi = phiStart + i * inverseSegments * phiLength;
  19962. var c = Math.cos( phi ),
  19963. s = Math.sin( phi );
  19964. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19965. var pt = points[ j ];
  19966. var vertex = new THREE.Vector3();
  19967. vertex.x = c * pt.x - s * pt.y;
  19968. vertex.y = s * pt.x + c * pt.y;
  19969. vertex.z = pt.z;
  19970. this.vertices.push( vertex );
  19971. }
  19972. }
  19973. var np = points.length;
  19974. for ( var i = 0, il = segments; i < il; i ++ ) {
  19975. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19976. var base = j + np * i;
  19977. var a = base;
  19978. var b = base + np;
  19979. var c = base + 1 + np;
  19980. var d = base + 1;
  19981. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19982. var u0 = i * inverseSegments;
  19983. var v0 = j * inversePointLength;
  19984. var u1 = u0 + inverseSegments;
  19985. var v1 = v0 + inversePointLength;
  19986. this.faceVertexUvs[ 0 ].push( [
  19987. new THREE.Vector2( u0, v0 ),
  19988. new THREE.Vector2( u1, v0 ),
  19989. new THREE.Vector2( u1, v1 ),
  19990. new THREE.Vector2( u0, v1 )
  19991. ] );
  19992. }
  19993. }
  19994. this.mergeVertices();
  19995. this.computeCentroids();
  19996. this.computeFaceNormals();
  19997. this.computeVertexNormals();
  19998. };
  19999. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20000. /**
  20001. * @author mrdoob / http://mrdoob.com/
  20002. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  20003. */
  20004. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  20005. THREE.Geometry.call( this );
  20006. this.width = width;
  20007. this.height = height;
  20008. this.widthSegments = widthSegments || 1;
  20009. this.heightSegments = heightSegments || 1;
  20010. var ix, iz;
  20011. var width_half = width / 2;
  20012. var height_half = height / 2;
  20013. var gridX = this.widthSegments;
  20014. var gridZ = this.heightSegments;
  20015. var gridX1 = gridX + 1;
  20016. var gridZ1 = gridZ + 1;
  20017. var segment_width = this.width / gridX;
  20018. var segment_height = this.height / gridZ;
  20019. var normal = new THREE.Vector3( 0, 0, 1 );
  20020. for ( iz = 0; iz < gridZ1; iz ++ ) {
  20021. for ( ix = 0; ix < gridX1; ix ++ ) {
  20022. var x = ix * segment_width - width_half;
  20023. var y = iz * segment_height - height_half;
  20024. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  20025. }
  20026. }
  20027. for ( iz = 0; iz < gridZ; iz ++ ) {
  20028. for ( ix = 0; ix < gridX; ix ++ ) {
  20029. var a = ix + gridX1 * iz;
  20030. var b = ix + gridX1 * ( iz + 1 );
  20031. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  20032. var d = ( ix + 1 ) + gridX1 * iz;
  20033. var face = new THREE.Face4( a, b, c, d );
  20034. face.normal.copy( normal );
  20035. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  20036. this.faces.push( face );
  20037. this.faceVertexUvs[ 0 ].push( [
  20038. new THREE.Vector2( ix / gridX, 1 - iz / gridZ ),
  20039. new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  20040. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  20041. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  20042. ] );
  20043. }
  20044. }
  20045. this.computeCentroids();
  20046. };
  20047. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20048. /**
  20049. * @author Kaleb Murphy
  20050. */
  20051. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  20052. THREE.Geometry.call( this );
  20053. innerRadius = innerRadius || 0;
  20054. outerRadius = outerRadius || 50;
  20055. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  20056. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  20057. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  20058. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  20059. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  20060. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  20061. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  20062. var vertex = new THREE.Vector3();
  20063. var segment = thetaStart + o / thetaSegments * thetaLength;
  20064. vertex.x = radius * Math.cos( segment );
  20065. vertex.y = radius * Math.sin( segment );
  20066. this.vertices.push( vertex );
  20067. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  20068. }
  20069. radius += radiusStep;
  20070. }
  20071. var n = new THREE.Vector3( 0, 0, 1 );
  20072. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  20073. var thetaSegment = i * thetaSegments;
  20074. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  20075. var segment = o + thetaSegment;
  20076. var v1 = segment + i;
  20077. var v2 = segment + thetaSegments + i;
  20078. var v3 = segment + thetaSegments + 1 + i;
  20079. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  20080. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  20081. v1 = segment + i;
  20082. v2 = segment + thetaSegments + 1 + i;
  20083. v3 = segment + 1 + i;
  20084. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  20085. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  20086. }
  20087. }
  20088. this.computeCentroids();
  20089. this.computeFaceNormals();
  20090. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20091. };
  20092. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20093. /**
  20094. * @author mrdoob / http://mrdoob.com/
  20095. */
  20096. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  20097. THREE.Geometry.call( this );
  20098. this.radius = radius = radius || 50;
  20099. this.widthSegments = widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  20100. this.heightSegments = heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  20101. this.phiStart = phiStart = phiStart !== undefined ? phiStart : 0;
  20102. this.phiLength = phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  20103. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  20104. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  20105. var x, y, vertices = [], uvs = [];
  20106. for ( y = 0; y <= heightSegments; y ++ ) {
  20107. var verticesRow = [];
  20108. var uvsRow = [];
  20109. for ( x = 0; x <= widthSegments; x ++ ) {
  20110. var u = x / widthSegments;
  20111. var v = y / heightSegments;
  20112. var vertex = new THREE.Vector3();
  20113. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20114. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  20115. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20116. this.vertices.push( vertex );
  20117. verticesRow.push( this.vertices.length - 1 );
  20118. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  20119. }
  20120. vertices.push( verticesRow );
  20121. uvs.push( uvsRow );
  20122. }
  20123. for ( y = 0; y < this.heightSegments; y ++ ) {
  20124. for ( x = 0; x < this.widthSegments; x ++ ) {
  20125. var v1 = vertices[ y ][ x + 1 ];
  20126. var v2 = vertices[ y ][ x ];
  20127. var v3 = vertices[ y + 1 ][ x ];
  20128. var v4 = vertices[ y + 1 ][ x + 1 ];
  20129. var n1 = this.vertices[ v1 ].clone().normalize();
  20130. var n2 = this.vertices[ v2 ].clone().normalize();
  20131. var n3 = this.vertices[ v3 ].clone().normalize();
  20132. var n4 = this.vertices[ v4 ].clone().normalize();
  20133. var uv1 = uvs[ y ][ x + 1 ].clone();
  20134. var uv2 = uvs[ y ][ x ].clone();
  20135. var uv3 = uvs[ y + 1 ][ x ].clone();
  20136. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  20137. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  20138. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  20139. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  20140. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  20141. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  20142. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  20143. } else {
  20144. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  20145. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  20146. }
  20147. }
  20148. }
  20149. this.computeCentroids();
  20150. this.computeFaceNormals();
  20151. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20152. };
  20153. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20154. /**
  20155. * @author zz85 / http://www.lab4games.net/zz85/blog
  20156. * @author alteredq / http://alteredqualia.com/
  20157. *
  20158. * For creating 3D text geometry in three.js
  20159. *
  20160. * Text = 3D Text
  20161. *
  20162. * parameters = {
  20163. * size: <float>, // size of the text
  20164. * height: <float>, // thickness to extrude text
  20165. * curveSegments: <int>, // number of points on the curves
  20166. *
  20167. * font: <string>, // font name
  20168. * weight: <string>, // font weight (normal, bold)
  20169. * style: <string>, // font style (normal, italics)
  20170. *
  20171. * bevelEnabled: <bool>, // turn on bevel
  20172. * bevelThickness: <float>, // how deep into text bevel goes
  20173. * bevelSize: <float>, // how far from text outline is bevel
  20174. * }
  20175. *
  20176. */
  20177. /* Usage Examples
  20178. // TextGeometry wrapper
  20179. var text3d = new TextGeometry( text, options );
  20180. // Complete manner
  20181. var textShapes = THREE.FontUtils.generateShapes( text, options );
  20182. var text3d = new ExtrudeGeometry( textShapes, options );
  20183. */
  20184. THREE.TextGeometry = function ( text, parameters ) {
  20185. parameters = parameters || {};
  20186. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  20187. // translate parameters to ExtrudeGeometry API
  20188. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  20189. // defaults
  20190. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  20191. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  20192. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  20193. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  20194. };
  20195. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  20196. /**
  20197. * @author oosmoxiecode
  20198. * @author mrdoob / http://mrdoob.com/
  20199. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  20200. */
  20201. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  20202. THREE.Geometry.call( this );
  20203. var scope = this;
  20204. this.radius = radius || 100;
  20205. this.tube = tube || 40;
  20206. this.radialSegments = radialSegments || 8;
  20207. this.tubularSegments = tubularSegments || 6;
  20208. this.arc = arc || Math.PI * 2;
  20209. var center = new THREE.Vector3(), uvs = [], normals = [];
  20210. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  20211. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  20212. var u = i / this.tubularSegments * this.arc;
  20213. var v = j / this.radialSegments * Math.PI * 2;
  20214. center.x = this.radius * Math.cos( u );
  20215. center.y = this.radius * Math.sin( u );
  20216. var vertex = new THREE.Vector3();
  20217. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  20218. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  20219. vertex.z = this.tube * Math.sin( v );
  20220. this.vertices.push( vertex );
  20221. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  20222. normals.push( vertex.clone().sub( center ).normalize() );
  20223. }
  20224. }
  20225. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  20226. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  20227. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  20228. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  20229. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  20230. var d = ( this.tubularSegments + 1 ) * j + i;
  20231. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  20232. face.normal.add( normals[ a ] );
  20233. face.normal.add( normals[ b ] );
  20234. face.normal.add( normals[ c ] );
  20235. face.normal.add( normals[ d ] );
  20236. face.normal.normalize();
  20237. this.faces.push( face );
  20238. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  20239. }
  20240. }
  20241. this.computeCentroids();
  20242. };
  20243. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20244. /**
  20245. * @author oosmoxiecode
  20246. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  20247. */
  20248. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  20249. THREE.Geometry.call( this );
  20250. var scope = this;
  20251. this.radius = radius || 100;
  20252. this.tube = tube || 40;
  20253. this.radialSegments = radialSegments || 64;
  20254. this.tubularSegments = tubularSegments || 8;
  20255. this.p = p || 2;
  20256. this.q = q || 3;
  20257. this.heightScale = heightScale || 1;
  20258. this.grid = new Array( this.radialSegments );
  20259. var tang = new THREE.Vector3();
  20260. var n = new THREE.Vector3();
  20261. var bitan = new THREE.Vector3();
  20262. for ( var i = 0; i < this.radialSegments; ++ i ) {
  20263. this.grid[ i ] = new Array( this.tubularSegments );
  20264. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  20265. var p1 = getPos( u, this.q, this.p, this.radius, this.heightScale );
  20266. var p2 = getPos( u + 0.01, this.q, this.p, this.radius, this.heightScale );
  20267. tang.subVectors( p2, p1 );
  20268. n.addVectors( p2, p1 );
  20269. bitan.crossVectors( tang, n );
  20270. n.crossVectors( bitan, tang );
  20271. bitan.normalize();
  20272. n.normalize();
  20273. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  20274. var v = j / this.tubularSegments * 2 * Math.PI;
  20275. var cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20276. var cy = this.tube * Math.sin( v );
  20277. var pos = new THREE.Vector3();
  20278. pos.x = p1.x + cx * n.x + cy * bitan.x;
  20279. pos.y = p1.y + cx * n.y + cy * bitan.y;
  20280. pos.z = p1.z + cx * n.z + cy * bitan.z;
  20281. this.grid[ i ][ j ] = scope.vertices.push( pos ) - 1;
  20282. }
  20283. }
  20284. for ( var i = 0; i < this.radialSegments; ++ i ) {
  20285. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  20286. var ip = ( i + 1 ) % this.radialSegments;
  20287. var jp = ( j + 1 ) % this.tubularSegments;
  20288. var a = this.grid[ i ][ j ];
  20289. var b = this.grid[ ip ][ j ];
  20290. var c = this.grid[ ip ][ jp ];
  20291. var d = this.grid[ i ][ jp ];
  20292. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  20293. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  20294. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  20295. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  20296. this.faces.push( new THREE.Face4( a, b, c, d ) );
  20297. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  20298. }
  20299. }
  20300. this.computeCentroids();
  20301. this.computeFaceNormals();
  20302. this.computeVertexNormals();
  20303. function getPos( u, in_q, in_p, radius, heightScale ) {
  20304. var cu = Math.cos( u );
  20305. var su = Math.sin( u );
  20306. var quOverP = in_q / in_p * u;
  20307. var cs = Math.cos( quOverP );
  20308. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  20309. var ty = radius * ( 2 + cs ) * su * 0.5;
  20310. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  20311. return new THREE.Vector3( tx, ty, tz );
  20312. }
  20313. };
  20314. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20315. /**
  20316. * @author WestLangley / https://github.com/WestLangley
  20317. * @author zz85 / https://github.com/zz85
  20318. * @author miningold / https://github.com/miningold
  20319. *
  20320. * Modified from the TorusKnotGeometry by @oosmoxiecode
  20321. *
  20322. * Creates a tube which extrudes along a 3d spline
  20323. *
  20324. * Uses parallel transport frames as described in
  20325. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20326. */
  20327. THREE.TubeGeometry = function( path, segments, radius, radialSegments, closed ) {
  20328. THREE.Geometry.call( this );
  20329. this.path = path;
  20330. this.segments = segments || 64;
  20331. this.radius = radius || 1;
  20332. this.radialSegments = radialSegments || 8;
  20333. this.closed = closed || false;
  20334. this.grid = [];
  20335. var scope = this,
  20336. tangent,
  20337. normal,
  20338. binormal,
  20339. numpoints = this.segments + 1,
  20340. x, y, z,
  20341. tx, ty, tz,
  20342. u, v,
  20343. cx, cy,
  20344. pos, pos2 = new THREE.Vector3(),
  20345. i, j,
  20346. ip, jp,
  20347. a, b, c, d,
  20348. uva, uvb, uvc, uvd;
  20349. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  20350. tangents = frames.tangents,
  20351. normals = frames.normals,
  20352. binormals = frames.binormals;
  20353. // proxy internals
  20354. this.tangents = tangents;
  20355. this.normals = normals;
  20356. this.binormals = binormals;
  20357. function vert( x, y, z ) {
  20358. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  20359. }
  20360. // consruct the grid
  20361. for ( i = 0; i < numpoints; i++ ) {
  20362. this.grid[ i ] = [];
  20363. u = i / ( numpoints - 1 );
  20364. pos = path.getPointAt( u );
  20365. tangent = tangents[ i ];
  20366. normal = normals[ i ];
  20367. binormal = binormals[ i ];
  20368. for ( j = 0; j < this.radialSegments; j++ ) {
  20369. v = j / this.radialSegments * 2 * Math.PI;
  20370. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20371. cy = this.radius * Math.sin( v );
  20372. pos2.copy( pos );
  20373. pos2.x += cx * normal.x + cy * binormal.x;
  20374. pos2.y += cx * normal.y + cy * binormal.y;
  20375. pos2.z += cx * normal.z + cy * binormal.z;
  20376. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  20377. }
  20378. }
  20379. // construct the mesh
  20380. for ( i = 0; i < this.segments; i++ ) {
  20381. for ( j = 0; j < this.radialSegments; j++ ) {
  20382. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  20383. jp = (j + 1) % this.radialSegments;
  20384. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  20385. b = this.grid[ ip ][ j ];
  20386. c = this.grid[ ip ][ jp ];
  20387. d = this.grid[ i ][ jp ];
  20388. uva = new THREE.Vector2( i / this.segments, j / this.radialSegments );
  20389. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radialSegments );
  20390. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radialSegments );
  20391. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radialSegments );
  20392. this.faces.push( new THREE.Face4( a, b, c, d ) );
  20393. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  20394. }
  20395. }
  20396. this.computeCentroids();
  20397. this.computeFaceNormals();
  20398. this.computeVertexNormals();
  20399. };
  20400. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20401. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  20402. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  20403. var tangent = new THREE.Vector3(),
  20404. normal = new THREE.Vector3(),
  20405. binormal = new THREE.Vector3(),
  20406. tangents = [],
  20407. normals = [],
  20408. binormals = [],
  20409. vec = new THREE.Vector3(),
  20410. mat = new THREE.Matrix4(),
  20411. numpoints = segments + 1,
  20412. theta,
  20413. epsilon = 0.0001,
  20414. smallest,
  20415. tx, ty, tz,
  20416. i, u, v;
  20417. // expose internals
  20418. this.tangents = tangents;
  20419. this.normals = normals;
  20420. this.binormals = binormals;
  20421. // compute the tangent vectors for each segment on the path
  20422. for ( i = 0; i < numpoints; i++ ) {
  20423. u = i / ( numpoints - 1 );
  20424. tangents[ i ] = path.getTangentAt( u );
  20425. tangents[ i ].normalize();
  20426. }
  20427. initialNormal3();
  20428. function initialNormal1(lastBinormal) {
  20429. // fixed start binormal. Has dangers of 0 vectors
  20430. normals[ 0 ] = new THREE.Vector3();
  20431. binormals[ 0 ] = new THREE.Vector3();
  20432. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  20433. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  20434. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20435. }
  20436. function initialNormal2() {
  20437. // This uses the Frenet-Serret formula for deriving binormal
  20438. var t2 = path.getTangentAt( epsilon );
  20439. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  20440. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  20441. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  20442. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20443. }
  20444. function initialNormal3() {
  20445. // select an initial normal vector perpenicular to the first tangent vector,
  20446. // and in the direction of the smallest tangent xyz component
  20447. normals[ 0 ] = new THREE.Vector3();
  20448. binormals[ 0 ] = new THREE.Vector3();
  20449. smallest = Number.MAX_VALUE;
  20450. tx = Math.abs( tangents[ 0 ].x );
  20451. ty = Math.abs( tangents[ 0 ].y );
  20452. tz = Math.abs( tangents[ 0 ].z );
  20453. if ( tx <= smallest ) {
  20454. smallest = tx;
  20455. normal.set( 1, 0, 0 );
  20456. }
  20457. if ( ty <= smallest ) {
  20458. smallest = ty;
  20459. normal.set( 0, 1, 0 );
  20460. }
  20461. if ( tz <= smallest ) {
  20462. normal.set( 0, 0, 1 );
  20463. }
  20464. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20465. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20466. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20467. }
  20468. // compute the slowly-varying normal and binormal vectors for each segment on the path
  20469. for ( i = 1; i < numpoints; i++ ) {
  20470. normals[ i ] = normals[ i-1 ].clone();
  20471. binormals[ i ] = binormals[ i-1 ].clone();
  20472. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  20473. if ( vec.length() > epsilon ) {
  20474. vec.normalize();
  20475. theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  20476. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20477. }
  20478. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20479. }
  20480. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20481. if ( closed ) {
  20482. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), -1, 1 ) );
  20483. theta /= ( numpoints - 1 );
  20484. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  20485. theta = -theta;
  20486. }
  20487. for ( i = 1; i < numpoints; i++ ) {
  20488. // twist a little...
  20489. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20490. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20491. }
  20492. }
  20493. };
  20494. /**
  20495. * @author clockworkgeek / https://github.com/clockworkgeek
  20496. * @author timothypratley / https://github.com/timothypratley
  20497. * @author WestLangley / http://github.com/WestLangley
  20498. */
  20499. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  20500. THREE.Geometry.call( this );
  20501. radius = radius || 1;
  20502. detail = detail || 0;
  20503. var that = this;
  20504. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  20505. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  20506. }
  20507. var midpoints = [], p = this.vertices;
  20508. var f = [];
  20509. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20510. var v1 = p[ faces[ i ][ 0 ] ];
  20511. var v2 = p[ faces[ i ][ 1 ] ];
  20512. var v3 = p[ faces[ i ][ 2 ] ];
  20513. f[ i ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20514. }
  20515. for ( var i = 0, l = f.length; i < l; i ++ ) {
  20516. subdivide(f[ i ], detail);
  20517. }
  20518. // Handle case when face straddles the seam
  20519. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  20520. var uvs = this.faceVertexUvs[ 0 ][ i ];
  20521. var x0 = uvs[ 0 ].x;
  20522. var x1 = uvs[ 1 ].x;
  20523. var x2 = uvs[ 2 ].x;
  20524. var max = Math.max( x0, Math.max( x1, x2 ) );
  20525. var min = Math.min( x0, Math.min( x1, x2 ) );
  20526. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  20527. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  20528. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  20529. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  20530. }
  20531. }
  20532. // Apply radius
  20533. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  20534. this.vertices[ i ].multiplyScalar( radius );
  20535. }
  20536. // Merge vertices
  20537. this.mergeVertices();
  20538. this.computeCentroids();
  20539. this.computeFaceNormals();
  20540. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20541. // Project vector onto sphere's surface
  20542. function prepare( vector ) {
  20543. var vertex = vector.normalize().clone();
  20544. vertex.index = that.vertices.push( vertex ) - 1;
  20545. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  20546. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  20547. var v = inclination( vector ) / Math.PI + 0.5;
  20548. vertex.uv = new THREE.Vector2( u, 1 - v );
  20549. return vertex;
  20550. }
  20551. // Approximate a curved face with recursively sub-divided triangles.
  20552. function make( v1, v2, v3 ) {
  20553. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20554. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  20555. that.faces.push( face );
  20556. var azi = azimuth( face.centroid );
  20557. that.faceVertexUvs[ 0 ].push( [
  20558. correctUV( v1.uv, v1, azi ),
  20559. correctUV( v2.uv, v2, azi ),
  20560. correctUV( v3.uv, v3, azi )
  20561. ] );
  20562. }
  20563. // Analytically subdivide a face to the required detail level.
  20564. function subdivide(face, detail ) {
  20565. var cols = Math.pow(2, detail);
  20566. var cells = Math.pow(4, detail);
  20567. var a = prepare( that.vertices[ face.a ] );
  20568. var b = prepare( that.vertices[ face.b ] );
  20569. var c = prepare( that.vertices[ face.c ] );
  20570. var v = [];
  20571. // Construct all of the vertices for this subdivision.
  20572. for ( var i = 0 ; i <= cols; i ++ ) {
  20573. v[ i ] = [];
  20574. var aj = prepare( a.clone().lerp( c, i / cols ) );
  20575. var bj = prepare( b.clone().lerp( c, i / cols ) );
  20576. var rows = cols - i;
  20577. for ( var j = 0; j <= rows; j ++) {
  20578. if ( j == 0 && i == cols ) {
  20579. v[ i ][ j ] = aj;
  20580. } else {
  20581. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  20582. }
  20583. }
  20584. }
  20585. // Construct all of the faces.
  20586. for ( var i = 0; i < cols ; i ++ ) {
  20587. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  20588. var k = Math.floor( j / 2 );
  20589. if ( j % 2 == 0 ) {
  20590. make(
  20591. v[ i ][ k + 1],
  20592. v[ i + 1 ][ k ],
  20593. v[ i ][ k ]
  20594. );
  20595. } else {
  20596. make(
  20597. v[ i ][ k + 1 ],
  20598. v[ i + 1][ k + 1],
  20599. v[ i + 1 ][ k ]
  20600. );
  20601. }
  20602. }
  20603. }
  20604. }
  20605. // Angle around the Y axis, counter-clockwise when looking from above.
  20606. function azimuth( vector ) {
  20607. return Math.atan2( vector.z, -vector.x );
  20608. }
  20609. // Angle above the XZ plane.
  20610. function inclination( vector ) {
  20611. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20612. }
  20613. // Texture fixing helper. Spheres have some odd behaviours.
  20614. function correctUV( uv, vector, azimuth ) {
  20615. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  20616. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  20617. return uv.clone();
  20618. }
  20619. };
  20620. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20621. /**
  20622. * @author timothypratley / https://github.com/timothypratley
  20623. */
  20624. THREE.IcosahedronGeometry = function ( radius, detail ) {
  20625. this.radius = radius;
  20626. this.detail = detail;
  20627. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20628. var vertices = [
  20629. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  20630. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  20631. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  20632. ];
  20633. var faces = [
  20634. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  20635. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  20636. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  20637. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  20638. ];
  20639. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20640. };
  20641. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20642. /**
  20643. * @author timothypratley / https://github.com/timothypratley
  20644. */
  20645. THREE.OctahedronGeometry = function ( radius, detail ) {
  20646. var vertices = [
  20647. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  20648. ];
  20649. var faces = [
  20650. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  20651. ];
  20652. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20653. };
  20654. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20655. /**
  20656. * @author timothypratley / https://github.com/timothypratley
  20657. */
  20658. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20659. var vertices = [
  20660. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  20661. ];
  20662. var faces = [
  20663. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  20664. ];
  20665. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20666. };
  20667. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20668. /**
  20669. * @author zz85 / https://github.com/zz85
  20670. * Parametric Surfaces Geometry
  20671. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20672. *
  20673. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  20674. *
  20675. */
  20676. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  20677. THREE.Geometry.call( this );
  20678. var verts = this.vertices;
  20679. var faces = this.faces;
  20680. var uvs = this.faceVertexUvs[ 0 ];
  20681. useTris = (useTris === undefined) ? false : useTris;
  20682. var i, il, j, p;
  20683. var u, v;
  20684. var stackCount = stacks + 1;
  20685. var sliceCount = slices + 1;
  20686. for ( i = 0; i <= stacks; i ++ ) {
  20687. v = i / stacks;
  20688. for ( j = 0; j <= slices; j ++ ) {
  20689. u = j / slices;
  20690. p = func( u, v );
  20691. verts.push( p );
  20692. }
  20693. }
  20694. var a, b, c, d;
  20695. var uva, uvb, uvc, uvd;
  20696. for ( i = 0; i < stacks; i ++ ) {
  20697. for ( j = 0; j < slices; j ++ ) {
  20698. a = i * sliceCount + j;
  20699. b = i * sliceCount + j + 1;
  20700. c = (i + 1) * sliceCount + j;
  20701. d = (i + 1) * sliceCount + j + 1;
  20702. uva = new THREE.Vector2( j / slices, i / stacks );
  20703. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20704. uvc = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20705. uvd = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20706. if ( useTris ) {
  20707. faces.push( new THREE.Face3( a, b, c ) );
  20708. faces.push( new THREE.Face3( b, d, c ) );
  20709. uvs.push( [ uva, uvb, uvc ] );
  20710. uvs.push( [ uvb, uvd, uvc ] );
  20711. } else {
  20712. faces.push( new THREE.Face4( a, b, d, c ) );
  20713. uvs.push( [ uva, uvb, uvd, uvc ] );
  20714. }
  20715. }
  20716. }
  20717. // console.log(this);
  20718. // magic bullet
  20719. // var diff = this.mergeVertices();
  20720. // console.log('removed ', diff, ' vertices by merging');
  20721. this.computeCentroids();
  20722. this.computeFaceNormals();
  20723. this.computeVertexNormals();
  20724. };
  20725. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20726. /**
  20727. * @author sroucheray / http://sroucheray.org/
  20728. * @author mrdoob / http://mrdoob.com/
  20729. */
  20730. THREE.AxisHelper = function ( size ) {
  20731. size = size || 1;
  20732. var geometry = new THREE.Geometry();
  20733. geometry.vertices.push(
  20734. new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ),
  20735. new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ),
  20736. new THREE.Vector3(), new THREE.Vector3( 0, 0, size )
  20737. );
  20738. geometry.colors.push(
  20739. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20740. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20741. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20742. );
  20743. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20744. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20745. };
  20746. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20747. /**
  20748. * @author WestLangley / http://github.com/WestLangley
  20749. * @author zz85 / http://github.com/zz85
  20750. * @author bhouston / http://exocortex.com
  20751. *
  20752. * Creates an arrow for visualizing directions
  20753. *
  20754. * Parameters:
  20755. * dir - Vector3
  20756. * origin - Vector3
  20757. * length - Number
  20758. * hex - color in hex value
  20759. */
  20760. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  20761. // dir is assumed to be normalized
  20762. THREE.Object3D.call( this );
  20763. if ( hex === undefined ) hex = 0xffff00;
  20764. if ( length === undefined ) length = 1;
  20765. this.position = origin;
  20766. var lineGeometry = new THREE.Geometry();
  20767. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20768. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20769. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20770. this.line.matrixAutoUpdate = false;
  20771. this.add( this.line );
  20772. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  20773. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, 0.875, 0 ) );
  20774. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20775. this.cone.matrixAutoUpdate = false;
  20776. this.add( this.cone );
  20777. this.setDirection( dir );
  20778. this.setLength( length );
  20779. };
  20780. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20781. THREE.ArrowHelper.prototype.setDirection = function () {
  20782. var axis = new THREE.Vector3();
  20783. var radians;
  20784. return function ( dir ) {
  20785. // dir is assumed to be normalized
  20786. if ( dir.y > 0.99999 ) {
  20787. this.quaternion.set( 0, 0, 0, 1 );
  20788. } else if ( dir.y < - 0.99999 ) {
  20789. this.quaternion.set( 1, 0, 0, 0 );
  20790. } else {
  20791. axis.set( dir.z, 0, - dir.x ).normalize();
  20792. radians = Math.acos( dir.y );
  20793. this.quaternion.setFromAxisAngle( axis, radians );
  20794. }
  20795. };
  20796. }();
  20797. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  20798. this.scale.set( length, length, length );
  20799. };
  20800. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20801. this.line.material.color.setHex( hex );
  20802. this.cone.material.color.setHex( hex );
  20803. };
  20804. /**
  20805. * @author mrdoob / http://mrdoob.com/
  20806. */
  20807. THREE.BoxHelper = function ( object ) {
  20808. // 5____4
  20809. // 1/___0/|
  20810. // | 6__|_7
  20811. // 2/___3/
  20812. var vertices = [
  20813. new THREE.Vector3( 1, 1, 1 ),
  20814. new THREE.Vector3( - 1, 1, 1 ),
  20815. new THREE.Vector3( - 1, - 1, 1 ),
  20816. new THREE.Vector3( 1, - 1, 1 ),
  20817. new THREE.Vector3( 1, 1, - 1 ),
  20818. new THREE.Vector3( - 1, 1, - 1 ),
  20819. new THREE.Vector3( - 1, - 1, - 1 ),
  20820. new THREE.Vector3( 1, - 1, - 1 )
  20821. ];
  20822. this.vertices = vertices;
  20823. // TODO: Wouldn't be nice if Line had .segments?
  20824. var geometry = new THREE.Geometry();
  20825. geometry.vertices.push(
  20826. vertices[ 0 ], vertices[ 1 ],
  20827. vertices[ 1 ], vertices[ 2 ],
  20828. vertices[ 2 ], vertices[ 3 ],
  20829. vertices[ 3 ], vertices[ 0 ],
  20830. vertices[ 4 ], vertices[ 5 ],
  20831. vertices[ 5 ], vertices[ 6 ],
  20832. vertices[ 6 ], vertices[ 7 ],
  20833. vertices[ 7 ], vertices[ 4 ],
  20834. vertices[ 0 ], vertices[ 4 ],
  20835. vertices[ 1 ], vertices[ 5 ],
  20836. vertices[ 2 ], vertices[ 6 ],
  20837. vertices[ 3 ], vertices[ 7 ]
  20838. );
  20839. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  20840. if ( object !== undefined ) {
  20841. this.update( object );
  20842. }
  20843. };
  20844. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20845. THREE.BoxHelper.prototype.update = function ( object ) {
  20846. var geometry = object.geometry;
  20847. if ( geometry.boundingBox === null ) {
  20848. geometry.computeBoundingBox();
  20849. }
  20850. var min = geometry.boundingBox.min;
  20851. var max = geometry.boundingBox.max;
  20852. var vertices = this.vertices;
  20853. vertices[ 0 ].set( max.x, max.y, max.z );
  20854. vertices[ 1 ].set( min.x, max.y, max.z );
  20855. vertices[ 2 ].set( min.x, min.y, max.z );
  20856. vertices[ 3 ].set( max.x, min.y, max.z );
  20857. vertices[ 4 ].set( max.x, max.y, min.z );
  20858. vertices[ 5 ].set( min.x, max.y, min.z );
  20859. vertices[ 6 ].set( min.x, min.y, min.z );
  20860. vertices[ 7 ].set( max.x, min.y, min.z );
  20861. this.geometry.computeBoundingSphere();
  20862. this.geometry.verticesNeedUpdate = true;
  20863. this.matrixAutoUpdate = false;
  20864. this.matrixWorld = object.matrixWorld;
  20865. };
  20866. /**
  20867. * @author WestLangley / http://github.com/WestLangley
  20868. */
  20869. // a helper to show the world-axis-aligned bounding box for an object
  20870. THREE.BoundingBoxHelper = function ( object, hex ) {
  20871. var color = hex || 0x888888;
  20872. this.object = object;
  20873. this.box = new THREE.Box3();
  20874. THREE.Mesh.call( this, new THREE.CubeGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20875. };
  20876. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20877. THREE.BoundingBoxHelper.prototype.update = function () {
  20878. this.box.setFromObject( this.object );
  20879. this.box.size( this.scale );
  20880. this.box.center( this.position );
  20881. };
  20882. /**
  20883. * @author alteredq / http://alteredqualia.com/
  20884. *
  20885. * - shows frustum, line of sight and up of the camera
  20886. * - suitable for fast updates
  20887. * - based on frustum visualization in lightgl.js shadowmap example
  20888. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20889. */
  20890. THREE.CameraHelper = function ( camera ) {
  20891. THREE.Line.call( this );
  20892. var geometry = new THREE.Geometry();
  20893. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20894. var pointMap = {};
  20895. // colors
  20896. var hexFrustum = 0xffaa00;
  20897. var hexCone = 0xff0000;
  20898. var hexUp = 0x00aaff;
  20899. var hexTarget = 0xffffff;
  20900. var hexCross = 0x333333;
  20901. // near
  20902. addLine( "n1", "n2", hexFrustum );
  20903. addLine( "n2", "n4", hexFrustum );
  20904. addLine( "n4", "n3", hexFrustum );
  20905. addLine( "n3", "n1", hexFrustum );
  20906. // far
  20907. addLine( "f1", "f2", hexFrustum );
  20908. addLine( "f2", "f4", hexFrustum );
  20909. addLine( "f4", "f3", hexFrustum );
  20910. addLine( "f3", "f1", hexFrustum );
  20911. // sides
  20912. addLine( "n1", "f1", hexFrustum );
  20913. addLine( "n2", "f2", hexFrustum );
  20914. addLine( "n3", "f3", hexFrustum );
  20915. addLine( "n4", "f4", hexFrustum );
  20916. // cone
  20917. addLine( "p", "n1", hexCone );
  20918. addLine( "p", "n2", hexCone );
  20919. addLine( "p", "n3", hexCone );
  20920. addLine( "p", "n4", hexCone );
  20921. // up
  20922. addLine( "u1", "u2", hexUp );
  20923. addLine( "u2", "u3", hexUp );
  20924. addLine( "u3", "u1", hexUp );
  20925. // target
  20926. addLine( "c", "t", hexTarget );
  20927. addLine( "p", "c", hexCross );
  20928. // cross
  20929. addLine( "cn1", "cn2", hexCross );
  20930. addLine( "cn3", "cn4", hexCross );
  20931. addLine( "cf1", "cf2", hexCross );
  20932. addLine( "cf3", "cf4", hexCross );
  20933. function addLine( a, b, hex ) {
  20934. addPoint( a, hex );
  20935. addPoint( b, hex );
  20936. }
  20937. function addPoint( id, hex ) {
  20938. geometry.vertices.push( new THREE.Vector3() );
  20939. geometry.colors.push( new THREE.Color( hex ) );
  20940. if ( pointMap[ id ] === undefined ) {
  20941. pointMap[ id ] = [];
  20942. }
  20943. pointMap[ id ].push( geometry.vertices.length - 1 );
  20944. }
  20945. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20946. this.camera = camera;
  20947. this.matrixWorld = camera.matrixWorld;
  20948. this.matrixAutoUpdate = false;
  20949. this.pointMap = pointMap;
  20950. this.update();
  20951. };
  20952. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20953. THREE.CameraHelper.prototype.update = function () {
  20954. var vector = new THREE.Vector3();
  20955. var camera = new THREE.Camera();
  20956. var projector = new THREE.Projector();
  20957. return function () {
  20958. var scope = this;
  20959. var w = 1, h = 1;
  20960. // we need just camera projection matrix
  20961. // world matrix must be identity
  20962. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20963. // center / target
  20964. setPoint( "c", 0, 0, -1 );
  20965. setPoint( "t", 0, 0, 1 );
  20966. // near
  20967. setPoint( "n1", -w, -h, -1 );
  20968. setPoint( "n2", w, -h, -1 );
  20969. setPoint( "n3", -w, h, -1 );
  20970. setPoint( "n4", w, h, -1 );
  20971. // far
  20972. setPoint( "f1", -w, -h, 1 );
  20973. setPoint( "f2", w, -h, 1 );
  20974. setPoint( "f3", -w, h, 1 );
  20975. setPoint( "f4", w, h, 1 );
  20976. // up
  20977. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20978. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20979. setPoint( "u3", 0, h * 2, -1 );
  20980. // cross
  20981. setPoint( "cf1", -w, 0, 1 );
  20982. setPoint( "cf2", w, 0, 1 );
  20983. setPoint( "cf3", 0, -h, 1 );
  20984. setPoint( "cf4", 0, h, 1 );
  20985. setPoint( "cn1", -w, 0, -1 );
  20986. setPoint( "cn2", w, 0, -1 );
  20987. setPoint( "cn3", 0, -h, -1 );
  20988. setPoint( "cn4", 0, h, -1 );
  20989. function setPoint( point, x, y, z ) {
  20990. vector.set( x, y, z );
  20991. projector.unprojectVector( vector, camera );
  20992. var points = scope.pointMap[ point ];
  20993. if ( points !== undefined ) {
  20994. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20995. scope.geometry.vertices[ points[ i ] ].copy( vector );
  20996. }
  20997. }
  20998. }
  20999. this.geometry.verticesNeedUpdate = true;
  21000. };
  21001. }();
  21002. /**
  21003. * @author alteredq / http://alteredqualia.com/
  21004. * @author mrdoob / http://mrdoob.com/
  21005. */
  21006. THREE.DirectionalLightHelper = function ( light, sphereSize ) {
  21007. THREE.Object3D.call( this );
  21008. this.matrixAutoUpdate = false;
  21009. this.light = light;
  21010. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21011. var material = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  21012. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21013. this.lightSphere = new THREE.Mesh( geometry, material );
  21014. this.lightSphere.matrixWorld = this.light.matrixWorld;
  21015. this.lightSphere.matrixAutoUpdate = false;
  21016. this.add( this.lightSphere );
  21017. /*
  21018. this.targetSphere = new THREE.Mesh( geometry, material );
  21019. this.targetSphere.position = this.light.target.position;
  21020. this.add( this.targetSphere );
  21021. */
  21022. geometry = new THREE.Geometry();
  21023. geometry.vertices.push( this.light.position );
  21024. geometry.vertices.push( this.light.target.position );
  21025. geometry.computeLineDistances();
  21026. material = new THREE.LineDashedMaterial( { dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  21027. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21028. this.targetLine = new THREE.Line( geometry, material );
  21029. this.add( this.targetLine );
  21030. }
  21031. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21032. THREE.DirectionalLightHelper.prototype.update = function () {
  21033. this.lightSphere.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21034. this.targetLine.geometry.computeLineDistances();
  21035. this.targetLine.geometry.verticesNeedUpdate = true;
  21036. this.targetLine.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21037. };
  21038. /**
  21039. * @author mrdoob / http://mrdoob.com/
  21040. * @author WestLangley / http://github.com/WestLangley
  21041. */
  21042. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  21043. this.object = object;
  21044. this.size = size || 1;
  21045. var color = hex || 0xffff00;
  21046. var width = linewidth || 1;
  21047. var geometry = new THREE.Geometry();
  21048. var faces = this.object.geometry.faces;
  21049. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21050. geometry.vertices.push( new THREE.Vector3() );
  21051. geometry.vertices.push( new THREE.Vector3() );
  21052. }
  21053. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21054. this.matrixAutoUpdate = false;
  21055. this.normalMatrix = new THREE.Matrix3();
  21056. this.update();
  21057. };
  21058. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  21059. THREE.FaceNormalsHelper.prototype.update = ( function ( object ) {
  21060. var v1 = new THREE.Vector3();
  21061. return function ( object ) {
  21062. this.object.updateMatrixWorld( true );
  21063. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  21064. var vertices = this.geometry.vertices;
  21065. var faces = this.object.geometry.faces;
  21066. var worldMatrix = this.object.matrixWorld;
  21067. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21068. var face = faces[ i ];
  21069. v1.copy( face.normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  21070. var idx = 2 * i;
  21071. vertices[ idx ].copy( face.centroid ).applyMatrix4( worldMatrix );
  21072. vertices[ idx + 1 ].addVectors( vertices[ idx ], v1 );
  21073. }
  21074. this.geometry.verticesNeedUpdate = true;
  21075. return this;
  21076. }
  21077. }());
  21078. /**
  21079. * @author mrdoob / http://mrdoob.com/
  21080. */
  21081. THREE.GridHelper = function ( size, step ) {
  21082. var geometry = new THREE.Geometry();
  21083. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  21084. this.color1 = new THREE.Color( 0x444444 );
  21085. this.color2 = new THREE.Color( 0x888888 );
  21086. for ( var i = - size; i <= size; i += step ) {
  21087. geometry.vertices.push(
  21088. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  21089. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  21090. );
  21091. var color = i === 0 ? this.color1 : this.color2;
  21092. geometry.colors.push( color, color, color, color );
  21093. }
  21094. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  21095. };
  21096. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  21097. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  21098. this.color1.set( colorCenterLine );
  21099. this.color2.set( colorGrid );
  21100. this.geometry.colorsNeedUpdate = true;
  21101. }
  21102. /**
  21103. * @author alteredq / http://alteredqualia.com/
  21104. * @author mrdoob / http://mrdoob.com/
  21105. */
  21106. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  21107. THREE.Object3D.call( this );
  21108. this.light = light;
  21109. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21110. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  21111. for ( var i = 0, il = 8; i < il; i ++ ) {
  21112. geometry.faces[ i ].materialIndex = i < 4 ? 0 : 1;
  21113. }
  21114. var materialSky = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  21115. materialSky.color.copy( light.color ).multiplyScalar( light.intensity );
  21116. var materialGround = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  21117. materialGround.color.copy( light.groundColor ).multiplyScalar( light.intensity );
  21118. this.lightSphere = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( [ materialSky, materialGround ] ) );
  21119. this.lightSphere.position = light.position;
  21120. this.lightSphere.lookAt( new THREE.Vector3() );
  21121. this.add( this.lightSphere );
  21122. };
  21123. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21124. THREE.HemisphereLightHelper.prototype.update = function () {
  21125. this.lightSphere.lookAt( new THREE.Vector3() );
  21126. this.lightSphere.material.materials[ 0 ].color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21127. this.lightSphere.material.materials[ 1 ].color.copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  21128. };
  21129. /**
  21130. * @author alteredq / http://alteredqualia.com/
  21131. * @author mrdoob / http://mrdoob.com/
  21132. */
  21133. THREE.PointLightHelper = function ( light, sphereSize ) {
  21134. this.light = light;
  21135. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21136. var material = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  21137. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21138. THREE.Mesh.call( this, geometry, material );
  21139. this.matrixWorld = this.light.matrixWorld;
  21140. this.matrixAutoUpdate = false;
  21141. /*
  21142. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  21143. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  21144. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  21145. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  21146. var d = light.distance;
  21147. if ( d === 0.0 ) {
  21148. this.lightDistance.visible = false;
  21149. } else {
  21150. this.lightDistance.scale.set( d, d, d );
  21151. }
  21152. this.add( this.lightDistance );
  21153. */
  21154. };
  21155. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  21156. THREE.PointLightHelper.prototype.update = function () {
  21157. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21158. /*
  21159. var d = this.light.distance;
  21160. if ( d === 0.0 ) {
  21161. this.lightDistance.visible = false;
  21162. } else {
  21163. this.lightDistance.visible = true;
  21164. this.lightDistance.scale.set( d, d, d );
  21165. }
  21166. */
  21167. };
  21168. /**
  21169. * @author alteredq / http://alteredqualia.com/
  21170. * @author mrdoob / http://mrdoob.com/
  21171. * @author WestLangley / http://github.com/WestLangley
  21172. */
  21173. THREE.SpotLightHelper = function ( light ) {
  21174. // spotlight helper must be a child of the scene
  21175. this.light = light;
  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, opacity: 0.3, transparent: true } );
  21180. THREE.Mesh.call( this, geometry, material );
  21181. this.update();
  21182. };
  21183. THREE.SpotLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  21184. THREE.SpotLightHelper.prototype.update = ( function () {
  21185. var targetPosition = new THREE.Vector3();
  21186. return function() {
  21187. var coneLength = this.light.distance ? this.light.distance : 10000;
  21188. var coneWidth = coneLength * Math.tan( this.light.angle );
  21189. this.scale.set( coneWidth, coneWidth, coneLength );
  21190. this.light.updateMatrixWorld( true );
  21191. this.position.getPositionFromMatrix( this.light.matrixWorld );
  21192. this.light.target.updateMatrixWorld( true );
  21193. targetPosition.getPositionFromMatrix( this.light.target.matrixWorld );
  21194. this.lookAt( targetPosition );
  21195. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21196. }
  21197. }());
  21198. /**
  21199. * @author mrdoob / http://mrdoob.com/
  21200. * @author WestLangley / http://github.com/WestLangley
  21201. */
  21202. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  21203. this.object = object;
  21204. this.size = size || 1;
  21205. var color = hex || 0xff0000;
  21206. var width = linewidth || 1;
  21207. var geometry = new THREE.Geometry();
  21208. var vertices = object.geometry.vertices;
  21209. var faces = object.geometry.faces;
  21210. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21211. var face = faces[ i ];
  21212. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21213. geometry.vertices.push( new THREE.Vector3() );
  21214. geometry.vertices.push( new THREE.Vector3() );
  21215. }
  21216. }
  21217. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21218. this.matrixAutoUpdate = false;
  21219. this.normalMatrix = new THREE.Matrix3();
  21220. this.update();
  21221. };
  21222. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  21223. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  21224. var v1 = new THREE.Vector3();
  21225. return function( object ) {
  21226. var keys = [ 'a', 'b', 'c', 'd' ];
  21227. this.object.updateMatrixWorld( true );
  21228. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  21229. var vertices = this.geometry.vertices;
  21230. var verts = this.object.geometry.vertices;
  21231. var faces = this.object.geometry.faces;
  21232. var worldMatrix = this.object.matrixWorld;
  21233. var idx = 0;
  21234. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21235. var face = faces[ i ];
  21236. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21237. var vertexId = face[ keys[ j ] ];
  21238. var vertex = verts[ vertexId ];
  21239. var normal = face.vertexNormals[ j ];
  21240. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21241. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  21242. v1.add( vertices[ idx ] );
  21243. idx = idx + 1;
  21244. vertices[ idx ].copy( v1 );
  21245. idx = idx + 1;
  21246. }
  21247. }
  21248. this.geometry.verticesNeedUpdate = true;
  21249. return this;
  21250. }
  21251. }());
  21252. /**
  21253. * @author mrdoob / http://mrdoob.com/
  21254. * @author WestLangley / http://github.com/WestLangley
  21255. */
  21256. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  21257. this.object = object;
  21258. this.size = size || 1;
  21259. var color = hex || 0x0000ff;
  21260. var width = linewidth || 1;
  21261. var geometry = new THREE.Geometry();
  21262. var vertices = object.geometry.vertices;
  21263. var faces = object.geometry.faces;
  21264. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21265. var face = faces[ i ];
  21266. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21267. geometry.vertices.push( new THREE.Vector3() );
  21268. geometry.vertices.push( new THREE.Vector3() );
  21269. }
  21270. }
  21271. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21272. this.matrixAutoUpdate = false;
  21273. this.update();
  21274. };
  21275. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  21276. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  21277. var v1 = new THREE.Vector3();
  21278. return function( object ) {
  21279. var keys = [ 'a', 'b', 'c', 'd' ];
  21280. this.object.updateMatrixWorld( true );
  21281. var vertices = this.geometry.vertices;
  21282. var verts = this.object.geometry.vertices;
  21283. var faces = this.object.geometry.faces;
  21284. var worldMatrix = this.object.matrixWorld;
  21285. var idx = 0;
  21286. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21287. var face = faces[ i ];
  21288. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21289. var vertexId = face[ keys[ j ] ];
  21290. var vertex = verts[ vertexId ];
  21291. var tangent = face.vertexTangents[ j ];
  21292. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21293. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  21294. v1.add( vertices[ idx ] );
  21295. idx = idx + 1;
  21296. vertices[ idx ].copy( v1 );
  21297. idx = idx + 1;
  21298. }
  21299. }
  21300. this.geometry.verticesNeedUpdate = true;
  21301. return this;
  21302. }
  21303. }());
  21304. /**
  21305. * @author mrdoob / http://mrdoob.com/
  21306. */
  21307. THREE.WireframeHelper = function ( object ) {
  21308. var edge = [ 0, 0 ], hash = {};
  21309. var sortFunction = function ( a, b ) { return a - b };
  21310. var keys = [ 'a', 'b', 'c', 'd' ];
  21311. var geometry = new THREE.Geometry();
  21312. var vertices = object.geometry.vertices;
  21313. var faces = object.geometry.faces;
  21314. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21315. var face = faces[ i ];
  21316. var length = face instanceof THREE.Face4 ? 4 : 3;
  21317. for ( var j = 0; j < length; j ++ ) {
  21318. edge[ 0 ] = face[ keys[ j ] ];
  21319. edge[ 1 ] = face[ keys[ ( j + 1 ) % length ] ];
  21320. edge.sort( sortFunction );
  21321. var key = edge.toString();
  21322. if ( hash[ key ] === undefined ) {
  21323. geometry.vertices.push( vertices[ edge[ 0 ] ] );
  21324. geometry.vertices.push( vertices[ edge[ 1 ] ] );
  21325. hash[ key ] = true;
  21326. }
  21327. }
  21328. }
  21329. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffffff } ), THREE.LinePieces );
  21330. this.matrixAutoUpdate = false;
  21331. this.matrixWorld = object.matrixWorld;
  21332. };
  21333. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  21334. /**
  21335. * @author alteredq / http://alteredqualia.com/
  21336. */
  21337. THREE.ImmediateRenderObject = function () {
  21338. THREE.Object3D.call( this );
  21339. this.render = function ( renderCallback ) { };
  21340. };
  21341. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  21342. /**
  21343. * @author mikael emtinger / http://gomo.se/
  21344. * @author alteredq / http://alteredqualia.com/
  21345. */
  21346. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  21347. THREE.Object3D.call( this );
  21348. this.lensFlares = [];
  21349. this.positionScreen = new THREE.Vector3();
  21350. this.customUpdateCallback = undefined;
  21351. if( texture !== undefined ) {
  21352. this.add( texture, size, distance, blending, color );
  21353. }
  21354. };
  21355. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  21356. /*
  21357. * Add: adds another flare
  21358. */
  21359. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  21360. if( size === undefined ) size = -1;
  21361. if( distance === undefined ) distance = 0;
  21362. if( opacity === undefined ) opacity = 1;
  21363. if( color === undefined ) color = new THREE.Color( 0xffffff );
  21364. if( blending === undefined ) blending = THREE.NormalBlending;
  21365. distance = Math.min( distance, Math.max( 0, distance ) );
  21366. this.lensFlares.push( { texture: texture, // THREE.Texture
  21367. size: size, // size in pixels (-1 = use texture.width)
  21368. distance: distance, // distance (0-1) from light source (0=at light source)
  21369. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  21370. scale: 1, // scale
  21371. rotation: 1, // rotation
  21372. opacity: opacity, // opacity
  21373. color: color, // color
  21374. blending: blending } ); // blending
  21375. };
  21376. /*
  21377. * Update lens flares update positions on all flares based on the screen position
  21378. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  21379. */
  21380. THREE.LensFlare.prototype.updateLensFlares = function () {
  21381. var f, fl = this.lensFlares.length;
  21382. var flare;
  21383. var vecX = -this.positionScreen.x * 2;
  21384. var vecY = -this.positionScreen.y * 2;
  21385. for( f = 0; f < fl; f ++ ) {
  21386. flare = this.lensFlares[ f ];
  21387. flare.x = this.positionScreen.x + vecX * flare.distance;
  21388. flare.y = this.positionScreen.y + vecY * flare.distance;
  21389. flare.wantedRotation = flare.x * Math.PI * 0.25;
  21390. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  21391. }
  21392. };
  21393. /**
  21394. * @author alteredq / http://alteredqualia.com/
  21395. */
  21396. THREE.MorphBlendMesh = function( geometry, material ) {
  21397. THREE.Mesh.call( this, geometry, material );
  21398. this.animationsMap = {};
  21399. this.animationsList = [];
  21400. // prepare default animation
  21401. // (all frames played together in 1 second)
  21402. var numFrames = this.geometry.morphTargets.length;
  21403. var name = "__default";
  21404. var startFrame = 0;
  21405. var endFrame = numFrames - 1;
  21406. var fps = numFrames / 1;
  21407. this.createAnimation( name, startFrame, endFrame, fps );
  21408. this.setAnimationWeight( name, 1 );
  21409. };
  21410. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  21411. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  21412. var animation = {
  21413. startFrame: start,
  21414. endFrame: end,
  21415. length: end - start + 1,
  21416. fps: fps,
  21417. duration: ( end - start ) / fps,
  21418. lastFrame: 0,
  21419. currentFrame: 0,
  21420. active: false,
  21421. time: 0,
  21422. direction: 1,
  21423. weight: 1,
  21424. directionBackwards: false,
  21425. mirroredLoop: false
  21426. };
  21427. this.animationsMap[ name ] = animation;
  21428. this.animationsList.push( animation );
  21429. };
  21430. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21431. var pattern = /([a-z]+)(\d+)/;
  21432. var firstAnimation, frameRanges = {};
  21433. var geometry = this.geometry;
  21434. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21435. var morph = geometry.morphTargets[ i ];
  21436. var chunks = morph.name.match( pattern );
  21437. if ( chunks && chunks.length > 1 ) {
  21438. var name = chunks[ 1 ];
  21439. var num = chunks[ 2 ];
  21440. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  21441. var range = frameRanges[ name ];
  21442. if ( i < range.start ) range.start = i;
  21443. if ( i > range.end ) range.end = i;
  21444. if ( ! firstAnimation ) firstAnimation = name;
  21445. }
  21446. }
  21447. for ( var name in frameRanges ) {
  21448. var range = frameRanges[ name ];
  21449. this.createAnimation( name, range.start, range.end, fps );
  21450. }
  21451. this.firstAnimation = firstAnimation;
  21452. };
  21453. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  21454. var animation = this.animationsMap[ name ];
  21455. if ( animation ) {
  21456. animation.direction = 1;
  21457. animation.directionBackwards = false;
  21458. }
  21459. };
  21460. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  21461. var animation = this.animationsMap[ name ];
  21462. if ( animation ) {
  21463. animation.direction = -1;
  21464. animation.directionBackwards = true;
  21465. }
  21466. };
  21467. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  21468. var animation = this.animationsMap[ name ];
  21469. if ( animation ) {
  21470. animation.fps = fps;
  21471. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21472. }
  21473. };
  21474. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21475. var animation = this.animationsMap[ name ];
  21476. if ( animation ) {
  21477. animation.duration = duration;
  21478. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21479. }
  21480. };
  21481. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21482. var animation = this.animationsMap[ name ];
  21483. if ( animation ) {
  21484. animation.weight = weight;
  21485. }
  21486. };
  21487. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21488. var animation = this.animationsMap[ name ];
  21489. if ( animation ) {
  21490. animation.time = time;
  21491. }
  21492. };
  21493. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21494. var time = 0;
  21495. var animation = this.animationsMap[ name ];
  21496. if ( animation ) {
  21497. time = animation.time;
  21498. }
  21499. return time;
  21500. };
  21501. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21502. var duration = -1;
  21503. var animation = this.animationsMap[ name ];
  21504. if ( animation ) {
  21505. duration = animation.duration;
  21506. }
  21507. return duration;
  21508. };
  21509. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21510. var animation = this.animationsMap[ name ];
  21511. if ( animation ) {
  21512. animation.time = 0;
  21513. animation.active = true;
  21514. } else {
  21515. console.warn( "animation[" + name + "] undefined" );
  21516. }
  21517. };
  21518. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21519. var animation = this.animationsMap[ name ];
  21520. if ( animation ) {
  21521. animation.active = false;
  21522. }
  21523. };
  21524. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  21525. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21526. var animation = this.animationsList[ i ];
  21527. if ( ! animation.active ) continue;
  21528. var frameTime = animation.duration / animation.length;
  21529. animation.time += animation.direction * delta;
  21530. if ( animation.mirroredLoop ) {
  21531. if ( animation.time > animation.duration || animation.time < 0 ) {
  21532. animation.direction *= -1;
  21533. if ( animation.time > animation.duration ) {
  21534. animation.time = animation.duration;
  21535. animation.directionBackwards = true;
  21536. }
  21537. if ( animation.time < 0 ) {
  21538. animation.time = 0;
  21539. animation.directionBackwards = false;
  21540. }
  21541. }
  21542. } else {
  21543. animation.time = animation.time % animation.duration;
  21544. if ( animation.time < 0 ) animation.time += animation.duration;
  21545. }
  21546. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21547. var weight = animation.weight;
  21548. if ( keyframe !== animation.currentFrame ) {
  21549. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21550. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21551. this.morphTargetInfluences[ keyframe ] = 0;
  21552. animation.lastFrame = animation.currentFrame;
  21553. animation.currentFrame = keyframe;
  21554. }
  21555. var mix = ( animation.time % frameTime ) / frameTime;
  21556. if ( animation.directionBackwards ) mix = 1 - mix;
  21557. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21558. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21559. }
  21560. };
  21561. /**
  21562. * @author mikael emtinger / http://gomo.se/
  21563. * @author alteredq / http://alteredqualia.com/
  21564. */
  21565. THREE.LensFlarePlugin = function () {
  21566. var _gl, _renderer, _precision, _lensFlare = {};
  21567. this.init = function ( renderer ) {
  21568. _gl = renderer.context;
  21569. _renderer = renderer;
  21570. _precision = renderer.getPrecision();
  21571. _lensFlare.vertices = new Float32Array( 8 + 8 );
  21572. _lensFlare.faces = new Uint16Array( 6 );
  21573. var i = 0;
  21574. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  21575. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  21576. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  21577. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  21578. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21579. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21580. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  21581. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  21582. i = 0;
  21583. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  21584. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  21585. // buffers
  21586. _lensFlare.vertexBuffer = _gl.createBuffer();
  21587. _lensFlare.elementBuffer = _gl.createBuffer();
  21588. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21589. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  21590. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21591. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  21592. // textures
  21593. _lensFlare.tempTexture = _gl.createTexture();
  21594. _lensFlare.occlusionTexture = _gl.createTexture();
  21595. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21596. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21597. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21598. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21599. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21600. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21601. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21602. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21603. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21604. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21605. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21606. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21607. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21608. _lensFlare.hasVertexTexture = false;
  21609. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  21610. } else {
  21611. _lensFlare.hasVertexTexture = true;
  21612. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  21613. }
  21614. _lensFlare.attributes = {};
  21615. _lensFlare.uniforms = {};
  21616. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21617. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21618. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21619. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21620. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21621. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21622. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21623. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21624. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21625. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21626. };
  21627. /*
  21628. * Render lens flares
  21629. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21630. * reads these back and calculates occlusion.
  21631. * Then _lensFlare.update_lensFlares() is called to re-position and
  21632. * update transparency of flares. Then they are rendered.
  21633. *
  21634. */
  21635. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21636. var flares = scene.__webglFlares,
  21637. nFlares = flares.length;
  21638. if ( ! nFlares ) return;
  21639. var tempPosition = new THREE.Vector3();
  21640. var invAspect = viewportHeight / viewportWidth,
  21641. halfViewportWidth = viewportWidth * 0.5,
  21642. halfViewportHeight = viewportHeight * 0.5;
  21643. var size = 16 / viewportHeight,
  21644. scale = new THREE.Vector2( size * invAspect, size );
  21645. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21646. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21647. var uniforms = _lensFlare.uniforms,
  21648. attributes = _lensFlare.attributes;
  21649. // set _lensFlare program and reset blending
  21650. _gl.useProgram( _lensFlare.program );
  21651. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21652. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21653. // loop through all lens flares to update their occlusion and positions
  21654. // setup gl and common used attribs/unforms
  21655. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21656. _gl.uniform1i( uniforms.map, 1 );
  21657. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21658. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21659. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21660. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21661. _gl.disable( _gl.CULL_FACE );
  21662. _gl.depthMask( false );
  21663. var i, j, jl, flare, sprite;
  21664. for ( i = 0; i < nFlares; i ++ ) {
  21665. size = 16 / viewportHeight;
  21666. scale.set( size * invAspect, size );
  21667. // calc object screen position
  21668. flare = flares[ i ];
  21669. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21670. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  21671. tempPosition.applyProjection( camera.projectionMatrix );
  21672. // setup arrays for gl programs
  21673. screenPosition.copy( tempPosition )
  21674. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21675. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21676. // screen cull
  21677. if ( _lensFlare.hasVertexTexture || (
  21678. screenPositionPixels.x > 0 &&
  21679. screenPositionPixels.x < viewportWidth &&
  21680. screenPositionPixels.y > 0 &&
  21681. screenPositionPixels.y < viewportHeight ) ) {
  21682. // save current RGB to temp texture
  21683. _gl.activeTexture( _gl.TEXTURE1 );
  21684. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21685. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21686. // render pink quad
  21687. _gl.uniform1i( uniforms.renderType, 0 );
  21688. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21689. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21690. _gl.disable( _gl.BLEND );
  21691. _gl.enable( _gl.DEPTH_TEST );
  21692. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21693. // copy result to occlusionMap
  21694. _gl.activeTexture( _gl.TEXTURE0 );
  21695. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21696. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21697. // restore graphics
  21698. _gl.uniform1i( uniforms.renderType, 1 );
  21699. _gl.disable( _gl.DEPTH_TEST );
  21700. _gl.activeTexture( _gl.TEXTURE1 );
  21701. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21702. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21703. // update object positions
  21704. flare.positionScreen.copy( screenPosition )
  21705. if ( flare.customUpdateCallback ) {
  21706. flare.customUpdateCallback( flare );
  21707. } else {
  21708. flare.updateLensFlares();
  21709. }
  21710. // render flares
  21711. _gl.uniform1i( uniforms.renderType, 2 );
  21712. _gl.enable( _gl.BLEND );
  21713. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21714. sprite = flare.lensFlares[ j ];
  21715. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21716. screenPosition.x = sprite.x;
  21717. screenPosition.y = sprite.y;
  21718. screenPosition.z = sprite.z;
  21719. size = sprite.size * sprite.scale / viewportHeight;
  21720. scale.x = size * invAspect;
  21721. scale.y = size;
  21722. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21723. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21724. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21725. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21726. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21727. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21728. _renderer.setTexture( sprite.texture, 1 );
  21729. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21730. }
  21731. }
  21732. }
  21733. }
  21734. // restore gl
  21735. _gl.enable( _gl.CULL_FACE );
  21736. _gl.enable( _gl.DEPTH_TEST );
  21737. _gl.depthMask( true );
  21738. };
  21739. function createProgram ( shader, precision ) {
  21740. var program = _gl.createProgram();
  21741. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21742. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21743. var prefix = "precision " + precision + " float;\n";
  21744. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21745. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21746. _gl.compileShader( fragmentShader );
  21747. _gl.compileShader( vertexShader );
  21748. _gl.attachShader( program, fragmentShader );
  21749. _gl.attachShader( program, vertexShader );
  21750. _gl.linkProgram( program );
  21751. return program;
  21752. };
  21753. };
  21754. /**
  21755. * @author alteredq / http://alteredqualia.com/
  21756. */
  21757. THREE.ShadowMapPlugin = function () {
  21758. var _gl,
  21759. _renderer,
  21760. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21761. _frustum = new THREE.Frustum(),
  21762. _projScreenMatrix = new THREE.Matrix4(),
  21763. _min = new THREE.Vector3(),
  21764. _max = new THREE.Vector3(),
  21765. _matrixPosition = new THREE.Vector3();
  21766. this.init = function ( renderer ) {
  21767. _gl = renderer.context;
  21768. _renderer = renderer;
  21769. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21770. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21771. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21772. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21773. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21774. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21775. _depthMaterial._shadowPass = true;
  21776. _depthMaterialMorph._shadowPass = true;
  21777. _depthMaterialSkin._shadowPass = true;
  21778. _depthMaterialMorphSkin._shadowPass = true;
  21779. };
  21780. this.render = function ( scene, camera ) {
  21781. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21782. this.update( scene, camera );
  21783. };
  21784. this.update = function ( scene, camera ) {
  21785. var i, il, j, jl, n,
  21786. shadowMap, shadowMatrix, shadowCamera,
  21787. program, buffer, material,
  21788. webglObject, object, light,
  21789. renderList,
  21790. lights = [],
  21791. k = 0,
  21792. fog = null;
  21793. // set GL state for depth map
  21794. _gl.clearColor( 1, 1, 1, 1 );
  21795. _gl.disable( _gl.BLEND );
  21796. _gl.enable( _gl.CULL_FACE );
  21797. _gl.frontFace( _gl.CCW );
  21798. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21799. _gl.cullFace( _gl.FRONT );
  21800. } else {
  21801. _gl.cullFace( _gl.BACK );
  21802. }
  21803. _renderer.setDepthTest( true );
  21804. // preprocess lights
  21805. // - skip lights that are not casting shadows
  21806. // - create virtual lights for cascaded shadow maps
  21807. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21808. light = scene.__lights[ i ];
  21809. if ( ! light.castShadow ) continue;
  21810. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21811. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21812. var virtualLight;
  21813. if ( ! light.shadowCascadeArray[ n ] ) {
  21814. virtualLight = createVirtualLight( light, n );
  21815. virtualLight.originalCamera = camera;
  21816. var gyro = new THREE.Gyroscope();
  21817. gyro.position = light.shadowCascadeOffset;
  21818. gyro.add( virtualLight );
  21819. gyro.add( virtualLight.target );
  21820. camera.add( gyro );
  21821. light.shadowCascadeArray[ n ] = virtualLight;
  21822. console.log( "Created virtualLight", virtualLight );
  21823. } else {
  21824. virtualLight = light.shadowCascadeArray[ n ];
  21825. }
  21826. updateVirtualLight( light, n );
  21827. lights[ k ] = virtualLight;
  21828. k ++;
  21829. }
  21830. } else {
  21831. lights[ k ] = light;
  21832. k ++;
  21833. }
  21834. }
  21835. // render depth map
  21836. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21837. light = lights[ i ];
  21838. if ( ! light.shadowMap ) {
  21839. var shadowFilter = THREE.LinearFilter;
  21840. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21841. shadowFilter = THREE.NearestFilter;
  21842. }
  21843. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21844. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21845. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21846. light.shadowMatrix = new THREE.Matrix4();
  21847. }
  21848. if ( ! light.shadowCamera ) {
  21849. if ( light instanceof THREE.SpotLight ) {
  21850. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21851. } else if ( light instanceof THREE.DirectionalLight ) {
  21852. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21853. } else {
  21854. console.error( "Unsupported light type for shadow" );
  21855. continue;
  21856. }
  21857. scene.add( light.shadowCamera );
  21858. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21859. }
  21860. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21861. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21862. light.shadowCamera.add( light.cameraHelper );
  21863. }
  21864. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21865. updateShadowCamera( camera, light );
  21866. }
  21867. shadowMap = light.shadowMap;
  21868. shadowMatrix = light.shadowMatrix;
  21869. shadowCamera = light.shadowCamera;
  21870. shadowCamera.position.getPositionFromMatrix( light.matrixWorld );
  21871. _matrixPosition.getPositionFromMatrix( light.target.matrixWorld );
  21872. shadowCamera.lookAt( _matrixPosition );
  21873. shadowCamera.updateMatrixWorld();
  21874. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21875. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21876. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21877. // compute shadow matrix
  21878. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21879. 0.0, 0.5, 0.0, 0.5,
  21880. 0.0, 0.0, 0.5, 0.5,
  21881. 0.0, 0.0, 0.0, 1.0 );
  21882. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  21883. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  21884. // update camera matrices and frustum
  21885. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21886. _frustum.setFromMatrix( _projScreenMatrix );
  21887. // render shadow map
  21888. _renderer.setRenderTarget( shadowMap );
  21889. _renderer.clear();
  21890. // set object matrices & frustum culling
  21891. renderList = scene.__webglObjects;
  21892. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21893. webglObject = renderList[ j ];
  21894. object = webglObject.object;
  21895. webglObject.render = false;
  21896. if ( object.visible && object.castShadow ) {
  21897. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21898. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21899. webglObject.render = true;
  21900. }
  21901. }
  21902. }
  21903. // render regular objects
  21904. var objectMaterial, useMorphing, useSkinning;
  21905. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21906. webglObject = renderList[ j ];
  21907. if ( webglObject.render ) {
  21908. object = webglObject.object;
  21909. buffer = webglObject.buffer;
  21910. // culling is overriden globally for all objects
  21911. // while rendering depth map
  21912. // need to deal with MeshFaceMaterial somehow
  21913. // in that case just use the first of material.materials for now
  21914. // (proper solution would require to break objects by materials
  21915. // similarly to regular rendering and then set corresponding
  21916. // depth materials per each chunk instead of just once per object)
  21917. objectMaterial = getObjectMaterial( object );
  21918. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21919. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21920. if ( object.customDepthMaterial ) {
  21921. material = object.customDepthMaterial;
  21922. } else if ( useSkinning ) {
  21923. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21924. } else if ( useMorphing ) {
  21925. material = _depthMaterialMorph;
  21926. } else {
  21927. material = _depthMaterial;
  21928. }
  21929. if ( buffer instanceof THREE.BufferGeometry ) {
  21930. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21931. } else {
  21932. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21933. }
  21934. }
  21935. }
  21936. // set matrices and render immediate objects
  21937. renderList = scene.__webglObjectsImmediate;
  21938. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21939. webglObject = renderList[ j ];
  21940. object = webglObject.object;
  21941. if ( object.visible && object.castShadow ) {
  21942. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21943. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21944. }
  21945. }
  21946. }
  21947. // restore GL state
  21948. var clearColor = _renderer.getClearColor(),
  21949. clearAlpha = _renderer.getClearAlpha();
  21950. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21951. _gl.enable( _gl.BLEND );
  21952. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21953. _gl.cullFace( _gl.BACK );
  21954. }
  21955. };
  21956. function createVirtualLight( light, cascade ) {
  21957. var virtualLight = new THREE.DirectionalLight();
  21958. virtualLight.isVirtual = true;
  21959. virtualLight.onlyShadow = true;
  21960. virtualLight.castShadow = true;
  21961. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21962. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21963. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21964. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21965. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21966. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21967. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21968. virtualLight.shadowDarkness = light.shadowDarkness;
  21969. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21970. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21971. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21972. virtualLight.pointsWorld = [];
  21973. virtualLight.pointsFrustum = [];
  21974. var pointsWorld = virtualLight.pointsWorld,
  21975. pointsFrustum = virtualLight.pointsFrustum;
  21976. for ( var i = 0; i < 8; i ++ ) {
  21977. pointsWorld[ i ] = new THREE.Vector3();
  21978. pointsFrustum[ i ] = new THREE.Vector3();
  21979. }
  21980. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21981. var farZ = light.shadowCascadeFarZ[ cascade ];
  21982. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21983. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21984. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21985. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21986. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21987. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21988. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21989. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21990. return virtualLight;
  21991. }
  21992. // Synchronize virtual light with the original light
  21993. function updateVirtualLight( light, cascade ) {
  21994. var virtualLight = light.shadowCascadeArray[ cascade ];
  21995. virtualLight.position.copy( light.position );
  21996. virtualLight.target.position.copy( light.target.position );
  21997. virtualLight.lookAt( virtualLight.target );
  21998. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21999. virtualLight.shadowDarkness = light.shadowDarkness;
  22000. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  22001. var nearZ = light.shadowCascadeNearZ[ cascade ];
  22002. var farZ = light.shadowCascadeFarZ[ cascade ];
  22003. var pointsFrustum = virtualLight.pointsFrustum;
  22004. pointsFrustum[ 0 ].z = nearZ;
  22005. pointsFrustum[ 1 ].z = nearZ;
  22006. pointsFrustum[ 2 ].z = nearZ;
  22007. pointsFrustum[ 3 ].z = nearZ;
  22008. pointsFrustum[ 4 ].z = farZ;
  22009. pointsFrustum[ 5 ].z = farZ;
  22010. pointsFrustum[ 6 ].z = farZ;
  22011. pointsFrustum[ 7 ].z = farZ;
  22012. }
  22013. // Fit shadow camera's ortho frustum to camera frustum
  22014. function updateShadowCamera( camera, light ) {
  22015. var shadowCamera = light.shadowCamera,
  22016. pointsFrustum = light.pointsFrustum,
  22017. pointsWorld = light.pointsWorld;
  22018. _min.set( Infinity, Infinity, Infinity );
  22019. _max.set( -Infinity, -Infinity, -Infinity );
  22020. for ( var i = 0; i < 8; i ++ ) {
  22021. var p = pointsWorld[ i ];
  22022. p.copy( pointsFrustum[ i ] );
  22023. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  22024. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  22025. if ( p.x < _min.x ) _min.x = p.x;
  22026. if ( p.x > _max.x ) _max.x = p.x;
  22027. if ( p.y < _min.y ) _min.y = p.y;
  22028. if ( p.y > _max.y ) _max.y = p.y;
  22029. if ( p.z < _min.z ) _min.z = p.z;
  22030. if ( p.z > _max.z ) _max.z = p.z;
  22031. }
  22032. shadowCamera.left = _min.x;
  22033. shadowCamera.right = _max.x;
  22034. shadowCamera.top = _max.y;
  22035. shadowCamera.bottom = _min.y;
  22036. // can't really fit near/far
  22037. //shadowCamera.near = _min.z;
  22038. //shadowCamera.far = _max.z;
  22039. shadowCamera.updateProjectionMatrix();
  22040. }
  22041. // For the moment just ignore objects that have multiple materials with different animation methods
  22042. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  22043. function getObjectMaterial( object ) {
  22044. return object.material instanceof THREE.MeshFaceMaterial
  22045. ? object.material.materials[ 0 ]
  22046. : object.material;
  22047. };
  22048. };
  22049. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  22050. /**
  22051. * @author mikael emtinger / http://gomo.se/
  22052. * @author alteredq / http://alteredqualia.com/
  22053. */
  22054. THREE.SpritePlugin = function () {
  22055. var _gl, _renderer, _precision, _sprite = {};
  22056. this.init = function ( renderer ) {
  22057. _gl = renderer.context;
  22058. _renderer = renderer;
  22059. _precision = renderer.getPrecision();
  22060. _sprite.vertices = new Float32Array( 8 + 8 );
  22061. _sprite.faces = new Uint16Array( 6 );
  22062. var i = 0;
  22063. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  22064. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  22065. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  22066. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  22067. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  22068. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  22069. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  22070. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  22071. i = 0;
  22072. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  22073. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  22074. _sprite.vertexBuffer = _gl.createBuffer();
  22075. _sprite.elementBuffer = _gl.createBuffer();
  22076. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  22077. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  22078. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  22079. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  22080. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ], _precision );
  22081. _sprite.attributes = {};
  22082. _sprite.uniforms = {};
  22083. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  22084. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  22085. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  22086. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  22087. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  22088. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  22089. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  22090. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  22091. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  22092. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  22093. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  22094. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  22095. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  22096. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  22097. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  22098. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  22099. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  22100. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  22101. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  22102. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  22103. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  22104. };
  22105. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  22106. var sprites = scene.__webglSprites,
  22107. nSprites = sprites.length;
  22108. if ( ! nSprites ) return;
  22109. var attributes = _sprite.attributes,
  22110. uniforms = _sprite.uniforms;
  22111. var invAspect = viewportHeight / viewportWidth;
  22112. var halfViewportWidth = viewportWidth * 0.5,
  22113. halfViewportHeight = viewportHeight * 0.5;
  22114. // setup gl
  22115. _gl.useProgram( _sprite.program );
  22116. _gl.enableVertexAttribArray( attributes.position );
  22117. _gl.enableVertexAttribArray( attributes.uv );
  22118. _gl.disable( _gl.CULL_FACE );
  22119. _gl.enable( _gl.BLEND );
  22120. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  22121. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  22122. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  22123. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  22124. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  22125. _gl.activeTexture( _gl.TEXTURE0 );
  22126. _gl.uniform1i( uniforms.map, 0 );
  22127. var oldFogType = 0;
  22128. var sceneFogType = 0;
  22129. var fog = scene.fog;
  22130. if ( fog ) {
  22131. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  22132. if ( fog instanceof THREE.Fog ) {
  22133. _gl.uniform1f( uniforms.fogNear, fog.near );
  22134. _gl.uniform1f( uniforms.fogFar, fog.far );
  22135. _gl.uniform1i( uniforms.fogType, 1 );
  22136. oldFogType = 1;
  22137. sceneFogType = 1;
  22138. } else if ( fog instanceof THREE.FogExp2 ) {
  22139. _gl.uniform1f( uniforms.fogDensity, fog.density );
  22140. _gl.uniform1i( uniforms.fogType, 2 );
  22141. oldFogType = 2;
  22142. sceneFogType = 2;
  22143. }
  22144. } else {
  22145. _gl.uniform1i( uniforms.fogType, 0 );
  22146. oldFogType = 0;
  22147. sceneFogType = 0;
  22148. }
  22149. // update positions and sort
  22150. var i, sprite, material, screenPosition, size, fogType, scale = [];
  22151. for( i = 0; i < nSprites; i ++ ) {
  22152. sprite = sprites[ i ];
  22153. material = sprite.material;
  22154. if ( ! sprite.visible || material.opacity === 0 ) continue;
  22155. if ( ! material.useScreenCoordinates ) {
  22156. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  22157. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  22158. } else {
  22159. sprite.z = - sprite.position.z;
  22160. }
  22161. }
  22162. sprites.sort( painterSortStable );
  22163. // render all sprites
  22164. for( i = 0; i < nSprites; i ++ ) {
  22165. sprite = sprites[ i ];
  22166. material = sprite.material;
  22167. if ( ! sprite.visible || material.opacity === 0 ) continue;
  22168. if ( material.map && material.map.image && material.map.image.width ) {
  22169. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  22170. if ( material.useScreenCoordinates === true ) {
  22171. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  22172. _gl.uniform3f(
  22173. uniforms.screenPosition,
  22174. ( ( sprite.position.x * _renderer.devicePixelRatio ) - halfViewportWidth ) / halfViewportWidth,
  22175. ( halfViewportHeight - ( sprite.position.y * _renderer.devicePixelRatio ) ) / halfViewportHeight,
  22176. Math.max( 0, Math.min( 1, sprite.position.z ) )
  22177. );
  22178. scale[ 0 ] = _renderer.devicePixelRatio;
  22179. scale[ 1 ] = _renderer.devicePixelRatio;
  22180. } else {
  22181. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  22182. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  22183. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  22184. scale[ 0 ] = 1;
  22185. scale[ 1 ] = 1;
  22186. }
  22187. if ( scene.fog && material.fog ) {
  22188. fogType = sceneFogType;
  22189. } else {
  22190. fogType = 0;
  22191. }
  22192. if ( oldFogType !== fogType ) {
  22193. _gl.uniform1i( uniforms.fogType, fogType );
  22194. oldFogType = fogType;
  22195. }
  22196. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  22197. scale[ 0 ] *= size * invAspect * sprite.scale.x
  22198. scale[ 1 ] *= size * sprite.scale.y;
  22199. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  22200. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  22201. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  22202. _gl.uniform1f( uniforms.opacity, material.opacity );
  22203. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  22204. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  22205. _gl.uniform2fv( uniforms.scale, scale );
  22206. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  22207. _renderer.setDepthTest( material.depthTest );
  22208. _renderer.setDepthWrite( material.depthWrite );
  22209. _renderer.setTexture( material.map, 0 );
  22210. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  22211. }
  22212. }
  22213. // restore gl
  22214. _gl.enable( _gl.CULL_FACE );
  22215. };
  22216. function createProgram ( shader, precision ) {
  22217. var program = _gl.createProgram();
  22218. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  22219. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  22220. var prefix = "precision " + precision + " float;\n";
  22221. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  22222. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  22223. _gl.compileShader( fragmentShader );
  22224. _gl.compileShader( vertexShader );
  22225. _gl.attachShader( program, fragmentShader );
  22226. _gl.attachShader( program, vertexShader );
  22227. _gl.linkProgram( program );
  22228. return program;
  22229. };
  22230. function painterSortStable ( a, b ) {
  22231. if ( a.z !== b.z ) {
  22232. return b.z - a.z;
  22233. } else {
  22234. return b.id - a.id;
  22235. }
  22236. };
  22237. };
  22238. /**
  22239. * @author alteredq / http://alteredqualia.com/
  22240. */
  22241. THREE.DepthPassPlugin = function () {
  22242. this.enabled = false;
  22243. this.renderTarget = null;
  22244. var _gl,
  22245. _renderer,
  22246. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  22247. _frustum = new THREE.Frustum(),
  22248. _projScreenMatrix = new THREE.Matrix4();
  22249. this.init = function ( renderer ) {
  22250. _gl = renderer.context;
  22251. _renderer = renderer;
  22252. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  22253. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  22254. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  22255. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  22256. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  22257. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  22258. _depthMaterial._shadowPass = true;
  22259. _depthMaterialMorph._shadowPass = true;
  22260. _depthMaterialSkin._shadowPass = true;
  22261. _depthMaterialMorphSkin._shadowPass = true;
  22262. };
  22263. this.render = function ( scene, camera ) {
  22264. if ( ! this.enabled ) return;
  22265. this.update( scene, camera );
  22266. };
  22267. this.update = function ( scene, camera ) {
  22268. var i, il, j, jl, n,
  22269. program, buffer, material,
  22270. webglObject, object, light,
  22271. renderList,
  22272. fog = null;
  22273. // set GL state for depth map
  22274. _gl.clearColor( 1, 1, 1, 1 );
  22275. _gl.disable( _gl.BLEND );
  22276. _renderer.setDepthTest( true );
  22277. // update scene
  22278. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  22279. // update camera matrices and frustum
  22280. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  22281. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  22282. _frustum.setFromMatrix( _projScreenMatrix );
  22283. // render depth map
  22284. _renderer.setRenderTarget( this.renderTarget );
  22285. _renderer.clear();
  22286. // set object matrices & frustum culling
  22287. renderList = scene.__webglObjects;
  22288. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22289. webglObject = renderList[ j ];
  22290. object = webglObject.object;
  22291. webglObject.render = false;
  22292. if ( object.visible ) {
  22293. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  22294. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22295. webglObject.render = true;
  22296. }
  22297. }
  22298. }
  22299. // render regular objects
  22300. var objectMaterial, useMorphing, useSkinning;
  22301. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22302. webglObject = renderList[ j ];
  22303. if ( webglObject.render ) {
  22304. object = webglObject.object;
  22305. buffer = webglObject.buffer;
  22306. // todo: create proper depth material for particles
  22307. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  22308. objectMaterial = getObjectMaterial( object );
  22309. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  22310. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  22311. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  22312. if ( object.customDepthMaterial ) {
  22313. material = object.customDepthMaterial;
  22314. } else if ( useSkinning ) {
  22315. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  22316. } else if ( useMorphing ) {
  22317. material = _depthMaterialMorph;
  22318. } else {
  22319. material = _depthMaterial;
  22320. }
  22321. if ( buffer instanceof THREE.BufferGeometry ) {
  22322. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  22323. } else {
  22324. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  22325. }
  22326. }
  22327. }
  22328. // set matrices and render immediate objects
  22329. renderList = scene.__webglObjectsImmediate;
  22330. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22331. webglObject = renderList[ j ];
  22332. object = webglObject.object;
  22333. if ( object.visible ) {
  22334. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22335. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  22336. }
  22337. }
  22338. // restore GL state
  22339. var clearColor = _renderer.getClearColor(),
  22340. clearAlpha = _renderer.getClearAlpha();
  22341. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  22342. _gl.enable( _gl.BLEND );
  22343. };
  22344. // For the moment just ignore objects that have multiple materials with different animation methods
  22345. // Only the first material will be taken into account for deciding which depth material to use
  22346. function getObjectMaterial( object ) {
  22347. return object.material instanceof THREE.MeshFaceMaterial
  22348. ? object.material.materials[ 0 ]
  22349. : object.material;
  22350. };
  22351. };
  22352. /**
  22353. * @author mikael emtinger / http://gomo.se/
  22354. */
  22355. THREE.ShaderFlares = {
  22356. 'lensFlareVertexTexture': {
  22357. vertexShader: [
  22358. "uniform lowp int renderType;",
  22359. "uniform vec3 screenPosition;",
  22360. "uniform vec2 scale;",
  22361. "uniform float rotation;",
  22362. "uniform sampler2D occlusionMap;",
  22363. "attribute vec2 position;",
  22364. "attribute vec2 uv;",
  22365. "varying vec2 vUV;",
  22366. "varying float vVisibility;",
  22367. "void main() {",
  22368. "vUV = uv;",
  22369. "vec2 pos = position;",
  22370. "if( renderType == 2 ) {",
  22371. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  22372. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  22373. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  22374. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  22375. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  22376. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  22377. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  22378. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  22379. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  22380. "vVisibility = visibility.r / 9.0;",
  22381. "vVisibility *= 1.0 - visibility.g / 9.0;",
  22382. "vVisibility *= visibility.b / 9.0;",
  22383. "vVisibility *= 1.0 - visibility.a / 9.0;",
  22384. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22385. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22386. "}",
  22387. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22388. "}"
  22389. ].join( "\n" ),
  22390. fragmentShader: [
  22391. "uniform lowp int renderType;",
  22392. "uniform sampler2D map;",
  22393. "uniform float opacity;",
  22394. "uniform vec3 color;",
  22395. "varying vec2 vUV;",
  22396. "varying float vVisibility;",
  22397. "void main() {",
  22398. // pink square
  22399. "if( renderType == 0 ) {",
  22400. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  22401. // restore
  22402. "} else if( renderType == 1 ) {",
  22403. "gl_FragColor = texture2D( map, vUV );",
  22404. // flare
  22405. "} else {",
  22406. "vec4 texture = texture2D( map, vUV );",
  22407. "texture.a *= opacity * vVisibility;",
  22408. "gl_FragColor = texture;",
  22409. "gl_FragColor.rgb *= color;",
  22410. "}",
  22411. "}"
  22412. ].join( "\n" )
  22413. },
  22414. 'lensFlare': {
  22415. vertexShader: [
  22416. "uniform lowp int renderType;",
  22417. "uniform vec3 screenPosition;",
  22418. "uniform vec2 scale;",
  22419. "uniform float rotation;",
  22420. "attribute vec2 position;",
  22421. "attribute vec2 uv;",
  22422. "varying vec2 vUV;",
  22423. "void main() {",
  22424. "vUV = uv;",
  22425. "vec2 pos = position;",
  22426. "if( renderType == 2 ) {",
  22427. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22428. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22429. "}",
  22430. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22431. "}"
  22432. ].join( "\n" ),
  22433. fragmentShader: [
  22434. "precision mediump float;",
  22435. "uniform lowp int renderType;",
  22436. "uniform sampler2D map;",
  22437. "uniform sampler2D occlusionMap;",
  22438. "uniform float opacity;",
  22439. "uniform vec3 color;",
  22440. "varying vec2 vUV;",
  22441. "void main() {",
  22442. // pink square
  22443. "if( renderType == 0 ) {",
  22444. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  22445. // restore
  22446. "} else if( renderType == 1 ) {",
  22447. "gl_FragColor = texture2D( map, vUV );",
  22448. // flare
  22449. "} else {",
  22450. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  22451. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  22452. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  22453. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  22454. "visibility = ( 1.0 - visibility / 4.0 );",
  22455. "vec4 texture = texture2D( map, vUV );",
  22456. "texture.a *= opacity * visibility;",
  22457. "gl_FragColor = texture;",
  22458. "gl_FragColor.rgb *= color;",
  22459. "}",
  22460. "}"
  22461. ].join( "\n" )
  22462. }
  22463. };
  22464. /**
  22465. * @author mikael emtinger / http://gomo.se/
  22466. * @author alteredq / http://alteredqualia.com/
  22467. *
  22468. */
  22469. THREE.ShaderSprite = {
  22470. 'sprite': {
  22471. vertexShader: [
  22472. "uniform int useScreenCoordinates;",
  22473. "uniform int sizeAttenuation;",
  22474. "uniform vec3 screenPosition;",
  22475. "uniform mat4 modelViewMatrix;",
  22476. "uniform mat4 projectionMatrix;",
  22477. "uniform float rotation;",
  22478. "uniform vec2 scale;",
  22479. "uniform vec2 alignment;",
  22480. "uniform vec2 uvOffset;",
  22481. "uniform vec2 uvScale;",
  22482. "attribute vec2 position;",
  22483. "attribute vec2 uv;",
  22484. "varying vec2 vUV;",
  22485. "void main() {",
  22486. "vUV = uvOffset + uv * uvScale;",
  22487. "vec2 alignedPosition = position + alignment;",
  22488. "vec2 rotatedPosition;",
  22489. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  22490. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  22491. "vec4 finalPosition;",
  22492. "if( useScreenCoordinates != 0 ) {",
  22493. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  22494. "} else {",
  22495. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  22496. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  22497. "}",
  22498. "gl_Position = finalPosition;",
  22499. "}"
  22500. ].join( "\n" ),
  22501. fragmentShader: [
  22502. "uniform vec3 color;",
  22503. "uniform sampler2D map;",
  22504. "uniform float opacity;",
  22505. "uniform int fogType;",
  22506. "uniform vec3 fogColor;",
  22507. "uniform float fogDensity;",
  22508. "uniform float fogNear;",
  22509. "uniform float fogFar;",
  22510. "uniform float alphaTest;",
  22511. "varying vec2 vUV;",
  22512. "void main() {",
  22513. "vec4 texture = texture2D( map, vUV );",
  22514. "if ( texture.a < alphaTest ) discard;",
  22515. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  22516. "if ( fogType > 0 ) {",
  22517. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  22518. "float fogFactor = 0.0;",
  22519. "if ( fogType == 1 ) {",
  22520. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  22521. "} else {",
  22522. "const float LOG2 = 1.442695;",
  22523. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  22524. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  22525. "}",
  22526. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  22527. "}",
  22528. "}"
  22529. ].join( "\n" )
  22530. }
  22531. };