three.js 838 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. * @author bhouston / http://exocortex.com
  5. */
  6. var THREE = { REVISION: '67dev' };
  7. self.console = self.console || {
  8. info: function () {},
  9. log: function () {},
  10. debug: function () {},
  11. warn: function () {},
  12. error: function () {}
  13. };
  14. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  15. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  16. // requestAnimationFrame polyfill by Erik Möller
  17. // fixes from Paul Irish and Tino Zijdel
  18. // using 'self' instead of 'window' for compatibility with both NodeJS and IE10.
  19. ( function () {
  20. var lastTime = 0;
  21. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  22. for ( var x = 0; x < vendors.length && !self.requestAnimationFrame; ++ x ) {
  23. self.requestAnimationFrame = self[ vendors[ x ] + 'RequestAnimationFrame' ];
  24. self.cancelAnimationFrame = self[ vendors[ x ] + 'CancelAnimationFrame' ] || self[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  25. }
  26. if ( self.requestAnimationFrame === undefined && self['setTimeout'] !== undefined ) {
  27. self.requestAnimationFrame = function ( callback ) {
  28. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  29. var id = self.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  30. lastTime = currTime + timeToCall;
  31. return id;
  32. };
  33. }
  34. if( self.cancelAnimationFrame === undefined && self['clearTimeout'] !== undefined ) {
  35. self.cancelAnimationFrame = function ( id ) { self.clearTimeout( id ) };
  36. }
  37. }() );
  38. // GL STATE CONSTANTS
  39. THREE.CullFaceNone = 0;
  40. THREE.CullFaceBack = 1;
  41. THREE.CullFaceFront = 2;
  42. THREE.CullFaceFrontBack = 3;
  43. THREE.FrontFaceDirectionCW = 0;
  44. THREE.FrontFaceDirectionCCW = 1;
  45. // SHADOWING TYPES
  46. THREE.BasicShadowMap = 0;
  47. THREE.PCFShadowMap = 1;
  48. THREE.PCFSoftShadowMap = 2;
  49. // MATERIAL CONSTANTS
  50. // side
  51. THREE.FrontSide = 0;
  52. THREE.BackSide = 1;
  53. THREE.DoubleSide = 2;
  54. // shading
  55. THREE.NoShading = 0;
  56. THREE.FlatShading = 1;
  57. THREE.SmoothShading = 2;
  58. // colors
  59. THREE.NoColors = 0;
  60. THREE.FaceColors = 1;
  61. THREE.VertexColors = 2;
  62. // blending modes
  63. THREE.NoBlending = 0;
  64. THREE.NormalBlending = 1;
  65. THREE.AdditiveBlending = 2;
  66. THREE.SubtractiveBlending = 3;
  67. THREE.MultiplyBlending = 4;
  68. THREE.CustomBlending = 5;
  69. // custom blending equations
  70. // (numbers start from 100 not to clash with other
  71. // mappings to OpenGL constants defined in Texture.js)
  72. THREE.AddEquation = 100;
  73. THREE.SubtractEquation = 101;
  74. THREE.ReverseSubtractEquation = 102;
  75. // custom blending destination factors
  76. THREE.ZeroFactor = 200;
  77. THREE.OneFactor = 201;
  78. THREE.SrcColorFactor = 202;
  79. THREE.OneMinusSrcColorFactor = 203;
  80. THREE.SrcAlphaFactor = 204;
  81. THREE.OneMinusSrcAlphaFactor = 205;
  82. THREE.DstAlphaFactor = 206;
  83. THREE.OneMinusDstAlphaFactor = 207;
  84. // custom blending source factors
  85. //THREE.ZeroFactor = 200;
  86. //THREE.OneFactor = 201;
  87. //THREE.SrcAlphaFactor = 204;
  88. //THREE.OneMinusSrcAlphaFactor = 205;
  89. //THREE.DstAlphaFactor = 206;
  90. //THREE.OneMinusDstAlphaFactor = 207;
  91. THREE.DstColorFactor = 208;
  92. THREE.OneMinusDstColorFactor = 209;
  93. THREE.SrcAlphaSaturateFactor = 210;
  94. // TEXTURE CONSTANTS
  95. THREE.MultiplyOperation = 0;
  96. THREE.MixOperation = 1;
  97. THREE.AddOperation = 2;
  98. // Mapping modes
  99. THREE.UVMapping = function () {};
  100. THREE.CubeReflectionMapping = function () {};
  101. THREE.CubeRefractionMapping = function () {};
  102. THREE.SphericalReflectionMapping = function () {};
  103. THREE.SphericalRefractionMapping = function () {};
  104. // Wrapping modes
  105. THREE.RepeatWrapping = 1000;
  106. THREE.ClampToEdgeWrapping = 1001;
  107. THREE.MirroredRepeatWrapping = 1002;
  108. // Filters
  109. THREE.NearestFilter = 1003;
  110. THREE.NearestMipMapNearestFilter = 1004;
  111. THREE.NearestMipMapLinearFilter = 1005;
  112. THREE.LinearFilter = 1006;
  113. THREE.LinearMipMapNearestFilter = 1007;
  114. THREE.LinearMipMapLinearFilter = 1008;
  115. // Data types
  116. THREE.UnsignedByteType = 1009;
  117. THREE.ByteType = 1010;
  118. THREE.ShortType = 1011;
  119. THREE.UnsignedShortType = 1012;
  120. THREE.IntType = 1013;
  121. THREE.UnsignedIntType = 1014;
  122. THREE.FloatType = 1015;
  123. // Pixel types
  124. //THREE.UnsignedByteType = 1009;
  125. THREE.UnsignedShort4444Type = 1016;
  126. THREE.UnsignedShort5551Type = 1017;
  127. THREE.UnsignedShort565Type = 1018;
  128. // Pixel formats
  129. THREE.AlphaFormat = 1019;
  130. THREE.RGBFormat = 1020;
  131. THREE.RGBAFormat = 1021;
  132. THREE.LuminanceFormat = 1022;
  133. THREE.LuminanceAlphaFormat = 1023;
  134. // Compressed texture formats
  135. THREE.RGB_S3TC_DXT1_Format = 2001;
  136. THREE.RGBA_S3TC_DXT1_Format = 2002;
  137. THREE.RGBA_S3TC_DXT3_Format = 2003;
  138. THREE.RGBA_S3TC_DXT5_Format = 2004;
  139. /*
  140. // Potential future PVRTC compressed texture formats
  141. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  142. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  143. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  144. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  145. */
  146. /**
  147. * @author mrdoob / http://mrdoob.com/
  148. */
  149. THREE.Color = function ( color ) {
  150. if ( arguments.length === 3 ) {
  151. return this.setRGB( arguments[ 0 ], arguments[ 1 ], arguments[ 2 ] );
  152. }
  153. return this.set( color )
  154. };
  155. THREE.Color.prototype = {
  156. constructor: THREE.Color,
  157. r: 1, g: 1, b: 1,
  158. set: function ( value ) {
  159. if ( value instanceof THREE.Color ) {
  160. this.copy( value );
  161. } else if ( typeof value === 'number' ) {
  162. this.setHex( value );
  163. } else if ( typeof value === 'string' ) {
  164. this.setStyle( value );
  165. }
  166. return this;
  167. },
  168. setHex: function ( hex ) {
  169. hex = Math.floor( hex );
  170. this.r = ( hex >> 16 & 255 ) / 255;
  171. this.g = ( hex >> 8 & 255 ) / 255;
  172. this.b = ( hex & 255 ) / 255;
  173. return this;
  174. },
  175. setRGB: function ( r, g, b ) {
  176. this.r = r;
  177. this.g = g;
  178. this.b = b;
  179. return this;
  180. },
  181. setHSL: function ( h, s, l ) {
  182. // h,s,l ranges are in 0.0 - 1.0
  183. if ( s === 0 ) {
  184. this.r = this.g = this.b = l;
  185. } else {
  186. var hue2rgb = function ( p, q, t ) {
  187. if ( t < 0 ) t += 1;
  188. if ( t > 1 ) t -= 1;
  189. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  190. if ( t < 1 / 2 ) return q;
  191. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  192. return p;
  193. };
  194. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  195. var q = ( 2 * l ) - p;
  196. this.r = hue2rgb( q, p, h + 1 / 3 );
  197. this.g = hue2rgb( q, p, h );
  198. this.b = hue2rgb( q, p, h - 1 / 3 );
  199. }
  200. return this;
  201. },
  202. setStyle: function ( style ) {
  203. // rgb(255,0,0)
  204. if ( /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.test( style ) ) {
  205. var color = /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.exec( style );
  206. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  207. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  208. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  209. return this;
  210. }
  211. // rgb(100%,0%,0%)
  212. if ( /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.test( style ) ) {
  213. var color = /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.exec( style );
  214. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  215. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  216. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  217. return this;
  218. }
  219. // #ff0000
  220. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  221. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  222. this.setHex( parseInt( color[ 1 ], 16 ) );
  223. return this;
  224. }
  225. // #f00
  226. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  227. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  228. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  229. return this;
  230. }
  231. // red
  232. if ( /^(\w+)$/i.test( style ) ) {
  233. this.setHex( THREE.ColorKeywords[ style ] );
  234. return this;
  235. }
  236. },
  237. copy: function ( color ) {
  238. this.r = color.r;
  239. this.g = color.g;
  240. this.b = color.b;
  241. return this;
  242. },
  243. copyGammaToLinear: function ( color ) {
  244. this.r = color.r * color.r;
  245. this.g = color.g * color.g;
  246. this.b = color.b * color.b;
  247. return this;
  248. },
  249. copyLinearToGamma: function ( color ) {
  250. this.r = Math.sqrt( color.r );
  251. this.g = Math.sqrt( color.g );
  252. this.b = Math.sqrt( color.b );
  253. return this;
  254. },
  255. convertGammaToLinear: function () {
  256. var r = this.r, g = this.g, b = this.b;
  257. this.r = r * r;
  258. this.g = g * g;
  259. this.b = b * b;
  260. return this;
  261. },
  262. convertLinearToGamma: function () {
  263. this.r = Math.sqrt( this.r );
  264. this.g = Math.sqrt( this.g );
  265. this.b = Math.sqrt( this.b );
  266. return this;
  267. },
  268. getHex: function () {
  269. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  270. },
  271. getHexString: function () {
  272. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  273. },
  274. getHSL: function ( optionalTarget ) {
  275. // h,s,l ranges are in 0.0 - 1.0
  276. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  277. var r = this.r, g = this.g, b = this.b;
  278. var max = Math.max( r, g, b );
  279. var min = Math.min( r, g, b );
  280. var hue, saturation;
  281. var lightness = ( min + max ) / 2.0;
  282. if ( min === max ) {
  283. hue = 0;
  284. saturation = 0;
  285. } else {
  286. var delta = max - min;
  287. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  288. switch ( max ) {
  289. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  290. case g: hue = ( b - r ) / delta + 2; break;
  291. case b: hue = ( r - g ) / delta + 4; break;
  292. }
  293. hue /= 6;
  294. }
  295. hsl.h = hue;
  296. hsl.s = saturation;
  297. hsl.l = lightness;
  298. return hsl;
  299. },
  300. getStyle: function () {
  301. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  302. },
  303. offsetHSL: function ( h, s, l ) {
  304. var hsl = this.getHSL();
  305. hsl.h += h; hsl.s += s; hsl.l += l;
  306. this.setHSL( hsl.h, hsl.s, hsl.l );
  307. return this;
  308. },
  309. add: function ( color ) {
  310. this.r += color.r;
  311. this.g += color.g;
  312. this.b += color.b;
  313. return this;
  314. },
  315. addColors: function ( color1, color2 ) {
  316. this.r = color1.r + color2.r;
  317. this.g = color1.g + color2.g;
  318. this.b = color1.b + color2.b;
  319. return this;
  320. },
  321. addScalar: function ( s ) {
  322. this.r += s;
  323. this.g += s;
  324. this.b += s;
  325. return this;
  326. },
  327. multiply: function ( color ) {
  328. this.r *= color.r;
  329. this.g *= color.g;
  330. this.b *= color.b;
  331. return this;
  332. },
  333. multiplyScalar: function ( s ) {
  334. this.r *= s;
  335. this.g *= s;
  336. this.b *= s;
  337. return this;
  338. },
  339. lerp: function ( color, alpha ) {
  340. this.r += ( color.r - this.r ) * alpha;
  341. this.g += ( color.g - this.g ) * alpha;
  342. this.b += ( color.b - this.b ) * alpha;
  343. return this;
  344. },
  345. equals: function ( c ) {
  346. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  347. },
  348. fromArray: function ( array ) {
  349. this.r = array[ 0 ];
  350. this.g = array[ 1 ];
  351. this.b = array[ 2 ];
  352. return this;
  353. },
  354. toArray: function () {
  355. return [ this.r, this.g, this.b ];
  356. },
  357. clone: function () {
  358. return new THREE.Color().setRGB( this.r, this.g, this.b );
  359. }
  360. };
  361. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  362. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  363. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  364. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  365. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  366. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  367. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  368. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  369. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  370. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  371. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  372. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  373. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  374. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  375. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  376. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  377. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  378. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  379. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  380. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  381. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  382. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  383. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  384. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  385. /**
  386. * @author mikael emtinger / http://gomo.se/
  387. * @author alteredq / http://alteredqualia.com/
  388. * @author WestLangley / http://github.com/WestLangley
  389. * @author bhouston / http://exocortex.com
  390. */
  391. THREE.Quaternion = function ( x, y, z, w ) {
  392. this._x = x || 0;
  393. this._y = y || 0;
  394. this._z = z || 0;
  395. this._w = ( w !== undefined ) ? w : 1;
  396. };
  397. THREE.Quaternion.prototype = {
  398. constructor: THREE.Quaternion,
  399. _x: 0,_y: 0, _z: 0, _w: 0,
  400. get x () {
  401. return this._x;
  402. },
  403. set x ( value ) {
  404. this._x = value;
  405. this.onChangeCallback();
  406. },
  407. get y () {
  408. return this._y;
  409. },
  410. set y ( value ) {
  411. this._y = value;
  412. this.onChangeCallback();
  413. },
  414. get z () {
  415. return this._z;
  416. },
  417. set z ( value ) {
  418. this._z = value;
  419. this.onChangeCallback();
  420. },
  421. get w () {
  422. return this._w;
  423. },
  424. set w ( value ) {
  425. this._w = value;
  426. this.onChangeCallback();
  427. },
  428. set: function ( x, y, z, w ) {
  429. this._x = x;
  430. this._y = y;
  431. this._z = z;
  432. this._w = w;
  433. this.onChangeCallback();
  434. return this;
  435. },
  436. copy: function ( quaternion ) {
  437. this._x = quaternion._x;
  438. this._y = quaternion._y;
  439. this._z = quaternion._z;
  440. this._w = quaternion._w;
  441. this.onChangeCallback();
  442. return this;
  443. },
  444. setFromEuler: function ( euler, update ) {
  445. if ( euler instanceof THREE.Euler === false ) {
  446. throw new Error( 'ERROR: Quaternion\'s .setFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  447. }
  448. // http://www.mathworks.com/matlabcentral/fileexchange/
  449. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  450. // content/SpinCalc.m
  451. var c1 = Math.cos( euler._x / 2 );
  452. var c2 = Math.cos( euler._y / 2 );
  453. var c3 = Math.cos( euler._z / 2 );
  454. var s1 = Math.sin( euler._x / 2 );
  455. var s2 = Math.sin( euler._y / 2 );
  456. var s3 = Math.sin( euler._z / 2 );
  457. if ( euler.order === 'XYZ' ) {
  458. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  459. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  460. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  461. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  462. } else if ( euler.order === 'YXZ' ) {
  463. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  464. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  465. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  466. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  467. } else if ( euler.order === 'ZXY' ) {
  468. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  469. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  470. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  471. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  472. } else if ( euler.order === 'ZYX' ) {
  473. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  474. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  475. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  476. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  477. } else if ( euler.order === 'YZX' ) {
  478. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  479. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  480. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  481. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  482. } else if ( euler.order === 'XZY' ) {
  483. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  484. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  485. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  486. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  487. }
  488. if ( update !== false ) this.onChangeCallback();
  489. return this;
  490. },
  491. setFromAxisAngle: function ( axis, angle ) {
  492. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  493. // assumes axis is normalized
  494. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  495. this._x = axis.x * s;
  496. this._y = axis.y * s;
  497. this._z = axis.z * s;
  498. this._w = Math.cos( halfAngle );
  499. this.onChangeCallback();
  500. return this;
  501. },
  502. setFromRotationMatrix: function ( m ) {
  503. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  504. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  505. var te = m.elements,
  506. m11 = te[0], m12 = te[4], m13 = te[8],
  507. m21 = te[1], m22 = te[5], m23 = te[9],
  508. m31 = te[2], m32 = te[6], m33 = te[10],
  509. trace = m11 + m22 + m33,
  510. s;
  511. if ( trace > 0 ) {
  512. s = 0.5 / Math.sqrt( trace + 1.0 );
  513. this._w = 0.25 / s;
  514. this._x = ( m32 - m23 ) * s;
  515. this._y = ( m13 - m31 ) * s;
  516. this._z = ( m21 - m12 ) * s;
  517. } else if ( m11 > m22 && m11 > m33 ) {
  518. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  519. this._w = (m32 - m23 ) / s;
  520. this._x = 0.25 * s;
  521. this._y = (m12 + m21 ) / s;
  522. this._z = (m13 + m31 ) / s;
  523. } else if ( m22 > m33 ) {
  524. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  525. this._w = (m13 - m31 ) / s;
  526. this._x = (m12 + m21 ) / s;
  527. this._y = 0.25 * s;
  528. this._z = (m23 + m32 ) / s;
  529. } else {
  530. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  531. this._w = ( m21 - m12 ) / s;
  532. this._x = ( m13 + m31 ) / s;
  533. this._y = ( m23 + m32 ) / s;
  534. this._z = 0.25 * s;
  535. }
  536. this.onChangeCallback();
  537. return this;
  538. },
  539. setFromUnitVectors: function () {
  540. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  541. // assumes direction vectors vFrom and vTo are normalized
  542. var v1, r;
  543. var EPS = 0.000001;
  544. return function( vFrom, vTo ) {
  545. if ( v1 === undefined ) v1 = new THREE.Vector3();
  546. r = vFrom.dot( vTo ) + 1;
  547. if ( r < EPS ) {
  548. r = 0;
  549. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  550. v1.set( - vFrom.y, vFrom.x, 0 );
  551. } else {
  552. v1.set( 0, - vFrom.z, vFrom.y );
  553. }
  554. } else {
  555. v1.crossVectors( vFrom, vTo );
  556. }
  557. this._x = v1.x;
  558. this._y = v1.y;
  559. this._z = v1.z;
  560. this._w = r;
  561. this.normalize();
  562. return this;
  563. }
  564. }(),
  565. inverse: function () {
  566. this.conjugate().normalize();
  567. return this;
  568. },
  569. conjugate: function () {
  570. this._x *= -1;
  571. this._y *= -1;
  572. this._z *= -1;
  573. this.onChangeCallback();
  574. return this;
  575. },
  576. lengthSq: function () {
  577. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  578. },
  579. length: function () {
  580. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  581. },
  582. normalize: function () {
  583. var l = this.length();
  584. if ( l === 0 ) {
  585. this._x = 0;
  586. this._y = 0;
  587. this._z = 0;
  588. this._w = 1;
  589. } else {
  590. l = 1 / l;
  591. this._x = this._x * l;
  592. this._y = this._y * l;
  593. this._z = this._z * l;
  594. this._w = this._w * l;
  595. }
  596. this.onChangeCallback();
  597. return this;
  598. },
  599. multiply: function ( q, p ) {
  600. if ( p !== undefined ) {
  601. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  602. return this.multiplyQuaternions( q, p );
  603. }
  604. return this.multiplyQuaternions( this, q );
  605. },
  606. multiplyQuaternions: function ( a, b ) {
  607. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  608. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  609. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  610. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  611. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  612. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  613. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  614. this.onChangeCallback();
  615. return this;
  616. },
  617. multiplyVector3: function ( vector ) {
  618. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  619. return vector.applyQuaternion( this );
  620. },
  621. slerp: function ( qb, t ) {
  622. var x = this._x, y = this._y, z = this._z, w = this._w;
  623. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  624. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  625. if ( cosHalfTheta < 0 ) {
  626. this._w = -qb._w;
  627. this._x = -qb._x;
  628. this._y = -qb._y;
  629. this._z = -qb._z;
  630. cosHalfTheta = -cosHalfTheta;
  631. } else {
  632. this.copy( qb );
  633. }
  634. if ( cosHalfTheta >= 1.0 ) {
  635. this._w = w;
  636. this._x = x;
  637. this._y = y;
  638. this._z = z;
  639. return this;
  640. }
  641. var halfTheta = Math.acos( cosHalfTheta );
  642. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  643. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  644. this._w = 0.5 * ( w + this._w );
  645. this._x = 0.5 * ( x + this._x );
  646. this._y = 0.5 * ( y + this._y );
  647. this._z = 0.5 * ( z + this._z );
  648. return this;
  649. }
  650. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  651. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  652. this._w = ( w * ratioA + this._w * ratioB );
  653. this._x = ( x * ratioA + this._x * ratioB );
  654. this._y = ( y * ratioA + this._y * ratioB );
  655. this._z = ( z * ratioA + this._z * ratioB );
  656. this.onChangeCallback();
  657. return this;
  658. },
  659. equals: function ( quaternion ) {
  660. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  661. },
  662. fromArray: function ( array ) {
  663. this._x = array[ 0 ];
  664. this._y = array[ 1 ];
  665. this._z = array[ 2 ];
  666. this._w = array[ 3 ];
  667. this.onChangeCallback();
  668. return this;
  669. },
  670. toArray: function () {
  671. return [ this._x, this._y, this._z, this._w ];
  672. },
  673. onChange: function ( callback ) {
  674. this.onChangeCallback = callback;
  675. return this;
  676. },
  677. onChangeCallback: function () {},
  678. clone: function () {
  679. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  680. }
  681. };
  682. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  683. return qm.copy( qa ).slerp( qb, t );
  684. }
  685. /**
  686. * @author mrdoob / http://mrdoob.com/
  687. * @author philogb / http://blog.thejit.org/
  688. * @author egraether / http://egraether.com/
  689. * @author zz85 / http://www.lab4games.net/zz85/blog
  690. */
  691. THREE.Vector2 = function ( x, y ) {
  692. this.x = x || 0;
  693. this.y = y || 0;
  694. };
  695. THREE.Vector2.prototype = {
  696. constructor: THREE.Vector2,
  697. set: function ( x, y ) {
  698. this.x = x;
  699. this.y = y;
  700. return this;
  701. },
  702. setX: function ( x ) {
  703. this.x = x;
  704. return this;
  705. },
  706. setY: function ( y ) {
  707. this.y = y;
  708. return this;
  709. },
  710. setComponent: function ( index, value ) {
  711. switch ( index ) {
  712. case 0: this.x = value; break;
  713. case 1: this.y = value; break;
  714. default: throw new Error( "index is out of range: " + index );
  715. }
  716. },
  717. getComponent: function ( index ) {
  718. switch ( index ) {
  719. case 0: return this.x;
  720. case 1: return this.y;
  721. default: throw new Error( "index is out of range: " + index );
  722. }
  723. },
  724. copy: function ( v ) {
  725. this.x = v.x;
  726. this.y = v.y;
  727. return this;
  728. },
  729. add: function ( v, w ) {
  730. if ( w !== undefined ) {
  731. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  732. return this.addVectors( v, w );
  733. }
  734. this.x += v.x;
  735. this.y += v.y;
  736. return this;
  737. },
  738. addVectors: function ( a, b ) {
  739. this.x = a.x + b.x;
  740. this.y = a.y + b.y;
  741. return this;
  742. },
  743. addScalar: function ( s ) {
  744. this.x += s;
  745. this.y += s;
  746. return this;
  747. },
  748. sub: function ( v, w ) {
  749. if ( w !== undefined ) {
  750. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  751. return this.subVectors( v, w );
  752. }
  753. this.x -= v.x;
  754. this.y -= v.y;
  755. return this;
  756. },
  757. subVectors: function ( a, b ) {
  758. this.x = a.x - b.x;
  759. this.y = a.y - b.y;
  760. return this;
  761. },
  762. multiply: function ( v ) {
  763. this.x *= v.x;
  764. this.y *= v.y;
  765. return this;
  766. },
  767. multiplyScalar: function ( s ) {
  768. this.x *= s;
  769. this.y *= s;
  770. return this;
  771. },
  772. divide: function ( v ) {
  773. this.x /= v.x;
  774. this.y /= v.y;
  775. return this;
  776. },
  777. divideScalar: function ( scalar ) {
  778. if ( scalar !== 0 ) {
  779. var invScalar = 1 / scalar;
  780. this.x *= invScalar;
  781. this.y *= invScalar;
  782. } else {
  783. this.x = 0;
  784. this.y = 0;
  785. }
  786. return this;
  787. },
  788. min: function ( v ) {
  789. if ( this.x > v.x ) {
  790. this.x = v.x;
  791. }
  792. if ( this.y > v.y ) {
  793. this.y = v.y;
  794. }
  795. return this;
  796. },
  797. max: function ( v ) {
  798. if ( this.x < v.x ) {
  799. this.x = v.x;
  800. }
  801. if ( this.y < v.y ) {
  802. this.y = v.y;
  803. }
  804. return this;
  805. },
  806. clamp: function ( min, max ) {
  807. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  808. if ( this.x < min.x ) {
  809. this.x = min.x;
  810. } else if ( this.x > max.x ) {
  811. this.x = max.x;
  812. }
  813. if ( this.y < min.y ) {
  814. this.y = min.y;
  815. } else if ( this.y > max.y ) {
  816. this.y = max.y;
  817. }
  818. return this;
  819. },
  820. clampScalar: ( function () {
  821. var min, max;
  822. return function ( minVal, maxVal ) {
  823. if ( min === undefined ) {
  824. min = new THREE.Vector2();
  825. max = new THREE.Vector2();
  826. }
  827. min.set( minVal, minVal );
  828. max.set( maxVal, maxVal );
  829. return this.clamp( min, max );
  830. };
  831. } )(),
  832. floor: function () {
  833. this.x = Math.floor( this.x );
  834. this.y = Math.floor( this.y );
  835. return this;
  836. },
  837. ceil: function () {
  838. this.x = Math.ceil( this.x );
  839. this.y = Math.ceil( this.y );
  840. return this;
  841. },
  842. round: function () {
  843. this.x = Math.round( this.x );
  844. this.y = Math.round( this.y );
  845. return this;
  846. },
  847. roundToZero: function () {
  848. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  849. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  850. return this;
  851. },
  852. negate: function () {
  853. return this.multiplyScalar( - 1 );
  854. },
  855. dot: function ( v ) {
  856. return this.x * v.x + this.y * v.y;
  857. },
  858. lengthSq: function () {
  859. return this.x * this.x + this.y * this.y;
  860. },
  861. length: function () {
  862. return Math.sqrt( this.x * this.x + this.y * this.y );
  863. },
  864. normalize: function () {
  865. return this.divideScalar( this.length() );
  866. },
  867. distanceTo: function ( v ) {
  868. return Math.sqrt( this.distanceToSquared( v ) );
  869. },
  870. distanceToSquared: function ( v ) {
  871. var dx = this.x - v.x, dy = this.y - v.y;
  872. return dx * dx + dy * dy;
  873. },
  874. setLength: function ( l ) {
  875. var oldLength = this.length();
  876. if ( oldLength !== 0 && l !== oldLength ) {
  877. this.multiplyScalar( l / oldLength );
  878. }
  879. return this;
  880. },
  881. lerp: function ( v, alpha ) {
  882. this.x += ( v.x - this.x ) * alpha;
  883. this.y += ( v.y - this.y ) * alpha;
  884. return this;
  885. },
  886. equals: function( v ) {
  887. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  888. },
  889. fromArray: function ( array ) {
  890. this.x = array[ 0 ];
  891. this.y = array[ 1 ];
  892. return this;
  893. },
  894. toArray: function () {
  895. return [ this.x, this.y ];
  896. },
  897. clone: function () {
  898. return new THREE.Vector2( this.x, this.y );
  899. }
  900. };
  901. /**
  902. * @author mrdoob / http://mrdoob.com/
  903. * @author *kile / http://kile.stravaganza.org/
  904. * @author philogb / http://blog.thejit.org/
  905. * @author mikael emtinger / http://gomo.se/
  906. * @author egraether / http://egraether.com/
  907. * @author WestLangley / http://github.com/WestLangley
  908. */
  909. THREE.Vector3 = function ( x, y, z ) {
  910. this.x = x || 0;
  911. this.y = y || 0;
  912. this.z = z || 0;
  913. };
  914. THREE.Vector3.prototype = {
  915. constructor: THREE.Vector3,
  916. set: function ( x, y, z ) {
  917. this.x = x;
  918. this.y = y;
  919. this.z = z;
  920. return this;
  921. },
  922. setX: function ( x ) {
  923. this.x = x;
  924. return this;
  925. },
  926. setY: function ( y ) {
  927. this.y = y;
  928. return this;
  929. },
  930. setZ: function ( z ) {
  931. this.z = z;
  932. return this;
  933. },
  934. setComponent: function ( index, value ) {
  935. switch ( index ) {
  936. case 0: this.x = value; break;
  937. case 1: this.y = value; break;
  938. case 2: this.z = value; break;
  939. default: throw new Error( "index is out of range: " + index );
  940. }
  941. },
  942. getComponent: function ( index ) {
  943. switch ( index ) {
  944. case 0: return this.x;
  945. case 1: return this.y;
  946. case 2: return this.z;
  947. default: throw new Error( "index is out of range: " + index );
  948. }
  949. },
  950. copy: function ( v ) {
  951. this.x = v.x;
  952. this.y = v.y;
  953. this.z = v.z;
  954. return this;
  955. },
  956. add: function ( v, w ) {
  957. if ( w !== undefined ) {
  958. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  959. return this.addVectors( v, w );
  960. }
  961. this.x += v.x;
  962. this.y += v.y;
  963. this.z += v.z;
  964. return this;
  965. },
  966. addScalar: function ( s ) {
  967. this.x += s;
  968. this.y += s;
  969. this.z += s;
  970. return this;
  971. },
  972. addVectors: function ( a, b ) {
  973. this.x = a.x + b.x;
  974. this.y = a.y + b.y;
  975. this.z = a.z + b.z;
  976. return this;
  977. },
  978. sub: function ( v, w ) {
  979. if ( w !== undefined ) {
  980. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  981. return this.subVectors( v, w );
  982. }
  983. this.x -= v.x;
  984. this.y -= v.y;
  985. this.z -= v.z;
  986. return this;
  987. },
  988. subVectors: function ( a, b ) {
  989. this.x = a.x - b.x;
  990. this.y = a.y - b.y;
  991. this.z = a.z - b.z;
  992. return this;
  993. },
  994. multiply: function ( v, w ) {
  995. if ( w !== undefined ) {
  996. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  997. return this.multiplyVectors( v, w );
  998. }
  999. this.x *= v.x;
  1000. this.y *= v.y;
  1001. this.z *= v.z;
  1002. return this;
  1003. },
  1004. multiplyScalar: function ( scalar ) {
  1005. this.x *= scalar;
  1006. this.y *= scalar;
  1007. this.z *= scalar;
  1008. return this;
  1009. },
  1010. multiplyVectors: function ( a, b ) {
  1011. this.x = a.x * b.x;
  1012. this.y = a.y * b.y;
  1013. this.z = a.z * b.z;
  1014. return this;
  1015. },
  1016. applyEuler: function () {
  1017. var quaternion;
  1018. return function ( euler ) {
  1019. if ( euler instanceof THREE.Euler === false ) {
  1020. console.error( 'ERROR: Vector3\'s .applyEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  1021. }
  1022. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1023. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1024. return this;
  1025. };
  1026. }(),
  1027. applyAxisAngle: function () {
  1028. var quaternion;
  1029. return function ( axis, angle ) {
  1030. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1031. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1032. return this;
  1033. };
  1034. }(),
  1035. applyMatrix3: function ( m ) {
  1036. var x = this.x;
  1037. var y = this.y;
  1038. var z = this.z;
  1039. var e = m.elements;
  1040. this.x = e[0] * x + e[3] * y + e[6] * z;
  1041. this.y = e[1] * x + e[4] * y + e[7] * z;
  1042. this.z = e[2] * x + e[5] * y + e[8] * z;
  1043. return this;
  1044. },
  1045. applyMatrix4: function ( m ) {
  1046. // input: THREE.Matrix4 affine matrix
  1047. var x = this.x, y = this.y, z = this.z;
  1048. var e = m.elements;
  1049. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  1050. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  1051. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  1052. return this;
  1053. },
  1054. applyProjection: function ( m ) {
  1055. // input: THREE.Matrix4 projection matrix
  1056. var x = this.x, y = this.y, z = this.z;
  1057. var e = m.elements;
  1058. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  1059. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  1060. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  1061. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  1062. return this;
  1063. },
  1064. applyQuaternion: function ( q ) {
  1065. var x = this.x;
  1066. var y = this.y;
  1067. var z = this.z;
  1068. var qx = q.x;
  1069. var qy = q.y;
  1070. var qz = q.z;
  1071. var qw = q.w;
  1072. // calculate quat * vector
  1073. var ix = qw * x + qy * z - qz * y;
  1074. var iy = qw * y + qz * x - qx * z;
  1075. var iz = qw * z + qx * y - qy * x;
  1076. var iw = -qx * x - qy * y - qz * z;
  1077. // calculate result * inverse quat
  1078. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  1079. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  1080. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  1081. return this;
  1082. },
  1083. transformDirection: function ( m ) {
  1084. // input: THREE.Matrix4 affine matrix
  1085. // vector interpreted as a direction
  1086. var x = this.x, y = this.y, z = this.z;
  1087. var e = m.elements;
  1088. this.x = e[0] * x + e[4] * y + e[8] * z;
  1089. this.y = e[1] * x + e[5] * y + e[9] * z;
  1090. this.z = e[2] * x + e[6] * y + e[10] * z;
  1091. this.normalize();
  1092. return this;
  1093. },
  1094. divide: function ( v ) {
  1095. this.x /= v.x;
  1096. this.y /= v.y;
  1097. this.z /= v.z;
  1098. return this;
  1099. },
  1100. divideScalar: function ( scalar ) {
  1101. if ( scalar !== 0 ) {
  1102. var invScalar = 1 / scalar;
  1103. this.x *= invScalar;
  1104. this.y *= invScalar;
  1105. this.z *= invScalar;
  1106. } else {
  1107. this.x = 0;
  1108. this.y = 0;
  1109. this.z = 0;
  1110. }
  1111. return this;
  1112. },
  1113. min: function ( v ) {
  1114. if ( this.x > v.x ) {
  1115. this.x = v.x;
  1116. }
  1117. if ( this.y > v.y ) {
  1118. this.y = v.y;
  1119. }
  1120. if ( this.z > v.z ) {
  1121. this.z = v.z;
  1122. }
  1123. return this;
  1124. },
  1125. max: function ( v ) {
  1126. if ( this.x < v.x ) {
  1127. this.x = v.x;
  1128. }
  1129. if ( this.y < v.y ) {
  1130. this.y = v.y;
  1131. }
  1132. if ( this.z < v.z ) {
  1133. this.z = v.z;
  1134. }
  1135. return this;
  1136. },
  1137. clamp: function ( min, max ) {
  1138. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1139. if ( this.x < min.x ) {
  1140. this.x = min.x;
  1141. } else if ( this.x > max.x ) {
  1142. this.x = max.x;
  1143. }
  1144. if ( this.y < min.y ) {
  1145. this.y = min.y;
  1146. } else if ( this.y > max.y ) {
  1147. this.y = max.y;
  1148. }
  1149. if ( this.z < min.z ) {
  1150. this.z = min.z;
  1151. } else if ( this.z > max.z ) {
  1152. this.z = max.z;
  1153. }
  1154. return this;
  1155. },
  1156. clampScalar: ( function () {
  1157. var min, max;
  1158. return function ( minVal, maxVal ) {
  1159. if ( min === undefined ) {
  1160. min = new THREE.Vector3();
  1161. max = new THREE.Vector3();
  1162. }
  1163. min.set( minVal, minVal, minVal );
  1164. max.set( maxVal, maxVal, maxVal );
  1165. return this.clamp( min, max );
  1166. };
  1167. } )(),
  1168. floor: function () {
  1169. this.x = Math.floor( this.x );
  1170. this.y = Math.floor( this.y );
  1171. this.z = Math.floor( this.z );
  1172. return this;
  1173. },
  1174. ceil: function () {
  1175. this.x = Math.ceil( this.x );
  1176. this.y = Math.ceil( this.y );
  1177. this.z = Math.ceil( this.z );
  1178. return this;
  1179. },
  1180. round: function () {
  1181. this.x = Math.round( this.x );
  1182. this.y = Math.round( this.y );
  1183. this.z = Math.round( this.z );
  1184. return this;
  1185. },
  1186. roundToZero: function () {
  1187. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1188. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1189. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1190. return this;
  1191. },
  1192. negate: function () {
  1193. return this.multiplyScalar( - 1 );
  1194. },
  1195. dot: function ( v ) {
  1196. return this.x * v.x + this.y * v.y + this.z * v.z;
  1197. },
  1198. lengthSq: function () {
  1199. return this.x * this.x + this.y * this.y + this.z * this.z;
  1200. },
  1201. length: function () {
  1202. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1203. },
  1204. lengthManhattan: function () {
  1205. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1206. },
  1207. normalize: function () {
  1208. return this.divideScalar( this.length() );
  1209. },
  1210. setLength: function ( l ) {
  1211. var oldLength = this.length();
  1212. if ( oldLength !== 0 && l !== oldLength ) {
  1213. this.multiplyScalar( l / oldLength );
  1214. }
  1215. return this;
  1216. },
  1217. lerp: function ( v, alpha ) {
  1218. this.x += ( v.x - this.x ) * alpha;
  1219. this.y += ( v.y - this.y ) * alpha;
  1220. this.z += ( v.z - this.z ) * alpha;
  1221. return this;
  1222. },
  1223. cross: function ( v, w ) {
  1224. if ( w !== undefined ) {
  1225. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1226. return this.crossVectors( v, w );
  1227. }
  1228. var x = this.x, y = this.y, z = this.z;
  1229. this.x = y * v.z - z * v.y;
  1230. this.y = z * v.x - x * v.z;
  1231. this.z = x * v.y - y * v.x;
  1232. return this;
  1233. },
  1234. crossVectors: function ( a, b ) {
  1235. var ax = a.x, ay = a.y, az = a.z;
  1236. var bx = b.x, by = b.y, bz = b.z;
  1237. this.x = ay * bz - az * by;
  1238. this.y = az * bx - ax * bz;
  1239. this.z = ax * by - ay * bx;
  1240. return this;
  1241. },
  1242. projectOnVector: function () {
  1243. var v1, dot;
  1244. return function ( vector ) {
  1245. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1246. v1.copy( vector ).normalize();
  1247. dot = this.dot( v1 );
  1248. return this.copy( v1 ).multiplyScalar( dot );
  1249. };
  1250. }(),
  1251. projectOnPlane: function () {
  1252. var v1;
  1253. return function ( planeNormal ) {
  1254. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1255. v1.copy( this ).projectOnVector( planeNormal );
  1256. return this.sub( v1 );
  1257. }
  1258. }(),
  1259. reflect: function () {
  1260. // reflect incident vector off plane orthogonal to normal
  1261. // normal is assumed to have unit length
  1262. var v1;
  1263. return function ( normal ) {
  1264. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1265. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1266. }
  1267. }(),
  1268. angleTo: function ( v ) {
  1269. var theta = this.dot( v ) / ( this.length() * v.length() );
  1270. // clamp, to handle numerical problems
  1271. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1272. },
  1273. distanceTo: function ( v ) {
  1274. return Math.sqrt( this.distanceToSquared( v ) );
  1275. },
  1276. distanceToSquared: function ( v ) {
  1277. var dx = this.x - v.x;
  1278. var dy = this.y - v.y;
  1279. var dz = this.z - v.z;
  1280. return dx * dx + dy * dy + dz * dz;
  1281. },
  1282. setEulerFromRotationMatrix: function ( m, order ) {
  1283. console.error( "REMOVED: Vector3\'s setEulerFromRotationMatrix has been removed in favor of Euler.setFromRotationMatrix(), please update your code.");
  1284. },
  1285. setEulerFromQuaternion: function ( q, order ) {
  1286. console.error( "REMOVED: Vector3\'s setEulerFromQuaternion: has been removed in favor of Euler.setFromQuaternion(), please update your code.");
  1287. },
  1288. getPositionFromMatrix: function ( m ) {
  1289. console.warn( "DEPRECATED: Vector3\'s .getPositionFromMatrix() has been renamed to .setFromMatrixPosition(). Please update your code." );
  1290. return this.setFromMatrixPosition( m );
  1291. },
  1292. getScaleFromMatrix: function ( m ) {
  1293. console.warn( "DEPRECATED: Vector3\'s .getScaleFromMatrix() has been renamed to .setFromMatrixScale(). Please update your code." );
  1294. return this.setFromMatrixScale( m );
  1295. },
  1296. getColumnFromMatrix: function ( index, matrix ) {
  1297. console.warn( "DEPRECATED: Vector3\'s .getColumnFromMatrix() has been renamed to .setFromMatrixColumn(). Please update your code." );
  1298. return this.setFromMatrixColumn( index, matrix );
  1299. },
  1300. setFromMatrixPosition: function ( m ) {
  1301. this.x = m.elements[ 12 ];
  1302. this.y = m.elements[ 13 ];
  1303. this.z = m.elements[ 14 ];
  1304. return this;
  1305. },
  1306. setFromMatrixScale: function ( m ) {
  1307. var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
  1308. var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
  1309. var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
  1310. this.x = sx;
  1311. this.y = sy;
  1312. this.z = sz;
  1313. return this;
  1314. },
  1315. setFromMatrixColumn: function ( index, matrix ) {
  1316. var offset = index * 4;
  1317. var me = matrix.elements;
  1318. this.x = me[ offset ];
  1319. this.y = me[ offset + 1 ];
  1320. this.z = me[ offset + 2 ];
  1321. return this;
  1322. },
  1323. equals: function ( v ) {
  1324. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1325. },
  1326. fromArray: function ( array ) {
  1327. this.x = array[ 0 ];
  1328. this.y = array[ 1 ];
  1329. this.z = array[ 2 ];
  1330. return this;
  1331. },
  1332. toArray: function () {
  1333. return [ this.x, this.y, this.z ];
  1334. },
  1335. clone: function () {
  1336. return new THREE.Vector3( this.x, this.y, this.z );
  1337. }
  1338. };
  1339. /**
  1340. * @author supereggbert / http://www.paulbrunt.co.uk/
  1341. * @author philogb / http://blog.thejit.org/
  1342. * @author mikael emtinger / http://gomo.se/
  1343. * @author egraether / http://egraether.com/
  1344. * @author WestLangley / http://github.com/WestLangley
  1345. */
  1346. THREE.Vector4 = function ( x, y, z, w ) {
  1347. this.x = x || 0;
  1348. this.y = y || 0;
  1349. this.z = z || 0;
  1350. this.w = ( w !== undefined ) ? w : 1;
  1351. };
  1352. THREE.Vector4.prototype = {
  1353. constructor: THREE.Vector4,
  1354. set: function ( x, y, z, w ) {
  1355. this.x = x;
  1356. this.y = y;
  1357. this.z = z;
  1358. this.w = w;
  1359. return this;
  1360. },
  1361. setX: function ( x ) {
  1362. this.x = x;
  1363. return this;
  1364. },
  1365. setY: function ( y ) {
  1366. this.y = y;
  1367. return this;
  1368. },
  1369. setZ: function ( z ) {
  1370. this.z = z;
  1371. return this;
  1372. },
  1373. setW: function ( w ) {
  1374. this.w = w;
  1375. return this;
  1376. },
  1377. setComponent: function ( index, value ) {
  1378. switch ( index ) {
  1379. case 0: this.x = value; break;
  1380. case 1: this.y = value; break;
  1381. case 2: this.z = value; break;
  1382. case 3: this.w = value; break;
  1383. default: throw new Error( "index is out of range: " + index );
  1384. }
  1385. },
  1386. getComponent: function ( index ) {
  1387. switch ( index ) {
  1388. case 0: return this.x;
  1389. case 1: return this.y;
  1390. case 2: return this.z;
  1391. case 3: return this.w;
  1392. default: throw new Error( "index is out of range: " + index );
  1393. }
  1394. },
  1395. copy: function ( v ) {
  1396. this.x = v.x;
  1397. this.y = v.y;
  1398. this.z = v.z;
  1399. this.w = ( v.w !== undefined ) ? v.w : 1;
  1400. return this;
  1401. },
  1402. add: function ( v, w ) {
  1403. if ( w !== undefined ) {
  1404. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1405. return this.addVectors( v, w );
  1406. }
  1407. this.x += v.x;
  1408. this.y += v.y;
  1409. this.z += v.z;
  1410. this.w += v.w;
  1411. return this;
  1412. },
  1413. addScalar: function ( s ) {
  1414. this.x += s;
  1415. this.y += s;
  1416. this.z += s;
  1417. this.w += s;
  1418. return this;
  1419. },
  1420. addVectors: function ( a, b ) {
  1421. this.x = a.x + b.x;
  1422. this.y = a.y + b.y;
  1423. this.z = a.z + b.z;
  1424. this.w = a.w + b.w;
  1425. return this;
  1426. },
  1427. sub: function ( v, w ) {
  1428. if ( w !== undefined ) {
  1429. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1430. return this.subVectors( v, w );
  1431. }
  1432. this.x -= v.x;
  1433. this.y -= v.y;
  1434. this.z -= v.z;
  1435. this.w -= v.w;
  1436. return this;
  1437. },
  1438. subVectors: function ( a, b ) {
  1439. this.x = a.x - b.x;
  1440. this.y = a.y - b.y;
  1441. this.z = a.z - b.z;
  1442. this.w = a.w - b.w;
  1443. return this;
  1444. },
  1445. multiplyScalar: function ( scalar ) {
  1446. this.x *= scalar;
  1447. this.y *= scalar;
  1448. this.z *= scalar;
  1449. this.w *= scalar;
  1450. return this;
  1451. },
  1452. applyMatrix4: function ( m ) {
  1453. var x = this.x;
  1454. var y = this.y;
  1455. var z = this.z;
  1456. var w = this.w;
  1457. var e = m.elements;
  1458. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1459. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1460. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1461. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1462. return this;
  1463. },
  1464. divideScalar: function ( scalar ) {
  1465. if ( scalar !== 0 ) {
  1466. var invScalar = 1 / scalar;
  1467. this.x *= invScalar;
  1468. this.y *= invScalar;
  1469. this.z *= invScalar;
  1470. this.w *= invScalar;
  1471. } else {
  1472. this.x = 0;
  1473. this.y = 0;
  1474. this.z = 0;
  1475. this.w = 1;
  1476. }
  1477. return this;
  1478. },
  1479. setAxisAngleFromQuaternion: function ( q ) {
  1480. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1481. // q is assumed to be normalized
  1482. this.w = 2 * Math.acos( q.w );
  1483. var s = Math.sqrt( 1 - q.w * q.w );
  1484. if ( s < 0.0001 ) {
  1485. this.x = 1;
  1486. this.y = 0;
  1487. this.z = 0;
  1488. } else {
  1489. this.x = q.x / s;
  1490. this.y = q.y / s;
  1491. this.z = q.z / s;
  1492. }
  1493. return this;
  1494. },
  1495. setAxisAngleFromRotationMatrix: function ( m ) {
  1496. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1497. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1498. var angle, x, y, z, // variables for result
  1499. epsilon = 0.01, // margin to allow for rounding errors
  1500. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1501. te = m.elements,
  1502. m11 = te[0], m12 = te[4], m13 = te[8],
  1503. m21 = te[1], m22 = te[5], m23 = te[9],
  1504. m31 = te[2], m32 = te[6], m33 = te[10];
  1505. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1506. && ( Math.abs( m13 - m31 ) < epsilon )
  1507. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1508. // singularity found
  1509. // first check for identity matrix which must have +1 for all terms
  1510. // in leading diagonal and zero in other terms
  1511. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1512. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1513. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1514. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1515. // this singularity is identity matrix so angle = 0
  1516. this.set( 1, 0, 0, 0 );
  1517. return this; // zero angle, arbitrary axis
  1518. }
  1519. // otherwise this singularity is angle = 180
  1520. angle = Math.PI;
  1521. var xx = ( m11 + 1 ) / 2;
  1522. var yy = ( m22 + 1 ) / 2;
  1523. var zz = ( m33 + 1 ) / 2;
  1524. var xy = ( m12 + m21 ) / 4;
  1525. var xz = ( m13 + m31 ) / 4;
  1526. var yz = ( m23 + m32 ) / 4;
  1527. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1528. if ( xx < epsilon ) {
  1529. x = 0;
  1530. y = 0.707106781;
  1531. z = 0.707106781;
  1532. } else {
  1533. x = Math.sqrt( xx );
  1534. y = xy / x;
  1535. z = xz / x;
  1536. }
  1537. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1538. if ( yy < epsilon ) {
  1539. x = 0.707106781;
  1540. y = 0;
  1541. z = 0.707106781;
  1542. } else {
  1543. y = Math.sqrt( yy );
  1544. x = xy / y;
  1545. z = yz / y;
  1546. }
  1547. } else { // m33 is the largest diagonal term so base result on this
  1548. if ( zz < epsilon ) {
  1549. x = 0.707106781;
  1550. y = 0.707106781;
  1551. z = 0;
  1552. } else {
  1553. z = Math.sqrt( zz );
  1554. x = xz / z;
  1555. y = yz / z;
  1556. }
  1557. }
  1558. this.set( x, y, z, angle );
  1559. return this; // return 180 deg rotation
  1560. }
  1561. // as we have reached here there are no singularities so we can handle normally
  1562. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1563. + ( m13 - m31 ) * ( m13 - m31 )
  1564. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1565. if ( Math.abs( s ) < 0.001 ) s = 1;
  1566. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1567. // caught by singularity test above, but I've left it in just in case
  1568. this.x = ( m32 - m23 ) / s;
  1569. this.y = ( m13 - m31 ) / s;
  1570. this.z = ( m21 - m12 ) / s;
  1571. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1572. return this;
  1573. },
  1574. min: function ( v ) {
  1575. if ( this.x > v.x ) {
  1576. this.x = v.x;
  1577. }
  1578. if ( this.y > v.y ) {
  1579. this.y = v.y;
  1580. }
  1581. if ( this.z > v.z ) {
  1582. this.z = v.z;
  1583. }
  1584. if ( this.w > v.w ) {
  1585. this.w = v.w;
  1586. }
  1587. return this;
  1588. },
  1589. max: function ( v ) {
  1590. if ( this.x < v.x ) {
  1591. this.x = v.x;
  1592. }
  1593. if ( this.y < v.y ) {
  1594. this.y = v.y;
  1595. }
  1596. if ( this.z < v.z ) {
  1597. this.z = v.z;
  1598. }
  1599. if ( this.w < v.w ) {
  1600. this.w = v.w;
  1601. }
  1602. return this;
  1603. },
  1604. clamp: function ( min, max ) {
  1605. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1606. if ( this.x < min.x ) {
  1607. this.x = min.x;
  1608. } else if ( this.x > max.x ) {
  1609. this.x = max.x;
  1610. }
  1611. if ( this.y < min.y ) {
  1612. this.y = min.y;
  1613. } else if ( this.y > max.y ) {
  1614. this.y = max.y;
  1615. }
  1616. if ( this.z < min.z ) {
  1617. this.z = min.z;
  1618. } else if ( this.z > max.z ) {
  1619. this.z = max.z;
  1620. }
  1621. if ( this.w < min.w ) {
  1622. this.w = min.w;
  1623. } else if ( this.w > max.w ) {
  1624. this.w = max.w;
  1625. }
  1626. return this;
  1627. },
  1628. clampScalar: ( function () {
  1629. var min, max;
  1630. return function ( minVal, maxVal ) {
  1631. if ( min === undefined ) {
  1632. min = new THREE.Vector4();
  1633. max = new THREE.Vector4();
  1634. }
  1635. min.set( minVal, minVal, minVal, minVal );
  1636. max.set( maxVal, maxVal, maxVal, maxVal );
  1637. return this.clamp( min, max );
  1638. };
  1639. } )(),
  1640. floor: function () {
  1641. this.x = Math.floor( this.x );
  1642. this.y = Math.floor( this.y );
  1643. this.z = Math.floor( this.z );
  1644. this.w = Math.floor( this.w );
  1645. return this;
  1646. },
  1647. ceil: function () {
  1648. this.x = Math.ceil( this.x );
  1649. this.y = Math.ceil( this.y );
  1650. this.z = Math.ceil( this.z );
  1651. this.w = Math.ceil( this.w );
  1652. return this;
  1653. },
  1654. round: function () {
  1655. this.x = Math.round( this.x );
  1656. this.y = Math.round( this.y );
  1657. this.z = Math.round( this.z );
  1658. this.w = Math.round( this.w );
  1659. return this;
  1660. },
  1661. roundToZero: function () {
  1662. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1663. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1664. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1665. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1666. return this;
  1667. },
  1668. negate: function () {
  1669. return this.multiplyScalar( -1 );
  1670. },
  1671. dot: function ( v ) {
  1672. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1673. },
  1674. lengthSq: function () {
  1675. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1676. },
  1677. length: function () {
  1678. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1679. },
  1680. lengthManhattan: function () {
  1681. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1682. },
  1683. normalize: function () {
  1684. return this.divideScalar( this.length() );
  1685. },
  1686. setLength: function ( l ) {
  1687. var oldLength = this.length();
  1688. if ( oldLength !== 0 && l !== oldLength ) {
  1689. this.multiplyScalar( l / oldLength );
  1690. }
  1691. return this;
  1692. },
  1693. lerp: function ( v, alpha ) {
  1694. this.x += ( v.x - this.x ) * alpha;
  1695. this.y += ( v.y - this.y ) * alpha;
  1696. this.z += ( v.z - this.z ) * alpha;
  1697. this.w += ( v.w - this.w ) * alpha;
  1698. return this;
  1699. },
  1700. equals: function ( v ) {
  1701. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1702. },
  1703. fromArray: function ( array ) {
  1704. this.x = array[ 0 ];
  1705. this.y = array[ 1 ];
  1706. this.z = array[ 2 ];
  1707. this.w = array[ 3 ];
  1708. return this;
  1709. },
  1710. toArray: function () {
  1711. return [ this.x, this.y, this.z, this.w ];
  1712. },
  1713. clone: function () {
  1714. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1715. }
  1716. };
  1717. /**
  1718. * @author mrdoob / http://mrdoob.com/
  1719. * @author WestLangley / http://github.com/WestLangley
  1720. * @author bhouston / http://exocortex.com
  1721. */
  1722. THREE.Euler = function ( x, y, z, order ) {
  1723. this._x = x || 0;
  1724. this._y = y || 0;
  1725. this._z = z || 0;
  1726. this._order = order || THREE.Euler.DefaultOrder;
  1727. };
  1728. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1729. THREE.Euler.DefaultOrder = 'XYZ';
  1730. THREE.Euler.prototype = {
  1731. constructor: THREE.Euler,
  1732. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1733. get x () {
  1734. return this._x;
  1735. },
  1736. set x ( value ) {
  1737. this._x = value;
  1738. this.onChangeCallback();
  1739. },
  1740. get y () {
  1741. return this._y;
  1742. },
  1743. set y ( value ) {
  1744. this._y = value;
  1745. this.onChangeCallback();
  1746. },
  1747. get z () {
  1748. return this._z;
  1749. },
  1750. set z ( value ) {
  1751. this._z = value;
  1752. this.onChangeCallback();
  1753. },
  1754. get order () {
  1755. return this._order;
  1756. },
  1757. set order ( value ) {
  1758. this._order = value;
  1759. this.onChangeCallback();
  1760. },
  1761. set: function ( x, y, z, order ) {
  1762. this._x = x;
  1763. this._y = y;
  1764. this._z = z;
  1765. this._order = order || this._order;
  1766. this.onChangeCallback();
  1767. return this;
  1768. },
  1769. copy: function ( euler ) {
  1770. this._x = euler._x;
  1771. this._y = euler._y;
  1772. this._z = euler._z;
  1773. this._order = euler._order;
  1774. this.onChangeCallback();
  1775. return this;
  1776. },
  1777. setFromRotationMatrix: function ( m, order ) {
  1778. var clamp = THREE.Math.clamp;
  1779. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1780. var te = m.elements;
  1781. var m11 = te[0], m12 = te[4], m13 = te[8];
  1782. var m21 = te[1], m22 = te[5], m23 = te[9];
  1783. var m31 = te[2], m32 = te[6], m33 = te[10];
  1784. order = order || this._order;
  1785. if ( order === 'XYZ' ) {
  1786. this._y = Math.asin( clamp( m13, -1, 1 ) );
  1787. if ( Math.abs( m13 ) < 0.99999 ) {
  1788. this._x = Math.atan2( - m23, m33 );
  1789. this._z = Math.atan2( - m12, m11 );
  1790. } else {
  1791. this._x = Math.atan2( m32, m22 );
  1792. this._z = 0;
  1793. }
  1794. } else if ( order === 'YXZ' ) {
  1795. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  1796. if ( Math.abs( m23 ) < 0.99999 ) {
  1797. this._y = Math.atan2( m13, m33 );
  1798. this._z = Math.atan2( m21, m22 );
  1799. } else {
  1800. this._y = Math.atan2( - m31, m11 );
  1801. this._z = 0;
  1802. }
  1803. } else if ( order === 'ZXY' ) {
  1804. this._x = Math.asin( clamp( m32, -1, 1 ) );
  1805. if ( Math.abs( m32 ) < 0.99999 ) {
  1806. this._y = Math.atan2( - m31, m33 );
  1807. this._z = Math.atan2( - m12, m22 );
  1808. } else {
  1809. this._y = 0;
  1810. this._z = Math.atan2( m21, m11 );
  1811. }
  1812. } else if ( order === 'ZYX' ) {
  1813. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  1814. if ( Math.abs( m31 ) < 0.99999 ) {
  1815. this._x = Math.atan2( m32, m33 );
  1816. this._z = Math.atan2( m21, m11 );
  1817. } else {
  1818. this._x = 0;
  1819. this._z = Math.atan2( - m12, m22 );
  1820. }
  1821. } else if ( order === 'YZX' ) {
  1822. this._z = Math.asin( clamp( m21, -1, 1 ) );
  1823. if ( Math.abs( m21 ) < 0.99999 ) {
  1824. this._x = Math.atan2( - m23, m22 );
  1825. this._y = Math.atan2( - m31, m11 );
  1826. } else {
  1827. this._x = 0;
  1828. this._y = Math.atan2( m13, m33 );
  1829. }
  1830. } else if ( order === 'XZY' ) {
  1831. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  1832. if ( Math.abs( m12 ) < 0.99999 ) {
  1833. this._x = Math.atan2( m32, m22 );
  1834. this._y = Math.atan2( m13, m11 );
  1835. } else {
  1836. this._x = Math.atan2( - m23, m33 );
  1837. this._y = 0;
  1838. }
  1839. } else {
  1840. console.warn( 'WARNING: Euler.setFromRotationMatrix() given unsupported order: ' + order )
  1841. }
  1842. this._order = order;
  1843. this.onChangeCallback();
  1844. return this;
  1845. },
  1846. setFromQuaternion: function ( q, order, update ) {
  1847. var clamp = THREE.Math.clamp;
  1848. // q is assumed to be normalized
  1849. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1850. var sqx = q.x * q.x;
  1851. var sqy = q.y * q.y;
  1852. var sqz = q.z * q.z;
  1853. var sqw = q.w * q.w;
  1854. order = order || this._order;
  1855. if ( order === 'XYZ' ) {
  1856. this._x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1857. this._y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ), -1, 1 ) );
  1858. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1859. } else if ( order === 'YXZ' ) {
  1860. this._x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ), -1, 1 ) );
  1861. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1862. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1863. } else if ( order === 'ZXY' ) {
  1864. this._x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ), -1, 1 ) );
  1865. this._y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1866. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1867. } else if ( order === 'ZYX' ) {
  1868. this._x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1869. this._y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ), -1, 1 ) );
  1870. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1871. } else if ( order === 'YZX' ) {
  1872. this._x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1873. this._y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1874. this._z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ), -1, 1 ) );
  1875. } else if ( order === 'XZY' ) {
  1876. this._x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1877. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1878. this._z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ), -1, 1 ) );
  1879. } else {
  1880. console.warn( 'WARNING: Euler.setFromQuaternion() given unsupported order: ' + order )
  1881. }
  1882. this._order = order;
  1883. if ( update !== false ) this.onChangeCallback();
  1884. return this;
  1885. },
  1886. reorder: function () {
  1887. // WARNING: this discards revolution information -bhouston
  1888. var q = new THREE.Quaternion();
  1889. return function ( newOrder ) {
  1890. q.setFromEuler( this );
  1891. this.setFromQuaternion( q, newOrder );
  1892. };
  1893. }(),
  1894. equals: function ( euler ) {
  1895. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  1896. },
  1897. fromArray: function ( array ) {
  1898. this._x = array[ 0 ];
  1899. this._y = array[ 1 ];
  1900. this._z = array[ 2 ];
  1901. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  1902. this.onChangeCallback();
  1903. return this;
  1904. },
  1905. toArray: function () {
  1906. return [ this._x, this._y, this._z, this._order ];
  1907. },
  1908. onChange: function ( callback ) {
  1909. this.onChangeCallback = callback;
  1910. return this;
  1911. },
  1912. onChangeCallback: function () {},
  1913. clone: function () {
  1914. return new THREE.Euler( this._x, this._y, this._z, this._order );
  1915. }
  1916. };
  1917. /**
  1918. * @author bhouston / http://exocortex.com
  1919. */
  1920. THREE.Line3 = function ( start, end ) {
  1921. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1922. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1923. };
  1924. THREE.Line3.prototype = {
  1925. constructor: THREE.Line3,
  1926. set: function ( start, end ) {
  1927. this.start.copy( start );
  1928. this.end.copy( end );
  1929. return this;
  1930. },
  1931. copy: function ( line ) {
  1932. this.start.copy( line.start );
  1933. this.end.copy( line.end );
  1934. return this;
  1935. },
  1936. center: function ( optionalTarget ) {
  1937. var result = optionalTarget || new THREE.Vector3();
  1938. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1939. },
  1940. delta: function ( optionalTarget ) {
  1941. var result = optionalTarget || new THREE.Vector3();
  1942. return result.subVectors( this.end, this.start );
  1943. },
  1944. distanceSq: function () {
  1945. return this.start.distanceToSquared( this.end );
  1946. },
  1947. distance: function () {
  1948. return this.start.distanceTo( this.end );
  1949. },
  1950. at: function ( t, optionalTarget ) {
  1951. var result = optionalTarget || new THREE.Vector3();
  1952. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1953. },
  1954. closestPointToPointParameter: function() {
  1955. var startP = new THREE.Vector3();
  1956. var startEnd = new THREE.Vector3();
  1957. return function ( point, clampToLine ) {
  1958. startP.subVectors( point, this.start );
  1959. startEnd.subVectors( this.end, this.start );
  1960. var startEnd2 = startEnd.dot( startEnd );
  1961. var startEnd_startP = startEnd.dot( startP );
  1962. var t = startEnd_startP / startEnd2;
  1963. if ( clampToLine ) {
  1964. t = THREE.Math.clamp( t, 0, 1 );
  1965. }
  1966. return t;
  1967. };
  1968. }(),
  1969. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1970. var t = this.closestPointToPointParameter( point, clampToLine );
  1971. var result = optionalTarget || new THREE.Vector3();
  1972. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1973. },
  1974. applyMatrix4: function ( matrix ) {
  1975. this.start.applyMatrix4( matrix );
  1976. this.end.applyMatrix4( matrix );
  1977. return this;
  1978. },
  1979. equals: function ( line ) {
  1980. return line.start.equals( this.start ) && line.end.equals( this.end );
  1981. },
  1982. clone: function () {
  1983. return new THREE.Line3().copy( this );
  1984. }
  1985. };
  1986. /**
  1987. * @author bhouston / http://exocortex.com
  1988. */
  1989. THREE.Box2 = function ( min, max ) {
  1990. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1991. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1992. };
  1993. THREE.Box2.prototype = {
  1994. constructor: THREE.Box2,
  1995. set: function ( min, max ) {
  1996. this.min.copy( min );
  1997. this.max.copy( max );
  1998. return this;
  1999. },
  2000. setFromPoints: function ( points ) {
  2001. if ( points.length > 0 ) {
  2002. var point = points[ 0 ];
  2003. this.min.copy( point );
  2004. this.max.copy( point );
  2005. for ( var i = 1, il = points.length; i < il; i ++ ) {
  2006. point = points[ i ];
  2007. if ( point.x < this.min.x ) {
  2008. this.min.x = point.x;
  2009. } else if ( point.x > this.max.x ) {
  2010. this.max.x = point.x;
  2011. }
  2012. if ( point.y < this.min.y ) {
  2013. this.min.y = point.y;
  2014. } else if ( point.y > this.max.y ) {
  2015. this.max.y = point.y;
  2016. }
  2017. }
  2018. } else {
  2019. this.makeEmpty();
  2020. }
  2021. return this;
  2022. },
  2023. setFromCenterAndSize: function () {
  2024. var v1 = new THREE.Vector2();
  2025. return function ( center, size ) {
  2026. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2027. this.min.copy( center ).sub( halfSize );
  2028. this.max.copy( center ).add( halfSize );
  2029. return this;
  2030. };
  2031. }(),
  2032. copy: function ( box ) {
  2033. this.min.copy( box.min );
  2034. this.max.copy( box.max );
  2035. return this;
  2036. },
  2037. makeEmpty: function () {
  2038. this.min.x = this.min.y = Infinity;
  2039. this.max.x = this.max.y = -Infinity;
  2040. return this;
  2041. },
  2042. empty: function () {
  2043. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2044. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  2045. },
  2046. center: function ( optionalTarget ) {
  2047. var result = optionalTarget || new THREE.Vector2();
  2048. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2049. },
  2050. size: function ( optionalTarget ) {
  2051. var result = optionalTarget || new THREE.Vector2();
  2052. return result.subVectors( this.max, this.min );
  2053. },
  2054. expandByPoint: function ( point ) {
  2055. this.min.min( point );
  2056. this.max.max( point );
  2057. return this;
  2058. },
  2059. expandByVector: function ( vector ) {
  2060. this.min.sub( vector );
  2061. this.max.add( vector );
  2062. return this;
  2063. },
  2064. expandByScalar: function ( scalar ) {
  2065. this.min.addScalar( -scalar );
  2066. this.max.addScalar( scalar );
  2067. return this;
  2068. },
  2069. containsPoint: function ( point ) {
  2070. if ( point.x < this.min.x || point.x > this.max.x ||
  2071. point.y < this.min.y || point.y > this.max.y ) {
  2072. return false;
  2073. }
  2074. return true;
  2075. },
  2076. containsBox: function ( box ) {
  2077. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2078. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  2079. return true;
  2080. }
  2081. return false;
  2082. },
  2083. getParameter: function ( point, optionalTarget ) {
  2084. // This can potentially have a divide by zero if the box
  2085. // has a size dimension of 0.
  2086. var result = optionalTarget || new THREE.Vector2();
  2087. return result.set(
  2088. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2089. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  2090. );
  2091. },
  2092. isIntersectionBox: function ( box ) {
  2093. // using 6 splitting planes to rule out intersections.
  2094. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2095. box.max.y < this.min.y || box.min.y > this.max.y ) {
  2096. return false;
  2097. }
  2098. return true;
  2099. },
  2100. clampPoint: function ( point, optionalTarget ) {
  2101. var result = optionalTarget || new THREE.Vector2();
  2102. return result.copy( point ).clamp( this.min, this.max );
  2103. },
  2104. distanceToPoint: function () {
  2105. var v1 = new THREE.Vector2();
  2106. return function ( point ) {
  2107. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2108. return clampedPoint.sub( point ).length();
  2109. };
  2110. }(),
  2111. intersect: function ( box ) {
  2112. this.min.max( box.min );
  2113. this.max.min( box.max );
  2114. return this;
  2115. },
  2116. union: function ( box ) {
  2117. this.min.min( box.min );
  2118. this.max.max( box.max );
  2119. return this;
  2120. },
  2121. translate: function ( offset ) {
  2122. this.min.add( offset );
  2123. this.max.add( offset );
  2124. return this;
  2125. },
  2126. equals: function ( box ) {
  2127. return box.min.equals( this.min ) && box.max.equals( this.max );
  2128. },
  2129. clone: function () {
  2130. return new THREE.Box2().copy( this );
  2131. }
  2132. };
  2133. /**
  2134. * @author bhouston / http://exocortex.com
  2135. * @author WestLangley / http://github.com/WestLangley
  2136. */
  2137. THREE.Box3 = function ( min, max ) {
  2138. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2139. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  2140. };
  2141. THREE.Box3.prototype = {
  2142. constructor: THREE.Box3,
  2143. set: function ( min, max ) {
  2144. this.min.copy( min );
  2145. this.max.copy( max );
  2146. return this;
  2147. },
  2148. addPoint: function ( point ) {
  2149. if ( point.x < this.min.x ) {
  2150. this.min.x = point.x;
  2151. } else if ( point.x > this.max.x ) {
  2152. this.max.x = point.x;
  2153. }
  2154. if ( point.y < this.min.y ) {
  2155. this.min.y = point.y;
  2156. } else if ( point.y > this.max.y ) {
  2157. this.max.y = point.y;
  2158. }
  2159. if ( point.z < this.min.z ) {
  2160. this.min.z = point.z;
  2161. } else if ( point.z > this.max.z ) {
  2162. this.max.z = point.z;
  2163. }
  2164. },
  2165. setFromPoints: function ( points ) {
  2166. if ( points.length > 0 ) {
  2167. var point = points[ 0 ];
  2168. this.min.copy( point );
  2169. this.max.copy( point );
  2170. for ( var i = 1, il = points.length; i < il; i ++ ) {
  2171. this.addPoint( points[ i ] )
  2172. }
  2173. } else {
  2174. this.makeEmpty();
  2175. }
  2176. return this;
  2177. },
  2178. setFromCenterAndSize: function() {
  2179. var v1 = new THREE.Vector3();
  2180. return function ( center, size ) {
  2181. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2182. this.min.copy( center ).sub( halfSize );
  2183. this.max.copy( center ).add( halfSize );
  2184. return this;
  2185. };
  2186. }(),
  2187. setFromObject: function() {
  2188. // Computes the world-axis-aligned bounding box of an object (including its children),
  2189. // accounting for both the object's, and childrens', world transforms
  2190. var v1 = new THREE.Vector3();
  2191. return function( object ) {
  2192. var scope = this;
  2193. object.updateMatrixWorld( true );
  2194. this.makeEmpty();
  2195. object.traverse( function ( node ) {
  2196. if ( node.geometry !== undefined && node.geometry.vertices !== undefined ) {
  2197. var vertices = node.geometry.vertices;
  2198. for ( var i = 0, il = vertices.length; i < il; i++ ) {
  2199. v1.copy( vertices[ i ] );
  2200. v1.applyMatrix4( node.matrixWorld );
  2201. scope.expandByPoint( v1 );
  2202. }
  2203. }
  2204. } );
  2205. return this;
  2206. };
  2207. }(),
  2208. copy: function ( box ) {
  2209. this.min.copy( box.min );
  2210. this.max.copy( box.max );
  2211. return this;
  2212. },
  2213. makeEmpty: function () {
  2214. this.min.x = this.min.y = this.min.z = Infinity;
  2215. this.max.x = this.max.y = this.max.z = -Infinity;
  2216. return this;
  2217. },
  2218. empty: function () {
  2219. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2220. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2221. },
  2222. center: function ( optionalTarget ) {
  2223. var result = optionalTarget || new THREE.Vector3();
  2224. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2225. },
  2226. size: function ( optionalTarget ) {
  2227. var result = optionalTarget || new THREE.Vector3();
  2228. return result.subVectors( this.max, this.min );
  2229. },
  2230. expandByPoint: function ( point ) {
  2231. this.min.min( point );
  2232. this.max.max( point );
  2233. return this;
  2234. },
  2235. expandByVector: function ( vector ) {
  2236. this.min.sub( vector );
  2237. this.max.add( vector );
  2238. return this;
  2239. },
  2240. expandByScalar: function ( scalar ) {
  2241. this.min.addScalar( -scalar );
  2242. this.max.addScalar( scalar );
  2243. return this;
  2244. },
  2245. containsPoint: function ( point ) {
  2246. if ( point.x < this.min.x || point.x > this.max.x ||
  2247. point.y < this.min.y || point.y > this.max.y ||
  2248. point.z < this.min.z || point.z > this.max.z ) {
  2249. return false;
  2250. }
  2251. return true;
  2252. },
  2253. containsBox: function ( box ) {
  2254. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2255. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2256. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2257. return true;
  2258. }
  2259. return false;
  2260. },
  2261. getParameter: function ( point, optionalTarget ) {
  2262. // This can potentially have a divide by zero if the box
  2263. // has a size dimension of 0.
  2264. var result = optionalTarget || new THREE.Vector3();
  2265. return result.set(
  2266. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2267. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2268. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2269. );
  2270. },
  2271. isIntersectionBox: function ( box ) {
  2272. // using 6 splitting planes to rule out intersections.
  2273. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2274. box.max.y < this.min.y || box.min.y > this.max.y ||
  2275. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2276. return false;
  2277. }
  2278. return true;
  2279. },
  2280. clampPoint: function ( point, optionalTarget ) {
  2281. var result = optionalTarget || new THREE.Vector3();
  2282. return result.copy( point ).clamp( this.min, this.max );
  2283. },
  2284. distanceToPoint: function() {
  2285. var v1 = new THREE.Vector3();
  2286. return function ( point ) {
  2287. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2288. return clampedPoint.sub( point ).length();
  2289. };
  2290. }(),
  2291. getBoundingSphere: function() {
  2292. var v1 = new THREE.Vector3();
  2293. return function ( optionalTarget ) {
  2294. var result = optionalTarget || new THREE.Sphere();
  2295. result.center = this.center();
  2296. result.radius = this.size( v1 ).length() * 0.5;
  2297. return result;
  2298. };
  2299. }(),
  2300. intersect: function ( box ) {
  2301. this.min.max( box.min );
  2302. this.max.min( box.max );
  2303. return this;
  2304. },
  2305. union: function ( box ) {
  2306. this.min.min( box.min );
  2307. this.max.max( box.max );
  2308. return this;
  2309. },
  2310. applyMatrix4: function() {
  2311. var points = [
  2312. new THREE.Vector3(),
  2313. new THREE.Vector3(),
  2314. new THREE.Vector3(),
  2315. new THREE.Vector3(),
  2316. new THREE.Vector3(),
  2317. new THREE.Vector3(),
  2318. new THREE.Vector3(),
  2319. new THREE.Vector3()
  2320. ];
  2321. return function ( matrix ) {
  2322. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2323. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2324. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2325. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2326. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2327. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2328. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2329. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2330. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2331. this.makeEmpty();
  2332. this.setFromPoints( points );
  2333. return this;
  2334. };
  2335. }(),
  2336. translate: function ( offset ) {
  2337. this.min.add( offset );
  2338. this.max.add( offset );
  2339. return this;
  2340. },
  2341. equals: function ( box ) {
  2342. return box.min.equals( this.min ) && box.max.equals( this.max );
  2343. },
  2344. clone: function () {
  2345. return new THREE.Box3().copy( this );
  2346. }
  2347. };
  2348. /**
  2349. * @author alteredq / http://alteredqualia.com/
  2350. * @author WestLangley / http://github.com/WestLangley
  2351. * @author bhouston / http://exocortex.com
  2352. */
  2353. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2354. this.elements = new Float32Array(9);
  2355. this.set(
  2356. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  2357. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  2358. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  2359. );
  2360. };
  2361. THREE.Matrix3.prototype = {
  2362. constructor: THREE.Matrix3,
  2363. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2364. var te = this.elements;
  2365. te[0] = n11; te[3] = n12; te[6] = n13;
  2366. te[1] = n21; te[4] = n22; te[7] = n23;
  2367. te[2] = n31; te[5] = n32; te[8] = n33;
  2368. return this;
  2369. },
  2370. identity: function () {
  2371. this.set(
  2372. 1, 0, 0,
  2373. 0, 1, 0,
  2374. 0, 0, 1
  2375. );
  2376. return this;
  2377. },
  2378. copy: function ( m ) {
  2379. var me = m.elements;
  2380. this.set(
  2381. me[0], me[3], me[6],
  2382. me[1], me[4], me[7],
  2383. me[2], me[5], me[8]
  2384. );
  2385. return this;
  2386. },
  2387. multiplyVector3: function ( vector ) {
  2388. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2389. return vector.applyMatrix3( this );
  2390. },
  2391. multiplyVector3Array: function ( a ) {
  2392. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2393. return this.applyToVector3Array( a );
  2394. },
  2395. applyToVector3Array: function() {
  2396. var v1 = new THREE.Vector3();
  2397. return function ( a ) {
  2398. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2399. v1.x = a[ i ];
  2400. v1.y = a[ i + 1 ];
  2401. v1.z = a[ i + 2 ];
  2402. v1.applyMatrix3( this );
  2403. a[ i ] = v1.x;
  2404. a[ i + 1 ] = v1.y;
  2405. a[ i + 2 ] = v1.z;
  2406. }
  2407. return a;
  2408. };
  2409. }(),
  2410. multiplyScalar: function ( s ) {
  2411. var te = this.elements;
  2412. te[0] *= s; te[3] *= s; te[6] *= s;
  2413. te[1] *= s; te[4] *= s; te[7] *= s;
  2414. te[2] *= s; te[5] *= s; te[8] *= s;
  2415. return this;
  2416. },
  2417. determinant: function () {
  2418. var te = this.elements;
  2419. var a = te[0], b = te[1], c = te[2],
  2420. d = te[3], e = te[4], f = te[5],
  2421. g = te[6], h = te[7], i = te[8];
  2422. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2423. },
  2424. getInverse: function ( matrix, throwOnInvertible ) {
  2425. // input: THREE.Matrix4
  2426. // ( based on http://code.google.com/p/webgl-mjs/ )
  2427. var me = matrix.elements;
  2428. var te = this.elements;
  2429. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2430. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2431. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2432. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2433. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2434. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2435. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2436. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2437. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2438. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2439. // no inverse
  2440. if ( det === 0 ) {
  2441. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2442. if ( throwOnInvertible || false ) {
  2443. throw new Error( msg );
  2444. } else {
  2445. console.warn( msg );
  2446. }
  2447. this.identity();
  2448. return this;
  2449. }
  2450. this.multiplyScalar( 1.0 / det );
  2451. return this;
  2452. },
  2453. transpose: function () {
  2454. var tmp, m = this.elements;
  2455. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2456. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2457. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2458. return this;
  2459. },
  2460. getNormalMatrix: function ( m ) {
  2461. // input: THREE.Matrix4
  2462. this.getInverse( m ).transpose();
  2463. return this;
  2464. },
  2465. transposeIntoArray: function ( r ) {
  2466. var m = this.elements;
  2467. r[ 0 ] = m[ 0 ];
  2468. r[ 1 ] = m[ 3 ];
  2469. r[ 2 ] = m[ 6 ];
  2470. r[ 3 ] = m[ 1 ];
  2471. r[ 4 ] = m[ 4 ];
  2472. r[ 5 ] = m[ 7 ];
  2473. r[ 6 ] = m[ 2 ];
  2474. r[ 7 ] = m[ 5 ];
  2475. r[ 8 ] = m[ 8 ];
  2476. return this;
  2477. },
  2478. fromArray: function ( array ) {
  2479. this.elements.set( array );
  2480. return this;
  2481. },
  2482. toArray: function () {
  2483. var te = this.elements;
  2484. return [
  2485. te[ 0 ], te[ 1 ], te[ 2 ],
  2486. te[ 3 ], te[ 4 ], te[ 5 ],
  2487. te[ 6 ], te[ 7 ], te[ 8 ]
  2488. ];
  2489. },
  2490. clone: function () {
  2491. var te = this.elements;
  2492. return new THREE.Matrix3(
  2493. te[0], te[3], te[6],
  2494. te[1], te[4], te[7],
  2495. te[2], te[5], te[8]
  2496. );
  2497. }
  2498. };
  2499. /**
  2500. * @author mrdoob / http://mrdoob.com/
  2501. * @author supereggbert / http://www.paulbrunt.co.uk/
  2502. * @author philogb / http://blog.thejit.org/
  2503. * @author jordi_ros / http://plattsoft.com
  2504. * @author D1plo1d / http://github.com/D1plo1d
  2505. * @author alteredq / http://alteredqualia.com/
  2506. * @author mikael emtinger / http://gomo.se/
  2507. * @author timknip / http://www.floorplanner.com/
  2508. * @author bhouston / http://exocortex.com
  2509. * @author WestLangley / http://github.com/WestLangley
  2510. */
  2511. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2512. this.elements = new Float32Array( 16 );
  2513. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2514. // we should not support semi specification of Matrix4, it is just weird.
  2515. var te = this.elements;
  2516. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2517. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2518. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2519. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2520. };
  2521. THREE.Matrix4.prototype = {
  2522. constructor: THREE.Matrix4,
  2523. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2524. var te = this.elements;
  2525. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2526. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2527. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2528. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2529. return this;
  2530. },
  2531. identity: function () {
  2532. this.set(
  2533. 1, 0, 0, 0,
  2534. 0, 1, 0, 0,
  2535. 0, 0, 1, 0,
  2536. 0, 0, 0, 1
  2537. );
  2538. return this;
  2539. },
  2540. copy: function ( m ) {
  2541. this.elements.set( m.elements );
  2542. return this;
  2543. },
  2544. extractPosition: function ( m ) {
  2545. console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' );
  2546. return this.copyPosition( m );
  2547. },
  2548. copyPosition: function ( m ) {
  2549. var te = this.elements;
  2550. var me = m.elements;
  2551. te[12] = me[12];
  2552. te[13] = me[13];
  2553. te[14] = me[14];
  2554. return this;
  2555. },
  2556. extractRotation: function () {
  2557. var v1 = new THREE.Vector3();
  2558. return function ( m ) {
  2559. var te = this.elements;
  2560. var me = m.elements;
  2561. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2562. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2563. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2564. te[0] = me[0] * scaleX;
  2565. te[1] = me[1] * scaleX;
  2566. te[2] = me[2] * scaleX;
  2567. te[4] = me[4] * scaleY;
  2568. te[5] = me[5] * scaleY;
  2569. te[6] = me[6] * scaleY;
  2570. te[8] = me[8] * scaleZ;
  2571. te[9] = me[9] * scaleZ;
  2572. te[10] = me[10] * scaleZ;
  2573. return this;
  2574. };
  2575. }(),
  2576. makeRotationFromEuler: function ( euler ) {
  2577. if ( euler instanceof THREE.Euler === false ) {
  2578. console.error( 'ERROR: Matrix\'s .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  2579. }
  2580. var te = this.elements;
  2581. var x = euler.x, y = euler.y, z = euler.z;
  2582. var a = Math.cos( x ), b = Math.sin( x );
  2583. var c = Math.cos( y ), d = Math.sin( y );
  2584. var e = Math.cos( z ), f = Math.sin( z );
  2585. if ( euler.order === 'XYZ' ) {
  2586. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2587. te[0] = c * e;
  2588. te[4] = - c * f;
  2589. te[8] = d;
  2590. te[1] = af + be * d;
  2591. te[5] = ae - bf * d;
  2592. te[9] = - b * c;
  2593. te[2] = bf - ae * d;
  2594. te[6] = be + af * d;
  2595. te[10] = a * c;
  2596. } else if ( euler.order === 'YXZ' ) {
  2597. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2598. te[0] = ce + df * b;
  2599. te[4] = de * b - cf;
  2600. te[8] = a * d;
  2601. te[1] = a * f;
  2602. te[5] = a * e;
  2603. te[9] = - b;
  2604. te[2] = cf * b - de;
  2605. te[6] = df + ce * b;
  2606. te[10] = a * c;
  2607. } else if ( euler.order === 'ZXY' ) {
  2608. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2609. te[0] = ce - df * b;
  2610. te[4] = - a * f;
  2611. te[8] = de + cf * b;
  2612. te[1] = cf + de * b;
  2613. te[5] = a * e;
  2614. te[9] = df - ce * b;
  2615. te[2] = - a * d;
  2616. te[6] = b;
  2617. te[10] = a * c;
  2618. } else if ( euler.order === 'ZYX' ) {
  2619. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2620. te[0] = c * e;
  2621. te[4] = be * d - af;
  2622. te[8] = ae * d + bf;
  2623. te[1] = c * f;
  2624. te[5] = bf * d + ae;
  2625. te[9] = af * d - be;
  2626. te[2] = - d;
  2627. te[6] = b * c;
  2628. te[10] = a * c;
  2629. } else if ( euler.order === 'YZX' ) {
  2630. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2631. te[0] = c * e;
  2632. te[4] = bd - ac * f;
  2633. te[8] = bc * f + ad;
  2634. te[1] = f;
  2635. te[5] = a * e;
  2636. te[9] = - b * e;
  2637. te[2] = - d * e;
  2638. te[6] = ad * f + bc;
  2639. te[10] = ac - bd * f;
  2640. } else if ( euler.order === 'XZY' ) {
  2641. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2642. te[0] = c * e;
  2643. te[4] = - f;
  2644. te[8] = d * e;
  2645. te[1] = ac * f + bd;
  2646. te[5] = a * e;
  2647. te[9] = ad * f - bc;
  2648. te[2] = bc * f - ad;
  2649. te[6] = b * e;
  2650. te[10] = bd * f + ac;
  2651. }
  2652. // last column
  2653. te[3] = 0;
  2654. te[7] = 0;
  2655. te[11] = 0;
  2656. // bottom row
  2657. te[12] = 0;
  2658. te[13] = 0;
  2659. te[14] = 0;
  2660. te[15] = 1;
  2661. return this;
  2662. },
  2663. setRotationFromQuaternion: function ( q ) {
  2664. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' );
  2665. return this.makeRotationFromQuaternion( q );
  2666. },
  2667. makeRotationFromQuaternion: function ( q ) {
  2668. var te = this.elements;
  2669. var x = q.x, y = q.y, z = q.z, w = q.w;
  2670. var x2 = x + x, y2 = y + y, z2 = z + z;
  2671. var xx = x * x2, xy = x * y2, xz = x * z2;
  2672. var yy = y * y2, yz = y * z2, zz = z * z2;
  2673. var wx = w * x2, wy = w * y2, wz = w * z2;
  2674. te[0] = 1 - ( yy + zz );
  2675. te[4] = xy - wz;
  2676. te[8] = xz + wy;
  2677. te[1] = xy + wz;
  2678. te[5] = 1 - ( xx + zz );
  2679. te[9] = yz - wx;
  2680. te[2] = xz - wy;
  2681. te[6] = yz + wx;
  2682. te[10] = 1 - ( xx + yy );
  2683. // last column
  2684. te[3] = 0;
  2685. te[7] = 0;
  2686. te[11] = 0;
  2687. // bottom row
  2688. te[12] = 0;
  2689. te[13] = 0;
  2690. te[14] = 0;
  2691. te[15] = 1;
  2692. return this;
  2693. },
  2694. lookAt: function() {
  2695. var x = new THREE.Vector3();
  2696. var y = new THREE.Vector3();
  2697. var z = new THREE.Vector3();
  2698. return function ( eye, target, up ) {
  2699. var te = this.elements;
  2700. z.subVectors( eye, target ).normalize();
  2701. if ( z.length() === 0 ) {
  2702. z.z = 1;
  2703. }
  2704. x.crossVectors( up, z ).normalize();
  2705. if ( x.length() === 0 ) {
  2706. z.x += 0.0001;
  2707. x.crossVectors( up, z ).normalize();
  2708. }
  2709. y.crossVectors( z, x );
  2710. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2711. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2712. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2713. return this;
  2714. };
  2715. }(),
  2716. multiply: function ( m, n ) {
  2717. if ( n !== undefined ) {
  2718. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2719. return this.multiplyMatrices( m, n );
  2720. }
  2721. return this.multiplyMatrices( this, m );
  2722. },
  2723. multiplyMatrices: function ( a, b ) {
  2724. var ae = a.elements;
  2725. var be = b.elements;
  2726. var te = this.elements;
  2727. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2728. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2729. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2730. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2731. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2732. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2733. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2734. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2735. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2736. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2737. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2738. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2739. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2740. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2741. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2742. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2743. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2744. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2745. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2746. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2747. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2748. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2749. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2750. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2751. return this;
  2752. },
  2753. multiplyToArray: function ( a, b, r ) {
  2754. var te = this.elements;
  2755. this.multiplyMatrices( a, b );
  2756. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2757. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2758. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2759. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2760. return this;
  2761. },
  2762. multiplyScalar: function ( s ) {
  2763. var te = this.elements;
  2764. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2765. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2766. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2767. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2768. return this;
  2769. },
  2770. multiplyVector3: function ( vector ) {
  2771. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2772. return vector.applyProjection( this );
  2773. },
  2774. multiplyVector4: function ( vector ) {
  2775. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2776. return vector.applyMatrix4( this );
  2777. },
  2778. multiplyVector3Array: function ( a ) {
  2779. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2780. return this.applyToVector3Array( a );
  2781. },
  2782. applyToVector3Array: function() {
  2783. var v1 = new THREE.Vector3();
  2784. return function ( a ) {
  2785. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2786. v1.x = a[ i ];
  2787. v1.y = a[ i + 1 ];
  2788. v1.z = a[ i + 2 ];
  2789. v1.applyMatrix4( this );
  2790. a[ i ] = v1.x;
  2791. a[ i + 1 ] = v1.y;
  2792. a[ i + 2 ] = v1.z;
  2793. }
  2794. return a;
  2795. };
  2796. }(),
  2797. rotateAxis: function ( v ) {
  2798. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2799. v.transformDirection( this );
  2800. },
  2801. crossVector: function ( vector ) {
  2802. console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2803. return vector.applyMatrix4( this );
  2804. },
  2805. determinant: function () {
  2806. var te = this.elements;
  2807. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2808. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2809. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2810. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2811. //TODO: make this more efficient
  2812. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2813. return (
  2814. n41 * (
  2815. +n14 * n23 * n32
  2816. -n13 * n24 * n32
  2817. -n14 * n22 * n33
  2818. +n12 * n24 * n33
  2819. +n13 * n22 * n34
  2820. -n12 * n23 * n34
  2821. ) +
  2822. n42 * (
  2823. +n11 * n23 * n34
  2824. -n11 * n24 * n33
  2825. +n14 * n21 * n33
  2826. -n13 * n21 * n34
  2827. +n13 * n24 * n31
  2828. -n14 * n23 * n31
  2829. ) +
  2830. n43 * (
  2831. +n11 * n24 * n32
  2832. -n11 * n22 * n34
  2833. -n14 * n21 * n32
  2834. +n12 * n21 * n34
  2835. +n14 * n22 * n31
  2836. -n12 * n24 * n31
  2837. ) +
  2838. n44 * (
  2839. -n13 * n22 * n31
  2840. -n11 * n23 * n32
  2841. +n11 * n22 * n33
  2842. +n13 * n21 * n32
  2843. -n12 * n21 * n33
  2844. +n12 * n23 * n31
  2845. )
  2846. );
  2847. },
  2848. transpose: function () {
  2849. var te = this.elements;
  2850. var tmp;
  2851. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2852. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2853. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2854. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2855. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2856. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2857. return this;
  2858. },
  2859. flattenToArray: function ( flat ) {
  2860. var te = this.elements;
  2861. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2862. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2863. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2864. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2865. return flat;
  2866. },
  2867. flattenToArrayOffset: function( flat, offset ) {
  2868. var te = this.elements;
  2869. flat[ offset ] = te[0];
  2870. flat[ offset + 1 ] = te[1];
  2871. flat[ offset + 2 ] = te[2];
  2872. flat[ offset + 3 ] = te[3];
  2873. flat[ offset + 4 ] = te[4];
  2874. flat[ offset + 5 ] = te[5];
  2875. flat[ offset + 6 ] = te[6];
  2876. flat[ offset + 7 ] = te[7];
  2877. flat[ offset + 8 ] = te[8];
  2878. flat[ offset + 9 ] = te[9];
  2879. flat[ offset + 10 ] = te[10];
  2880. flat[ offset + 11 ] = te[11];
  2881. flat[ offset + 12 ] = te[12];
  2882. flat[ offset + 13 ] = te[13];
  2883. flat[ offset + 14 ] = te[14];
  2884. flat[ offset + 15 ] = te[15];
  2885. return flat;
  2886. },
  2887. getPosition: function() {
  2888. var v1 = new THREE.Vector3();
  2889. return function () {
  2890. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  2891. var te = this.elements;
  2892. return v1.set( te[12], te[13], te[14] );
  2893. };
  2894. }(),
  2895. setPosition: function ( v ) {
  2896. var te = this.elements;
  2897. te[12] = v.x;
  2898. te[13] = v.y;
  2899. te[14] = v.z;
  2900. return this;
  2901. },
  2902. getInverse: function ( m, throwOnInvertible ) {
  2903. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2904. var te = this.elements;
  2905. var me = m.elements;
  2906. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2907. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2908. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2909. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2910. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2911. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2912. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2913. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2914. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2915. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2916. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2917. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2918. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2919. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2920. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2921. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2922. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2923. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2924. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2925. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2926. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  2927. if ( det == 0 ) {
  2928. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2929. if ( throwOnInvertible || false ) {
  2930. throw new Error( msg );
  2931. } else {
  2932. console.warn( msg );
  2933. }
  2934. this.identity();
  2935. return this;
  2936. }
  2937. this.multiplyScalar( 1 / det );
  2938. return this;
  2939. },
  2940. translate: function ( v ) {
  2941. console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.');
  2942. },
  2943. rotateX: function ( angle ) {
  2944. console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.');
  2945. },
  2946. rotateY: function ( angle ) {
  2947. console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.');
  2948. },
  2949. rotateZ: function ( angle ) {
  2950. console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.');
  2951. },
  2952. rotateByAxis: function ( axis, angle ) {
  2953. console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.');
  2954. },
  2955. scale: function ( v ) {
  2956. var te = this.elements;
  2957. var x = v.x, y = v.y, z = v.z;
  2958. te[0] *= x; te[4] *= y; te[8] *= z;
  2959. te[1] *= x; te[5] *= y; te[9] *= z;
  2960. te[2] *= x; te[6] *= y; te[10] *= z;
  2961. te[3] *= x; te[7] *= y; te[11] *= z;
  2962. return this;
  2963. },
  2964. getMaxScaleOnAxis: function () {
  2965. var te = this.elements;
  2966. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2967. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2968. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2969. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2970. },
  2971. makeTranslation: function ( x, y, z ) {
  2972. this.set(
  2973. 1, 0, 0, x,
  2974. 0, 1, 0, y,
  2975. 0, 0, 1, z,
  2976. 0, 0, 0, 1
  2977. );
  2978. return this;
  2979. },
  2980. makeRotationX: function ( theta ) {
  2981. var c = Math.cos( theta ), s = Math.sin( theta );
  2982. this.set(
  2983. 1, 0, 0, 0,
  2984. 0, c, -s, 0,
  2985. 0, s, c, 0,
  2986. 0, 0, 0, 1
  2987. );
  2988. return this;
  2989. },
  2990. makeRotationY: function ( theta ) {
  2991. var c = Math.cos( theta ), s = Math.sin( theta );
  2992. this.set(
  2993. c, 0, s, 0,
  2994. 0, 1, 0, 0,
  2995. -s, 0, c, 0,
  2996. 0, 0, 0, 1
  2997. );
  2998. return this;
  2999. },
  3000. makeRotationZ: function ( theta ) {
  3001. var c = Math.cos( theta ), s = Math.sin( theta );
  3002. this.set(
  3003. c, -s, 0, 0,
  3004. s, c, 0, 0,
  3005. 0, 0, 1, 0,
  3006. 0, 0, 0, 1
  3007. );
  3008. return this;
  3009. },
  3010. makeRotationAxis: function ( axis, angle ) {
  3011. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3012. var c = Math.cos( angle );
  3013. var s = Math.sin( angle );
  3014. var t = 1 - c;
  3015. var x = axis.x, y = axis.y, z = axis.z;
  3016. var tx = t * x, ty = t * y;
  3017. this.set(
  3018. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3019. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3020. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3021. 0, 0, 0, 1
  3022. );
  3023. return this;
  3024. },
  3025. makeScale: function ( x, y, z ) {
  3026. this.set(
  3027. x, 0, 0, 0,
  3028. 0, y, 0, 0,
  3029. 0, 0, z, 0,
  3030. 0, 0, 0, 1
  3031. );
  3032. return this;
  3033. },
  3034. compose: function ( position, quaternion, scale ) {
  3035. this.makeRotationFromQuaternion( quaternion );
  3036. this.scale( scale );
  3037. this.setPosition( position );
  3038. return this;
  3039. },
  3040. decompose: function () {
  3041. var vector = new THREE.Vector3();
  3042. var matrix = new THREE.Matrix4();
  3043. return function ( position, quaternion, scale ) {
  3044. var te = this.elements;
  3045. var sx = vector.set( te[0], te[1], te[2] ).length();
  3046. var sy = vector.set( te[4], te[5], te[6] ).length();
  3047. var sz = vector.set( te[8], te[9], te[10] ).length();
  3048. // if determine is negative, we need to invert one scale
  3049. var det = this.determinant();
  3050. if( det < 0 ) {
  3051. sx = -sx;
  3052. }
  3053. position.x = te[12];
  3054. position.y = te[13];
  3055. position.z = te[14];
  3056. // scale the rotation part
  3057. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  3058. var invSX = 1 / sx;
  3059. var invSY = 1 / sy;
  3060. var invSZ = 1 / sz;
  3061. matrix.elements[0] *= invSX;
  3062. matrix.elements[1] *= invSX;
  3063. matrix.elements[2] *= invSX;
  3064. matrix.elements[4] *= invSY;
  3065. matrix.elements[5] *= invSY;
  3066. matrix.elements[6] *= invSY;
  3067. matrix.elements[8] *= invSZ;
  3068. matrix.elements[9] *= invSZ;
  3069. matrix.elements[10] *= invSZ;
  3070. quaternion.setFromRotationMatrix( matrix );
  3071. scale.x = sx;
  3072. scale.y = sy;
  3073. scale.z = sz;
  3074. return this;
  3075. };
  3076. }(),
  3077. makeFrustum: function ( left, right, bottom, top, near, far ) {
  3078. var te = this.elements;
  3079. var x = 2 * near / ( right - left );
  3080. var y = 2 * near / ( top - bottom );
  3081. var a = ( right + left ) / ( right - left );
  3082. var b = ( top + bottom ) / ( top - bottom );
  3083. var c = - ( far + near ) / ( far - near );
  3084. var d = - 2 * far * near / ( far - near );
  3085. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  3086. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  3087. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  3088. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  3089. return this;
  3090. },
  3091. makePerspective: function ( fov, aspect, near, far ) {
  3092. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  3093. var ymin = - ymax;
  3094. var xmin = ymin * aspect;
  3095. var xmax = ymax * aspect;
  3096. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  3097. },
  3098. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  3099. var te = this.elements;
  3100. var w = right - left;
  3101. var h = top - bottom;
  3102. var p = far - near;
  3103. var x = ( right + left ) / w;
  3104. var y = ( top + bottom ) / h;
  3105. var z = ( far + near ) / p;
  3106. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  3107. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  3108. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  3109. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  3110. return this;
  3111. },
  3112. fromArray: function ( array ) {
  3113. this.elements.set( array );
  3114. return this;
  3115. },
  3116. toArray: function () {
  3117. var te = this.elements;
  3118. return [
  3119. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  3120. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  3121. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  3122. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  3123. ];
  3124. },
  3125. clone: function () {
  3126. var te = this.elements;
  3127. return new THREE.Matrix4(
  3128. te[0], te[4], te[8], te[12],
  3129. te[1], te[5], te[9], te[13],
  3130. te[2], te[6], te[10], te[14],
  3131. te[3], te[7], te[11], te[15]
  3132. );
  3133. }
  3134. };
  3135. /**
  3136. * @author bhouston / http://exocortex.com
  3137. */
  3138. THREE.Ray = function ( origin, direction ) {
  3139. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  3140. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  3141. };
  3142. THREE.Ray.prototype = {
  3143. constructor: THREE.Ray,
  3144. set: function ( origin, direction ) {
  3145. this.origin.copy( origin );
  3146. this.direction.copy( direction );
  3147. return this;
  3148. },
  3149. copy: function ( ray ) {
  3150. this.origin.copy( ray.origin );
  3151. this.direction.copy( ray.direction );
  3152. return this;
  3153. },
  3154. at: function ( t, optionalTarget ) {
  3155. var result = optionalTarget || new THREE.Vector3();
  3156. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3157. },
  3158. recast: function () {
  3159. var v1 = new THREE.Vector3();
  3160. return function ( t ) {
  3161. this.origin.copy( this.at( t, v1 ) );
  3162. return this;
  3163. };
  3164. }(),
  3165. closestPointToPoint: function ( point, optionalTarget ) {
  3166. var result = optionalTarget || new THREE.Vector3();
  3167. result.subVectors( point, this.origin );
  3168. var directionDistance = result.dot( this.direction );
  3169. if ( directionDistance < 0 ) {
  3170. return result.copy( this.origin );
  3171. }
  3172. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3173. },
  3174. distanceToPoint: function () {
  3175. var v1 = new THREE.Vector3();
  3176. return function ( point ) {
  3177. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3178. // point behind the ray
  3179. if ( directionDistance < 0 ) {
  3180. return this.origin.distanceTo( point );
  3181. }
  3182. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3183. return v1.distanceTo( point );
  3184. };
  3185. }(),
  3186. distanceSqToSegment: function( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3187. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3188. // It returns the min distance between the ray and the segment
  3189. // defined by v0 and v1
  3190. // It can also set two optional targets :
  3191. // - The closest point on the ray
  3192. // - The closest point on the segment
  3193. var segCenter = v0.clone().add( v1 ).multiplyScalar( 0.5 );
  3194. var segDir = v1.clone().sub( v0 ).normalize();
  3195. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3196. var diff = this.origin.clone().sub( segCenter );
  3197. var a01 = - this.direction.dot( segDir );
  3198. var b0 = diff.dot( this.direction );
  3199. var b1 = - diff.dot( segDir );
  3200. var c = diff.lengthSq();
  3201. var det = Math.abs( 1 - a01 * a01 );
  3202. var s0, s1, sqrDist, extDet;
  3203. if ( det >= 0 ) {
  3204. // The ray and segment are not parallel.
  3205. s0 = a01 * b1 - b0;
  3206. s1 = a01 * b0 - b1;
  3207. extDet = segExtent * det;
  3208. if ( s0 >= 0 ) {
  3209. if ( s1 >= - extDet ) {
  3210. if ( s1 <= extDet ) {
  3211. // region 0
  3212. // Minimum at interior points of ray and segment.
  3213. var invDet = 1 / det;
  3214. s0 *= invDet;
  3215. s1 *= invDet;
  3216. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3217. } else {
  3218. // region 1
  3219. s1 = segExtent;
  3220. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3221. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3222. }
  3223. } else {
  3224. // region 5
  3225. s1 = - segExtent;
  3226. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3227. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3228. }
  3229. } else {
  3230. if ( s1 <= - extDet) {
  3231. // region 4
  3232. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3233. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3234. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3235. } else if ( s1 <= extDet ) {
  3236. // region 3
  3237. s0 = 0;
  3238. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3239. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3240. } else {
  3241. // region 2
  3242. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3243. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3244. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3245. }
  3246. }
  3247. } else {
  3248. // Ray and segment are parallel.
  3249. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3250. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3251. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3252. }
  3253. if ( optionalPointOnRay ) {
  3254. optionalPointOnRay.copy( this.direction.clone().multiplyScalar( s0 ).add( this.origin ) );
  3255. }
  3256. if ( optionalPointOnSegment ) {
  3257. optionalPointOnSegment.copy( segDir.clone().multiplyScalar( s1 ).add( segCenter ) );
  3258. }
  3259. return sqrDist;
  3260. },
  3261. isIntersectionSphere: function ( sphere ) {
  3262. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3263. },
  3264. isIntersectionPlane: function ( plane ) {
  3265. // check if the ray lies on the plane first
  3266. var distToPoint = plane.distanceToPoint( this.origin );
  3267. if ( distToPoint === 0 ) {
  3268. return true;
  3269. }
  3270. var denominator = plane.normal.dot( this.direction );
  3271. if ( denominator * distToPoint < 0 ) {
  3272. return true
  3273. }
  3274. // ray origin is behind the plane (and is pointing behind it)
  3275. return false;
  3276. },
  3277. distanceToPlane: function ( plane ) {
  3278. var denominator = plane.normal.dot( this.direction );
  3279. if ( denominator == 0 ) {
  3280. // line is coplanar, return origin
  3281. if( plane.distanceToPoint( this.origin ) == 0 ) {
  3282. return 0;
  3283. }
  3284. // Null is preferable to undefined since undefined means.... it is undefined
  3285. return null;
  3286. }
  3287. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3288. // Return if the ray never intersects the plane
  3289. return t >= 0 ? t : null;
  3290. },
  3291. intersectPlane: function ( plane, optionalTarget ) {
  3292. var t = this.distanceToPlane( plane );
  3293. if ( t === null ) {
  3294. return null;
  3295. }
  3296. return this.at( t, optionalTarget );
  3297. },
  3298. isIntersectionBox: function () {
  3299. var v = new THREE.Vector3();
  3300. return function ( box ) {
  3301. return this.intersectBox( box, v ) !== null;
  3302. }
  3303. }(),
  3304. intersectBox: function ( box , optionalTarget ) {
  3305. // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
  3306. var tmin,tmax,tymin,tymax,tzmin,tzmax;
  3307. var invdirx = 1/this.direction.x,
  3308. invdiry = 1/this.direction.y,
  3309. invdirz = 1/this.direction.z;
  3310. var origin = this.origin;
  3311. if (invdirx >= 0) {
  3312. tmin = (box.min.x - origin.x) * invdirx;
  3313. tmax = (box.max.x - origin.x) * invdirx;
  3314. } else {
  3315. tmin = (box.max.x - origin.x) * invdirx;
  3316. tmax = (box.min.x - origin.x) * invdirx;
  3317. }
  3318. if (invdiry >= 0) {
  3319. tymin = (box.min.y - origin.y) * invdiry;
  3320. tymax = (box.max.y - origin.y) * invdiry;
  3321. } else {
  3322. tymin = (box.max.y - origin.y) * invdiry;
  3323. tymax = (box.min.y - origin.y) * invdiry;
  3324. }
  3325. if ((tmin > tymax) || (tymin > tmax)) return null;
  3326. // These lines also handle the case where tmin or tmax is NaN
  3327. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3328. if (tymin > tmin || tmin !== tmin ) tmin = tymin;
  3329. if (tymax < tmax || tmax !== tmax ) tmax = tymax;
  3330. if (invdirz >= 0) {
  3331. tzmin = (box.min.z - origin.z) * invdirz;
  3332. tzmax = (box.max.z - origin.z) * invdirz;
  3333. } else {
  3334. tzmin = (box.max.z - origin.z) * invdirz;
  3335. tzmax = (box.min.z - origin.z) * invdirz;
  3336. }
  3337. if ((tmin > tzmax) || (tzmin > tmax)) return null;
  3338. if (tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3339. if (tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3340. //return point closest to the ray (positive side)
  3341. if ( tmax < 0 ) return null;
  3342. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3343. },
  3344. intersectTriangle: function() {
  3345. // Compute the offset origin, edges, and normal.
  3346. var diff = new THREE.Vector3();
  3347. var edge1 = new THREE.Vector3();
  3348. var edge2 = new THREE.Vector3();
  3349. var normal = new THREE.Vector3();
  3350. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3351. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3352. edge1.subVectors( b, a );
  3353. edge2.subVectors( c, a );
  3354. normal.crossVectors( edge1, edge2 );
  3355. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3356. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3357. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3358. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3359. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3360. var DdN = this.direction.dot( normal );
  3361. var sign;
  3362. if ( DdN > 0 ) {
  3363. if ( backfaceCulling ) return null;
  3364. sign = 1;
  3365. } else if ( DdN < 0 ) {
  3366. sign = - 1;
  3367. DdN = - DdN;
  3368. } else {
  3369. return null;
  3370. }
  3371. diff.subVectors( this.origin, a );
  3372. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3373. // b1 < 0, no intersection
  3374. if ( DdQxE2 < 0 ) {
  3375. return null;
  3376. }
  3377. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3378. // b2 < 0, no intersection
  3379. if ( DdE1xQ < 0 ) {
  3380. return null;
  3381. }
  3382. // b1+b2 > 1, no intersection
  3383. if ( DdQxE2 + DdE1xQ > DdN ) {
  3384. return null;
  3385. }
  3386. // Line intersects triangle, check if ray does.
  3387. var QdN = - sign * diff.dot( normal );
  3388. // t < 0, no intersection
  3389. if ( QdN < 0 ) {
  3390. return null;
  3391. }
  3392. // Ray intersects triangle.
  3393. return this.at( QdN / DdN, optionalTarget );
  3394. }
  3395. }(),
  3396. applyMatrix4: function ( matrix4 ) {
  3397. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3398. this.origin.applyMatrix4( matrix4 );
  3399. this.direction.sub( this.origin );
  3400. this.direction.normalize();
  3401. return this;
  3402. },
  3403. equals: function ( ray ) {
  3404. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3405. },
  3406. clone: function () {
  3407. return new THREE.Ray().copy( this );
  3408. }
  3409. };
  3410. /**
  3411. * @author bhouston / http://exocortex.com
  3412. * @author mrdoob / http://mrdoob.com/
  3413. */
  3414. THREE.Sphere = function ( center, radius ) {
  3415. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3416. this.radius = ( radius !== undefined ) ? radius : 0;
  3417. };
  3418. THREE.Sphere.prototype = {
  3419. constructor: THREE.Sphere,
  3420. set: function ( center, radius ) {
  3421. this.center.copy( center );
  3422. this.radius = radius;
  3423. return this;
  3424. },
  3425. setFromPoints: function () {
  3426. var box = new THREE.Box3();
  3427. return function ( points, optionalCenter ) {
  3428. var center = this.center;
  3429. if ( optionalCenter !== undefined ) {
  3430. center.copy( optionalCenter );
  3431. } else {
  3432. box.setFromPoints( points ).center( center );
  3433. }
  3434. var maxRadiusSq = 0;
  3435. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3436. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3437. }
  3438. this.radius = Math.sqrt( maxRadiusSq );
  3439. return this;
  3440. };
  3441. }(),
  3442. copy: function ( sphere ) {
  3443. this.center.copy( sphere.center );
  3444. this.radius = sphere.radius;
  3445. return this;
  3446. },
  3447. empty: function () {
  3448. return ( this.radius <= 0 );
  3449. },
  3450. containsPoint: function ( point ) {
  3451. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3452. },
  3453. distanceToPoint: function ( point ) {
  3454. return ( point.distanceTo( this.center ) - this.radius );
  3455. },
  3456. intersectsSphere: function ( sphere ) {
  3457. var radiusSum = this.radius + sphere.radius;
  3458. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3459. },
  3460. clampPoint: function ( point, optionalTarget ) {
  3461. var deltaLengthSq = this.center.distanceToSquared( point );
  3462. var result = optionalTarget || new THREE.Vector3();
  3463. result.copy( point );
  3464. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3465. result.sub( this.center ).normalize();
  3466. result.multiplyScalar( this.radius ).add( this.center );
  3467. }
  3468. return result;
  3469. },
  3470. getBoundingBox: function ( optionalTarget ) {
  3471. var box = optionalTarget || new THREE.Box3();
  3472. box.set( this.center, this.center );
  3473. box.expandByScalar( this.radius );
  3474. return box;
  3475. },
  3476. applyMatrix4: function ( matrix ) {
  3477. this.center.applyMatrix4( matrix );
  3478. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3479. return this;
  3480. },
  3481. translate: function ( offset ) {
  3482. this.center.add( offset );
  3483. return this;
  3484. },
  3485. equals: function ( sphere ) {
  3486. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3487. },
  3488. clone: function () {
  3489. return new THREE.Sphere().copy( this );
  3490. }
  3491. };
  3492. /**
  3493. * @author mrdoob / http://mrdoob.com/
  3494. * @author alteredq / http://alteredqualia.com/
  3495. * @author bhouston / http://exocortex.com
  3496. */
  3497. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3498. this.planes = [
  3499. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3500. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3501. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3502. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3503. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3504. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3505. ];
  3506. };
  3507. THREE.Frustum.prototype = {
  3508. constructor: THREE.Frustum,
  3509. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3510. var planes = this.planes;
  3511. planes[0].copy( p0 );
  3512. planes[1].copy( p1 );
  3513. planes[2].copy( p2 );
  3514. planes[3].copy( p3 );
  3515. planes[4].copy( p4 );
  3516. planes[5].copy( p5 );
  3517. return this;
  3518. },
  3519. copy: function ( frustum ) {
  3520. var planes = this.planes;
  3521. for( var i = 0; i < 6; i ++ ) {
  3522. planes[i].copy( frustum.planes[i] );
  3523. }
  3524. return this;
  3525. },
  3526. setFromMatrix: function ( m ) {
  3527. var planes = this.planes;
  3528. var me = m.elements;
  3529. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  3530. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  3531. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  3532. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  3533. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3534. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3535. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3536. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3537. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3538. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3539. return this;
  3540. },
  3541. intersectsObject: function () {
  3542. var sphere = new THREE.Sphere();
  3543. return function ( object ) {
  3544. var geometry = object.geometry;
  3545. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3546. sphere.copy( geometry.boundingSphere );
  3547. sphere.applyMatrix4( object.matrixWorld );
  3548. return this.intersectsSphere( sphere );
  3549. };
  3550. }(),
  3551. intersectsSphere: function ( sphere ) {
  3552. var planes = this.planes;
  3553. var center = sphere.center;
  3554. var negRadius = -sphere.radius;
  3555. for ( var i = 0; i < 6; i ++ ) {
  3556. var distance = planes[ i ].distanceToPoint( center );
  3557. if ( distance < negRadius ) {
  3558. return false;
  3559. }
  3560. }
  3561. return true;
  3562. },
  3563. intersectsBox : function() {
  3564. var p1 = new THREE.Vector3(),
  3565. p2 = new THREE.Vector3();
  3566. return function( box ) {
  3567. var planes = this.planes;
  3568. for ( var i = 0; i < 6 ; i ++ ) {
  3569. var plane = planes[i];
  3570. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3571. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3572. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3573. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3574. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3575. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3576. var d1 = plane.distanceToPoint( p1 );
  3577. var d2 = plane.distanceToPoint( p2 );
  3578. // if both outside plane, no intersection
  3579. if ( d1 < 0 && d2 < 0 ) {
  3580. return false;
  3581. }
  3582. }
  3583. return true;
  3584. };
  3585. }(),
  3586. containsPoint: function ( point ) {
  3587. var planes = this.planes;
  3588. for ( var i = 0; i < 6; i ++ ) {
  3589. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3590. return false;
  3591. }
  3592. }
  3593. return true;
  3594. },
  3595. clone: function () {
  3596. return new THREE.Frustum().copy( this );
  3597. }
  3598. };
  3599. /**
  3600. * @author bhouston / http://exocortex.com
  3601. */
  3602. THREE.Plane = function ( normal, constant ) {
  3603. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3604. this.constant = ( constant !== undefined ) ? constant : 0;
  3605. };
  3606. THREE.Plane.prototype = {
  3607. constructor: THREE.Plane,
  3608. set: function ( normal, constant ) {
  3609. this.normal.copy( normal );
  3610. this.constant = constant;
  3611. return this;
  3612. },
  3613. setComponents: function ( x, y, z, w ) {
  3614. this.normal.set( x, y, z );
  3615. this.constant = w;
  3616. return this;
  3617. },
  3618. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3619. this.normal.copy( normal );
  3620. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3621. return this;
  3622. },
  3623. setFromCoplanarPoints: function() {
  3624. var v1 = new THREE.Vector3();
  3625. var v2 = new THREE.Vector3();
  3626. return function ( a, b, c ) {
  3627. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3628. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3629. this.setFromNormalAndCoplanarPoint( normal, a );
  3630. return this;
  3631. };
  3632. }(),
  3633. copy: function ( plane ) {
  3634. this.normal.copy( plane.normal );
  3635. this.constant = plane.constant;
  3636. return this;
  3637. },
  3638. normalize: function () {
  3639. // Note: will lead to a divide by zero if the plane is invalid.
  3640. var inverseNormalLength = 1.0 / this.normal.length();
  3641. this.normal.multiplyScalar( inverseNormalLength );
  3642. this.constant *= inverseNormalLength;
  3643. return this;
  3644. },
  3645. negate: function () {
  3646. this.constant *= -1;
  3647. this.normal.negate();
  3648. return this;
  3649. },
  3650. distanceToPoint: function ( point ) {
  3651. return this.normal.dot( point ) + this.constant;
  3652. },
  3653. distanceToSphere: function ( sphere ) {
  3654. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3655. },
  3656. projectPoint: function ( point, optionalTarget ) {
  3657. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3658. },
  3659. orthoPoint: function ( point, optionalTarget ) {
  3660. var perpendicularMagnitude = this.distanceToPoint( point );
  3661. var result = optionalTarget || new THREE.Vector3();
  3662. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3663. },
  3664. isIntersectionLine: function ( line ) {
  3665. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3666. var startSign = this.distanceToPoint( line.start );
  3667. var endSign = this.distanceToPoint( line.end );
  3668. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3669. },
  3670. intersectLine: function() {
  3671. var v1 = new THREE.Vector3();
  3672. return function ( line, optionalTarget ) {
  3673. var result = optionalTarget || new THREE.Vector3();
  3674. var direction = line.delta( v1 );
  3675. var denominator = this.normal.dot( direction );
  3676. if ( denominator == 0 ) {
  3677. // line is coplanar, return origin
  3678. if( this.distanceToPoint( line.start ) == 0 ) {
  3679. return result.copy( line.start );
  3680. }
  3681. // Unsure if this is the correct method to handle this case.
  3682. return undefined;
  3683. }
  3684. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3685. if( t < 0 || t > 1 ) {
  3686. return undefined;
  3687. }
  3688. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3689. };
  3690. }(),
  3691. coplanarPoint: function ( optionalTarget ) {
  3692. var result = optionalTarget || new THREE.Vector3();
  3693. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3694. },
  3695. applyMatrix4: function() {
  3696. var v1 = new THREE.Vector3();
  3697. var v2 = new THREE.Vector3();
  3698. var m1 = new THREE.Matrix3();
  3699. return function ( matrix, optionalNormalMatrix ) {
  3700. // compute new normal based on theory here:
  3701. // http://www.songho.ca/opengl/gl_normaltransform.html
  3702. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  3703. var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix );
  3704. var newCoplanarPoint = this.coplanarPoint( v2 );
  3705. newCoplanarPoint.applyMatrix4( matrix );
  3706. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3707. return this;
  3708. };
  3709. }(),
  3710. translate: function ( offset ) {
  3711. this.constant = this.constant - offset.dot( this.normal );
  3712. return this;
  3713. },
  3714. equals: function ( plane ) {
  3715. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3716. },
  3717. clone: function () {
  3718. return new THREE.Plane().copy( this );
  3719. }
  3720. };
  3721. /**
  3722. * @author alteredq / http://alteredqualia.com/
  3723. * @author mrdoob / http://mrdoob.com/
  3724. */
  3725. THREE.Math = {
  3726. generateUUID: function () {
  3727. // http://www.broofa.com/Tools/Math.uuid.htm
  3728. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  3729. var uuid = new Array(36);
  3730. var rnd = 0, r;
  3731. return function () {
  3732. for ( var i = 0; i < 36; i ++ ) {
  3733. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3734. uuid[ i ] = '-';
  3735. } else if ( i == 14 ) {
  3736. uuid[ i ] = '4';
  3737. } else {
  3738. if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
  3739. r = rnd & 0xf;
  3740. rnd = rnd >> 4;
  3741. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  3742. }
  3743. }
  3744. return uuid.join('');
  3745. };
  3746. }(),
  3747. // Clamp value to range <a, b>
  3748. clamp: function ( x, a, b ) {
  3749. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3750. },
  3751. // Clamp value to range <a, inf)
  3752. clampBottom: function ( x, a ) {
  3753. return x < a ? a : x;
  3754. },
  3755. // Linear mapping from range <a1, a2> to range <b1, b2>
  3756. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3757. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3758. },
  3759. // http://en.wikipedia.org/wiki/Smoothstep
  3760. smoothstep: function ( x, min, max ) {
  3761. if ( x <= min ) return 0;
  3762. if ( x >= max ) return 1;
  3763. x = ( x - min )/( max - min );
  3764. return x*x*(3 - 2*x);
  3765. },
  3766. smootherstep: function ( x, min, max ) {
  3767. if ( x <= min ) return 0;
  3768. if ( x >= max ) return 1;
  3769. x = ( x - min )/( max - min );
  3770. return x*x*x*(x*(x*6 - 15) + 10);
  3771. },
  3772. // Random float from <0, 1> with 16 bits of randomness
  3773. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3774. random16: function () {
  3775. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3776. },
  3777. // Random integer from <low, high> interval
  3778. randInt: function ( low, high ) {
  3779. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3780. },
  3781. // Random float from <low, high> interval
  3782. randFloat: function ( low, high ) {
  3783. return low + Math.random() * ( high - low );
  3784. },
  3785. // Random float from <-range/2, range/2> interval
  3786. randFloatSpread: function ( range ) {
  3787. return range * ( 0.5 - Math.random() );
  3788. },
  3789. sign: function ( x ) {
  3790. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : 0;
  3791. },
  3792. degToRad: function() {
  3793. var degreeToRadiansFactor = Math.PI / 180;
  3794. return function ( degrees ) {
  3795. return degrees * degreeToRadiansFactor;
  3796. };
  3797. }(),
  3798. radToDeg: function() {
  3799. var radianToDegreesFactor = 180 / Math.PI;
  3800. return function ( radians ) {
  3801. return radians * radianToDegreesFactor;
  3802. };
  3803. }(),
  3804. isPowerOfTwo: function ( value ) {
  3805. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  3806. }
  3807. };
  3808. /**
  3809. * Spline from Tween.js, slightly optimized (and trashed)
  3810. * http://sole.github.com/tween.js/examples/05_spline.html
  3811. *
  3812. * @author mrdoob / http://mrdoob.com/
  3813. * @author alteredq / http://alteredqualia.com/
  3814. */
  3815. THREE.Spline = function ( points ) {
  3816. this.points = points;
  3817. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3818. point, intPoint, weight, w2, w3,
  3819. pa, pb, pc, pd;
  3820. this.initFromArray = function( a ) {
  3821. this.points = [];
  3822. for ( var i = 0; i < a.length; i++ ) {
  3823. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3824. }
  3825. };
  3826. this.getPoint = function ( k ) {
  3827. point = ( this.points.length - 1 ) * k;
  3828. intPoint = Math.floor( point );
  3829. weight = point - intPoint;
  3830. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3831. c[ 1 ] = intPoint;
  3832. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3833. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3834. pa = this.points[ c[ 0 ] ];
  3835. pb = this.points[ c[ 1 ] ];
  3836. pc = this.points[ c[ 2 ] ];
  3837. pd = this.points[ c[ 3 ] ];
  3838. w2 = weight * weight;
  3839. w3 = weight * w2;
  3840. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3841. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3842. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3843. return v3;
  3844. };
  3845. this.getControlPointsArray = function () {
  3846. var i, p, l = this.points.length,
  3847. coords = [];
  3848. for ( i = 0; i < l; i ++ ) {
  3849. p = this.points[ i ];
  3850. coords[ i ] = [ p.x, p.y, p.z ];
  3851. }
  3852. return coords;
  3853. };
  3854. // approximate length by summing linear segments
  3855. this.getLength = function ( nSubDivisions ) {
  3856. var i, index, nSamples, position,
  3857. point = 0, intPoint = 0, oldIntPoint = 0,
  3858. oldPosition = new THREE.Vector3(),
  3859. tmpVec = new THREE.Vector3(),
  3860. chunkLengths = [],
  3861. totalLength = 0;
  3862. // first point has 0 length
  3863. chunkLengths[ 0 ] = 0;
  3864. if ( !nSubDivisions ) nSubDivisions = 100;
  3865. nSamples = this.points.length * nSubDivisions;
  3866. oldPosition.copy( this.points[ 0 ] );
  3867. for ( i = 1; i < nSamples; i ++ ) {
  3868. index = i / nSamples;
  3869. position = this.getPoint( index );
  3870. tmpVec.copy( position );
  3871. totalLength += tmpVec.distanceTo( oldPosition );
  3872. oldPosition.copy( position );
  3873. point = ( this.points.length - 1 ) * index;
  3874. intPoint = Math.floor( point );
  3875. if ( intPoint != oldIntPoint ) {
  3876. chunkLengths[ intPoint ] = totalLength;
  3877. oldIntPoint = intPoint;
  3878. }
  3879. }
  3880. // last point ends with total length
  3881. chunkLengths[ chunkLengths.length ] = totalLength;
  3882. return { chunks: chunkLengths, total: totalLength };
  3883. };
  3884. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3885. var i, j,
  3886. index, indexCurrent, indexNext,
  3887. linearDistance, realDistance,
  3888. sampling, position,
  3889. newpoints = [],
  3890. tmpVec = new THREE.Vector3(),
  3891. sl = this.getLength();
  3892. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3893. for ( i = 1; i < this.points.length; i++ ) {
  3894. //tmpVec.copy( this.points[ i - 1 ] );
  3895. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3896. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3897. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3898. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3899. indexNext = i / ( this.points.length - 1 );
  3900. for ( j = 1; j < sampling - 1; j++ ) {
  3901. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3902. position = this.getPoint( index );
  3903. newpoints.push( tmpVec.copy( position ).clone() );
  3904. }
  3905. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3906. }
  3907. this.points = newpoints;
  3908. };
  3909. // Catmull-Rom
  3910. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3911. var v0 = ( p2 - p0 ) * 0.5,
  3912. v1 = ( p3 - p1 ) * 0.5;
  3913. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3914. };
  3915. };
  3916. /**
  3917. * @author bhouston / http://exocortex.com
  3918. * @author mrdoob / http://mrdoob.com/
  3919. */
  3920. THREE.Triangle = function ( a, b, c ) {
  3921. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3922. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3923. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3924. };
  3925. THREE.Triangle.normal = function() {
  3926. var v0 = new THREE.Vector3();
  3927. return function ( a, b, c, optionalTarget ) {
  3928. var result = optionalTarget || new THREE.Vector3();
  3929. result.subVectors( c, b );
  3930. v0.subVectors( a, b );
  3931. result.cross( v0 );
  3932. var resultLengthSq = result.lengthSq();
  3933. if( resultLengthSq > 0 ) {
  3934. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3935. }
  3936. return result.set( 0, 0, 0 );
  3937. };
  3938. }();
  3939. // static/instance method to calculate barycoordinates
  3940. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3941. THREE.Triangle.barycoordFromPoint = function() {
  3942. var v0 = new THREE.Vector3();
  3943. var v1 = new THREE.Vector3();
  3944. var v2 = new THREE.Vector3();
  3945. return function ( point, a, b, c, optionalTarget ) {
  3946. v0.subVectors( c, a );
  3947. v1.subVectors( b, a );
  3948. v2.subVectors( point, a );
  3949. var dot00 = v0.dot( v0 );
  3950. var dot01 = v0.dot( v1 );
  3951. var dot02 = v0.dot( v2 );
  3952. var dot11 = v1.dot( v1 );
  3953. var dot12 = v1.dot( v2 );
  3954. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3955. var result = optionalTarget || new THREE.Vector3();
  3956. // colinear or singular triangle
  3957. if( denom == 0 ) {
  3958. // arbitrary location outside of triangle?
  3959. // not sure if this is the best idea, maybe should be returning undefined
  3960. return result.set( -2, -1, -1 );
  3961. }
  3962. var invDenom = 1 / denom;
  3963. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3964. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3965. // barycoordinates must always sum to 1
  3966. return result.set( 1 - u - v, v, u );
  3967. };
  3968. }();
  3969. THREE.Triangle.containsPoint = function() {
  3970. var v1 = new THREE.Vector3();
  3971. return function ( point, a, b, c ) {
  3972. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3973. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3974. };
  3975. }();
  3976. THREE.Triangle.prototype = {
  3977. constructor: THREE.Triangle,
  3978. set: function ( a, b, c ) {
  3979. this.a.copy( a );
  3980. this.b.copy( b );
  3981. this.c.copy( c );
  3982. return this;
  3983. },
  3984. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3985. this.a.copy( points[i0] );
  3986. this.b.copy( points[i1] );
  3987. this.c.copy( points[i2] );
  3988. return this;
  3989. },
  3990. copy: function ( triangle ) {
  3991. this.a.copy( triangle.a );
  3992. this.b.copy( triangle.b );
  3993. this.c.copy( triangle.c );
  3994. return this;
  3995. },
  3996. area: function() {
  3997. var v0 = new THREE.Vector3();
  3998. var v1 = new THREE.Vector3();
  3999. return function () {
  4000. v0.subVectors( this.c, this.b );
  4001. v1.subVectors( this.a, this.b );
  4002. return v0.cross( v1 ).length() * 0.5;
  4003. };
  4004. }(),
  4005. midpoint: function ( optionalTarget ) {
  4006. var result = optionalTarget || new THREE.Vector3();
  4007. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4008. },
  4009. normal: function ( optionalTarget ) {
  4010. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  4011. },
  4012. plane: function ( optionalTarget ) {
  4013. var result = optionalTarget || new THREE.Plane();
  4014. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  4015. },
  4016. barycoordFromPoint: function ( point, optionalTarget ) {
  4017. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  4018. },
  4019. containsPoint: function ( point ) {
  4020. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  4021. },
  4022. equals: function ( triangle ) {
  4023. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4024. },
  4025. clone: function () {
  4026. return new THREE.Triangle().copy( this );
  4027. }
  4028. };
  4029. /**
  4030. * @author mrdoob / http://mrdoob.com/
  4031. */
  4032. THREE.Vertex = function ( v ) {
  4033. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  4034. return v;
  4035. };
  4036. /**
  4037. * @author alteredq / http://alteredqualia.com/
  4038. */
  4039. THREE.Clock = function ( autoStart ) {
  4040. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  4041. this.startTime = 0;
  4042. this.oldTime = 0;
  4043. this.elapsedTime = 0;
  4044. this.running = false;
  4045. };
  4046. THREE.Clock.prototype = {
  4047. constructor: THREE.Clock,
  4048. start: function () {
  4049. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  4050. ? self.performance.now()
  4051. : Date.now();
  4052. this.oldTime = this.startTime;
  4053. this.running = true;
  4054. },
  4055. stop: function () {
  4056. this.getElapsedTime();
  4057. this.running = false;
  4058. },
  4059. getElapsedTime: function () {
  4060. this.getDelta();
  4061. return this.elapsedTime;
  4062. },
  4063. getDelta: function () {
  4064. var diff = 0;
  4065. if ( this.autoStart && ! this.running ) {
  4066. this.start();
  4067. }
  4068. if ( this.running ) {
  4069. var newTime = self.performance !== undefined && self.performance.now !== undefined
  4070. ? self.performance.now()
  4071. : Date.now();
  4072. diff = 0.001 * ( newTime - this.oldTime );
  4073. this.oldTime = newTime;
  4074. this.elapsedTime += diff;
  4075. }
  4076. return diff;
  4077. }
  4078. };
  4079. /**
  4080. * https://github.com/mrdoob/eventdispatcher.js/
  4081. */
  4082. THREE.EventDispatcher = function () {}
  4083. THREE.EventDispatcher.prototype = {
  4084. constructor: THREE.EventDispatcher,
  4085. apply: function ( object ) {
  4086. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  4087. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  4088. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  4089. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  4090. },
  4091. addEventListener: function ( type, listener ) {
  4092. if ( this._listeners === undefined ) this._listeners = {};
  4093. var listeners = this._listeners;
  4094. if ( listeners[ type ] === undefined ) {
  4095. listeners[ type ] = [];
  4096. }
  4097. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4098. listeners[ type ].push( listener );
  4099. }
  4100. },
  4101. hasEventListener: function ( type, listener ) {
  4102. if ( this._listeners === undefined ) return false;
  4103. var listeners = this._listeners;
  4104. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  4105. return true;
  4106. }
  4107. return false;
  4108. },
  4109. removeEventListener: function ( type, listener ) {
  4110. if ( this._listeners === undefined ) return;
  4111. var listeners = this._listeners;
  4112. var listenerArray = listeners[ type ];
  4113. if ( listenerArray !== undefined ) {
  4114. var index = listenerArray.indexOf( listener );
  4115. if ( index !== - 1 ) {
  4116. listenerArray.splice( index, 1 );
  4117. }
  4118. }
  4119. },
  4120. dispatchEvent: function ( event ) {
  4121. if ( this._listeners === undefined ) return;
  4122. var listeners = this._listeners;
  4123. var listenerArray = listeners[ event.type ];
  4124. if ( listenerArray !== undefined ) {
  4125. event.target = this;
  4126. var array = [];
  4127. var length = listenerArray.length;
  4128. for ( var i = 0; i < length; i ++ ) {
  4129. array[ i ] = listenerArray[ i ];
  4130. }
  4131. for ( var i = 0; i < length; i ++ ) {
  4132. array[ i ].call( this, event );
  4133. }
  4134. }
  4135. }
  4136. };
  4137. /**
  4138. * @author mrdoob / http://mrdoob.com/
  4139. * @author bhouston / http://exocortex.com/
  4140. * @author stephomi / http://stephaneginier.com/
  4141. */
  4142. ( function ( THREE ) {
  4143. THREE.Raycaster = function ( origin, direction, near, far ) {
  4144. this.ray = new THREE.Ray( origin, direction );
  4145. // direction is assumed to be normalized (for accurate distance calculations)
  4146. this.near = near || 0;
  4147. this.far = far || Infinity;
  4148. };
  4149. var sphere = new THREE.Sphere();
  4150. var localRay = new THREE.Ray();
  4151. var facePlane = new THREE.Plane();
  4152. var intersectPoint = new THREE.Vector3();
  4153. var matrixPosition = new THREE.Vector3();
  4154. var inverseMatrix = new THREE.Matrix4();
  4155. var descSort = function ( a, b ) {
  4156. return a.distance - b.distance;
  4157. };
  4158. var vA = new THREE.Vector3();
  4159. var vB = new THREE.Vector3();
  4160. var vC = new THREE.Vector3();
  4161. var intersectObject = function ( object, raycaster, intersects ) {
  4162. if ( object instanceof THREE.Sprite ) {
  4163. matrixPosition.setFromMatrixPosition( object.matrixWorld );
  4164. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  4165. if ( distance > object.scale.x ) {
  4166. return intersects;
  4167. }
  4168. intersects.push( {
  4169. distance: distance,
  4170. point: object.position,
  4171. face: null,
  4172. object: object
  4173. } );
  4174. } else if ( object instanceof THREE.LOD ) {
  4175. matrixPosition.setFromMatrixPosition( object.matrixWorld );
  4176. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  4177. intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );
  4178. } else if ( object instanceof THREE.Mesh ) {
  4179. var geometry = object.geometry;
  4180. // Checking boundingSphere distance to ray
  4181. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4182. sphere.copy( geometry.boundingSphere );
  4183. sphere.applyMatrix4( object.matrixWorld );
  4184. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4185. return intersects;
  4186. }
  4187. // Check boundingBox before continuing
  4188. inverseMatrix.getInverse( object.matrixWorld );
  4189. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4190. if ( geometry.boundingBox !== null ) {
  4191. if ( localRay.isIntersectionBox( geometry.boundingBox ) === false ) {
  4192. return intersects;
  4193. }
  4194. }
  4195. if ( geometry instanceof THREE.BufferGeometry ) {
  4196. var material = object.material;
  4197. if ( material === undefined ) return intersects;
  4198. var attributes = geometry.attributes;
  4199. var a, b, c;
  4200. var precision = raycaster.precision;
  4201. if ( attributes.index !== undefined ) {
  4202. var indices = attributes.index.array;
  4203. var positions = attributes.position.array;
  4204. var offsets = geometry.offsets;
  4205. if ( offsets.length === 0 ) {
  4206. offsets = [ { start: 0, count: positions.length, index: 0 } ];
  4207. }
  4208. for ( var oi = 0, ol = offsets.length; oi < ol; ++oi ) {
  4209. var start = offsets[ oi ].start;
  4210. var count = offsets[ oi ].count;
  4211. var index = offsets[ oi ].index;
  4212. for ( var i = start, il = start + count; i < il; i += 3 ) {
  4213. a = index + indices[ i ];
  4214. b = index + indices[ i + 1 ];
  4215. c = index + indices[ i + 2 ];
  4216. vA.set(
  4217. positions[ a * 3 ],
  4218. positions[ a * 3 + 1 ],
  4219. positions[ a * 3 + 2 ]
  4220. );
  4221. vB.set(
  4222. positions[ b * 3 ],
  4223. positions[ b * 3 + 1 ],
  4224. positions[ b * 3 + 2 ]
  4225. );
  4226. vC.set(
  4227. positions[ c * 3 ],
  4228. positions[ c * 3 + 1 ],
  4229. positions[ c * 3 + 2 ]
  4230. );
  4231. if ( material.side === THREE.BackSide ) {
  4232. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4233. } else {
  4234. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4235. }
  4236. if ( intersectionPoint === null ) continue;
  4237. intersectionPoint.applyMatrix4( object.matrixWorld );
  4238. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4239. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4240. intersects.push( {
  4241. distance: distance,
  4242. point: intersectionPoint,
  4243. indices: [a, b, c],
  4244. face: null,
  4245. faceIndex: null,
  4246. object: object
  4247. } );
  4248. }
  4249. }
  4250. } else {
  4251. var offsets = geometry.offsets;
  4252. var positions = attributes.position.array;
  4253. for ( var i = 0, il = attributes.position.array.length; i < il; i += 3 ) {
  4254. a = i;
  4255. b = i + 1;
  4256. c = i + 2;
  4257. vA.set(
  4258. positions[ a * 3 ],
  4259. positions[ a * 3 + 1 ],
  4260. positions[ a * 3 + 2 ]
  4261. );
  4262. vB.set(
  4263. positions[ b * 3 ],
  4264. positions[ b * 3 + 1 ],
  4265. positions[ b * 3 + 2 ]
  4266. );
  4267. vC.set(
  4268. positions[ c * 3 ],
  4269. positions[ c * 3 + 1 ],
  4270. positions[ c * 3 + 2 ]
  4271. );
  4272. if ( material.side === THREE.BackSide ) {
  4273. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4274. } else {
  4275. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4276. }
  4277. if ( intersectionPoint === null ) continue;
  4278. intersectionPoint.applyMatrix4( object.matrixWorld );
  4279. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4280. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4281. intersects.push( {
  4282. distance: distance,
  4283. point: intersectionPoint,
  4284. indices: [a, b, c],
  4285. face: null,
  4286. faceIndex: null,
  4287. object: object
  4288. } );
  4289. }
  4290. }
  4291. } else if ( geometry instanceof THREE.Geometry ) {
  4292. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4293. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  4294. var a, b, c, d;
  4295. var precision = raycaster.precision;
  4296. var vertices = geometry.vertices;
  4297. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  4298. var face = geometry.faces[ f ];
  4299. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  4300. if ( material === undefined ) continue;
  4301. a = vertices[ face.a ];
  4302. b = vertices[ face.b ];
  4303. c = vertices[ face.c ];
  4304. if ( material.morphTargets === true ) {
  4305. var morphTargets = geometry.morphTargets;
  4306. var morphInfluences = object.morphTargetInfluences;
  4307. vA.set( 0, 0, 0 );
  4308. vB.set( 0, 0, 0 );
  4309. vC.set( 0, 0, 0 );
  4310. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  4311. var influence = morphInfluences[ t ];
  4312. if ( influence === 0 ) continue;
  4313. var targets = morphTargets[ t ].vertices;
  4314. vA.x += ( targets[ face.a ].x - a.x ) * influence;
  4315. vA.y += ( targets[ face.a ].y - a.y ) * influence;
  4316. vA.z += ( targets[ face.a ].z - a.z ) * influence;
  4317. vB.x += ( targets[ face.b ].x - b.x ) * influence;
  4318. vB.y += ( targets[ face.b ].y - b.y ) * influence;
  4319. vB.z += ( targets[ face.b ].z - b.z ) * influence;
  4320. vC.x += ( targets[ face.c ].x - c.x ) * influence;
  4321. vC.y += ( targets[ face.c ].y - c.y ) * influence;
  4322. vC.z += ( targets[ face.c ].z - c.z ) * influence;
  4323. }
  4324. vA.add( a );
  4325. vB.add( b );
  4326. vC.add( c );
  4327. a = vA;
  4328. b = vB;
  4329. c = vC;
  4330. }
  4331. if ( material.side === THREE.BackSide ) {
  4332. var intersectionPoint = localRay.intersectTriangle( c, b, a, true );
  4333. } else {
  4334. var intersectionPoint = localRay.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide );
  4335. }
  4336. if ( intersectionPoint === null ) continue;
  4337. intersectionPoint.applyMatrix4( object.matrixWorld );
  4338. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4339. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4340. intersects.push( {
  4341. distance: distance,
  4342. point: intersectionPoint,
  4343. face: face,
  4344. faceIndex: f,
  4345. object: object
  4346. } );
  4347. }
  4348. }
  4349. } else if ( object instanceof THREE.Line ) {
  4350. var precision = raycaster.linePrecision;
  4351. var precisionSq = precision * precision;
  4352. var geometry = object.geometry;
  4353. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4354. // Checking boundingSphere distance to ray
  4355. sphere.copy( geometry.boundingSphere );
  4356. sphere.applyMatrix4( object.matrixWorld );
  4357. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4358. return intersects;
  4359. }
  4360. inverseMatrix.getInverse( object.matrixWorld );
  4361. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4362. /* if ( geometry instanceof THREE.BufferGeometry ) {
  4363. } else */ if ( geometry instanceof THREE.Geometry ) {
  4364. var vertices = geometry.vertices;
  4365. var nbVertices = vertices.length;
  4366. var interSegment = new THREE.Vector3();
  4367. var interRay = new THREE.Vector3();
  4368. var step = object.type === THREE.LineStrip ? 1 : 2;
  4369. for ( var i = 0; i < nbVertices - 1; i = i + step ) {
  4370. var distSq = localRay.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  4371. if ( distSq > precisionSq ) continue;
  4372. var distance = localRay.origin.distanceTo( interRay );
  4373. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  4374. intersects.push( {
  4375. distance: distance,
  4376. // What do we want? intersection point on the ray or on the segment??
  4377. // point: raycaster.ray.at( distance ),
  4378. point: interSegment.clone().applyMatrix4( object.matrixWorld ),
  4379. face: null,
  4380. faceIndex: null,
  4381. object: object
  4382. } );
  4383. }
  4384. }
  4385. }
  4386. };
  4387. var intersectDescendants = function ( object, raycaster, intersects ) {
  4388. var descendants = object.getDescendants();
  4389. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  4390. intersectObject( descendants[ i ], raycaster, intersects );
  4391. }
  4392. };
  4393. //
  4394. THREE.Raycaster.prototype.precision = 0.0001;
  4395. THREE.Raycaster.prototype.linePrecision = 1;
  4396. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  4397. this.ray.set( origin, direction );
  4398. // direction is assumed to be normalized (for accurate distance calculations)
  4399. };
  4400. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  4401. var intersects = [];
  4402. if ( recursive === true ) {
  4403. intersectDescendants( object, this, intersects );
  4404. }
  4405. intersectObject( object, this, intersects );
  4406. intersects.sort( descSort );
  4407. return intersects;
  4408. };
  4409. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  4410. var intersects = [];
  4411. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4412. intersectObject( objects[ i ], this, intersects );
  4413. if ( recursive === true ) {
  4414. intersectDescendants( objects[ i ], this, intersects );
  4415. }
  4416. }
  4417. intersects.sort( descSort );
  4418. return intersects;
  4419. };
  4420. }( THREE ) );
  4421. /**
  4422. * @author mrdoob / http://mrdoob.com/
  4423. * @author mikael emtinger / http://gomo.se/
  4424. * @author alteredq / http://alteredqualia.com/
  4425. * @author WestLangley / http://github.com/WestLangley
  4426. */
  4427. THREE.Object3D = function () {
  4428. this.id = THREE.Object3DIdCount ++;
  4429. this.uuid = THREE.Math.generateUUID();
  4430. this.name = '';
  4431. this.parent = undefined;
  4432. this.children = [];
  4433. this.up = new THREE.Vector3( 0, 1, 0 );
  4434. this.position = new THREE.Vector3();
  4435. var scope = this;
  4436. Object.defineProperties( this, {
  4437. rotation: {
  4438. enumerable: true,
  4439. value: new THREE.Euler().onChange( function () {
  4440. scope.quaternion.setFromEuler( scope.rotation, false );
  4441. } )
  4442. },
  4443. quaternion: {
  4444. enumerable: true,
  4445. value: new THREE.Quaternion().onChange( function () {
  4446. scope.rotation.setFromQuaternion( scope.quaternion, undefined, false );
  4447. } )
  4448. },
  4449. scale: {
  4450. enumerable: true,
  4451. value: new THREE.Vector3( 1, 1, 1 )
  4452. }
  4453. } );
  4454. this.renderDepth = null;
  4455. this.rotationAutoUpdate = true;
  4456. this.matrix = new THREE.Matrix4();
  4457. this.matrixWorld = new THREE.Matrix4();
  4458. this.matrixAutoUpdate = true;
  4459. this.matrixWorldNeedsUpdate = false;
  4460. this.visible = true;
  4461. this.castShadow = false;
  4462. this.receiveShadow = false;
  4463. this.frustumCulled = true;
  4464. this.userData = {};
  4465. };
  4466. THREE.Object3D.prototype = {
  4467. constructor: THREE.Object3D,
  4468. get eulerOrder () {
  4469. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4470. return this.rotation.order;
  4471. },
  4472. set eulerOrder ( value ) {
  4473. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4474. this.rotation.order = value;
  4475. },
  4476. get useQuaternion () {
  4477. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4478. },
  4479. set useQuaternion ( value ) {
  4480. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4481. },
  4482. applyMatrix: function ( matrix ) {
  4483. this.matrix.multiplyMatrices( matrix, this.matrix );
  4484. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4485. },
  4486. setRotationFromAxisAngle: function ( axis, angle ) {
  4487. // assumes axis is normalized
  4488. this.quaternion.setFromAxisAngle( axis, angle );
  4489. },
  4490. setRotationFromEuler: function ( euler ) {
  4491. this.quaternion.setFromEuler( euler, true );
  4492. },
  4493. setRotationFromMatrix: function ( m ) {
  4494. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4495. this.quaternion.setFromRotationMatrix( m );
  4496. },
  4497. setRotationFromQuaternion: function ( q ) {
  4498. // assumes q is normalized
  4499. this.quaternion.copy( q );
  4500. },
  4501. rotateOnAxis: function() {
  4502. // rotate object on axis in object space
  4503. // axis is assumed to be normalized
  4504. var q1 = new THREE.Quaternion();
  4505. return function ( axis, angle ) {
  4506. q1.setFromAxisAngle( axis, angle );
  4507. this.quaternion.multiply( q1 );
  4508. return this;
  4509. }
  4510. }(),
  4511. rotateX: function () {
  4512. var v1 = new THREE.Vector3( 1, 0, 0 );
  4513. return function ( angle ) {
  4514. return this.rotateOnAxis( v1, angle );
  4515. };
  4516. }(),
  4517. rotateY: function () {
  4518. var v1 = new THREE.Vector3( 0, 1, 0 );
  4519. return function ( angle ) {
  4520. return this.rotateOnAxis( v1, angle );
  4521. };
  4522. }(),
  4523. rotateZ: function () {
  4524. var v1 = new THREE.Vector3( 0, 0, 1 );
  4525. return function ( angle ) {
  4526. return this.rotateOnAxis( v1, angle );
  4527. };
  4528. }(),
  4529. translateOnAxis: function () {
  4530. // translate object by distance along axis in object space
  4531. // axis is assumed to be normalized
  4532. var v1 = new THREE.Vector3();
  4533. return function ( axis, distance ) {
  4534. v1.copy( axis );
  4535. v1.applyQuaternion( this.quaternion );
  4536. this.position.add( v1.multiplyScalar( distance ) );
  4537. return this;
  4538. }
  4539. }(),
  4540. translate: function ( distance, axis ) {
  4541. console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
  4542. return this.translateOnAxis( axis, distance );
  4543. },
  4544. translateX: function () {
  4545. var v1 = new THREE.Vector3( 1, 0, 0 );
  4546. return function ( distance ) {
  4547. return this.translateOnAxis( v1, distance );
  4548. };
  4549. }(),
  4550. translateY: function () {
  4551. var v1 = new THREE.Vector3( 0, 1, 0 );
  4552. return function ( distance ) {
  4553. return this.translateOnAxis( v1, distance );
  4554. };
  4555. }(),
  4556. translateZ: function () {
  4557. var v1 = new THREE.Vector3( 0, 0, 1 );
  4558. return function ( distance ) {
  4559. return this.translateOnAxis( v1, distance );
  4560. };
  4561. }(),
  4562. localToWorld: function ( vector ) {
  4563. return vector.applyMatrix4( this.matrixWorld );
  4564. },
  4565. worldToLocal: function () {
  4566. var m1 = new THREE.Matrix4();
  4567. return function ( vector ) {
  4568. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4569. };
  4570. }(),
  4571. lookAt: function () {
  4572. // This routine does not support objects with rotated and/or translated parent(s)
  4573. var m1 = new THREE.Matrix4();
  4574. return function ( vector ) {
  4575. m1.lookAt( vector, this.position, this.up );
  4576. this.quaternion.setFromRotationMatrix( m1 );
  4577. };
  4578. }(),
  4579. add: function ( object ) {
  4580. if ( object === this ) {
  4581. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  4582. return;
  4583. }
  4584. if ( object instanceof THREE.Object3D ) {
  4585. if ( object.parent !== undefined ) {
  4586. object.parent.remove( object );
  4587. }
  4588. object.parent = this;
  4589. object.dispatchEvent( { type: 'added' } );
  4590. this.children.push( object );
  4591. // add to scene
  4592. var scene = this;
  4593. while ( scene.parent !== undefined ) {
  4594. scene = scene.parent;
  4595. }
  4596. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4597. scene.__addObject( object );
  4598. }
  4599. }
  4600. },
  4601. remove: function ( object ) {
  4602. var index = this.children.indexOf( object );
  4603. if ( index !== - 1 ) {
  4604. object.parent = undefined;
  4605. object.dispatchEvent( { type: 'removed' } );
  4606. this.children.splice( index, 1 );
  4607. // remove from scene
  4608. var scene = this;
  4609. while ( scene.parent !== undefined ) {
  4610. scene = scene.parent;
  4611. }
  4612. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4613. scene.__removeObject( object );
  4614. }
  4615. }
  4616. },
  4617. traverse: function ( callback ) {
  4618. callback( this );
  4619. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4620. this.children[ i ].traverse( callback );
  4621. }
  4622. },
  4623. getObjectById: function ( id, recursive ) {
  4624. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4625. var child = this.children[ i ];
  4626. if ( child.id === id ) {
  4627. return child;
  4628. }
  4629. if ( recursive === true ) {
  4630. child = child.getObjectById( id, recursive );
  4631. if ( child !== undefined ) {
  4632. return child;
  4633. }
  4634. }
  4635. }
  4636. return undefined;
  4637. },
  4638. getObjectByName: function ( name, recursive ) {
  4639. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4640. var child = this.children[ i ];
  4641. if ( child.name === name ) {
  4642. return child;
  4643. }
  4644. if ( recursive === true ) {
  4645. child = child.getObjectByName( name, recursive );
  4646. if ( child !== undefined ) {
  4647. return child;
  4648. }
  4649. }
  4650. }
  4651. return undefined;
  4652. },
  4653. getChildByName: function ( name, recursive ) {
  4654. console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
  4655. return this.getObjectByName( name, recursive );
  4656. },
  4657. getDescendants: function ( array ) {
  4658. if ( array === undefined ) array = [];
  4659. Array.prototype.push.apply( array, this.children );
  4660. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4661. this.children[ i ].getDescendants( array );
  4662. }
  4663. return array;
  4664. },
  4665. updateMatrix: function () {
  4666. this.matrix.compose( this.position, this.quaternion, this.scale );
  4667. this.matrixWorldNeedsUpdate = true;
  4668. },
  4669. updateMatrixWorld: function ( force ) {
  4670. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4671. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4672. if ( this.parent === undefined ) {
  4673. this.matrixWorld.copy( this.matrix );
  4674. } else {
  4675. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4676. }
  4677. this.matrixWorldNeedsUpdate = false;
  4678. force = true;
  4679. }
  4680. // update children
  4681. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4682. this.children[ i ].updateMatrixWorld( force );
  4683. }
  4684. },
  4685. clone: function ( object, recursive ) {
  4686. if ( object === undefined ) object = new THREE.Object3D();
  4687. if ( recursive === undefined ) recursive = true;
  4688. object.name = this.name;
  4689. object.up.copy( this.up );
  4690. object.position.copy( this.position );
  4691. object.quaternion.copy( this.quaternion );
  4692. object.scale.copy( this.scale );
  4693. object.renderDepth = this.renderDepth;
  4694. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4695. object.matrix.copy( this.matrix );
  4696. object.matrixWorld.copy( this.matrixWorld );
  4697. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4698. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4699. object.visible = this.visible;
  4700. object.castShadow = this.castShadow;
  4701. object.receiveShadow = this.receiveShadow;
  4702. object.frustumCulled = this.frustumCulled;
  4703. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4704. if ( recursive === true ) {
  4705. for ( var i = 0; i < this.children.length; i ++ ) {
  4706. var child = this.children[ i ];
  4707. object.add( child.clone() );
  4708. }
  4709. }
  4710. return object;
  4711. }
  4712. };
  4713. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  4714. THREE.Object3DIdCount = 0;
  4715. /**
  4716. * @author mrdoob / http://mrdoob.com/
  4717. * @author supereggbert / http://www.paulbrunt.co.uk/
  4718. * @author julianwa / https://github.com/julianwa
  4719. */
  4720. THREE.Projector = function () {
  4721. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  4722. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  4723. _face, _faceCount, _facePool = [], _facePoolLength = 0,
  4724. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  4725. _sprite, _spriteCount, _spritePool = [], _spritePoolLength = 0,
  4726. _renderData = { objects: [], lights: [], elements: [] },
  4727. _vA = new THREE.Vector3(),
  4728. _vB = new THREE.Vector3(),
  4729. _vC = new THREE.Vector3(),
  4730. _vector3 = new THREE.Vector3(),
  4731. _vector4 = new THREE.Vector4(),
  4732. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  4733. _boundingBox = new THREE.Box3(),
  4734. _points3 = new Array( 3 ),
  4735. _points4 = new Array( 4 ),
  4736. _viewMatrix = new THREE.Matrix4(),
  4737. _viewProjectionMatrix = new THREE.Matrix4(),
  4738. _modelMatrix,
  4739. _modelViewProjectionMatrix = new THREE.Matrix4(),
  4740. _normalMatrix = new THREE.Matrix3(),
  4741. _frustum = new THREE.Frustum(),
  4742. _clippedVertex1PositionScreen = new THREE.Vector4(),
  4743. _clippedVertex2PositionScreen = new THREE.Vector4();
  4744. this.projectVector = function ( vector, camera ) {
  4745. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4746. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  4747. return vector.applyProjection( _viewProjectionMatrix );
  4748. };
  4749. this.unprojectVector = function () {
  4750. var projectionMatrixInverse = new THREE.Matrix4();
  4751. return function ( vector, camera ) {
  4752. projectionMatrixInverse.getInverse( camera.projectionMatrix );
  4753. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, projectionMatrixInverse );
  4754. return vector.applyProjection( _viewProjectionMatrix );
  4755. };
  4756. }();
  4757. this.pickingRay = function ( vector, camera ) {
  4758. // set two vectors with opposing z values
  4759. vector.z = -1.0;
  4760. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4761. this.unprojectVector( vector, camera );
  4762. this.unprojectVector( end, camera );
  4763. // find direction from vector to end
  4764. end.sub( vector ).normalize();
  4765. return new THREE.Raycaster( vector, end );
  4766. };
  4767. var projectObject = function ( object ) {
  4768. if ( object.visible === false ) return;
  4769. if ( object instanceof THREE.Light ) {
  4770. _renderData.lights.push( object );
  4771. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Sprite ) {
  4772. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4773. _object = getNextObjectInPool();
  4774. _object.id = object.id;
  4775. _object.object = object;
  4776. if ( object.renderDepth !== null ) {
  4777. _object.z = object.renderDepth;
  4778. } else {
  4779. _vector3.setFromMatrixPosition( object.matrixWorld );
  4780. _vector3.applyProjection( _viewProjectionMatrix );
  4781. _object.z = _vector3.z;
  4782. }
  4783. _renderData.objects.push( _object );
  4784. }
  4785. }
  4786. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  4787. projectObject( object.children[ i ] );
  4788. }
  4789. };
  4790. var projectGraph = function ( root, sortObjects ) {
  4791. _objectCount = 0;
  4792. _renderData.objects.length = 0;
  4793. _renderData.lights.length = 0;
  4794. projectObject( root );
  4795. if ( sortObjects === true ) {
  4796. _renderData.objects.sort( painterSort );
  4797. }
  4798. };
  4799. var RenderList = function () {
  4800. var normals = [];
  4801. var uvs = [];
  4802. var object = null;
  4803. var material = null;
  4804. var normalMatrix = new THREE.Matrix3();
  4805. var setObject = function ( value ) {
  4806. object = value;
  4807. material = object.material;
  4808. normalMatrix.getNormalMatrix( object.matrixWorld );
  4809. normals.length = 0;
  4810. uvs.length = 0;
  4811. };
  4812. var projectVertex = function ( vertex ) {
  4813. var position = vertex.position;
  4814. var positionWorld = vertex.positionWorld;
  4815. var positionScreen = vertex.positionScreen;
  4816. positionWorld.copy( position ).applyMatrix4( _modelMatrix );
  4817. positionScreen.copy( positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4818. var invW = 1 / positionScreen.w;
  4819. positionScreen.x *= invW;
  4820. positionScreen.y *= invW;
  4821. positionScreen.z *= invW;
  4822. vertex.visible = positionScreen.x >= -1 && positionScreen.x <= 1 &&
  4823. positionScreen.y >= -1 && positionScreen.y <= 1 &&
  4824. positionScreen.z >= -1 && positionScreen.z <= 1;
  4825. };
  4826. var pushVertex = function ( x, y, z ) {
  4827. _vertex = getNextVertexInPool();
  4828. _vertex.position.set( x, y, z );
  4829. projectVertex( _vertex );
  4830. };
  4831. var pushNormal = function ( x, y, z ) {
  4832. normals.push( x, y, z );
  4833. };
  4834. var pushUv = function ( x, y ) {
  4835. uvs.push( x, y );
  4836. };
  4837. var checkTriangleVisibility = function ( v1, v2, v3 ) {
  4838. if ( v1.visible === true || v2.visible === true || v3.visible === true ) return true;
  4839. _points3[ 0 ] = v1.positionScreen;
  4840. _points3[ 1 ] = v2.positionScreen;
  4841. _points3[ 2 ] = v3.positionScreen;
  4842. return _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) );
  4843. };
  4844. var checkBackfaceCulling = function ( v1, v2, v3 ) {
  4845. return ( ( v3.positionScreen.x - v1.positionScreen.x ) *
  4846. ( v2.positionScreen.y - v1.positionScreen.y ) -
  4847. ( v3.positionScreen.y - v1.positionScreen.y ) *
  4848. ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4849. };
  4850. var pushLine = function ( a, b ) {
  4851. var v1 = _vertexPool[ a ];
  4852. var v2 = _vertexPool[ b ];
  4853. _line = getNextLineInPool();
  4854. _line.id = object.id;
  4855. _line.v1.copy( v1 );
  4856. _line.v2.copy( v2 );
  4857. _line.z = ( v1.positionScreen.z + v2.positionScreen.z ) / 2;
  4858. _line.material = object.material;
  4859. _renderData.elements.push( _line );
  4860. };
  4861. var pushTriangle = function ( a, b, c ) {
  4862. var v1 = _vertexPool[ a ];
  4863. var v2 = _vertexPool[ b ];
  4864. var v3 = _vertexPool[ c ];
  4865. if ( checkTriangleVisibility( v1, v2, v3 ) === false ) return;
  4866. if ( material.side === THREE.DoubleSide || checkBackfaceCulling( v1, v2, v3 ) === true ) {
  4867. _face = getNextFaceInPool();
  4868. _face.id = object.id;
  4869. _face.v1.copy( v1 );
  4870. _face.v2.copy( v2 );
  4871. _face.v3.copy( v3 );
  4872. _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
  4873. for ( var i = 0; i < 3; i ++ ) {
  4874. var offset = arguments[ i ] * 3;
  4875. var normal = _face.vertexNormalsModel[ i ];
  4876. normal.set( normals[ offset ], normals[ offset + 1 ], normals[ offset + 2 ] );
  4877. normal.applyMatrix3( normalMatrix ).normalize();
  4878. var offset2 = arguments[ i ] * 2;
  4879. var uv = _face.uvs[ i ];
  4880. uv.set( uvs[ offset2 ], uvs[ offset2 + 1 ] );
  4881. }
  4882. _face.vertexNormalsLength = 3;
  4883. _face.material = object.material;
  4884. _renderData.elements.push( _face );
  4885. }
  4886. };
  4887. return {
  4888. setObject: setObject,
  4889. projectVertex: projectVertex,
  4890. checkTriangleVisibility: checkTriangleVisibility,
  4891. checkBackfaceCulling: checkBackfaceCulling,
  4892. pushVertex: pushVertex,
  4893. pushNormal: pushNormal,
  4894. pushUv: pushUv,
  4895. pushLine: pushLine,
  4896. pushTriangle: pushTriangle
  4897. }
  4898. };
  4899. var renderList = new RenderList();
  4900. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4901. var object, geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs,
  4902. isFaceMaterial, objectMaterials;
  4903. _faceCount = 0;
  4904. _lineCount = 0;
  4905. _spriteCount = 0;
  4906. _renderData.elements.length = 0;
  4907. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4908. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4909. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4910. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4911. _frustum.setFromMatrix( _viewProjectionMatrix );
  4912. projectGraph( scene, sortObjects );
  4913. for ( var o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4914. object = _renderData.objects[ o ].object;
  4915. geometry = object.geometry;
  4916. renderList.setObject( object );
  4917. _modelMatrix = object.matrixWorld;
  4918. _vertexCount = 0;
  4919. if ( object instanceof THREE.Mesh ) {
  4920. if ( geometry instanceof THREE.BufferGeometry ) {
  4921. var attributes = geometry.attributes;
  4922. var offsets = geometry.offsets;
  4923. if ( attributes.position === undefined ) continue;
  4924. var positions = attributes.position.array;
  4925. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  4926. renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  4927. }
  4928. if ( attributes.normal !== undefined ) {
  4929. var normals = attributes.normal.array;
  4930. for ( var i = 0, l = normals.length; i < l; i += 3 ) {
  4931. renderList.pushNormal( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] );
  4932. }
  4933. }
  4934. if ( attributes.uv !== undefined ) {
  4935. var uvs = attributes.uv.array;
  4936. for ( var i = 0, l = uvs.length; i < l; i += 2 ) {
  4937. renderList.pushUv( uvs[ i ], uvs[ i + 1 ] );
  4938. }
  4939. }
  4940. if ( attributes.index !== undefined ) {
  4941. var indices = attributes.index.array;
  4942. if ( offsets.length > 0 ) {
  4943. for ( var o = 0; o < offsets.length; o ++ ) {
  4944. var offset = offsets[ o ];
  4945. var index = offset.index;
  4946. for ( var i = offset.start, l = offset.start + offset.count; i < l; i += 3 ) {
  4947. renderList.pushTriangle( indices[ i ] + index, indices[ i + 1 ] + index, indices[ i + 2 ] + index );
  4948. }
  4949. }
  4950. } else {
  4951. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  4952. renderList.pushTriangle( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  4953. }
  4954. }
  4955. } else {
  4956. for ( var i = 0, l = positions.length / 3; i < l; i += 3 ) {
  4957. renderList.pushTriangle( i, i + 1, i + 2 );
  4958. }
  4959. }
  4960. } else if ( geometry instanceof THREE.Geometry ) {
  4961. vertices = geometry.vertices;
  4962. faces = geometry.faces;
  4963. faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  4964. _normalMatrix.getNormalMatrix( _modelMatrix );
  4965. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4966. objectMaterials = isFaceMaterial === true ? object.material : null;
  4967. for ( var v = 0, vl = vertices.length; v < vl; v ++ ) {
  4968. var vertex = vertices[ v ];
  4969. renderList.pushVertex( vertex.x, vertex.y, vertex.z );
  4970. }
  4971. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  4972. face = faces[ f ];
  4973. var material = isFaceMaterial === true
  4974. ? objectMaterials.materials[ face.materialIndex ]
  4975. : object.material;
  4976. if ( material === undefined ) continue;
  4977. var side = material.side;
  4978. var v1 = _vertexPool[ face.a ];
  4979. var v2 = _vertexPool[ face.b ];
  4980. var v3 = _vertexPool[ face.c ];
  4981. if ( material.morphTargets === true ) {
  4982. var morphTargets = geometry.morphTargets;
  4983. var morphInfluences = object.morphTargetInfluences;
  4984. var v1p = v1.position;
  4985. var v2p = v2.position;
  4986. var v3p = v3.position;
  4987. _vA.set( 0, 0, 0 );
  4988. _vB.set( 0, 0, 0 );
  4989. _vC.set( 0, 0, 0 );
  4990. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  4991. var influence = morphInfluences[ t ];
  4992. if ( influence === 0 ) continue;
  4993. var targets = morphTargets[ t ].vertices;
  4994. _vA.x += ( targets[ face.a ].x - v1p.x ) * influence;
  4995. _vA.y += ( targets[ face.a ].y - v1p.y ) * influence;
  4996. _vA.z += ( targets[ face.a ].z - v1p.z ) * influence;
  4997. _vB.x += ( targets[ face.b ].x - v2p.x ) * influence;
  4998. _vB.y += ( targets[ face.b ].y - v2p.y ) * influence;
  4999. _vB.z += ( targets[ face.b ].z - v2p.z ) * influence;
  5000. _vC.x += ( targets[ face.c ].x - v3p.x ) * influence;
  5001. _vC.y += ( targets[ face.c ].y - v3p.y ) * influence;
  5002. _vC.z += ( targets[ face.c ].z - v3p.z ) * influence;
  5003. }
  5004. v1.position.add( _vA );
  5005. v2.position.add( _vB );
  5006. v3.position.add( _vC );
  5007. renderList.projectVertex( v1 );
  5008. renderList.projectVertex( v2 );
  5009. renderList.projectVertex( v3 );
  5010. }
  5011. if ( renderList.checkTriangleVisibility( v1, v2, v3 ) === false ) continue;
  5012. var visible = renderList.checkBackfaceCulling( v1, v2, v3 );
  5013. if ( side !== THREE.DoubleSide ) {
  5014. if ( side === THREE.FrontSide && visible === false ) continue;
  5015. if ( side === THREE.BackSide && visible === true ) continue;
  5016. }
  5017. _face = getNextFaceInPool();
  5018. _face.id = object.id;
  5019. _face.v1.copy( v1 );
  5020. _face.v2.copy( v2 );
  5021. _face.v3.copy( v3 );
  5022. _face.normalModel.copy( face.normal );
  5023. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  5024. _face.normalModel.negate();
  5025. }
  5026. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  5027. faceVertexNormals = face.vertexNormals;
  5028. for ( var n = 0, nl = Math.min( faceVertexNormals.length, 3 ); n < nl; n ++ ) {
  5029. var normalModel = _face.vertexNormalsModel[ n ];
  5030. normalModel.copy( faceVertexNormals[ n ] );
  5031. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  5032. normalModel.negate();
  5033. }
  5034. normalModel.applyMatrix3( _normalMatrix ).normalize();
  5035. }
  5036. _face.vertexNormalsLength = faceVertexNormals.length;
  5037. var vertexUvs = faceVertexUvs[ f ];
  5038. if ( vertexUvs !== undefined ) {
  5039. for ( var u = 0; u < 3; u ++ ) {
  5040. _face.uvs[ u ].copy( vertexUvs[ u ] );
  5041. }
  5042. }
  5043. _face.color = face.color;
  5044. _face.material = material;
  5045. _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
  5046. _renderData.elements.push( _face );
  5047. }
  5048. }
  5049. } else if ( object instanceof THREE.Line ) {
  5050. if ( geometry instanceof THREE.BufferGeometry ) {
  5051. var attributes = geometry.attributes;
  5052. if ( attributes.position !== undefined ) {
  5053. var positions = attributes.position.array;
  5054. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  5055. renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5056. }
  5057. if ( attributes.index !== undefined ) {
  5058. var indices = attributes.index.array;
  5059. for ( var i = 0, l = indices.length; i < l; i += 2 ) {
  5060. renderList.pushLine( indices[ i ], indices[ i + 1 ] );
  5061. }
  5062. } else {
  5063. for ( var i = 0, l = ( positions.length / 3 ) - 1; i < l; i ++ ) {
  5064. renderList.pushLine( i, i + 1 );
  5065. }
  5066. }
  5067. }
  5068. } else if ( geometry instanceof THREE.Geometry ) {
  5069. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  5070. vertices = object.geometry.vertices;
  5071. if ( vertices.length === 0 ) continue;
  5072. v1 = getNextVertexInPool();
  5073. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  5074. // Handle LineStrip and LinePieces
  5075. var step = object.type === THREE.LinePieces ? 2 : 1;
  5076. for ( var v = 1, vl = vertices.length; v < vl; v ++ ) {
  5077. v1 = getNextVertexInPool();
  5078. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  5079. if ( ( v + 1 ) % step > 0 ) continue;
  5080. v2 = _vertexPool[ _vertexCount - 2 ];
  5081. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  5082. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  5083. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  5084. // Perform the perspective divide
  5085. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  5086. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  5087. _line = getNextLineInPool();
  5088. _line.id = object.id;
  5089. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  5090. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  5091. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  5092. _line.material = object.material;
  5093. if ( object.material.vertexColors === THREE.VertexColors ) {
  5094. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  5095. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  5096. }
  5097. _renderData.elements.push( _line );
  5098. }
  5099. }
  5100. }
  5101. } else if ( object instanceof THREE.Sprite ) {
  5102. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  5103. _vector4.applyMatrix4( _viewProjectionMatrix );
  5104. var invW = 1 / _vector4.w;
  5105. _vector4.z *= invW;
  5106. if ( _vector4.z >= -1 && _vector4.z <= 1 ) {
  5107. _sprite = getNextSpriteInPool();
  5108. _sprite.id = object.id;
  5109. _sprite.x = _vector4.x * invW;
  5110. _sprite.y = _vector4.y * invW;
  5111. _sprite.z = _vector4.z;
  5112. _sprite.object = object;
  5113. _sprite.rotation = object.rotation;
  5114. _sprite.scale.x = object.scale.x * Math.abs( _sprite.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  5115. _sprite.scale.y = object.scale.y * Math.abs( _sprite.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  5116. _sprite.material = object.material;
  5117. _renderData.elements.push( _sprite );
  5118. }
  5119. }
  5120. }
  5121. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  5122. return _renderData;
  5123. };
  5124. // Pools
  5125. function getNextObjectInPool() {
  5126. if ( _objectCount === _objectPoolLength ) {
  5127. var object = new THREE.RenderableObject();
  5128. _objectPool.push( object );
  5129. _objectPoolLength ++;
  5130. _objectCount ++;
  5131. return object;
  5132. }
  5133. return _objectPool[ _objectCount ++ ];
  5134. }
  5135. function getNextVertexInPool() {
  5136. if ( _vertexCount === _vertexPoolLength ) {
  5137. var vertex = new THREE.RenderableVertex();
  5138. _vertexPool.push( vertex );
  5139. _vertexPoolLength ++;
  5140. _vertexCount ++;
  5141. return vertex;
  5142. }
  5143. return _vertexPool[ _vertexCount ++ ];
  5144. }
  5145. function getNextFaceInPool() {
  5146. if ( _faceCount === _facePoolLength ) {
  5147. var face = new THREE.RenderableFace();
  5148. _facePool.push( face );
  5149. _facePoolLength ++;
  5150. _faceCount ++;
  5151. return face;
  5152. }
  5153. return _facePool[ _faceCount ++ ];
  5154. }
  5155. function getNextLineInPool() {
  5156. if ( _lineCount === _linePoolLength ) {
  5157. var line = new THREE.RenderableLine();
  5158. _linePool.push( line );
  5159. _linePoolLength ++;
  5160. _lineCount ++
  5161. return line;
  5162. }
  5163. return _linePool[ _lineCount ++ ];
  5164. }
  5165. function getNextSpriteInPool() {
  5166. if ( _spriteCount === _spritePoolLength ) {
  5167. var sprite = new THREE.RenderableSprite();
  5168. _spritePool.push( sprite );
  5169. _spritePoolLength ++;
  5170. _spriteCount ++
  5171. return sprite;
  5172. }
  5173. return _spritePool[ _spriteCount ++ ];
  5174. }
  5175. //
  5176. function painterSort( a, b ) {
  5177. if ( a.z !== b.z ) {
  5178. return b.z - a.z;
  5179. } else if ( a.id !== b.id ) {
  5180. return a.id - b.id;
  5181. } else {
  5182. return 0;
  5183. }
  5184. }
  5185. function clipLine( s1, s2 ) {
  5186. var alpha1 = 0, alpha2 = 1,
  5187. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  5188. // Z = -1 and Z = +1, respectively.
  5189. bc1near = s1.z + s1.w,
  5190. bc2near = s2.z + s2.w,
  5191. bc1far = - s1.z + s1.w,
  5192. bc2far = - s2.z + s2.w;
  5193. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  5194. // Both vertices lie entirely within all clip planes.
  5195. return true;
  5196. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  5197. // Both vertices lie entirely outside one of the clip planes.
  5198. return false;
  5199. } else {
  5200. // The line segment spans at least one clip plane.
  5201. if ( bc1near < 0 ) {
  5202. // v1 lies outside the near plane, v2 inside
  5203. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  5204. } else if ( bc2near < 0 ) {
  5205. // v2 lies outside the near plane, v1 inside
  5206. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  5207. }
  5208. if ( bc1far < 0 ) {
  5209. // v1 lies outside the far plane, v2 inside
  5210. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  5211. } else if ( bc2far < 0 ) {
  5212. // v2 lies outside the far plane, v2 inside
  5213. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  5214. }
  5215. if ( alpha2 < alpha1 ) {
  5216. // The line segment spans two boundaries, but is outside both of them.
  5217. // (This can't happen when we're only clipping against just near/far but good
  5218. // to leave the check here for future usage if other clip planes are added.)
  5219. return false;
  5220. } else {
  5221. // Update the s1 and s2 vertices to match the clipped line segment.
  5222. s1.lerp( s2, alpha1 );
  5223. s2.lerp( s1, 1 - alpha2 );
  5224. return true;
  5225. }
  5226. }
  5227. }
  5228. };
  5229. /**
  5230. * @author mrdoob / http://mrdoob.com/
  5231. * @author alteredq / http://alteredqualia.com/
  5232. */
  5233. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  5234. this.a = a;
  5235. this.b = b;
  5236. this.c = c;
  5237. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  5238. this.vertexNormals = normal instanceof Array ? normal : [ ];
  5239. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  5240. this.vertexColors = color instanceof Array ? color : [];
  5241. this.vertexTangents = [];
  5242. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  5243. };
  5244. THREE.Face3.prototype = {
  5245. constructor: THREE.Face3,
  5246. clone: function () {
  5247. var face = new THREE.Face3( this.a, this.b, this.c );
  5248. face.normal.copy( this.normal );
  5249. face.color.copy( this.color );
  5250. face.materialIndex = this.materialIndex;
  5251. var i, il;
  5252. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  5253. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  5254. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  5255. return face;
  5256. }
  5257. };
  5258. /**
  5259. * @author mrdoob / http://mrdoob.com/
  5260. */
  5261. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  5262. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.')
  5263. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  5264. };
  5265. /**
  5266. * @author mrdoob / http://mrdoob.com/
  5267. */
  5268. THREE.BufferAttribute = function () {};
  5269. THREE.BufferAttribute.prototype = {
  5270. constructor: THREE.BufferAttribute,
  5271. get length () {
  5272. return this.array.length;
  5273. },
  5274. set: function ( value ) {
  5275. this.array.set( value );
  5276. },
  5277. setX: function ( index, x ) {
  5278. this.array[ index * this.itemSize ] = x;
  5279. },
  5280. setY: function ( index, y ) {
  5281. this.array[ index * this.itemSize + 1 ] = y;
  5282. },
  5283. setZ: function ( index, z ) {
  5284. this.array[ index * this.itemSize + 2 ] = z;
  5285. },
  5286. setXY: function ( index, x, y ) {
  5287. index *= this.itemSize;
  5288. this.array[ index ] = x;
  5289. this.array[ index + 1 ] = y;
  5290. },
  5291. setXYZ: function ( index, x, y, z ) {
  5292. index *= this.itemSize;
  5293. this.array[ index ] = x;
  5294. this.array[ index + 1 ] = y;
  5295. this.array[ index + 2 ] = z;
  5296. },
  5297. setXYZW: function ( index, x, y, z, w ) {
  5298. index *= this.itemSize;
  5299. this.array[ index ] = x;
  5300. this.array[ index + 1 ] = y;
  5301. this.array[ index + 2 ] = z;
  5302. this.array[ index + 3 ] = w;
  5303. }
  5304. };
  5305. //
  5306. THREE.Int8Attribute = function ( size, itemSize ) {
  5307. this.array = new Int8Array( size * itemSize );
  5308. this.itemSize = itemSize;
  5309. };
  5310. THREE.Int8Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5311. THREE.Uint8Attribute = function ( size, itemSize ) {
  5312. this.array = new Uint8Array( size * itemSize );
  5313. this.itemSize = itemSize;
  5314. };
  5315. THREE.Uint8Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5316. THREE.Uint8ClampedAttribute = function ( size, itemSize ) {
  5317. this.array = new Uint8ClampedArray( size * itemSize );
  5318. this.itemSize = itemSize;
  5319. };
  5320. THREE.Uint8ClampedAttribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5321. THREE.Int16Attribute = function ( size, itemSize ) {
  5322. this.array = new Int16Array( size * itemSize );
  5323. this.itemSize = itemSize;
  5324. };
  5325. THREE.Int16Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5326. THREE.Uint16Attribute = function ( size, itemSize ) {
  5327. this.array = new Uint16Array( size * itemSize );
  5328. this.itemSize = itemSize;
  5329. };
  5330. THREE.Uint16Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5331. THREE.Int32Attribute = function ( size, itemSize ) {
  5332. this.array = new Int32Array( size * itemSize );
  5333. this.itemSize = itemSize;
  5334. };
  5335. THREE.Int32Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5336. THREE.Uint32Attribute = function ( size, itemSize ) {
  5337. this.array = new Uint32Array( size * itemSize );
  5338. this.itemSize = itemSize;
  5339. };
  5340. THREE.Uint32Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5341. THREE.Float32Attribute = function ( size, itemSize ) {
  5342. this.array = new Float32Array( size * itemSize );
  5343. this.itemSize = itemSize;
  5344. };
  5345. THREE.Float32Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5346. THREE.Float64Attribute = function ( size, itemSize ) {
  5347. this.array = new Float64Array( size * itemSize );
  5348. this.itemSize = itemSize;
  5349. };
  5350. THREE.Float64Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5351. /**
  5352. * @author alteredq / http://alteredqualia.com/
  5353. */
  5354. THREE.BufferGeometry = function () {
  5355. this.id = THREE.GeometryIdCount ++;
  5356. this.uuid = THREE.Math.generateUUID();
  5357. this.name = '';
  5358. this.attributes = {};
  5359. this.drawcalls = [];
  5360. this.offsets = this.drawcalls; // backwards compatibility
  5361. this.boundingBox = null;
  5362. this.boundingSphere = null;
  5363. };
  5364. THREE.BufferGeometry.prototype = {
  5365. constructor: THREE.BufferGeometry,
  5366. addAttribute: function ( name, attribute ) {
  5367. if ( attribute instanceof THREE.BufferAttribute === false ) {
  5368. console.warn( 'DEPRECATED: BufferGeometry\'s addAttribute() now expects ( name, attribute ).' );
  5369. this.attributes[ name ] = { array: arguments[ 1 ], itemSize: arguments[ 2 ] };
  5370. return;
  5371. }
  5372. this.attributes[ name ] = attribute;
  5373. },
  5374. getAttribute: function ( name ) {
  5375. return this.attributes[ name ];
  5376. },
  5377. addDrawCall: function ( start, count, indexOffset ) {
  5378. this.drawcalls.push( {
  5379. start: start,
  5380. count: count,
  5381. index: indexOffset !== undefined ? indexOffset : 0
  5382. } );
  5383. },
  5384. applyMatrix: function ( matrix ) {
  5385. var position = this.attributes.position;
  5386. if ( position !== undefined ) {
  5387. matrix.applyToVector3Array( position.array );
  5388. position.needsUpdate = true;
  5389. }
  5390. var normal = this.attributes.normal;
  5391. if ( normal !== undefined ) {
  5392. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5393. normalMatrix.applyToVector3Array( normal.array );
  5394. normal.needsUpdate = true;
  5395. }
  5396. },
  5397. computeBoundingBox: function () {
  5398. if ( this.boundingBox === null ) {
  5399. this.boundingBox = new THREE.Box3();
  5400. }
  5401. var positions = this.attributes[ "position" ].array;
  5402. if ( positions ) {
  5403. var bb = this.boundingBox;
  5404. if( positions.length >= 3 ) {
  5405. bb.min.x = bb.max.x = positions[ 0 ];
  5406. bb.min.y = bb.max.y = positions[ 1 ];
  5407. bb.min.z = bb.max.z = positions[ 2 ];
  5408. }
  5409. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  5410. var x = positions[ i ];
  5411. var y = positions[ i + 1 ];
  5412. var z = positions[ i + 2 ];
  5413. // bounding box
  5414. if ( x < bb.min.x ) {
  5415. bb.min.x = x;
  5416. } else if ( x > bb.max.x ) {
  5417. bb.max.x = x;
  5418. }
  5419. if ( y < bb.min.y ) {
  5420. bb.min.y = y;
  5421. } else if ( y > bb.max.y ) {
  5422. bb.max.y = y;
  5423. }
  5424. if ( z < bb.min.z ) {
  5425. bb.min.z = z;
  5426. } else if ( z > bb.max.z ) {
  5427. bb.max.z = z;
  5428. }
  5429. }
  5430. }
  5431. if ( positions === undefined || positions.length === 0 ) {
  5432. this.boundingBox.min.set( 0, 0, 0 );
  5433. this.boundingBox.max.set( 0, 0, 0 );
  5434. }
  5435. },
  5436. computeBoundingSphere: function () {
  5437. var box = new THREE.Box3();
  5438. var vector = new THREE.Vector3();
  5439. return function () {
  5440. if ( this.boundingSphere === null ) {
  5441. this.boundingSphere = new THREE.Sphere();
  5442. }
  5443. var positions = this.attributes[ "position" ].array;
  5444. if ( positions ) {
  5445. box.makeEmpty();
  5446. var center = this.boundingSphere.center;
  5447. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5448. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5449. box.addPoint( vector );
  5450. }
  5451. box.center( center );
  5452. // hoping to find a boundingSphere with a radius smaller than the
  5453. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  5454. var maxRadiusSq = 0;
  5455. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5456. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5457. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  5458. }
  5459. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5460. }
  5461. }
  5462. }(),
  5463. computeFaceNormals: function () {
  5464. // backwards compatibility
  5465. },
  5466. computeVertexNormals: function () {
  5467. if ( this.attributes[ "position" ] ) {
  5468. var i, il;
  5469. var j, jl;
  5470. var nVertexElements = this.attributes[ "position" ].array.length;
  5471. if ( this.attributes[ "normal" ] === undefined ) {
  5472. this.attributes[ "normal" ] = {
  5473. itemSize: 3,
  5474. array: new Float32Array( nVertexElements )
  5475. };
  5476. } else {
  5477. // reset existing normals to zero
  5478. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  5479. this.attributes[ "normal" ].array[ i ] = 0;
  5480. }
  5481. }
  5482. var positions = this.attributes[ "position" ].array;
  5483. var normals = this.attributes[ "normal" ].array;
  5484. var vA, vB, vC, x, y, z,
  5485. pA = new THREE.Vector3(),
  5486. pB = new THREE.Vector3(),
  5487. pC = new THREE.Vector3(),
  5488. cb = new THREE.Vector3(),
  5489. ab = new THREE.Vector3();
  5490. // indexed elements
  5491. if ( this.attributes[ "index" ] ) {
  5492. var indices = this.attributes[ "index" ].array;
  5493. var offsets = this.offsets;
  5494. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5495. var start = offsets[ j ].start;
  5496. var count = offsets[ j ].count;
  5497. var index = offsets[ j ].index;
  5498. for ( i = start, il = start + count; i < il; i += 3 ) {
  5499. vA = index + indices[ i ];
  5500. vB = index + indices[ i + 1 ];
  5501. vC = index + indices[ i + 2 ];
  5502. x = positions[ vA * 3 ];
  5503. y = positions[ vA * 3 + 1 ];
  5504. z = positions[ vA * 3 + 2 ];
  5505. pA.set( x, y, z );
  5506. x = positions[ vB * 3 ];
  5507. y = positions[ vB * 3 + 1 ];
  5508. z = positions[ vB * 3 + 2 ];
  5509. pB.set( x, y, z );
  5510. x = positions[ vC * 3 ];
  5511. y = positions[ vC * 3 + 1 ];
  5512. z = positions[ vC * 3 + 2 ];
  5513. pC.set( x, y, z );
  5514. cb.subVectors( pC, pB );
  5515. ab.subVectors( pA, pB );
  5516. cb.cross( ab );
  5517. normals[ vA * 3 ] += cb.x;
  5518. normals[ vA * 3 + 1 ] += cb.y;
  5519. normals[ vA * 3 + 2 ] += cb.z;
  5520. normals[ vB * 3 ] += cb.x;
  5521. normals[ vB * 3 + 1 ] += cb.y;
  5522. normals[ vB * 3 + 2 ] += cb.z;
  5523. normals[ vC * 3 ] += cb.x;
  5524. normals[ vC * 3 + 1 ] += cb.y;
  5525. normals[ vC * 3 + 2 ] += cb.z;
  5526. }
  5527. }
  5528. // non-indexed elements (unconnected triangle soup)
  5529. } else {
  5530. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5531. x = positions[ i ];
  5532. y = positions[ i + 1 ];
  5533. z = positions[ i + 2 ];
  5534. pA.set( x, y, z );
  5535. x = positions[ i + 3 ];
  5536. y = positions[ i + 4 ];
  5537. z = positions[ i + 5 ];
  5538. pB.set( x, y, z );
  5539. x = positions[ i + 6 ];
  5540. y = positions[ i + 7 ];
  5541. z = positions[ i + 8 ];
  5542. pC.set( x, y, z );
  5543. cb.subVectors( pC, pB );
  5544. ab.subVectors( pA, pB );
  5545. cb.cross( ab );
  5546. normals[ i ] = cb.x;
  5547. normals[ i + 1 ] = cb.y;
  5548. normals[ i + 2 ] = cb.z;
  5549. normals[ i + 3 ] = cb.x;
  5550. normals[ i + 4 ] = cb.y;
  5551. normals[ i + 5 ] = cb.z;
  5552. normals[ i + 6 ] = cb.x;
  5553. normals[ i + 7 ] = cb.y;
  5554. normals[ i + 8 ] = cb.z;
  5555. }
  5556. }
  5557. this.normalizeNormals();
  5558. this.normalsNeedUpdate = true;
  5559. }
  5560. },
  5561. normalizeNormals: function () {
  5562. var normals = this.attributes[ "normal" ].array;
  5563. var x, y, z, n;
  5564. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5565. x = normals[ i ];
  5566. y = normals[ i + 1 ];
  5567. z = normals[ i + 2 ];
  5568. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5569. normals[ i ] *= n;
  5570. normals[ i + 1 ] *= n;
  5571. normals[ i + 2 ] *= n;
  5572. }
  5573. },
  5574. computeTangents: function () {
  5575. // based on http://www.terathon.com/code/tangent.html
  5576. // (per vertex tangents)
  5577. if ( this.attributes[ "index" ] === undefined ||
  5578. this.attributes[ "position" ] === undefined ||
  5579. this.attributes[ "normal" ] === undefined ||
  5580. this.attributes[ "uv" ] === undefined ) {
  5581. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5582. return;
  5583. }
  5584. var indices = this.attributes[ "index" ].array;
  5585. var positions = this.attributes[ "position" ].array;
  5586. var normals = this.attributes[ "normal" ].array;
  5587. var uvs = this.attributes[ "uv" ].array;
  5588. var nVertices = positions.length / 3;
  5589. if ( this.attributes[ "tangent" ] === undefined ) {
  5590. var nTangentElements = 4 * nVertices;
  5591. this.attributes[ "tangent" ] = {
  5592. itemSize: 4,
  5593. array: new Float32Array( nTangentElements )
  5594. };
  5595. }
  5596. var tangents = this.attributes[ "tangent" ].array;
  5597. var tan1 = [], tan2 = [];
  5598. for ( var k = 0; k < nVertices; k ++ ) {
  5599. tan1[ k ] = new THREE.Vector3();
  5600. tan2[ k ] = new THREE.Vector3();
  5601. }
  5602. var xA, yA, zA,
  5603. xB, yB, zB,
  5604. xC, yC, zC,
  5605. uA, vA,
  5606. uB, vB,
  5607. uC, vC,
  5608. x1, x2, y1, y2, z1, z2,
  5609. s1, s2, t1, t2, r;
  5610. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5611. function handleTriangle( a, b, c ) {
  5612. xA = positions[ a * 3 ];
  5613. yA = positions[ a * 3 + 1 ];
  5614. zA = positions[ a * 3 + 2 ];
  5615. xB = positions[ b * 3 ];
  5616. yB = positions[ b * 3 + 1 ];
  5617. zB = positions[ b * 3 + 2 ];
  5618. xC = positions[ c * 3 ];
  5619. yC = positions[ c * 3 + 1 ];
  5620. zC = positions[ c * 3 + 2 ];
  5621. uA = uvs[ a * 2 ];
  5622. vA = uvs[ a * 2 + 1 ];
  5623. uB = uvs[ b * 2 ];
  5624. vB = uvs[ b * 2 + 1 ];
  5625. uC = uvs[ c * 2 ];
  5626. vC = uvs[ c * 2 + 1 ];
  5627. x1 = xB - xA;
  5628. x2 = xC - xA;
  5629. y1 = yB - yA;
  5630. y2 = yC - yA;
  5631. z1 = zB - zA;
  5632. z2 = zC - zA;
  5633. s1 = uB - uA;
  5634. s2 = uC - uA;
  5635. t1 = vB - vA;
  5636. t2 = vC - vA;
  5637. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5638. sdir.set(
  5639. ( t2 * x1 - t1 * x2 ) * r,
  5640. ( t2 * y1 - t1 * y2 ) * r,
  5641. ( t2 * z1 - t1 * z2 ) * r
  5642. );
  5643. tdir.set(
  5644. ( s1 * x2 - s2 * x1 ) * r,
  5645. ( s1 * y2 - s2 * y1 ) * r,
  5646. ( s1 * z2 - s2 * z1 ) * r
  5647. );
  5648. tan1[ a ].add( sdir );
  5649. tan1[ b ].add( sdir );
  5650. tan1[ c ].add( sdir );
  5651. tan2[ a ].add( tdir );
  5652. tan2[ b ].add( tdir );
  5653. tan2[ c ].add( tdir );
  5654. }
  5655. var i, il;
  5656. var j, jl;
  5657. var iA, iB, iC;
  5658. var offsets = this.offsets;
  5659. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5660. var start = offsets[ j ].start;
  5661. var count = offsets[ j ].count;
  5662. var index = offsets[ j ].index;
  5663. for ( i = start, il = start + count; i < il; i += 3 ) {
  5664. iA = index + indices[ i ];
  5665. iB = index + indices[ i + 1 ];
  5666. iC = index + indices[ i + 2 ];
  5667. handleTriangle( iA, iB, iC );
  5668. }
  5669. }
  5670. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5671. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5672. var w, t, test;
  5673. function handleVertex( v ) {
  5674. n.x = normals[ v * 3 ];
  5675. n.y = normals[ v * 3 + 1 ];
  5676. n.z = normals[ v * 3 + 2 ];
  5677. n2.copy( n );
  5678. t = tan1[ v ];
  5679. // Gram-Schmidt orthogonalize
  5680. tmp.copy( t );
  5681. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5682. // Calculate handedness
  5683. tmp2.crossVectors( n2, t );
  5684. test = tmp2.dot( tan2[ v ] );
  5685. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5686. tangents[ v * 4 ] = tmp.x;
  5687. tangents[ v * 4 + 1 ] = tmp.y;
  5688. tangents[ v * 4 + 2 ] = tmp.z;
  5689. tangents[ v * 4 + 3 ] = w;
  5690. }
  5691. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5692. var start = offsets[ j ].start;
  5693. var count = offsets[ j ].count;
  5694. var index = offsets[ j ].index;
  5695. for ( i = start, il = start + count; i < il; i += 3 ) {
  5696. iA = index + indices[ i ];
  5697. iB = index + indices[ i + 1 ];
  5698. iC = index + indices[ i + 2 ];
  5699. handleVertex( iA );
  5700. handleVertex( iB );
  5701. handleVertex( iC );
  5702. }
  5703. }
  5704. },
  5705. /*
  5706. computeOffsets
  5707. Compute the draw offset for large models by chunking the index buffer into chunks of 65k addressable vertices.
  5708. This method will effectively rewrite the index buffer and remap all attributes to match the new indices.
  5709. WARNING: This method will also expand the vertex count to prevent sprawled triangles across draw offsets.
  5710. indexBufferSize - Defaults to 65535, but allows for larger or smaller chunks.
  5711. */
  5712. computeOffsets: function(indexBufferSize) {
  5713. var size = indexBufferSize;
  5714. if(indexBufferSize === undefined)
  5715. size = 65535; //WebGL limits type of index buffer values to 16-bit.
  5716. var s = Date.now();
  5717. var indices = this.attributes['index'].array;
  5718. var vertices = this.attributes['position'].array;
  5719. var verticesCount = (vertices.length/3);
  5720. var facesCount = (indices.length/3);
  5721. /*
  5722. console.log("Computing buffers in offsets of "+size+" -> indices:"+indices.length+" vertices:"+vertices.length);
  5723. console.log("Faces to process: "+(indices.length/3));
  5724. console.log("Reordering "+verticesCount+" vertices.");
  5725. */
  5726. var sortedIndices = new Uint16Array( indices.length ); //16-bit buffers
  5727. var indexPtr = 0;
  5728. var vertexPtr = 0;
  5729. var offsets = [ { start:0, count:0, index:0 } ];
  5730. var offset = offsets[0];
  5731. var duplicatedVertices = 0;
  5732. var newVerticeMaps = 0;
  5733. var faceVertices = new Int32Array(6);
  5734. var vertexMap = new Int32Array( vertices.length );
  5735. var revVertexMap = new Int32Array( vertices.length );
  5736. for(var j = 0; j < vertices.length; j++) { vertexMap[j] = -1; revVertexMap[j] = -1; }
  5737. /*
  5738. Traverse every face and reorder vertices in the proper offsets of 65k.
  5739. We can have more than 65k entries in the index buffer per offset, but only reference 65k values.
  5740. */
  5741. for(var findex = 0; findex < facesCount; findex++) {
  5742. newVerticeMaps = 0;
  5743. for(var vo = 0; vo < 3; vo++) {
  5744. var vid = indices[ findex*3 + vo ];
  5745. if(vertexMap[vid] == -1) {
  5746. //Unmapped vertice
  5747. faceVertices[vo*2] = vid;
  5748. faceVertices[vo*2+1] = -1;
  5749. newVerticeMaps++;
  5750. } else if(vertexMap[vid] < offset.index) {
  5751. //Reused vertices from previous block (duplicate)
  5752. faceVertices[vo*2] = vid;
  5753. faceVertices[vo*2+1] = -1;
  5754. duplicatedVertices++;
  5755. } else {
  5756. //Reused vertice in the current block
  5757. faceVertices[vo*2] = vid;
  5758. faceVertices[vo*2+1] = vertexMap[vid];
  5759. }
  5760. }
  5761. var faceMax = vertexPtr + newVerticeMaps;
  5762. if(faceMax > (offset.index + size)) {
  5763. var new_offset = { start:indexPtr, count:0, index:vertexPtr };
  5764. offsets.push(new_offset);
  5765. offset = new_offset;
  5766. //Re-evaluate reused vertices in light of new offset.
  5767. for(var v = 0; v < 6; v+=2) {
  5768. var new_vid = faceVertices[v+1];
  5769. if(new_vid > -1 && new_vid < offset.index)
  5770. faceVertices[v+1] = -1;
  5771. }
  5772. }
  5773. //Reindex the face.
  5774. for(var v = 0; v < 6; v+=2) {
  5775. var vid = faceVertices[v];
  5776. var new_vid = faceVertices[v+1];
  5777. if(new_vid === -1)
  5778. new_vid = vertexPtr++;
  5779. vertexMap[vid] = new_vid;
  5780. revVertexMap[new_vid] = vid;
  5781. sortedIndices[indexPtr++] = new_vid - offset.index; //XXX overflows at 16bit
  5782. offset.count++;
  5783. }
  5784. }
  5785. /* Move all attribute values to map to the new computed indices , also expand the vertice stack to match our new vertexPtr. */
  5786. this.reorderBuffers(sortedIndices, revVertexMap, vertexPtr);
  5787. this.offsets = offsets;
  5788. /*
  5789. var orderTime = Date.now();
  5790. console.log("Reorder time: "+(orderTime-s)+"ms");
  5791. console.log("Duplicated "+duplicatedVertices+" vertices.");
  5792. console.log("Compute Buffers time: "+(Date.now()-s)+"ms");
  5793. console.log("Draw offsets: "+offsets.length);
  5794. */
  5795. return offsets;
  5796. },
  5797. /*
  5798. reoderBuffers:
  5799. Reorder attributes based on a new indexBuffer and indexMap.
  5800. indexBuffer - Uint16Array of the new ordered indices.
  5801. indexMap - Int32Array where the position is the new vertex ID and the value the old vertex ID for each vertex.
  5802. vertexCount - Amount of total vertices considered in this reordering (in case you want to grow the vertice stack).
  5803. */
  5804. reorderBuffers: function(indexBuffer, indexMap, vertexCount) {
  5805. /* Create a copy of all attributes for reordering. */
  5806. var sortedAttributes = {};
  5807. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  5808. for( var attr in this.attributes ) {
  5809. if(attr == 'index')
  5810. continue;
  5811. var sourceArray = this.attributes[attr].array;
  5812. for ( var i = 0, il = types.length; i < il; i++ ) {
  5813. var type = types[i];
  5814. if (sourceArray instanceof type) {
  5815. sortedAttributes[attr] = new type( this.attributes[attr].itemSize * vertexCount );
  5816. break;
  5817. }
  5818. }
  5819. }
  5820. /* Move attribute positions based on the new index map */
  5821. for(var new_vid = 0; new_vid < vertexCount; new_vid++) {
  5822. var vid = indexMap[new_vid];
  5823. for ( var attr in this.attributes ) {
  5824. if(attr == 'index')
  5825. continue;
  5826. var attrArray = this.attributes[attr].array;
  5827. var attrSize = this.attributes[attr].itemSize;
  5828. var sortedAttr = sortedAttributes[attr];
  5829. for(var k = 0; k < attrSize; k++)
  5830. sortedAttr[ new_vid * attrSize + k ] = attrArray[ vid * attrSize + k ];
  5831. }
  5832. }
  5833. /* Carry the new sorted buffers locally */
  5834. this.attributes['index'].array = indexBuffer;
  5835. for ( var attr in this.attributes ) {
  5836. if(attr == 'index')
  5837. continue;
  5838. this.attributes[attr].array = sortedAttributes[attr];
  5839. this.attributes[attr].numItems = this.attributes[attr].itemSize * vertexCount;
  5840. }
  5841. },
  5842. clone: function () {
  5843. var geometry = new THREE.BufferGeometry();
  5844. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  5845. for ( var attr in this.attributes ) {
  5846. var sourceAttr = this.attributes[ attr ];
  5847. var sourceArray = sourceAttr.array;
  5848. var attribute = {
  5849. itemSize: sourceAttr.itemSize,
  5850. array: null
  5851. };
  5852. for ( var i = 0, il = types.length; i < il; i ++ ) {
  5853. var type = types[ i ];
  5854. if ( sourceArray instanceof type ) {
  5855. attribute.array = new type( sourceArray );
  5856. break;
  5857. }
  5858. }
  5859. geometry.attributes[ attr ] = attribute;
  5860. }
  5861. for ( var i = 0, il = this.offsets.length; i < il; i ++ ) {
  5862. var offset = this.offsets[ i ];
  5863. geometry.offsets.push( {
  5864. start: offset.start,
  5865. index: offset.index,
  5866. count: offset.count
  5867. } );
  5868. }
  5869. return geometry;
  5870. },
  5871. dispose: function () {
  5872. this.dispatchEvent( { type: 'dispose' } );
  5873. }
  5874. };
  5875. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  5876. /**
  5877. * @author mrdoob / http://mrdoob.com/
  5878. */
  5879. THREE.BufferGeometryManipulator = function ( bufferGeometry ) {
  5880. this.vertices = [];
  5881. this.normals = [];
  5882. this.uvs = [];
  5883. var attributes = bufferGeometry.attributes;
  5884. var length = attributes.position.array.length / 3;
  5885. for ( var i = 0; i < length; i ++ ) {
  5886. this.vertices.push( new THREE.ProxyVector3( attributes.position.array, i * 3 ) );
  5887. this.normals.push( new THREE.ProxyVector3( attributes.normal.array, i * 3 ) );
  5888. this.uvs.push( new THREE.ProxyVector2( attributes.uv.array, i * 2 ) );
  5889. }
  5890. };
  5891. /**
  5892. * @author mrdoob / http://mrdoob.com/
  5893. * @author kile / http://kile.stravaganza.org/
  5894. * @author alteredq / http://alteredqualia.com/
  5895. * @author mikael emtinger / http://gomo.se/
  5896. * @author zz85 / http://www.lab4games.net/zz85/blog
  5897. * @author bhouston / http://exocortex.com
  5898. */
  5899. THREE.Geometry = function () {
  5900. this.id = THREE.GeometryIdCount ++;
  5901. this.uuid = THREE.Math.generateUUID();
  5902. this.name = '';
  5903. this.vertices = [];
  5904. this.colors = []; // one-to-one vertex colors, used in ParticleSystem and Line
  5905. this.faces = [];
  5906. this.faceVertexUvs = [[]];
  5907. this.morphTargets = [];
  5908. this.morphColors = [];
  5909. this.morphNormals = [];
  5910. this.skinWeights = [];
  5911. this.skinIndices = [];
  5912. this.lineDistances = [];
  5913. this.boundingBox = null;
  5914. this.boundingSphere = null;
  5915. this.hasTangents = false;
  5916. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  5917. // update flags
  5918. this.verticesNeedUpdate = false;
  5919. this.elementsNeedUpdate = false;
  5920. this.uvsNeedUpdate = false;
  5921. this.normalsNeedUpdate = false;
  5922. this.tangentsNeedUpdate = false;
  5923. this.colorsNeedUpdate = false;
  5924. this.lineDistancesNeedUpdate = false;
  5925. this.buffersNeedUpdate = false;
  5926. };
  5927. THREE.Geometry.prototype = {
  5928. constructor: THREE.Geometry,
  5929. applyMatrix: function ( matrix ) {
  5930. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5931. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  5932. var vertex = this.vertices[ i ];
  5933. vertex.applyMatrix4( matrix );
  5934. }
  5935. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  5936. var face = this.faces[ i ];
  5937. face.normal.applyMatrix3( normalMatrix ).normalize();
  5938. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  5939. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  5940. }
  5941. }
  5942. if ( this.boundingBox instanceof THREE.Box3 ) {
  5943. this.computeBoundingBox();
  5944. }
  5945. if ( this.boundingSphere instanceof THREE.Sphere ) {
  5946. this.computeBoundingSphere();
  5947. }
  5948. },
  5949. computeFaceNormals: function () {
  5950. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5951. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5952. var face = this.faces[ f ];
  5953. var vA = this.vertices[ face.a ];
  5954. var vB = this.vertices[ face.b ];
  5955. var vC = this.vertices[ face.c ];
  5956. cb.subVectors( vC, vB );
  5957. ab.subVectors( vA, vB );
  5958. cb.cross( ab );
  5959. cb.normalize();
  5960. face.normal.copy( cb );
  5961. }
  5962. },
  5963. computeVertexNormals: function ( areaWeighted ) {
  5964. var v, vl, f, fl, face, vertices;
  5965. vertices = new Array( this.vertices.length );
  5966. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5967. vertices[ v ] = new THREE.Vector3();
  5968. }
  5969. if ( areaWeighted ) {
  5970. // vertex normals weighted by triangle areas
  5971. // http://www.iquilezles.org/www/articles/normals/normals.htm
  5972. var vA, vB, vC, vD;
  5973. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  5974. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  5975. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5976. face = this.faces[ f ];
  5977. vA = this.vertices[ face.a ];
  5978. vB = this.vertices[ face.b ];
  5979. vC = this.vertices[ face.c ];
  5980. cb.subVectors( vC, vB );
  5981. ab.subVectors( vA, vB );
  5982. cb.cross( ab );
  5983. vertices[ face.a ].add( cb );
  5984. vertices[ face.b ].add( cb );
  5985. vertices[ face.c ].add( cb );
  5986. }
  5987. } else {
  5988. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5989. face = this.faces[ f ];
  5990. vertices[ face.a ].add( face.normal );
  5991. vertices[ face.b ].add( face.normal );
  5992. vertices[ face.c ].add( face.normal );
  5993. }
  5994. }
  5995. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5996. vertices[ v ].normalize();
  5997. }
  5998. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5999. face = this.faces[ f ];
  6000. face.vertexNormals[ 0 ] = vertices[ face.a ].clone();
  6001. face.vertexNormals[ 1 ] = vertices[ face.b ].clone();
  6002. face.vertexNormals[ 2 ] = vertices[ face.c ].clone();
  6003. }
  6004. },
  6005. computeMorphNormals: function () {
  6006. var i, il, f, fl, face;
  6007. // save original normals
  6008. // - create temp variables on first access
  6009. // otherwise just copy (for faster repeated calls)
  6010. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6011. face = this.faces[ f ];
  6012. if ( ! face.__originalFaceNormal ) {
  6013. face.__originalFaceNormal = face.normal.clone();
  6014. } else {
  6015. face.__originalFaceNormal.copy( face.normal );
  6016. }
  6017. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  6018. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  6019. if ( ! face.__originalVertexNormals[ i ] ) {
  6020. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  6021. } else {
  6022. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  6023. }
  6024. }
  6025. }
  6026. // use temp geometry to compute face and vertex normals for each morph
  6027. var tmpGeo = new THREE.Geometry();
  6028. tmpGeo.faces = this.faces;
  6029. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  6030. // create on first access
  6031. if ( ! this.morphNormals[ i ] ) {
  6032. this.morphNormals[ i ] = {};
  6033. this.morphNormals[ i ].faceNormals = [];
  6034. this.morphNormals[ i ].vertexNormals = [];
  6035. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  6036. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  6037. var faceNormal, vertexNormals;
  6038. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6039. face = this.faces[ f ];
  6040. faceNormal = new THREE.Vector3();
  6041. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  6042. dstNormalsFace.push( faceNormal );
  6043. dstNormalsVertex.push( vertexNormals );
  6044. }
  6045. }
  6046. var morphNormals = this.morphNormals[ i ];
  6047. // set vertices to morph target
  6048. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  6049. // compute morph normals
  6050. tmpGeo.computeFaceNormals();
  6051. tmpGeo.computeVertexNormals();
  6052. // store morph normals
  6053. var faceNormal, vertexNormals;
  6054. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6055. face = this.faces[ f ];
  6056. faceNormal = morphNormals.faceNormals[ f ];
  6057. vertexNormals = morphNormals.vertexNormals[ f ];
  6058. faceNormal.copy( face.normal );
  6059. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  6060. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  6061. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  6062. }
  6063. }
  6064. // restore original normals
  6065. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6066. face = this.faces[ f ];
  6067. face.normal = face.__originalFaceNormal;
  6068. face.vertexNormals = face.__originalVertexNormals;
  6069. }
  6070. },
  6071. computeTangents: function () {
  6072. // based on http://www.terathon.com/code/tangent.html
  6073. // tangents go to vertices
  6074. var f, fl, v, vl, i, il, vertexIndex,
  6075. face, uv, vA, vB, vC, uvA, uvB, uvC,
  6076. x1, x2, y1, y2, z1, z2,
  6077. s1, s2, t1, t2, r, t, test,
  6078. tan1 = [], tan2 = [],
  6079. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  6080. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  6081. n = new THREE.Vector3(), w;
  6082. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  6083. tan1[ v ] = new THREE.Vector3();
  6084. tan2[ v ] = new THREE.Vector3();
  6085. }
  6086. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  6087. vA = context.vertices[ a ];
  6088. vB = context.vertices[ b ];
  6089. vC = context.vertices[ c ];
  6090. uvA = uv[ ua ];
  6091. uvB = uv[ ub ];
  6092. uvC = uv[ uc ];
  6093. x1 = vB.x - vA.x;
  6094. x2 = vC.x - vA.x;
  6095. y1 = vB.y - vA.y;
  6096. y2 = vC.y - vA.y;
  6097. z1 = vB.z - vA.z;
  6098. z2 = vC.z - vA.z;
  6099. s1 = uvB.x - uvA.x;
  6100. s2 = uvC.x - uvA.x;
  6101. t1 = uvB.y - uvA.y;
  6102. t2 = uvC.y - uvA.y;
  6103. r = 1.0 / ( s1 * t2 - s2 * t1 );
  6104. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  6105. ( t2 * y1 - t1 * y2 ) * r,
  6106. ( t2 * z1 - t1 * z2 ) * r );
  6107. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  6108. ( s1 * y2 - s2 * y1 ) * r,
  6109. ( s1 * z2 - s2 * z1 ) * r );
  6110. tan1[ a ].add( sdir );
  6111. tan1[ b ].add( sdir );
  6112. tan1[ c ].add( sdir );
  6113. tan2[ a ].add( tdir );
  6114. tan2[ b ].add( tdir );
  6115. tan2[ c ].add( tdir );
  6116. }
  6117. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6118. face = this.faces[ f ];
  6119. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  6120. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  6121. }
  6122. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  6123. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6124. face = this.faces[ f ];
  6125. for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i++ ) {
  6126. n.copy( face.vertexNormals[ i ] );
  6127. vertexIndex = face[ faceIndex[ i ] ];
  6128. t = tan1[ vertexIndex ];
  6129. // Gram-Schmidt orthogonalize
  6130. tmp.copy( t );
  6131. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6132. // Calculate handedness
  6133. tmp2.crossVectors( face.vertexNormals[ i ], t );
  6134. test = tmp2.dot( tan2[ vertexIndex ] );
  6135. w = (test < 0.0) ? -1.0 : 1.0;
  6136. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  6137. }
  6138. }
  6139. this.hasTangents = true;
  6140. },
  6141. computeLineDistances: function ( ) {
  6142. var d = 0;
  6143. var vertices = this.vertices;
  6144. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6145. if ( i > 0 ) {
  6146. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  6147. }
  6148. this.lineDistances[ i ] = d;
  6149. }
  6150. },
  6151. computeBoundingBox: function () {
  6152. if ( this.boundingBox === null ) {
  6153. this.boundingBox = new THREE.Box3();
  6154. }
  6155. this.boundingBox.setFromPoints( this.vertices );
  6156. },
  6157. computeBoundingSphere: function () {
  6158. if ( this.boundingSphere === null ) {
  6159. this.boundingSphere = new THREE.Sphere();
  6160. }
  6161. this.boundingSphere.setFromPoints( this.vertices );
  6162. },
  6163. /*
  6164. * Checks for duplicate vertices with hashmap.
  6165. * Duplicated vertices are removed
  6166. * and faces' vertices are updated.
  6167. */
  6168. mergeVertices: function () {
  6169. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  6170. var unique = [], changes = [];
  6171. var v, key;
  6172. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  6173. var precision = Math.pow( 10, precisionPoints );
  6174. var i,il, face;
  6175. var indices, k, j, jl, u;
  6176. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  6177. v = this.vertices[ i ];
  6178. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  6179. if ( verticesMap[ key ] === undefined ) {
  6180. verticesMap[ key ] = i;
  6181. unique.push( this.vertices[ i ] );
  6182. changes[ i ] = unique.length - 1;
  6183. } else {
  6184. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  6185. changes[ i ] = changes[ verticesMap[ key ] ];
  6186. }
  6187. };
  6188. // if faces are completely degenerate after merging vertices, we
  6189. // have to remove them from the geometry.
  6190. var faceIndicesToRemove = [];
  6191. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  6192. face = this.faces[ i ];
  6193. face.a = changes[ face.a ];
  6194. face.b = changes[ face.b ];
  6195. face.c = changes[ face.c ];
  6196. indices = [ face.a, face.b, face.c ];
  6197. var dupIndex = -1;
  6198. // if any duplicate vertices are found in a Face3
  6199. // we have to remove the face as nothing can be saved
  6200. for ( var n = 0; n < 3; n ++ ) {
  6201. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  6202. dupIndex = n;
  6203. faceIndicesToRemove.push( i );
  6204. break;
  6205. }
  6206. }
  6207. }
  6208. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  6209. var idx = faceIndicesToRemove[ i ];
  6210. this.faces.splice( idx, 1 );
  6211. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  6212. this.faceVertexUvs[ j ].splice( idx, 1 );
  6213. }
  6214. }
  6215. // Use unique set of vertices
  6216. var diff = this.vertices.length - unique.length;
  6217. this.vertices = unique;
  6218. return diff;
  6219. },
  6220. // Geometry splitting
  6221. makeGroups: ( function () {
  6222. var geometryGroupCounter = 0;
  6223. return function ( usesFaceMaterial, maxVerticesInGroup ) {
  6224. var f, fl, face, materialIndex,
  6225. groupHash, hash_map = {};
  6226. var numMorphTargets = this.morphTargets.length;
  6227. var numMorphNormals = this.morphNormals.length;
  6228. this.geometryGroups = {};
  6229. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6230. face = this.faces[ f ];
  6231. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  6232. if ( ! ( materialIndex in hash_map ) ) {
  6233. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  6234. }
  6235. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  6236. if ( ! ( groupHash in this.geometryGroups ) ) {
  6237. this.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  6238. }
  6239. if ( this.geometryGroups[ groupHash ].vertices + 3 > maxVerticesInGroup ) {
  6240. hash_map[ materialIndex ].counter += 1;
  6241. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  6242. if ( ! ( groupHash in this.geometryGroups ) ) {
  6243. this.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  6244. }
  6245. }
  6246. this.geometryGroups[ groupHash ].faces3.push( f );
  6247. this.geometryGroups[ groupHash ].vertices += 3;
  6248. }
  6249. this.geometryGroupsList = [];
  6250. for ( var g in this.geometryGroups ) {
  6251. this.geometryGroups[ g ].id = geometryGroupCounter ++;
  6252. this.geometryGroupsList.push( this.geometryGroups[ g ] );
  6253. }
  6254. };
  6255. } )(),
  6256. clone: function () {
  6257. var geometry = new THREE.Geometry();
  6258. var vertices = this.vertices;
  6259. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6260. geometry.vertices.push( vertices[ i ].clone() );
  6261. }
  6262. var faces = this.faces;
  6263. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  6264. geometry.faces.push( faces[ i ].clone() );
  6265. }
  6266. var uvs = this.faceVertexUvs[ 0 ];
  6267. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  6268. var uv = uvs[ i ], uvCopy = [];
  6269. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  6270. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  6271. }
  6272. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  6273. }
  6274. return geometry;
  6275. },
  6276. dispose: function () {
  6277. this.dispatchEvent( { type: 'dispose' } );
  6278. }
  6279. };
  6280. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  6281. THREE.GeometryIdCount = 0;
  6282. /**
  6283. * @author mrdoob / http://mrdoob.com/
  6284. */
  6285. THREE.Geometry2 = function ( vertices, normals, uvs ) {
  6286. THREE.BufferGeometry.call( this );
  6287. this.attributes[ 'position' ] = { array: vertices, itemSize: 3 };
  6288. this.attributes[ 'normal' ] = { array: normals, itemSize: 3 };
  6289. this.attributes[ 'uv' ] = { array: uvs, itemSize: 2 };
  6290. };
  6291. THREE.Geometry2.prototype = Object.create( THREE.BufferGeometry.prototype );
  6292. THREE.Geometry99 = function ( ) {
  6293. THREE.BufferGeometry.call( this );
  6294. };
  6295. THREE.Geometry99.prototype = Object.create( THREE.BufferGeometry.prototype );
  6296. Object.defineProperties( THREE.Geometry99.prototype, {
  6297. vertices: {
  6298. enumerable: true,
  6299. get: function () { return this.createVertexProxies(); }
  6300. },
  6301. faces: {
  6302. enumerable: true,
  6303. get: function () { return this.createFaceProxies() }
  6304. },
  6305. faceVertexUvs: {
  6306. enumerable: true,
  6307. get: function () { return this.createUvProxies() }
  6308. },
  6309. // TODO - fill in additional proxies:
  6310. // - morphColors
  6311. // - morphNormals
  6312. // - morphTargets
  6313. // - skinIndex
  6314. // - skinWeights
  6315. verticesNeedUpdate: {
  6316. enumerable: true,
  6317. get: function () { return this.attributes[ 'position' ].needsUpdate; } ,
  6318. set: function ( v ) { this.attributes[ 'position' ].needsUpdate = v; }
  6319. },
  6320. colorsNeedUpdate: {
  6321. enumerable: true,
  6322. get: function () { if ( this.attributes[ 'color' ] ) return this.attributes[ 'color' ].needsUpdate; } ,
  6323. set: function ( v ) { if ( this.attributes[ 'color' ] ) this.attributes[ 'color' ].needsUpdate = v; }
  6324. },
  6325. normalsNeedUpdate: {
  6326. enumerable: true,
  6327. get: function () { if ( this.attributes[ 'normal' ] ) return this.attributes[ 'normal' ].needsUpdate; } ,
  6328. set: function ( v ) { if ( this.attributes[ 'normal' ] ) this.attributes[ 'normal' ].needsUpdate = v; }
  6329. },
  6330. });
  6331. THREE.Geometry99.prototype.createVertexProxies = function () {
  6332. // Replace the prototype getter with a local array property
  6333. Object.defineProperty( this, "vertices", { value: [] } );
  6334. // If the attribute buffer has already been populated, set up proxy objects
  6335. this.populateProxyFromBuffer( this.vertices, "position", THREE.TypedVector3, 3 );
  6336. // Return a reference to the newly-created array
  6337. return this.vertices;
  6338. }
  6339. THREE.Geometry99.prototype.createFaceProxies = function () {
  6340. // Replace the prototype getter with a local array property
  6341. Object.defineProperty( this, "faces", { value: [] } );
  6342. // If the attribute buffer has already been populated, set up proxy objects
  6343. var faces = this.faces,
  6344. indexarray = false,
  6345. positionarray = false,
  6346. normalarray = false,
  6347. colorarray = false;
  6348. if ( this.attributes.position ) {
  6349. positionarray = this.attributes[ 'position' ].array;
  6350. }
  6351. if ( this.attributes.index ) {
  6352. indexarray = this.attributes[ 'index' ].array;
  6353. }
  6354. if (this.attributes[ 'normal' ]) {
  6355. normalarray = this.attributes[ 'normal' ].array;
  6356. }
  6357. if (this.attributes[ 'color' ]) {
  6358. colorarray = this.attributes[ 'color' ].array;
  6359. }
  6360. if (indexarray) {
  6361. for ( var i = 0, l = indexarray.length / 3; i < l; i ++ ) {
  6362. var o = i * 3;
  6363. // Generate face.vertexNormals and face.vertexFaceColors
  6364. var vertexNormals = false,
  6365. vertexColors = false;
  6366. if (normalarray) {
  6367. vertexNormals = [
  6368. new THREE.TypedVector3(normalarray, indexarray[o] * 3),
  6369. new THREE.TypedVector3(normalarray, indexarray[o+1] * 3),
  6370. new THREE.TypedVector3(normalarray, indexarray[o+2] * 3),
  6371. ]
  6372. }
  6373. // TODO - do BufferGeometries support face normals?
  6374. if (colorarray) {
  6375. vertexColors = [
  6376. new THREE.TypedColor(colorarray, indexarray[o] * 3),
  6377. new THREE.TypedColor(colorarray, indexarray[o+1] * 3),
  6378. new THREE.TypedColor(colorarray, indexarray[o+2] * 3),
  6379. ]
  6380. }
  6381. var face = new THREE.TypedFace3( indexarray, i * 3, vertexNormals );
  6382. }
  6383. } else {
  6384. for ( var i = 0, l = positionarray.length / 3; i < l; i += 3 ) {
  6385. var o = i * 3;
  6386. var v1 = i, v2 = i+1, v3 = i+2;
  6387. // Generate face.vertexNormals and face.vertexColors
  6388. // TODO - do BufferGeometries support face normals/face colors?
  6389. // Maybe they could be implemented using some sort of TypedMultiVector3 which would let us expose a single
  6390. // face.normal Vector3, and it would simultaneously update the three vertexNormals involved in this face with the same values
  6391. var vertexNormals = false,
  6392. vertexColors = false;
  6393. if (normalarray) {
  6394. vertexNormals = [
  6395. new THREE.TypedVector3(normalarray, o),
  6396. new THREE.TypedVector3(normalarray, o+3),
  6397. new THREE.TypedVector3(normalarray, o+6),
  6398. ];
  6399. }
  6400. if (colorarray) {
  6401. vertexColors = [
  6402. new THREE.TypedColor(colorarray, o),
  6403. new THREE.TypedColor(colorarray, o+3),
  6404. new THREE.TypedColor(colorarray, o+6),
  6405. ];
  6406. }
  6407. var face = new THREE.Face3( v1, v2, v3, vertexNormals, vertexColors );
  6408. faces.push(face);
  6409. }
  6410. }
  6411. // Return a reference to the newly-created array
  6412. return this.faces;
  6413. }
  6414. THREE.Geometry99.prototype.createUvProxies = function () {
  6415. // Replace the prototype getter with a local array property
  6416. Object.defineProperty( this, "faceVertexUvs", { value: [[]] } );
  6417. // If the attribute buffer has already been populated, set up proxy objects
  6418. if ( this.attributes.uv ) {
  6419. var faces = this.faces;
  6420. var uvarray = this.attributes.uv.array;
  6421. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  6422. var f = faces[i];
  6423. this.faceVertexUvs[ 0 ][ i ] = [];
  6424. this.faceVertexUvs[ 0 ][ i ][ 0 ] = new THREE.TypedVector2( uvarray, f.a * 2 );
  6425. this.faceVertexUvs[ 0 ][ i ][ 1 ] = new THREE.TypedVector2( uvarray, f.b * 2 );
  6426. this.faceVertexUvs[ 0 ][ i ][ 2 ] = new THREE.TypedVector2( uvarray, f.c * 2 );
  6427. }
  6428. }
  6429. // Return a reference to the newly-created array
  6430. return this.faceVertexUvs;
  6431. }
  6432. THREE.Geometry99.prototype.populateProxyFromBuffer = function ( attr, buffername, proxytype, itemsize, offset, count ) {
  6433. if ( this.attributes[ buffername ] ) {
  6434. var array = this.attributes[ buffername ].array;
  6435. var size = itemsize || this.attributes[ buffername ].itemSize;
  6436. var start = offset || 0;
  6437. count = count || ( array.length / size - start );
  6438. for ( var i = start, l = start + count; i < l; i ++ ) {
  6439. attr.push( new proxytype( array, i * size ) );
  6440. }
  6441. }
  6442. }
  6443. // Proxies
  6444. THREE.TypedVector2 = function ( array, offset ) {
  6445. this.array = array;
  6446. this.offset = offset;
  6447. };
  6448. THREE.TypedVector2.prototype = Object.create( THREE.Vector2.prototype );
  6449. Object.defineProperties( THREE.TypedVector2.prototype, {
  6450. 'x': {
  6451. get: function () { return this.array[ this.offset ]; },
  6452. set: function ( v ) { this.array[ this.offset ] = v; }
  6453. },
  6454. 'y': {
  6455. get: function () { return this.array[ this.offset + 1 ]; },
  6456. set: function ( v ) { this.array[ this.offset + 1 ] = v; }
  6457. }
  6458. } );
  6459. //
  6460. THREE.TypedVector3 = function ( array, offset ) {
  6461. this.array = array;
  6462. this.offset = offset;
  6463. };
  6464. THREE.TypedVector3.prototype = Object.create( THREE.Vector3.prototype );
  6465. Object.defineProperties( THREE.TypedVector3.prototype, {
  6466. 'x': {
  6467. get: function () { return this.array[ this.offset ]; },
  6468. set: function ( v ) { this.array[ this.offset ] = v; }
  6469. },
  6470. 'y': {
  6471. get: function () { return this.array[ this.offset + 1 ]; },
  6472. set: function ( v ) { this.array[ this.offset + 1 ] = v; }
  6473. },
  6474. 'z': {
  6475. get: function () { return this.array[ this.offset + 2 ]; },
  6476. set: function ( v ) { this.array[ this.offset + 2 ] = v; }
  6477. }
  6478. } );
  6479. //
  6480. THREE.TypedFace3 = function ( array, offset, vertexNormals ) {
  6481. this.array = array;
  6482. this.offset = offset;
  6483. this.vertexNormals = vertexNormals;
  6484. //THREE.Face3.call( this, array[offset], array[offset+1], array[offset+2] /*, normal, color, materialIndex */);
  6485. }
  6486. THREE.TypedFace3.prototype = Object.create( THREE.Face3.prototype );
  6487. Object.defineProperties( THREE.TypedFace3.prototype, {
  6488. 'a': {
  6489. enumerable: true,
  6490. get: function () { return this.array[ this.offset ]; },
  6491. set: function ( v ) { this.array[ this.offset ] = v; }
  6492. },
  6493. 'b': {
  6494. enumerable: true,
  6495. get: function () { return this.array[ this.offset + 1 ]; },
  6496. set: function ( v ) { this.array[ this.offset + 1 ] = v; }
  6497. },
  6498. 'c': {
  6499. enumerable: true,
  6500. get: function () { return this.array[ this.offset + 2 ]; },
  6501. set: function ( v ) { this.array[ this.offset + 2 ] = v; }
  6502. },
  6503. } );
  6504. THREE.TypedColor = function ( array, offset ) {
  6505. this.array = array;
  6506. this.offset = offset;
  6507. }
  6508. THREE.TypedColor.prototype = Object.create( THREE.Color.prototype );
  6509. Object.defineProperties( THREE.TypedColor.prototype, {
  6510. 'r': {
  6511. enumerable: true,
  6512. get: function () { return this.array[ this.offset ]; },
  6513. set: function ( v ) { this.array[ this.offset ] = v; }
  6514. },
  6515. 'g': {
  6516. enumerable: true,
  6517. get: function () { return this.array[ this.offset + 1 ]; },
  6518. set: function ( v ) { this.array[ this.offset + 1 ] = v; }
  6519. },
  6520. 'b': {
  6521. enumerable: true,
  6522. get: function () { return this.array[ this.offset + 2 ]; },
  6523. set: function ( v ) { this.array[ this.offset + 2 ] = v; }
  6524. }
  6525. } );
  6526. /**
  6527. * @author mrdoob / http://mrdoob.com/
  6528. */
  6529. THREE.IndexedGeometry2 = function ( indices, vertices, normals, uvs ) {
  6530. THREE.BufferGeometry.call( this );
  6531. this.attributes[ 'index' ] = { array: indices, itemSize: 1 };
  6532. this.attributes[ 'position' ] = { array: vertices, itemSize: 3 };
  6533. this.attributes[ 'normal' ] = { array: normals, itemSize: 3 };
  6534. this.attributes[ 'uv' ] = { array: uvs, itemSize: 2 };
  6535. };
  6536. THREE.IndexedGeometry2.prototype = Object.create( THREE.Geometry99.prototype );
  6537. /**
  6538. * @author mrdoob / http://mrdoob.com/
  6539. * @author mikael emtinger / http://gomo.se/
  6540. * @author WestLangley / http://github.com/WestLangley
  6541. */
  6542. THREE.Camera = function () {
  6543. THREE.Object3D.call( this );
  6544. this.matrixWorldInverse = new THREE.Matrix4();
  6545. this.projectionMatrix = new THREE.Matrix4();
  6546. };
  6547. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  6548. THREE.Camera.prototype.lookAt = function () {
  6549. // This routine does not support cameras with rotated and/or translated parent(s)
  6550. var m1 = new THREE.Matrix4();
  6551. return function ( vector ) {
  6552. m1.lookAt( this.position, vector, this.up );
  6553. this.quaternion.setFromRotationMatrix( m1 );
  6554. };
  6555. }();
  6556. THREE.Camera.prototype.clone = function (camera) {
  6557. if ( camera === undefined ) camera = new THREE.Camera();
  6558. THREE.Object3D.prototype.clone.call( this, camera );
  6559. camera.matrixWorldInverse.copy( this.matrixWorldInverse );
  6560. camera.projectionMatrix.copy( this.projectionMatrix );
  6561. return camera;
  6562. };
  6563. /**
  6564. * @author alteredq / http://alteredqualia.com/
  6565. */
  6566. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  6567. THREE.Camera.call( this );
  6568. this.left = left;
  6569. this.right = right;
  6570. this.top = top;
  6571. this.bottom = bottom;
  6572. this.near = ( near !== undefined ) ? near : 0.1;
  6573. this.far = ( far !== undefined ) ? far : 2000;
  6574. this.updateProjectionMatrix();
  6575. };
  6576. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  6577. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  6578. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  6579. };
  6580. THREE.OrthographicCamera.prototype.clone = function () {
  6581. var camera = new THREE.OrthographicCamera();
  6582. THREE.Camera.prototype.clone.call( this, camera );
  6583. camera.left = this.left;
  6584. camera.right = this.right;
  6585. camera.top = this.top;
  6586. camera.bottom = this.bottom;
  6587. camera.near = this.near;
  6588. camera.far = this.far;
  6589. return camera;
  6590. };
  6591. /**
  6592. * @author mrdoob / http://mrdoob.com/
  6593. * @author greggman / http://games.greggman.com/
  6594. * @author zz85 / http://www.lab4games.net/zz85/blog
  6595. */
  6596. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  6597. THREE.Camera.call( this );
  6598. this.fov = fov !== undefined ? fov : 50;
  6599. this.aspect = aspect !== undefined ? aspect : 1;
  6600. this.near = near !== undefined ? near : 0.1;
  6601. this.far = far !== undefined ? far : 2000;
  6602. this.updateProjectionMatrix();
  6603. };
  6604. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  6605. /**
  6606. * Uses Focal Length (in mm) to estimate and set FOV
  6607. * 35mm (fullframe) camera is used if frame size is not specified;
  6608. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  6609. */
  6610. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  6611. if ( frameHeight === undefined ) frameHeight = 24;
  6612. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  6613. this.updateProjectionMatrix();
  6614. }
  6615. /**
  6616. * Sets an offset in a larger frustum. This is useful for multi-window or
  6617. * multi-monitor/multi-machine setups.
  6618. *
  6619. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6620. * the monitors are in grid like this
  6621. *
  6622. * +---+---+---+
  6623. * | A | B | C |
  6624. * +---+---+---+
  6625. * | D | E | F |
  6626. * +---+---+---+
  6627. *
  6628. * then for each monitor you would call it like this
  6629. *
  6630. * var w = 1920;
  6631. * var h = 1080;
  6632. * var fullWidth = w * 3;
  6633. * var fullHeight = h * 2;
  6634. *
  6635. * --A--
  6636. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6637. * --B--
  6638. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6639. * --C--
  6640. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6641. * --D--
  6642. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6643. * --E--
  6644. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  6645. * --F--
  6646. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  6647. *
  6648. * Note there is no reason monitors have to be the same size or in a grid.
  6649. */
  6650. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  6651. this.fullWidth = fullWidth;
  6652. this.fullHeight = fullHeight;
  6653. this.x = x;
  6654. this.y = y;
  6655. this.width = width;
  6656. this.height = height;
  6657. this.updateProjectionMatrix();
  6658. };
  6659. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  6660. if ( this.fullWidth ) {
  6661. var aspect = this.fullWidth / this.fullHeight;
  6662. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  6663. var bottom = -top;
  6664. var left = aspect * bottom;
  6665. var right = aspect * top;
  6666. var width = Math.abs( right - left );
  6667. var height = Math.abs( top - bottom );
  6668. this.projectionMatrix.makeFrustum(
  6669. left + this.x * width / this.fullWidth,
  6670. left + ( this.x + this.width ) * width / this.fullWidth,
  6671. top - ( this.y + this.height ) * height / this.fullHeight,
  6672. top - this.y * height / this.fullHeight,
  6673. this.near,
  6674. this.far
  6675. );
  6676. } else {
  6677. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  6678. }
  6679. };
  6680. THREE.PerspectiveCamera.prototype.clone = function () {
  6681. var camera = new THREE.PerspectiveCamera();
  6682. THREE.Camera.prototype.clone.call( this, camera );
  6683. camera.fov = this.fov;
  6684. camera.aspect = this.aspect;
  6685. camera.near = this.near;
  6686. camera.far = this.far;
  6687. return camera;
  6688. };
  6689. /**
  6690. * @author mrdoob / http://mrdoob.com/
  6691. * @author alteredq / http://alteredqualia.com/
  6692. */
  6693. THREE.Light = function ( color ) {
  6694. THREE.Object3D.call( this );
  6695. this.color = new THREE.Color( color );
  6696. };
  6697. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  6698. THREE.Light.prototype.clone = function ( light ) {
  6699. if ( light === undefined ) light = new THREE.Light();
  6700. THREE.Object3D.prototype.clone.call( this, light );
  6701. light.color.copy( this.color );
  6702. return light;
  6703. };
  6704. /**
  6705. * @author mrdoob / http://mrdoob.com/
  6706. */
  6707. THREE.AmbientLight = function ( color ) {
  6708. THREE.Light.call( this, color );
  6709. };
  6710. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  6711. THREE.AmbientLight.prototype.clone = function () {
  6712. var light = new THREE.AmbientLight();
  6713. THREE.Light.prototype.clone.call( this, light );
  6714. return light;
  6715. };
  6716. /**
  6717. * @author MPanknin / http://www.redplant.de/
  6718. * @author alteredq / http://alteredqualia.com/
  6719. */
  6720. THREE.AreaLight = function ( color, intensity ) {
  6721. THREE.Light.call( this, color );
  6722. this.normal = new THREE.Vector3( 0, -1, 0 );
  6723. this.right = new THREE.Vector3( 1, 0, 0 );
  6724. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6725. this.width = 1.0;
  6726. this.height = 1.0;
  6727. this.constantAttenuation = 1.5;
  6728. this.linearAttenuation = 0.5;
  6729. this.quadraticAttenuation = 0.1;
  6730. };
  6731. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  6732. /**
  6733. * @author mrdoob / http://mrdoob.com/
  6734. * @author alteredq / http://alteredqualia.com/
  6735. */
  6736. THREE.DirectionalLight = function ( color, intensity ) {
  6737. THREE.Light.call( this, color );
  6738. this.position.set( 0, 1, 0 );
  6739. this.target = new THREE.Object3D();
  6740. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6741. this.castShadow = false;
  6742. this.onlyShadow = false;
  6743. //
  6744. this.shadowCameraNear = 50;
  6745. this.shadowCameraFar = 5000;
  6746. this.shadowCameraLeft = -500;
  6747. this.shadowCameraRight = 500;
  6748. this.shadowCameraTop = 500;
  6749. this.shadowCameraBottom = -500;
  6750. this.shadowCameraVisible = false;
  6751. this.shadowBias = 0;
  6752. this.shadowDarkness = 0.5;
  6753. this.shadowMapWidth = 512;
  6754. this.shadowMapHeight = 512;
  6755. //
  6756. this.shadowCascade = false;
  6757. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  6758. this.shadowCascadeCount = 2;
  6759. this.shadowCascadeBias = [ 0, 0, 0 ];
  6760. this.shadowCascadeWidth = [ 512, 512, 512 ];
  6761. this.shadowCascadeHeight = [ 512, 512, 512 ];
  6762. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  6763. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  6764. this.shadowCascadeArray = [];
  6765. //
  6766. this.shadowMap = null;
  6767. this.shadowMapSize = null;
  6768. this.shadowCamera = null;
  6769. this.shadowMatrix = null;
  6770. };
  6771. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  6772. THREE.DirectionalLight.prototype.clone = function () {
  6773. var light = new THREE.DirectionalLight();
  6774. THREE.Light.prototype.clone.call( this, light );
  6775. light.target = this.target.clone();
  6776. light.intensity = this.intensity;
  6777. light.castShadow = this.castShadow;
  6778. light.onlyShadow = this.onlyShadow;
  6779. //
  6780. light.shadowCameraNear = this.shadowCameraNear;
  6781. light.shadowCameraFar = this.shadowCameraFar;
  6782. light.shadowCameraLeft = this.shadowCameraLeft;
  6783. light.shadowCameraRight = this.shadowCameraRight;
  6784. light.shadowCameraTop = this.shadowCameraTop;
  6785. light.shadowCameraBottom = this.shadowCameraBottom;
  6786. light.shadowCameraVisible = this.shadowCameraVisible;
  6787. light.shadowBias = this.shadowBias;
  6788. light.shadowDarkness = this.shadowDarkness;
  6789. light.shadowMapWidth = this.shadowMapWidth;
  6790. light.shadowMapHeight = this.shadowMapHeight;
  6791. //
  6792. light.shadowCascade = this.shadowCascade;
  6793. light.shadowCascadeOffset.copy( this.shadowCascadeOffset );
  6794. light.shadowCascadeCount = this.shadowCascadeCount;
  6795. light.shadowCascadeBias = this.shadowCascadeBias.slice( 0 );
  6796. light.shadowCascadeWidth = this.shadowCascadeWidth.slice( 0 );
  6797. light.shadowCascadeHeight = this.shadowCascadeHeight.slice( 0 );
  6798. light.shadowCascadeNearZ = this.shadowCascadeNearZ.slice( 0 );
  6799. light.shadowCascadeFarZ = this.shadowCascadeFarZ.slice( 0 );
  6800. return light;
  6801. };
  6802. /**
  6803. * @author alteredq / http://alteredqualia.com/
  6804. */
  6805. THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
  6806. THREE.Light.call( this, skyColor );
  6807. this.position.set( 0, 100, 0 );
  6808. this.groundColor = new THREE.Color( groundColor );
  6809. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6810. };
  6811. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  6812. THREE.HemisphereLight.prototype.clone = function () {
  6813. var light = new THREE.HemisphereLight();
  6814. THREE.Light.prototype.clone.call( this, light );
  6815. light.groundColor.copy( this.groundColor );
  6816. light.intensity = this.intensity;
  6817. return light;
  6818. };
  6819. /**
  6820. * @author mrdoob / http://mrdoob.com/
  6821. */
  6822. THREE.PointLight = function ( color, intensity, distance ) {
  6823. THREE.Light.call( this, color );
  6824. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6825. this.distance = ( distance !== undefined ) ? distance : 0;
  6826. };
  6827. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  6828. THREE.PointLight.prototype.clone = function () {
  6829. var light = new THREE.PointLight();
  6830. THREE.Light.prototype.clone.call( this, light );
  6831. light.intensity = this.intensity;
  6832. light.distance = this.distance;
  6833. return light;
  6834. };
  6835. /**
  6836. * @author alteredq / http://alteredqualia.com/
  6837. */
  6838. THREE.SpotLight = function ( color, intensity, distance, angle, exponent ) {
  6839. THREE.Light.call( this, color );
  6840. this.position.set( 0, 1, 0 );
  6841. this.target = new THREE.Object3D();
  6842. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6843. this.distance = ( distance !== undefined ) ? distance : 0;
  6844. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  6845. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  6846. this.castShadow = false;
  6847. this.onlyShadow = false;
  6848. //
  6849. this.shadowCameraNear = 50;
  6850. this.shadowCameraFar = 5000;
  6851. this.shadowCameraFov = 50;
  6852. this.shadowCameraVisible = false;
  6853. this.shadowBias = 0;
  6854. this.shadowDarkness = 0.5;
  6855. this.shadowMapWidth = 512;
  6856. this.shadowMapHeight = 512;
  6857. //
  6858. this.shadowMap = null;
  6859. this.shadowMapSize = null;
  6860. this.shadowCamera = null;
  6861. this.shadowMatrix = null;
  6862. };
  6863. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  6864. THREE.SpotLight.prototype.clone = function () {
  6865. var light = new THREE.SpotLight();
  6866. THREE.Light.prototype.clone.call( this, light );
  6867. light.target = this.target.clone();
  6868. light.intensity = this.intensity;
  6869. light.distance = this.distance;
  6870. light.angle = this.angle;
  6871. light.exponent = this.exponent;
  6872. light.castShadow = this.castShadow;
  6873. light.onlyShadow = this.onlyShadow;
  6874. //
  6875. light.shadowCameraNear = this.shadowCameraNear;
  6876. light.shadowCameraFar = this.shadowCameraFar;
  6877. light.shadowCameraFov = this.shadowCameraFov;
  6878. light.shadowCameraVisible = this.shadowCameraVisible;
  6879. light.shadowBias = this.shadowBias;
  6880. light.shadowDarkness = this.shadowDarkness;
  6881. light.shadowMapWidth = this.shadowMapWidth;
  6882. light.shadowMapHeight = this.shadowMapHeight;
  6883. return light;
  6884. };
  6885. /**
  6886. * @author mrdoob / http://mrdoob.com/
  6887. */
  6888. THREE.Cache = function () {
  6889. this.files = {};
  6890. };
  6891. THREE.Cache.prototype = {
  6892. constructor: THREE.Cache,
  6893. add: function ( key, file ) {
  6894. // console.log( 'THREE.Cache', 'Adding key:', key );
  6895. this.files[ key ] = file;
  6896. },
  6897. get: function ( key ) {
  6898. // console.log( 'THREE.Cache', 'Checking key:', key );
  6899. return this.files[ key ];
  6900. },
  6901. remove: function ( key ) {
  6902. delete this.files[ key ];
  6903. },
  6904. clear: function () {
  6905. this.files = {}
  6906. }
  6907. };
  6908. /**
  6909. * @author alteredq / http://alteredqualia.com/
  6910. */
  6911. THREE.Loader = function ( showStatus ) {
  6912. this.showStatus = showStatus;
  6913. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  6914. this.imageLoader = new THREE.ImageLoader();
  6915. this.onLoadStart = function () {};
  6916. this.onLoadProgress = function () {};
  6917. this.onLoadComplete = function () {};
  6918. };
  6919. THREE.Loader.prototype = {
  6920. constructor: THREE.Loader,
  6921. crossOrigin: undefined,
  6922. addStatusElement: function () {
  6923. var e = document.createElement( "div" );
  6924. e.style.position = "absolute";
  6925. e.style.right = "0px";
  6926. e.style.top = "0px";
  6927. e.style.fontSize = "0.8em";
  6928. e.style.textAlign = "left";
  6929. e.style.background = "rgba(0,0,0,0.25)";
  6930. e.style.color = "#fff";
  6931. e.style.width = "120px";
  6932. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  6933. e.style.zIndex = 1000;
  6934. e.innerHTML = "Loading ...";
  6935. return e;
  6936. },
  6937. updateProgress: function ( progress ) {
  6938. var message = "Loaded ";
  6939. if ( progress.total ) {
  6940. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  6941. } else {
  6942. message += ( progress.loaded / 1024 ).toFixed(2) + " KB";
  6943. }
  6944. this.statusDomElement.innerHTML = message;
  6945. },
  6946. extractUrlBase: function ( url ) {
  6947. var parts = url.split( '/' );
  6948. if ( parts.length === 1 ) return './';
  6949. parts.pop();
  6950. return parts.join( '/' ) + '/';
  6951. },
  6952. initMaterials: function ( materials, texturePath ) {
  6953. var array = [];
  6954. for ( var i = 0; i < materials.length; ++ i ) {
  6955. array[ i ] = this.createMaterial( materials[ i ], texturePath );
  6956. }
  6957. return array;
  6958. },
  6959. needsTangents: function ( materials ) {
  6960. for( var i = 0, il = materials.length; i < il; i ++ ) {
  6961. var m = materials[ i ];
  6962. if ( m instanceof THREE.ShaderMaterial ) return true;
  6963. }
  6964. return false;
  6965. },
  6966. createMaterial: function ( m, texturePath ) {
  6967. var scope = this;
  6968. function nearest_pow2( n ) {
  6969. var l = Math.log( n ) / Math.LN2;
  6970. return Math.pow( 2, Math.round( l ) );
  6971. }
  6972. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  6973. var isCompressed = /\.dds$/i.test( sourceFile );
  6974. var fullPath = texturePath + sourceFile;
  6975. if ( isCompressed ) {
  6976. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  6977. where[ name ] = texture;
  6978. } else {
  6979. var texture = document.createElement( 'canvas' );
  6980. where[ name ] = new THREE.Texture( texture );
  6981. }
  6982. where[ name ].sourceFile = sourceFile;
  6983. if( repeat ) {
  6984. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  6985. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  6986. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  6987. }
  6988. if ( offset ) {
  6989. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  6990. }
  6991. if ( wrap ) {
  6992. var wrapMap = {
  6993. "repeat": THREE.RepeatWrapping,
  6994. "mirror": THREE.MirroredRepeatWrapping
  6995. }
  6996. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  6997. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  6998. }
  6999. if ( anisotropy ) {
  7000. where[ name ].anisotropy = anisotropy;
  7001. }
  7002. if ( ! isCompressed ) {
  7003. var texture = where[ name ];
  7004. scope.imageLoader.crossOrigin = scope.crossOrigin;
  7005. scope.imageLoader.load( fullPath, function ( image ) {
  7006. if ( THREE.Math.isPowerOfTwo( image.width ) === false ||
  7007. THREE.Math.isPowerOfTwo( image.height ) === false ) {
  7008. var width = nearest_pow2( image.width );
  7009. var height = nearest_pow2( image.height );
  7010. texture.image.width = width;
  7011. texture.image.height = height;
  7012. texture.image.getContext( '2d' ).drawImage( image, 0, 0, width, height );
  7013. } else {
  7014. texture.image = image;
  7015. }
  7016. texture.needsUpdate = true;
  7017. } );
  7018. }
  7019. }
  7020. function rgb2hex( rgb ) {
  7021. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  7022. }
  7023. // defaults
  7024. var mtype = "MeshLambertMaterial";
  7025. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  7026. // parameters from model file
  7027. if ( m.shading ) {
  7028. var shading = m.shading.toLowerCase();
  7029. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  7030. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  7031. }
  7032. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  7033. mpars.blending = THREE[ m.blending ];
  7034. }
  7035. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  7036. mpars.transparent = m.transparent;
  7037. }
  7038. if ( m.depthTest !== undefined ) {
  7039. mpars.depthTest = m.depthTest;
  7040. }
  7041. if ( m.depthWrite !== undefined ) {
  7042. mpars.depthWrite = m.depthWrite;
  7043. }
  7044. if ( m.visible !== undefined ) {
  7045. mpars.visible = m.visible;
  7046. }
  7047. if ( m.flipSided !== undefined ) {
  7048. mpars.side = THREE.BackSide;
  7049. }
  7050. if ( m.doubleSided !== undefined ) {
  7051. mpars.side = THREE.DoubleSide;
  7052. }
  7053. if ( m.wireframe !== undefined ) {
  7054. mpars.wireframe = m.wireframe;
  7055. }
  7056. if ( m.vertexColors !== undefined ) {
  7057. if ( m.vertexColors === "face" ) {
  7058. mpars.vertexColors = THREE.FaceColors;
  7059. } else if ( m.vertexColors ) {
  7060. mpars.vertexColors = THREE.VertexColors;
  7061. }
  7062. }
  7063. // colors
  7064. if ( m.colorDiffuse ) {
  7065. mpars.color = rgb2hex( m.colorDiffuse );
  7066. } else if ( m.DbgColor ) {
  7067. mpars.color = m.DbgColor;
  7068. }
  7069. if ( m.colorSpecular ) {
  7070. mpars.specular = rgb2hex( m.colorSpecular );
  7071. }
  7072. if ( m.colorAmbient ) {
  7073. mpars.ambient = rgb2hex( m.colorAmbient );
  7074. }
  7075. // modifiers
  7076. if ( m.transparency ) {
  7077. mpars.opacity = m.transparency;
  7078. }
  7079. if ( m.specularCoef ) {
  7080. mpars.shininess = m.specularCoef;
  7081. }
  7082. // textures
  7083. if ( m.mapDiffuse && texturePath ) {
  7084. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  7085. }
  7086. if ( m.mapLight && texturePath ) {
  7087. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  7088. }
  7089. if ( m.mapBump && texturePath ) {
  7090. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  7091. }
  7092. if ( m.mapNormal && texturePath ) {
  7093. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  7094. }
  7095. if ( m.mapSpecular && texturePath ) {
  7096. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  7097. }
  7098. //
  7099. if ( m.mapBumpScale ) {
  7100. mpars.bumpScale = m.mapBumpScale;
  7101. }
  7102. // special case for normal mapped material
  7103. if ( m.mapNormal ) {
  7104. var shader = THREE.ShaderLib[ "normalmap" ];
  7105. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  7106. uniforms[ "tNormal" ].value = mpars.normalMap;
  7107. if ( m.mapNormalFactor ) {
  7108. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  7109. }
  7110. if ( mpars.map ) {
  7111. uniforms[ "tDiffuse" ].value = mpars.map;
  7112. uniforms[ "enableDiffuse" ].value = true;
  7113. }
  7114. if ( mpars.specularMap ) {
  7115. uniforms[ "tSpecular" ].value = mpars.specularMap;
  7116. uniforms[ "enableSpecular" ].value = true;
  7117. }
  7118. if ( mpars.lightMap ) {
  7119. uniforms[ "tAO" ].value = mpars.lightMap;
  7120. uniforms[ "enableAO" ].value = true;
  7121. }
  7122. // for the moment don't handle displacement texture
  7123. uniforms[ "diffuse" ].value.setHex( mpars.color );
  7124. uniforms[ "specular" ].value.setHex( mpars.specular );
  7125. uniforms[ "ambient" ].value.setHex( mpars.ambient );
  7126. uniforms[ "shininess" ].value = mpars.shininess;
  7127. if ( mpars.opacity !== undefined ) {
  7128. uniforms[ "opacity" ].value = mpars.opacity;
  7129. }
  7130. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  7131. var material = new THREE.ShaderMaterial( parameters );
  7132. if ( mpars.transparent ) {
  7133. material.transparent = true;
  7134. }
  7135. } else {
  7136. var material = new THREE[ mtype ]( mpars );
  7137. }
  7138. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  7139. return material;
  7140. }
  7141. };
  7142. /**
  7143. * @author mrdoob / http://mrdoob.com/
  7144. */
  7145. THREE.XHRLoader = function ( manager ) {
  7146. this.cache = new THREE.Cache();
  7147. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7148. };
  7149. THREE.XHRLoader.prototype = {
  7150. constructor: THREE.XHRLoader,
  7151. load: function ( url, onLoad, onProgress, onError ) {
  7152. var scope = this;
  7153. var cached = scope.cache.get( url );
  7154. if ( cached !== undefined ) {
  7155. onLoad( cached );
  7156. return;
  7157. }
  7158. var request = new XMLHttpRequest();
  7159. if ( onLoad !== undefined ) {
  7160. request.addEventListener( 'load', function ( event ) {
  7161. scope.cache.add( url, event.target.responseText );
  7162. onLoad( event.target.responseText );
  7163. scope.manager.itemEnd( url );
  7164. }, false );
  7165. }
  7166. if ( onProgress !== undefined ) {
  7167. request.addEventListener( 'progress', function ( event ) {
  7168. onProgress( event );
  7169. }, false );
  7170. }
  7171. if ( onError !== undefined ) {
  7172. request.addEventListener( 'error', function ( event ) {
  7173. onError( event );
  7174. }, false );
  7175. }
  7176. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  7177. request.open( 'GET', url, true );
  7178. request.send( null );
  7179. scope.manager.itemStart( url );
  7180. },
  7181. setCrossOrigin: function ( value ) {
  7182. this.crossOrigin = value;
  7183. }
  7184. };
  7185. /**
  7186. * @author mrdoob / http://mrdoob.com/
  7187. */
  7188. THREE.ImageLoader = function ( manager ) {
  7189. this.cache = new THREE.Cache();
  7190. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7191. };
  7192. THREE.ImageLoader.prototype = {
  7193. constructor: THREE.ImageLoader,
  7194. load: function ( url, onLoad, onProgress, onError ) {
  7195. var scope = this;
  7196. var cached = scope.cache.get( url );
  7197. if ( cached !== undefined ) {
  7198. onLoad( cached );
  7199. return;
  7200. }
  7201. var image = document.createElement( 'img' );
  7202. if ( onLoad !== undefined ) {
  7203. image.addEventListener( 'load', function ( event ) {
  7204. scope.cache.add( url, this );
  7205. onLoad( this );
  7206. scope.manager.itemEnd( url );
  7207. }, false );
  7208. }
  7209. if ( onProgress !== undefined ) {
  7210. image.addEventListener( 'progress', function ( event ) {
  7211. onProgress( event );
  7212. }, false );
  7213. }
  7214. if ( onError !== undefined ) {
  7215. image.addEventListener( 'error', function ( event ) {
  7216. onError( event );
  7217. }, false );
  7218. }
  7219. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  7220. image.src = url;
  7221. scope.manager.itemStart( url );
  7222. return image;
  7223. },
  7224. setCrossOrigin: function ( value ) {
  7225. this.crossOrigin = value;
  7226. }
  7227. }
  7228. /**
  7229. * @author mrdoob / http://mrdoob.com/
  7230. * @author alteredq / http://alteredqualia.com/
  7231. */
  7232. THREE.JSONLoader = function ( showStatus ) {
  7233. THREE.Loader.call( this, showStatus );
  7234. this.withCredentials = false;
  7235. };
  7236. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  7237. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  7238. var scope = this;
  7239. // todo: unify load API to for easier SceneLoader use
  7240. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  7241. this.onLoadStart();
  7242. this.loadAjaxJSON( this, url, callback, texturePath );
  7243. };
  7244. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  7245. var xhr = new XMLHttpRequest();
  7246. var length = 0;
  7247. xhr.onreadystatechange = function () {
  7248. if ( xhr.readyState === xhr.DONE ) {
  7249. if ( xhr.status === 200 || xhr.status === 0 ) {
  7250. if ( xhr.responseText ) {
  7251. var json = JSON.parse( xhr.responseText );
  7252. if ( json.metadata !== undefined && json.metadata.type === 'scene' ) {
  7253. console.error( 'THREE.JSONLoader: "' + url + '" seems to be a Scene. Use THREE.SceneLoader instead.' );
  7254. return;
  7255. }
  7256. var result = context.parse( json, texturePath );
  7257. callback( result.geometry, result.materials );
  7258. } else {
  7259. console.error( 'THREE.JSONLoader: "' + url + '" seems to be unreachable or the file is empty.' );
  7260. }
  7261. // in context of more complex asset initialization
  7262. // do not block on single failed file
  7263. // maybe should go even one more level up
  7264. context.onLoadComplete();
  7265. } else {
  7266. console.error( 'THREE.JSONLoader: Couldn\'t load "' + url + '" (' + xhr.status + ')' );
  7267. }
  7268. } else if ( xhr.readyState === xhr.LOADING ) {
  7269. if ( callbackProgress ) {
  7270. if ( length === 0 ) {
  7271. length = xhr.getResponseHeader( 'Content-Length' );
  7272. }
  7273. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  7274. }
  7275. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  7276. if ( callbackProgress !== undefined ) {
  7277. length = xhr.getResponseHeader( "Content-Length" );
  7278. }
  7279. }
  7280. };
  7281. xhr.open( "GET", url, true );
  7282. xhr.withCredentials = this.withCredentials;
  7283. xhr.send( null );
  7284. };
  7285. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  7286. var scope = this,
  7287. geometry = new THREE.Geometry(),
  7288. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  7289. parseModel( scale );
  7290. parseSkin();
  7291. parseMorphing( scale );
  7292. geometry.computeFaceNormals();
  7293. geometry.computeBoundingSphere();
  7294. function parseModel( scale ) {
  7295. function isBitSet( value, position ) {
  7296. return value & ( 1 << position );
  7297. }
  7298. var i, j, fi,
  7299. offset, zLength,
  7300. colorIndex, normalIndex, uvIndex, materialIndex,
  7301. type,
  7302. isQuad,
  7303. hasMaterial,
  7304. hasFaceVertexUv,
  7305. hasFaceNormal, hasFaceVertexNormal,
  7306. hasFaceColor, hasFaceVertexColor,
  7307. vertex, face, faceA, faceB, color, hex, normal,
  7308. uvLayer, uv, u, v,
  7309. faces = json.faces,
  7310. vertices = json.vertices,
  7311. normals = json.normals,
  7312. colors = json.colors,
  7313. nUvLayers = 0;
  7314. if ( json.uvs !== undefined ) {
  7315. // disregard empty arrays
  7316. for ( i = 0; i < json.uvs.length; i++ ) {
  7317. if ( json.uvs[ i ].length ) nUvLayers ++;
  7318. }
  7319. for ( i = 0; i < nUvLayers; i++ ) {
  7320. geometry.faceVertexUvs[ i ] = [];
  7321. }
  7322. }
  7323. offset = 0;
  7324. zLength = vertices.length;
  7325. while ( offset < zLength ) {
  7326. vertex = new THREE.Vector3();
  7327. vertex.x = vertices[ offset ++ ] * scale;
  7328. vertex.y = vertices[ offset ++ ] * scale;
  7329. vertex.z = vertices[ offset ++ ] * scale;
  7330. geometry.vertices.push( vertex );
  7331. }
  7332. offset = 0;
  7333. zLength = faces.length;
  7334. while ( offset < zLength ) {
  7335. type = faces[ offset ++ ];
  7336. isQuad = isBitSet( type, 0 );
  7337. hasMaterial = isBitSet( type, 1 );
  7338. hasFaceVertexUv = isBitSet( type, 3 );
  7339. hasFaceNormal = isBitSet( type, 4 );
  7340. hasFaceVertexNormal = isBitSet( type, 5 );
  7341. hasFaceColor = isBitSet( type, 6 );
  7342. hasFaceVertexColor = isBitSet( type, 7 );
  7343. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  7344. if ( isQuad ) {
  7345. faceA = new THREE.Face3();
  7346. faceA.a = faces[ offset ];
  7347. faceA.b = faces[ offset + 1 ];
  7348. faceA.c = faces[ offset + 3 ];
  7349. faceB = new THREE.Face3();
  7350. faceB.a = faces[ offset + 1 ];
  7351. faceB.b = faces[ offset + 2 ];
  7352. faceB.c = faces[ offset + 3 ];
  7353. offset += 4;
  7354. if ( hasMaterial ) {
  7355. materialIndex = faces[ offset ++ ];
  7356. faceA.materialIndex = materialIndex;
  7357. faceB.materialIndex = materialIndex;
  7358. }
  7359. // to get face <=> uv index correspondence
  7360. fi = geometry.faces.length;
  7361. if ( hasFaceVertexUv ) {
  7362. for ( i = 0; i < nUvLayers; i++ ) {
  7363. uvLayer = json.uvs[ i ];
  7364. geometry.faceVertexUvs[ i ][ fi ] = [];
  7365. geometry.faceVertexUvs[ i ][ fi + 1 ] = []
  7366. for ( j = 0; j < 4; j ++ ) {
  7367. uvIndex = faces[ offset ++ ];
  7368. u = uvLayer[ uvIndex * 2 ];
  7369. v = uvLayer[ uvIndex * 2 + 1 ];
  7370. uv = new THREE.Vector2( u, v );
  7371. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7372. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  7373. }
  7374. }
  7375. }
  7376. if ( hasFaceNormal ) {
  7377. normalIndex = faces[ offset ++ ] * 3;
  7378. faceA.normal.set(
  7379. normals[ normalIndex ++ ],
  7380. normals[ normalIndex ++ ],
  7381. normals[ normalIndex ]
  7382. );
  7383. faceB.normal.copy( faceA.normal );
  7384. }
  7385. if ( hasFaceVertexNormal ) {
  7386. for ( i = 0; i < 4; i++ ) {
  7387. normalIndex = faces[ offset ++ ] * 3;
  7388. normal = new THREE.Vector3(
  7389. normals[ normalIndex ++ ],
  7390. normals[ normalIndex ++ ],
  7391. normals[ normalIndex ]
  7392. );
  7393. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  7394. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  7395. }
  7396. }
  7397. if ( hasFaceColor ) {
  7398. colorIndex = faces[ offset ++ ];
  7399. hex = colors[ colorIndex ];
  7400. faceA.color.setHex( hex );
  7401. faceB.color.setHex( hex );
  7402. }
  7403. if ( hasFaceVertexColor ) {
  7404. for ( i = 0; i < 4; i++ ) {
  7405. colorIndex = faces[ offset ++ ];
  7406. hex = colors[ colorIndex ];
  7407. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  7408. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  7409. }
  7410. }
  7411. geometry.faces.push( faceA );
  7412. geometry.faces.push( faceB );
  7413. } else {
  7414. face = new THREE.Face3();
  7415. face.a = faces[ offset ++ ];
  7416. face.b = faces[ offset ++ ];
  7417. face.c = faces[ offset ++ ];
  7418. if ( hasMaterial ) {
  7419. materialIndex = faces[ offset ++ ];
  7420. face.materialIndex = materialIndex;
  7421. }
  7422. // to get face <=> uv index correspondence
  7423. fi = geometry.faces.length;
  7424. if ( hasFaceVertexUv ) {
  7425. for ( i = 0; i < nUvLayers; i++ ) {
  7426. uvLayer = json.uvs[ i ];
  7427. geometry.faceVertexUvs[ i ][ fi ] = [];
  7428. for ( j = 0; j < 3; j ++ ) {
  7429. uvIndex = faces[ offset ++ ];
  7430. u = uvLayer[ uvIndex * 2 ];
  7431. v = uvLayer[ uvIndex * 2 + 1 ];
  7432. uv = new THREE.Vector2( u, v );
  7433. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7434. }
  7435. }
  7436. }
  7437. if ( hasFaceNormal ) {
  7438. normalIndex = faces[ offset ++ ] * 3;
  7439. face.normal.set(
  7440. normals[ normalIndex ++ ],
  7441. normals[ normalIndex ++ ],
  7442. normals[ normalIndex ]
  7443. );
  7444. }
  7445. if ( hasFaceVertexNormal ) {
  7446. for ( i = 0; i < 3; i++ ) {
  7447. normalIndex = faces[ offset ++ ] * 3;
  7448. normal = new THREE.Vector3(
  7449. normals[ normalIndex ++ ],
  7450. normals[ normalIndex ++ ],
  7451. normals[ normalIndex ]
  7452. );
  7453. face.vertexNormals.push( normal );
  7454. }
  7455. }
  7456. if ( hasFaceColor ) {
  7457. colorIndex = faces[ offset ++ ];
  7458. face.color.setHex( colors[ colorIndex ] );
  7459. }
  7460. if ( hasFaceVertexColor ) {
  7461. for ( i = 0; i < 3; i++ ) {
  7462. colorIndex = faces[ offset ++ ];
  7463. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  7464. }
  7465. }
  7466. geometry.faces.push( face );
  7467. }
  7468. }
  7469. };
  7470. function parseSkin() {
  7471. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  7472. if ( json.skinWeights ) {
  7473. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  7474. var x = json.skinWeights[ i ];
  7475. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  7476. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  7477. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  7478. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  7479. }
  7480. }
  7481. if ( json.skinIndices ) {
  7482. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  7483. var a = json.skinIndices[ i ];
  7484. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  7485. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  7486. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  7487. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  7488. }
  7489. }
  7490. geometry.bones = json.bones;
  7491. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  7492. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  7493. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  7494. }
  7495. // could change this to json.animations[0] or remove completely
  7496. geometry.animation = json.animation;
  7497. geometry.animations = json.animations;
  7498. };
  7499. function parseMorphing( scale ) {
  7500. if ( json.morphTargets !== undefined ) {
  7501. var i, l, v, vl, dstVertices, srcVertices;
  7502. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  7503. geometry.morphTargets[ i ] = {};
  7504. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  7505. geometry.morphTargets[ i ].vertices = [];
  7506. dstVertices = geometry.morphTargets[ i ].vertices;
  7507. srcVertices = json.morphTargets [ i ].vertices;
  7508. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  7509. var vertex = new THREE.Vector3();
  7510. vertex.x = srcVertices[ v ] * scale;
  7511. vertex.y = srcVertices[ v + 1 ] * scale;
  7512. vertex.z = srcVertices[ v + 2 ] * scale;
  7513. dstVertices.push( vertex );
  7514. }
  7515. }
  7516. }
  7517. if ( json.morphColors !== undefined ) {
  7518. var i, l, c, cl, dstColors, srcColors, color;
  7519. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  7520. geometry.morphColors[ i ] = {};
  7521. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  7522. geometry.morphColors[ i ].colors = [];
  7523. dstColors = geometry.morphColors[ i ].colors;
  7524. srcColors = json.morphColors [ i ].colors;
  7525. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  7526. color = new THREE.Color( 0xffaa00 );
  7527. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  7528. dstColors.push( color );
  7529. }
  7530. }
  7531. }
  7532. };
  7533. if ( json.materials === undefined || json.materials.length === 0 ) {
  7534. return { geometry: geometry };
  7535. } else {
  7536. var materials = this.initMaterials( json.materials, texturePath );
  7537. if ( this.needsTangents( materials ) ) {
  7538. geometry.computeTangents();
  7539. }
  7540. return { geometry: geometry, materials: materials };
  7541. }
  7542. };
  7543. /**
  7544. * @author mrdoob / http://mrdoob.com/
  7545. */
  7546. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  7547. var scope = this;
  7548. var loaded = 0, total = 0;
  7549. this.onLoad = onLoad;
  7550. this.onProgress = onProgress;
  7551. this.onError = onError;
  7552. this.itemStart = function ( url ) {
  7553. total ++;
  7554. };
  7555. this.itemEnd = function ( url ) {
  7556. loaded ++;
  7557. if ( scope.onProgress !== undefined ) {
  7558. scope.onProgress( url, loaded, total );
  7559. }
  7560. if ( loaded === total && scope.onLoad !== undefined ) {
  7561. scope.onLoad();
  7562. }
  7563. };
  7564. };
  7565. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  7566. /**
  7567. * @author mrdoob / http://mrdoob.com/
  7568. */
  7569. THREE.BufferGeometryLoader = function ( manager ) {
  7570. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7571. };
  7572. THREE.BufferGeometryLoader.prototype = {
  7573. constructor: THREE.BufferGeometryLoader,
  7574. load: function ( url, onLoad, onProgress, onError ) {
  7575. var scope = this;
  7576. var loader = new THREE.XHRLoader();
  7577. loader.setCrossOrigin( this.crossOrigin );
  7578. loader.load( url, function ( text ) {
  7579. onLoad( scope.parse( JSON.parse( text ) ) );
  7580. } );
  7581. },
  7582. setCrossOrigin: function ( value ) {
  7583. this.crossOrigin = value;
  7584. },
  7585. parse: function ( json ) {
  7586. var geometry = new THREE.BufferGeometry();
  7587. var attributes = json.attributes;
  7588. var offsets = json.offsets;
  7589. var boundingSphere = json.boundingSphere;
  7590. for ( var key in attributes ) {
  7591. var attribute = attributes[ key ];
  7592. geometry.attributes[ key ] = {
  7593. itemSize: attribute.itemSize,
  7594. array: new self[ attribute.type ]( attribute.array )
  7595. }
  7596. }
  7597. if ( offsets !== undefined ) {
  7598. geometry.offsets = JSON.parse( JSON.stringify( offsets ) );
  7599. }
  7600. if ( boundingSphere !== undefined ) {
  7601. geometry.boundingSphere = new THREE.Sphere(
  7602. new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ),
  7603. boundingSphere.radius
  7604. );
  7605. }
  7606. return geometry;
  7607. }
  7608. };
  7609. /**
  7610. * @author mrdoob / http://mrdoob.com/
  7611. */
  7612. THREE.MaterialLoader = function ( manager ) {
  7613. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7614. };
  7615. THREE.MaterialLoader.prototype = {
  7616. constructor: THREE.MaterialLoader,
  7617. load: function ( url, onLoad, onProgress, onError ) {
  7618. var scope = this;
  7619. var loader = new THREE.XHRLoader();
  7620. loader.setCrossOrigin( this.crossOrigin );
  7621. loader.load( url, function ( text ) {
  7622. onLoad( scope.parse( JSON.parse( text ) ) );
  7623. } );
  7624. },
  7625. setCrossOrigin: function ( value ) {
  7626. this.crossOrigin = value;
  7627. },
  7628. parse: function ( json ) {
  7629. var material = new THREE[ json.type ];
  7630. if ( json.color !== undefined ) material.color.setHex( json.color );
  7631. if ( json.ambient !== undefined ) material.ambient.setHex( json.ambient );
  7632. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  7633. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  7634. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  7635. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  7636. if ( json.blending !== undefined ) material.blending = json.blending;
  7637. if ( json.side !== undefined ) material.side = json.side;
  7638. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  7639. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  7640. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  7641. if ( json.materials !== undefined ) {
  7642. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  7643. material.materials.push( this.parse( json.materials[ i ] ) );
  7644. }
  7645. }
  7646. return material;
  7647. }
  7648. };
  7649. /**
  7650. * @author mrdoob / http://mrdoob.com/
  7651. */
  7652. THREE.ObjectLoader = function ( manager ) {
  7653. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7654. };
  7655. THREE.ObjectLoader.prototype = {
  7656. constructor: THREE.ObjectLoader,
  7657. load: function ( url, onLoad, onProgress, onError ) {
  7658. var scope = this;
  7659. var loader = new THREE.XHRLoader( scope.manager );
  7660. loader.setCrossOrigin( this.crossOrigin );
  7661. loader.load( url, function ( text ) {
  7662. onLoad( scope.parse( JSON.parse( text ) ) );
  7663. } );
  7664. },
  7665. setCrossOrigin: function ( value ) {
  7666. this.crossOrigin = value;
  7667. },
  7668. parse: function ( json ) {
  7669. var geometries = this.parseGeometries( json.geometries );
  7670. var materials = this.parseMaterials( json.materials );
  7671. var object = this.parseObject( json.object, geometries, materials );
  7672. return object;
  7673. },
  7674. parseGeometries: function ( json ) {
  7675. var geometries = {};
  7676. if ( json !== undefined ) {
  7677. var geometryLoader = new THREE.JSONLoader();
  7678. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  7679. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7680. var geometry;
  7681. var data = json[ i ];
  7682. switch ( data.type ) {
  7683. case 'PlaneGeometry':
  7684. geometry = new THREE.PlaneGeometry(
  7685. data.width,
  7686. data.height,
  7687. data.widthSegments,
  7688. data.heightSegments
  7689. );
  7690. break;
  7691. case 'BoxGeometry':
  7692. case 'CubeGeometry': // DEPRECATED
  7693. geometry = new THREE.BoxGeometry(
  7694. data.width,
  7695. data.height,
  7696. data.depth,
  7697. data.widthSegments,
  7698. data.heightSegments,
  7699. data.depthSegments
  7700. );
  7701. break;
  7702. case 'CircleGeometry':
  7703. geometry = new THREE.CircleGeometry(
  7704. data.radius,
  7705. data.segments
  7706. );
  7707. break;
  7708. case 'CylinderGeometry':
  7709. geometry = new THREE.CylinderGeometry(
  7710. data.radiusTop,
  7711. data.radiusBottom,
  7712. data.height,
  7713. data.radialSegments,
  7714. data.heightSegments,
  7715. data.openEnded
  7716. );
  7717. break;
  7718. case 'SphereGeometry':
  7719. geometry = new THREE.SphereGeometry(
  7720. data.radius,
  7721. data.widthSegments,
  7722. data.heightSegments,
  7723. data.phiStart,
  7724. data.phiLength,
  7725. data.thetaStart,
  7726. data.thetaLength
  7727. );
  7728. break;
  7729. case 'IcosahedronGeometry':
  7730. geometry = new THREE.IcosahedronGeometry(
  7731. data.radius,
  7732. data.detail
  7733. );
  7734. break;
  7735. case 'TorusGeometry':
  7736. geometry = new THREE.TorusGeometry(
  7737. data.radius,
  7738. data.tube,
  7739. data.radialSegments,
  7740. data.tubularSegments,
  7741. data.arc
  7742. );
  7743. break;
  7744. case 'TorusKnotGeometry':
  7745. geometry = new THREE.TorusKnotGeometry(
  7746. data.radius,
  7747. data.tube,
  7748. data.radialSegments,
  7749. data.tubularSegments,
  7750. data.p,
  7751. data.q,
  7752. data.heightScale
  7753. );
  7754. break;
  7755. case 'BufferGeometry':
  7756. geometry = bufferGeometryLoader.parse( data.data );
  7757. break;
  7758. case 'Geometry':
  7759. geometry = geometryLoader.parse( data.data ).geometry;
  7760. break;
  7761. }
  7762. geometry.uuid = data.uuid;
  7763. if ( data.name !== undefined ) geometry.name = data.name;
  7764. geometries[ data.uuid ] = geometry;
  7765. }
  7766. }
  7767. return geometries;
  7768. },
  7769. parseMaterials: function ( json ) {
  7770. var materials = {};
  7771. if ( json !== undefined ) {
  7772. var loader = new THREE.MaterialLoader();
  7773. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7774. var data = json[ i ];
  7775. var material = loader.parse( data );
  7776. material.uuid = data.uuid;
  7777. if ( data.name !== undefined ) material.name = data.name;
  7778. materials[ data.uuid ] = material;
  7779. }
  7780. }
  7781. return materials;
  7782. },
  7783. parseObject: function () {
  7784. var matrix = new THREE.Matrix4();
  7785. return function ( data, geometries, materials ) {
  7786. var object;
  7787. switch ( data.type ) {
  7788. case 'Scene':
  7789. object = new THREE.Scene();
  7790. break;
  7791. case 'PerspectiveCamera':
  7792. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  7793. break;
  7794. case 'OrthographicCamera':
  7795. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  7796. break;
  7797. case 'AmbientLight':
  7798. object = new THREE.AmbientLight( data.color );
  7799. break;
  7800. case 'DirectionalLight':
  7801. object = new THREE.DirectionalLight( data.color, data.intensity );
  7802. break;
  7803. case 'PointLight':
  7804. object = new THREE.PointLight( data.color, data.intensity, data.distance );
  7805. break;
  7806. case 'SpotLight':
  7807. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent );
  7808. break;
  7809. case 'HemisphereLight':
  7810. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  7811. break;
  7812. case 'Mesh':
  7813. var geometry = geometries[ data.geometry ];
  7814. var material = materials[ data.material ];
  7815. if ( geometry === undefined ) {
  7816. console.error( 'THREE.ObjectLoader: Undefined geometry ' + data.geometry );
  7817. }
  7818. if ( material === undefined ) {
  7819. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  7820. }
  7821. object = new THREE.Mesh( geometry, material );
  7822. break;
  7823. case 'Sprite':
  7824. var material = materials[ data.material ];
  7825. if ( material === undefined ) {
  7826. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  7827. }
  7828. object = new THREE.Sprite( material );
  7829. break;
  7830. default:
  7831. object = new THREE.Object3D();
  7832. }
  7833. object.uuid = data.uuid;
  7834. if ( data.name !== undefined ) object.name = data.name;
  7835. if ( data.matrix !== undefined ) {
  7836. matrix.fromArray( data.matrix );
  7837. matrix.decompose( object.position, object.quaternion, object.scale );
  7838. } else {
  7839. if ( data.position !== undefined ) object.position.fromArray( data.position );
  7840. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  7841. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  7842. }
  7843. if ( data.visible !== undefined ) object.visible = data.visible;
  7844. if ( data.userData !== undefined ) object.userData = data.userData;
  7845. if ( data.children !== undefined ) {
  7846. for ( var child in data.children ) {
  7847. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  7848. }
  7849. }
  7850. return object;
  7851. }
  7852. }()
  7853. };
  7854. /**
  7855. * @author alteredq / http://alteredqualia.com/
  7856. */
  7857. THREE.SceneLoader = function () {
  7858. this.onLoadStart = function () {};
  7859. this.onLoadProgress = function() {};
  7860. this.onLoadComplete = function () {};
  7861. this.callbackSync = function () {};
  7862. this.callbackProgress = function () {};
  7863. this.geometryHandlers = {};
  7864. this.hierarchyHandlers = {};
  7865. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  7866. };
  7867. THREE.SceneLoader.prototype = {
  7868. constructor: THREE.SceneLoader,
  7869. load: function ( url, onLoad, onProgress, onError ) {
  7870. var scope = this;
  7871. var loader = new THREE.XHRLoader( scope.manager );
  7872. loader.setCrossOrigin( this.crossOrigin );
  7873. loader.load( url, function ( text ) {
  7874. scope.parse( JSON.parse( text ), onLoad, url );
  7875. } );
  7876. },
  7877. setCrossOrigin: function ( value ) {
  7878. this.crossOrigin = value;
  7879. },
  7880. addGeometryHandler: function ( typeID, loaderClass ) {
  7881. this.geometryHandlers[ typeID ] = { "loaderClass": loaderClass };
  7882. },
  7883. addHierarchyHandler: function ( typeID, loaderClass ) {
  7884. this.hierarchyHandlers[ typeID ] = { "loaderClass": loaderClass };
  7885. },
  7886. parse: function ( json, callbackFinished, url ) {
  7887. var scope = this;
  7888. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  7889. var geometry, material, camera, fog,
  7890. texture, images, color,
  7891. light, hex, intensity,
  7892. counter_models, counter_textures,
  7893. total_models, total_textures,
  7894. result;
  7895. var target_array = [];
  7896. var data = json;
  7897. // async geometry loaders
  7898. for ( var typeID in this.geometryHandlers ) {
  7899. var loaderClass = this.geometryHandlers[ typeID ][ "loaderClass" ];
  7900. this.geometryHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  7901. }
  7902. // async hierachy loaders
  7903. for ( var typeID in this.hierarchyHandlers ) {
  7904. var loaderClass = this.hierarchyHandlers[ typeID ][ "loaderClass" ];
  7905. this.hierarchyHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  7906. }
  7907. counter_models = 0;
  7908. counter_textures = 0;
  7909. result = {
  7910. scene: new THREE.Scene(),
  7911. geometries: {},
  7912. face_materials: {},
  7913. materials: {},
  7914. textures: {},
  7915. objects: {},
  7916. cameras: {},
  7917. lights: {},
  7918. fogs: {},
  7919. empties: {},
  7920. groups: {}
  7921. };
  7922. if ( data.transform ) {
  7923. var position = data.transform.position,
  7924. rotation = data.transform.rotation,
  7925. scale = data.transform.scale;
  7926. if ( position ) {
  7927. result.scene.position.fromArray( position );
  7928. }
  7929. if ( rotation ) {
  7930. result.scene.rotation.fromArray( rotation );
  7931. }
  7932. if ( scale ) {
  7933. result.scene.scale.fromArray( scale );
  7934. }
  7935. if ( position || rotation || scale ) {
  7936. result.scene.updateMatrix();
  7937. result.scene.updateMatrixWorld();
  7938. }
  7939. }
  7940. function get_url( source_url, url_type ) {
  7941. if ( url_type == "relativeToHTML" ) {
  7942. return source_url;
  7943. } else {
  7944. return urlBase + source_url;
  7945. }
  7946. };
  7947. // toplevel loader function, delegates to handle_children
  7948. function handle_objects() {
  7949. handle_children( result.scene, data.objects );
  7950. }
  7951. // handle all the children from the loaded json and attach them to given parent
  7952. function handle_children( parent, children ) {
  7953. var mat, dst, pos, rot, scl, quat;
  7954. for ( var objID in children ) {
  7955. // check by id if child has already been handled,
  7956. // if not, create new object
  7957. var object = result.objects[ objID ];
  7958. var objJSON = children[ objID ];
  7959. if ( object === undefined ) {
  7960. // meshes
  7961. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7962. if ( objJSON.loading === undefined ) {
  7963. var reservedTypes = {
  7964. "type": 1, "url": 1, "material": 1,
  7965. "position": 1, "rotation": 1, "scale" : 1,
  7966. "visible": 1, "children": 1, "userData": 1,
  7967. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1
  7968. };
  7969. var loaderParameters = {};
  7970. for ( var parType in objJSON ) {
  7971. if ( ! ( parType in reservedTypes ) ) {
  7972. loaderParameters[ parType ] = objJSON[ parType ];
  7973. }
  7974. }
  7975. material = result.materials[ objJSON.material ];
  7976. objJSON.loading = true;
  7977. var loader = scope.hierarchyHandlers[ objJSON.type ][ "loaderObject" ];
  7978. // ColladaLoader
  7979. if ( loader.options ) {
  7980. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  7981. // UTF8Loader
  7982. // OBJLoader
  7983. } else {
  7984. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  7985. }
  7986. }
  7987. } else if ( objJSON.geometry !== undefined ) {
  7988. geometry = result.geometries[ objJSON.geometry ];
  7989. // geometry already loaded
  7990. if ( geometry ) {
  7991. var needsTangents = false;
  7992. material = result.materials[ objJSON.material ];
  7993. needsTangents = material instanceof THREE.ShaderMaterial;
  7994. pos = objJSON.position;
  7995. rot = objJSON.rotation;
  7996. scl = objJSON.scale;
  7997. mat = objJSON.matrix;
  7998. quat = objJSON.quaternion;
  7999. // use materials from the model file
  8000. // if there is no material specified in the object
  8001. if ( ! objJSON.material ) {
  8002. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  8003. }
  8004. // use materials from the model file
  8005. // if there is just empty face material
  8006. // (must create new material as each model has its own face material)
  8007. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  8008. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  8009. }
  8010. if ( material instanceof THREE.MeshFaceMaterial ) {
  8011. for ( var i = 0; i < material.materials.length; i ++ ) {
  8012. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  8013. }
  8014. }
  8015. if ( needsTangents ) {
  8016. geometry.computeTangents();
  8017. }
  8018. if ( objJSON.skin ) {
  8019. object = new THREE.SkinnedMesh( geometry, material );
  8020. } else if ( objJSON.morph ) {
  8021. object = new THREE.MorphAnimMesh( geometry, material );
  8022. if ( objJSON.duration !== undefined ) {
  8023. object.duration = objJSON.duration;
  8024. }
  8025. if ( objJSON.time !== undefined ) {
  8026. object.time = objJSON.time;
  8027. }
  8028. if ( objJSON.mirroredLoop !== undefined ) {
  8029. object.mirroredLoop = objJSON.mirroredLoop;
  8030. }
  8031. if ( material.morphNormals ) {
  8032. geometry.computeMorphNormals();
  8033. }
  8034. } else {
  8035. object = new THREE.Mesh( geometry, material );
  8036. }
  8037. object.name = objID;
  8038. if ( mat ) {
  8039. object.matrixAutoUpdate = false;
  8040. object.matrix.set(
  8041. mat[0], mat[1], mat[2], mat[3],
  8042. mat[4], mat[5], mat[6], mat[7],
  8043. mat[8], mat[9], mat[10], mat[11],
  8044. mat[12], mat[13], mat[14], mat[15]
  8045. );
  8046. } else {
  8047. object.position.fromArray( pos );
  8048. if ( quat ) {
  8049. object.quaternion.fromArray( quat );
  8050. } else {
  8051. object.rotation.fromArray( rot );
  8052. }
  8053. object.scale.fromArray( scl );
  8054. }
  8055. object.visible = objJSON.visible;
  8056. object.castShadow = objJSON.castShadow;
  8057. object.receiveShadow = objJSON.receiveShadow;
  8058. parent.add( object );
  8059. result.objects[ objID ] = object;
  8060. }
  8061. // lights
  8062. } else if ( objJSON.type === "AmbientLight" || objJSON.type === "PointLight" ||
  8063. objJSON.type === "DirectionalLight" || objJSON.type === "SpotLight" ||
  8064. objJSON.type === "HemisphereLight" || objJSON.type === "AreaLight" ) {
  8065. var color = objJSON.color;
  8066. var intensity = objJSON.intensity;
  8067. var distance = objJSON.distance;
  8068. var position = objJSON.position;
  8069. var rotation = objJSON.rotation;
  8070. switch ( objJSON.type ) {
  8071. case 'AmbientLight':
  8072. light = new THREE.AmbientLight( color );
  8073. break;
  8074. case 'PointLight':
  8075. light = new THREE.PointLight( color, intensity, distance );
  8076. light.position.fromArray( position );
  8077. break;
  8078. case 'DirectionalLight':
  8079. light = new THREE.DirectionalLight( color, intensity );
  8080. light.position.fromArray( objJSON.direction );
  8081. break;
  8082. case 'SpotLight':
  8083. light = new THREE.SpotLight( color, intensity, distance, 1 );
  8084. light.angle = objJSON.angle;
  8085. light.position.fromArray( position );
  8086. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  8087. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  8088. break;
  8089. case 'HemisphereLight':
  8090. light = new THREE.DirectionalLight( color, intensity, distance );
  8091. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  8092. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  8093. break;
  8094. case 'AreaLight':
  8095. light = new THREE.AreaLight(color, intensity);
  8096. light.position.fromArray( position );
  8097. light.width = objJSON.size;
  8098. light.height = objJSON.size_y;
  8099. break;
  8100. }
  8101. parent.add( light );
  8102. light.name = objID;
  8103. result.lights[ objID ] = light;
  8104. result.objects[ objID ] = light;
  8105. // cameras
  8106. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  8107. pos = objJSON.position;
  8108. rot = objJSON.rotation;
  8109. quat = objJSON.quaternion;
  8110. if ( objJSON.type === "PerspectiveCamera" ) {
  8111. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  8112. } else if ( objJSON.type === "OrthographicCamera" ) {
  8113. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  8114. }
  8115. camera.name = objID;
  8116. camera.position.fromArray( pos );
  8117. if ( quat !== undefined ) {
  8118. camera.quaternion.fromArray( quat );
  8119. } else if ( rot !== undefined ) {
  8120. camera.rotation.fromArray( rot );
  8121. }
  8122. parent.add( camera );
  8123. result.cameras[ objID ] = camera;
  8124. result.objects[ objID ] = camera;
  8125. // pure Object3D
  8126. } else {
  8127. pos = objJSON.position;
  8128. rot = objJSON.rotation;
  8129. scl = objJSON.scale;
  8130. quat = objJSON.quaternion;
  8131. object = new THREE.Object3D();
  8132. object.name = objID;
  8133. object.position.fromArray( pos );
  8134. if ( quat ) {
  8135. object.quaternion.fromArray( quat );
  8136. } else {
  8137. object.rotation.fromArray( rot );
  8138. }
  8139. object.scale.fromArray( scl );
  8140. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  8141. parent.add( object );
  8142. result.objects[ objID ] = object;
  8143. result.empties[ objID ] = object;
  8144. }
  8145. if ( object ) {
  8146. if ( objJSON.userData !== undefined ) {
  8147. for ( var key in objJSON.userData ) {
  8148. var value = objJSON.userData[ key ];
  8149. object.userData[ key ] = value;
  8150. }
  8151. }
  8152. if ( objJSON.groups !== undefined ) {
  8153. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  8154. var groupID = objJSON.groups[ i ];
  8155. if ( result.groups[ groupID ] === undefined ) {
  8156. result.groups[ groupID ] = [];
  8157. }
  8158. result.groups[ groupID ].push( objID );
  8159. }
  8160. }
  8161. }
  8162. }
  8163. if ( object !== undefined && objJSON.children !== undefined ) {
  8164. handle_children( object, objJSON.children );
  8165. }
  8166. }
  8167. };
  8168. function handle_mesh( geo, mat, id ) {
  8169. result.geometries[ id ] = geo;
  8170. result.face_materials[ id ] = mat;
  8171. handle_objects();
  8172. };
  8173. function handle_hierarchy( node, id, parent, material, obj ) {
  8174. var p = obj.position;
  8175. var r = obj.rotation;
  8176. var q = obj.quaternion;
  8177. var s = obj.scale;
  8178. node.position.fromArray( p );
  8179. if ( q ) {
  8180. node.quaternion.fromArray( q );
  8181. } else {
  8182. node.rotation.fromArray( r );
  8183. }
  8184. node.scale.fromArray( s );
  8185. // override children materials
  8186. // if object material was specified in JSON explicitly
  8187. if ( material ) {
  8188. node.traverse( function ( child ) {
  8189. child.material = material;
  8190. } );
  8191. }
  8192. // override children visibility
  8193. // with root node visibility as specified in JSON
  8194. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  8195. node.traverse( function ( child ) {
  8196. child.visible = visible;
  8197. } );
  8198. parent.add( node );
  8199. node.name = id;
  8200. result.objects[ id ] = node;
  8201. handle_objects();
  8202. };
  8203. function create_callback_geometry( id ) {
  8204. return function ( geo, mat ) {
  8205. geo.name = id;
  8206. handle_mesh( geo, mat, id );
  8207. counter_models -= 1;
  8208. scope.onLoadComplete();
  8209. async_callback_gate();
  8210. }
  8211. };
  8212. function create_callback_hierachy( id, parent, material, obj ) {
  8213. return function ( event ) {
  8214. var result;
  8215. // loaders which use EventDispatcher
  8216. if ( event.content ) {
  8217. result = event.content;
  8218. // ColladaLoader
  8219. } else if ( event.dae ) {
  8220. result = event.scene;
  8221. // UTF8Loader
  8222. } else {
  8223. result = event;
  8224. }
  8225. handle_hierarchy( result, id, parent, material, obj );
  8226. counter_models -= 1;
  8227. scope.onLoadComplete();
  8228. async_callback_gate();
  8229. }
  8230. };
  8231. function create_callback_embed( id ) {
  8232. return function ( geo, mat ) {
  8233. geo.name = id;
  8234. result.geometries[ id ] = geo;
  8235. result.face_materials[ id ] = mat;
  8236. }
  8237. };
  8238. function async_callback_gate() {
  8239. var progress = {
  8240. totalModels : total_models,
  8241. totalTextures : total_textures,
  8242. loadedModels : total_models - counter_models,
  8243. loadedTextures : total_textures - counter_textures
  8244. };
  8245. scope.callbackProgress( progress, result );
  8246. scope.onLoadProgress();
  8247. if ( counter_models === 0 && counter_textures === 0 ) {
  8248. finalize();
  8249. callbackFinished( result );
  8250. }
  8251. };
  8252. function finalize() {
  8253. // take care of targets which could be asynchronously loaded objects
  8254. for ( var i = 0; i < target_array.length; i ++ ) {
  8255. var ta = target_array[ i ];
  8256. var target = result.objects[ ta.targetName ];
  8257. if ( target ) {
  8258. ta.object.target = target;
  8259. } else {
  8260. // if there was error and target of specified name doesn't exist in the scene file
  8261. // create instead dummy target
  8262. // (target must be added to scene explicitly as parent is already added)
  8263. ta.object.target = new THREE.Object3D();
  8264. result.scene.add( ta.object.target );
  8265. }
  8266. ta.object.target.userData.targetInverse = ta.object;
  8267. }
  8268. };
  8269. var callbackTexture = function ( count ) {
  8270. counter_textures -= count;
  8271. async_callback_gate();
  8272. scope.onLoadComplete();
  8273. };
  8274. // must use this instead of just directly calling callbackTexture
  8275. // because of closure in the calling context loop
  8276. var generateTextureCallback = function ( count ) {
  8277. return function () {
  8278. callbackTexture( count );
  8279. };
  8280. };
  8281. function traverse_json_hierarchy( objJSON, callback ) {
  8282. callback( objJSON );
  8283. if ( objJSON.children !== undefined ) {
  8284. for ( var objChildID in objJSON.children ) {
  8285. traverse_json_hierarchy( objJSON.children[ objChildID ], callback );
  8286. }
  8287. }
  8288. };
  8289. // first go synchronous elements
  8290. // fogs
  8291. var fogID, fogJSON;
  8292. for ( fogID in data.fogs ) {
  8293. fogJSON = data.fogs[ fogID ];
  8294. if ( fogJSON.type === "linear" ) {
  8295. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  8296. } else if ( fogJSON.type === "exp2" ) {
  8297. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  8298. }
  8299. color = fogJSON.color;
  8300. fog.color.setRGB( color[0], color[1], color[2] );
  8301. result.fogs[ fogID ] = fog;
  8302. }
  8303. // now come potentially asynchronous elements
  8304. // geometries
  8305. // count how many geometries will be loaded asynchronously
  8306. var geoID, geoJSON;
  8307. for ( geoID in data.geometries ) {
  8308. geoJSON = data.geometries[ geoID ];
  8309. if ( geoJSON.type in this.geometryHandlers ) {
  8310. counter_models += 1;
  8311. scope.onLoadStart();
  8312. }
  8313. }
  8314. // count how many hierarchies will be loaded asynchronously
  8315. for ( var objID in data.objects ) {
  8316. traverse_json_hierarchy( data.objects[ objID ], function ( objJSON ) {
  8317. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  8318. counter_models += 1;
  8319. scope.onLoadStart();
  8320. }
  8321. });
  8322. }
  8323. total_models = counter_models;
  8324. for ( geoID in data.geometries ) {
  8325. geoJSON = data.geometries[ geoID ];
  8326. if ( geoJSON.type === "cube" ) {
  8327. geometry = new THREE.BoxGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  8328. geometry.name = geoID;
  8329. result.geometries[ geoID ] = geometry;
  8330. } else if ( geoJSON.type === "plane" ) {
  8331. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  8332. geometry.name = geoID;
  8333. result.geometries[ geoID ] = geometry;
  8334. } else if ( geoJSON.type === "sphere" ) {
  8335. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  8336. geometry.name = geoID;
  8337. result.geometries[ geoID ] = geometry;
  8338. } else if ( geoJSON.type === "cylinder" ) {
  8339. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  8340. geometry.name = geoID;
  8341. result.geometries[ geoID ] = geometry;
  8342. } else if ( geoJSON.type === "torus" ) {
  8343. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  8344. geometry.name = geoID;
  8345. result.geometries[ geoID ] = geometry;
  8346. } else if ( geoJSON.type === "icosahedron" ) {
  8347. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  8348. geometry.name = geoID;
  8349. result.geometries[ geoID ] = geometry;
  8350. } else if ( geoJSON.type in this.geometryHandlers ) {
  8351. var loaderParameters = {};
  8352. for ( var parType in geoJSON ) {
  8353. if ( parType !== "type" && parType !== "url" ) {
  8354. loaderParameters[ parType ] = geoJSON[ parType ];
  8355. }
  8356. }
  8357. var loader = this.geometryHandlers[ geoJSON.type ][ "loaderObject" ];
  8358. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  8359. } else if ( geoJSON.type === "embedded" ) {
  8360. var modelJson = data.embeds[ geoJSON.id ],
  8361. texture_path = "";
  8362. // pass metadata along to jsonLoader so it knows the format version
  8363. modelJson.metadata = data.metadata;
  8364. if ( modelJson ) {
  8365. var jsonLoader = this.geometryHandlers[ "ascii" ][ "loaderObject" ];
  8366. var model = jsonLoader.parse( modelJson, texture_path );
  8367. create_callback_embed( geoID )( model.geometry, model.materials );
  8368. }
  8369. }
  8370. }
  8371. // textures
  8372. // count how many textures will be loaded asynchronously
  8373. var textureID, textureJSON;
  8374. for ( textureID in data.textures ) {
  8375. textureJSON = data.textures[ textureID ];
  8376. if ( textureJSON.url instanceof Array ) {
  8377. counter_textures += textureJSON.url.length;
  8378. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  8379. scope.onLoadStart();
  8380. }
  8381. } else {
  8382. counter_textures += 1;
  8383. scope.onLoadStart();
  8384. }
  8385. }
  8386. total_textures = counter_textures;
  8387. for ( textureID in data.textures ) {
  8388. textureJSON = data.textures[ textureID ];
  8389. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  8390. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  8391. }
  8392. if ( textureJSON.url instanceof Array ) {
  8393. var count = textureJSON.url.length;
  8394. var url_array = [];
  8395. for( var i = 0; i < count; i ++ ) {
  8396. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  8397. }
  8398. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  8399. if ( isCompressed ) {
  8400. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  8401. } else {
  8402. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  8403. }
  8404. } else {
  8405. var isCompressed = /\.dds$/i.test( textureJSON.url );
  8406. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  8407. var textureCallback = generateTextureCallback( 1 );
  8408. if ( isCompressed ) {
  8409. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  8410. } else {
  8411. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  8412. }
  8413. if ( THREE[ textureJSON.minFilter ] !== undefined )
  8414. texture.minFilter = THREE[ textureJSON.minFilter ];
  8415. if ( THREE[ textureJSON.magFilter ] !== undefined )
  8416. texture.magFilter = THREE[ textureJSON.magFilter ];
  8417. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  8418. if ( textureJSON.repeat ) {
  8419. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  8420. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  8421. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  8422. }
  8423. if ( textureJSON.offset ) {
  8424. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  8425. }
  8426. // handle wrap after repeat so that default repeat can be overriden
  8427. if ( textureJSON.wrap ) {
  8428. var wrapMap = {
  8429. "repeat": THREE.RepeatWrapping,
  8430. "mirror": THREE.MirroredRepeatWrapping
  8431. }
  8432. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  8433. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  8434. }
  8435. }
  8436. result.textures[ textureID ] = texture;
  8437. }
  8438. // materials
  8439. var matID, matJSON;
  8440. var parID;
  8441. for ( matID in data.materials ) {
  8442. matJSON = data.materials[ matID ];
  8443. for ( parID in matJSON.parameters ) {
  8444. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  8445. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  8446. } else if ( parID === "shading" ) {
  8447. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  8448. } else if ( parID === "side" ) {
  8449. if ( matJSON.parameters[ parID ] == "double" ) {
  8450. matJSON.parameters[ parID ] = THREE.DoubleSide;
  8451. } else if ( matJSON.parameters[ parID ] == "back" ) {
  8452. matJSON.parameters[ parID ] = THREE.BackSide;
  8453. } else {
  8454. matJSON.parameters[ parID ] = THREE.FrontSide;
  8455. }
  8456. } else if ( parID === "blending" ) {
  8457. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  8458. } else if ( parID === "combine" ) {
  8459. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  8460. } else if ( parID === "vertexColors" ) {
  8461. if ( matJSON.parameters[ parID ] == "face" ) {
  8462. matJSON.parameters[ parID ] = THREE.FaceColors;
  8463. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  8464. } else if ( matJSON.parameters[ parID ] ) {
  8465. matJSON.parameters[ parID ] = THREE.VertexColors;
  8466. }
  8467. } else if ( parID === "wrapRGB" ) {
  8468. var v3 = matJSON.parameters[ parID ];
  8469. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  8470. }
  8471. }
  8472. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  8473. matJSON.parameters.transparent = true;
  8474. }
  8475. if ( matJSON.parameters.normalMap ) {
  8476. var shader = THREE.ShaderLib[ "normalmap" ];
  8477. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  8478. var diffuse = matJSON.parameters.color;
  8479. var specular = matJSON.parameters.specular;
  8480. var ambient = matJSON.parameters.ambient;
  8481. var shininess = matJSON.parameters.shininess;
  8482. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  8483. if ( matJSON.parameters.normalScale ) {
  8484. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  8485. }
  8486. if ( matJSON.parameters.map ) {
  8487. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  8488. uniforms[ "enableDiffuse" ].value = true;
  8489. }
  8490. if ( matJSON.parameters.envMap ) {
  8491. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  8492. uniforms[ "enableReflection" ].value = true;
  8493. uniforms[ "reflectivity" ].value = matJSON.parameters.reflectivity;
  8494. }
  8495. if ( matJSON.parameters.lightMap ) {
  8496. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  8497. uniforms[ "enableAO" ].value = true;
  8498. }
  8499. if ( matJSON.parameters.specularMap ) {
  8500. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  8501. uniforms[ "enableSpecular" ].value = true;
  8502. }
  8503. if ( matJSON.parameters.displacementMap ) {
  8504. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  8505. uniforms[ "enableDisplacement" ].value = true;
  8506. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  8507. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  8508. }
  8509. uniforms[ "diffuse" ].value.setHex( diffuse );
  8510. uniforms[ "specular" ].value.setHex( specular );
  8511. uniforms[ "ambient" ].value.setHex( ambient );
  8512. uniforms[ "shininess" ].value = shininess;
  8513. if ( matJSON.parameters.opacity ) {
  8514. uniforms[ "opacity" ].value = matJSON.parameters.opacity;
  8515. }
  8516. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  8517. material = new THREE.ShaderMaterial( parameters );
  8518. } else {
  8519. material = new THREE[ matJSON.type ]( matJSON.parameters );
  8520. }
  8521. material.name = matID;
  8522. result.materials[ matID ] = material;
  8523. }
  8524. // second pass through all materials to initialize MeshFaceMaterials
  8525. // that could be referring to other materials out of order
  8526. for ( matID in data.materials ) {
  8527. matJSON = data.materials[ matID ];
  8528. if ( matJSON.parameters.materials ) {
  8529. var materialArray = [];
  8530. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  8531. var label = matJSON.parameters.materials[ i ];
  8532. materialArray.push( result.materials[ label ] );
  8533. }
  8534. result.materials[ matID ].materials = materialArray;
  8535. }
  8536. }
  8537. // objects ( synchronous init of procedural primitives )
  8538. handle_objects();
  8539. // defaults
  8540. if ( result.cameras && data.defaults.camera ) {
  8541. result.currentCamera = result.cameras[ data.defaults.camera ];
  8542. }
  8543. if ( result.fogs && data.defaults.fog ) {
  8544. result.scene.fog = result.fogs[ data.defaults.fog ];
  8545. }
  8546. // synchronous callback
  8547. scope.callbackSync( result );
  8548. // just in case there are no async elements
  8549. async_callback_gate();
  8550. }
  8551. }
  8552. /**
  8553. * @author mrdoob / http://mrdoob.com/
  8554. */
  8555. THREE.TextureLoader = function ( manager ) {
  8556. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  8557. };
  8558. THREE.TextureLoader.prototype = {
  8559. constructor: THREE.TextureLoader,
  8560. load: function ( url, onLoad, onProgress, onError ) {
  8561. var scope = this;
  8562. var loader = new THREE.ImageLoader( scope.manager );
  8563. loader.setCrossOrigin( this.crossOrigin );
  8564. loader.load( url, function ( image ) {
  8565. var texture = new THREE.Texture( image );
  8566. texture.needsUpdate = true;
  8567. if ( onLoad !== undefined ) {
  8568. onLoad( texture );
  8569. }
  8570. } );
  8571. },
  8572. setCrossOrigin: function ( value ) {
  8573. this.crossOrigin = value;
  8574. }
  8575. };
  8576. /**
  8577. * @author mrdoob / http://mrdoob.com/
  8578. * @author alteredq / http://alteredqualia.com/
  8579. */
  8580. THREE.Material = function () {
  8581. this.id = THREE.MaterialIdCount ++;
  8582. this.uuid = THREE.Math.generateUUID();
  8583. this.name = '';
  8584. this.side = THREE.FrontSide;
  8585. this.opacity = 1;
  8586. this.transparent = false;
  8587. this.blending = THREE.NormalBlending;
  8588. this.blendSrc = THREE.SrcAlphaFactor;
  8589. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  8590. this.blendEquation = THREE.AddEquation;
  8591. this.depthTest = true;
  8592. this.depthWrite = true;
  8593. this.polygonOffset = false;
  8594. this.polygonOffsetFactor = 0;
  8595. this.polygonOffsetUnits = 0;
  8596. this.alphaTest = 0;
  8597. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  8598. this.visible = true;
  8599. this.needsUpdate = true;
  8600. };
  8601. THREE.Material.prototype = {
  8602. constructor: THREE.Material,
  8603. setValues: function ( values ) {
  8604. if ( values === undefined ) return;
  8605. for ( var key in values ) {
  8606. var newValue = values[ key ];
  8607. if ( newValue === undefined ) {
  8608. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  8609. continue;
  8610. }
  8611. if ( key in this ) {
  8612. var currentValue = this[ key ];
  8613. if ( currentValue instanceof THREE.Color ) {
  8614. currentValue.set( newValue );
  8615. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  8616. currentValue.copy( newValue );
  8617. } else if ( key == 'overdraw') {
  8618. // ensure overdraw is backwards-compatable with legacy boolean type
  8619. this[ key ] = Number(newValue);
  8620. } else {
  8621. this[ key ] = newValue;
  8622. }
  8623. }
  8624. }
  8625. },
  8626. clone: function ( material ) {
  8627. if ( material === undefined ) material = new THREE.Material();
  8628. material.name = this.name;
  8629. material.side = this.side;
  8630. material.opacity = this.opacity;
  8631. material.transparent = this.transparent;
  8632. material.blending = this.blending;
  8633. material.blendSrc = this.blendSrc;
  8634. material.blendDst = this.blendDst;
  8635. material.blendEquation = this.blendEquation;
  8636. material.depthTest = this.depthTest;
  8637. material.depthWrite = this.depthWrite;
  8638. material.polygonOffset = this.polygonOffset;
  8639. material.polygonOffsetFactor = this.polygonOffsetFactor;
  8640. material.polygonOffsetUnits = this.polygonOffsetUnits;
  8641. material.alphaTest = this.alphaTest;
  8642. material.overdraw = this.overdraw;
  8643. material.visible = this.visible;
  8644. return material;
  8645. },
  8646. dispose: function () {
  8647. this.dispatchEvent( { type: 'dispose' } );
  8648. }
  8649. };
  8650. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  8651. THREE.MaterialIdCount = 0;
  8652. /**
  8653. * @author mrdoob / http://mrdoob.com/
  8654. * @author alteredq / http://alteredqualia.com/
  8655. *
  8656. * parameters = {
  8657. * color: <hex>,
  8658. * opacity: <float>,
  8659. *
  8660. * blending: THREE.NormalBlending,
  8661. * depthTest: <bool>,
  8662. * depthWrite: <bool>,
  8663. *
  8664. * linewidth: <float>,
  8665. * linecap: "round",
  8666. * linejoin: "round",
  8667. *
  8668. * vertexColors: <bool>
  8669. *
  8670. * fog: <bool>
  8671. * }
  8672. */
  8673. THREE.LineBasicMaterial = function ( parameters ) {
  8674. THREE.Material.call( this );
  8675. this.color = new THREE.Color( 0xffffff );
  8676. this.linewidth = 1;
  8677. this.linecap = 'round';
  8678. this.linejoin = 'round';
  8679. this.vertexColors = false;
  8680. this.fog = true;
  8681. this.setValues( parameters );
  8682. };
  8683. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8684. THREE.LineBasicMaterial.prototype.clone = function () {
  8685. var material = new THREE.LineBasicMaterial();
  8686. THREE.Material.prototype.clone.call( this, material );
  8687. material.color.copy( this.color );
  8688. material.linewidth = this.linewidth;
  8689. material.linecap = this.linecap;
  8690. material.linejoin = this.linejoin;
  8691. material.vertexColors = this.vertexColors;
  8692. material.fog = this.fog;
  8693. return material;
  8694. };
  8695. /**
  8696. * @author alteredq / http://alteredqualia.com/
  8697. *
  8698. * parameters = {
  8699. * color: <hex>,
  8700. * opacity: <float>,
  8701. *
  8702. * blending: THREE.NormalBlending,
  8703. * depthTest: <bool>,
  8704. * depthWrite: <bool>,
  8705. *
  8706. * linewidth: <float>,
  8707. *
  8708. * scale: <float>,
  8709. * dashSize: <float>,
  8710. * gapSize: <float>,
  8711. *
  8712. * vertexColors: <bool>
  8713. *
  8714. * fog: <bool>
  8715. * }
  8716. */
  8717. THREE.LineDashedMaterial = function ( parameters ) {
  8718. THREE.Material.call( this );
  8719. this.color = new THREE.Color( 0xffffff );
  8720. this.linewidth = 1;
  8721. this.scale = 1;
  8722. this.dashSize = 3;
  8723. this.gapSize = 1;
  8724. this.vertexColors = false;
  8725. this.fog = true;
  8726. this.setValues( parameters );
  8727. };
  8728. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  8729. THREE.LineDashedMaterial.prototype.clone = function () {
  8730. var material = new THREE.LineDashedMaterial();
  8731. THREE.Material.prototype.clone.call( this, material );
  8732. material.color.copy( this.color );
  8733. material.linewidth = this.linewidth;
  8734. material.scale = this.scale;
  8735. material.dashSize = this.dashSize;
  8736. material.gapSize = this.gapSize;
  8737. material.vertexColors = this.vertexColors;
  8738. material.fog = this.fog;
  8739. return material;
  8740. };
  8741. /**
  8742. * @author mrdoob / http://mrdoob.com/
  8743. * @author alteredq / http://alteredqualia.com/
  8744. *
  8745. * parameters = {
  8746. * color: <hex>,
  8747. * opacity: <float>,
  8748. * map: new THREE.Texture( <Image> ),
  8749. *
  8750. * lightMap: new THREE.Texture( <Image> ),
  8751. *
  8752. * specularMap: new THREE.Texture( <Image> ),
  8753. *
  8754. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8755. * combine: THREE.Multiply,
  8756. * reflectivity: <float>,
  8757. * refractionRatio: <float>,
  8758. *
  8759. * shading: THREE.SmoothShading,
  8760. * blending: THREE.NormalBlending,
  8761. * depthTest: <bool>,
  8762. * depthWrite: <bool>,
  8763. *
  8764. * wireframe: <boolean>,
  8765. * wireframeLinewidth: <float>,
  8766. *
  8767. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8768. *
  8769. * skinning: <bool>,
  8770. * morphTargets: <bool>,
  8771. *
  8772. * fog: <bool>
  8773. * }
  8774. */
  8775. THREE.MeshBasicMaterial = function ( parameters ) {
  8776. THREE.Material.call( this );
  8777. this.color = new THREE.Color( 0xffffff ); // emissive
  8778. this.map = null;
  8779. this.lightMap = null;
  8780. this.specularMap = null;
  8781. this.envMap = null;
  8782. this.combine = THREE.MultiplyOperation;
  8783. this.reflectivity = 1;
  8784. this.refractionRatio = 0.98;
  8785. this.fog = true;
  8786. this.shading = THREE.SmoothShading;
  8787. this.wireframe = false;
  8788. this.wireframeLinewidth = 1;
  8789. this.wireframeLinecap = 'round';
  8790. this.wireframeLinejoin = 'round';
  8791. this.vertexColors = THREE.NoColors;
  8792. this.skinning = false;
  8793. this.morphTargets = false;
  8794. this.setValues( parameters );
  8795. };
  8796. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8797. THREE.MeshBasicMaterial.prototype.clone = function () {
  8798. var material = new THREE.MeshBasicMaterial();
  8799. THREE.Material.prototype.clone.call( this, material );
  8800. material.color.copy( this.color );
  8801. material.map = this.map;
  8802. material.lightMap = this.lightMap;
  8803. material.specularMap = this.specularMap;
  8804. material.envMap = this.envMap;
  8805. material.combine = this.combine;
  8806. material.reflectivity = this.reflectivity;
  8807. material.refractionRatio = this.refractionRatio;
  8808. material.fog = this.fog;
  8809. material.shading = this.shading;
  8810. material.wireframe = this.wireframe;
  8811. material.wireframeLinewidth = this.wireframeLinewidth;
  8812. material.wireframeLinecap = this.wireframeLinecap;
  8813. material.wireframeLinejoin = this.wireframeLinejoin;
  8814. material.vertexColors = this.vertexColors;
  8815. material.skinning = this.skinning;
  8816. material.morphTargets = this.morphTargets;
  8817. return material;
  8818. };
  8819. /**
  8820. * @author mrdoob / http://mrdoob.com/
  8821. * @author alteredq / http://alteredqualia.com/
  8822. *
  8823. * parameters = {
  8824. * color: <hex>,
  8825. * ambient: <hex>,
  8826. * emissive: <hex>,
  8827. * opacity: <float>,
  8828. *
  8829. * map: new THREE.Texture( <Image> ),
  8830. *
  8831. * lightMap: new THREE.Texture( <Image> ),
  8832. *
  8833. * specularMap: new THREE.Texture( <Image> ),
  8834. *
  8835. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8836. * combine: THREE.Multiply,
  8837. * reflectivity: <float>,
  8838. * refractionRatio: <float>,
  8839. *
  8840. * shading: THREE.SmoothShading,
  8841. * blending: THREE.NormalBlending,
  8842. * depthTest: <bool>,
  8843. * depthWrite: <bool>,
  8844. *
  8845. * wireframe: <boolean>,
  8846. * wireframeLinewidth: <float>,
  8847. *
  8848. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8849. *
  8850. * skinning: <bool>,
  8851. * morphTargets: <bool>,
  8852. * morphNormals: <bool>,
  8853. *
  8854. * fog: <bool>
  8855. * }
  8856. */
  8857. THREE.MeshLambertMaterial = function ( parameters ) {
  8858. THREE.Material.call( this );
  8859. this.color = new THREE.Color( 0xffffff ); // diffuse
  8860. this.ambient = new THREE.Color( 0xffffff );
  8861. this.emissive = new THREE.Color( 0x000000 );
  8862. this.wrapAround = false;
  8863. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8864. this.map = null;
  8865. this.lightMap = null;
  8866. this.specularMap = null;
  8867. this.envMap = null;
  8868. this.combine = THREE.MultiplyOperation;
  8869. this.reflectivity = 1;
  8870. this.refractionRatio = 0.98;
  8871. this.fog = true;
  8872. this.shading = THREE.SmoothShading;
  8873. this.wireframe = false;
  8874. this.wireframeLinewidth = 1;
  8875. this.wireframeLinecap = 'round';
  8876. this.wireframeLinejoin = 'round';
  8877. this.vertexColors = THREE.NoColors;
  8878. this.skinning = false;
  8879. this.morphTargets = false;
  8880. this.morphNormals = false;
  8881. this.setValues( parameters );
  8882. };
  8883. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  8884. THREE.MeshLambertMaterial.prototype.clone = function () {
  8885. var material = new THREE.MeshLambertMaterial();
  8886. THREE.Material.prototype.clone.call( this, material );
  8887. material.color.copy( this.color );
  8888. material.ambient.copy( this.ambient );
  8889. material.emissive.copy( this.emissive );
  8890. material.wrapAround = this.wrapAround;
  8891. material.wrapRGB.copy( this.wrapRGB );
  8892. material.map = this.map;
  8893. material.lightMap = this.lightMap;
  8894. material.specularMap = this.specularMap;
  8895. material.envMap = this.envMap;
  8896. material.combine = this.combine;
  8897. material.reflectivity = this.reflectivity;
  8898. material.refractionRatio = this.refractionRatio;
  8899. material.fog = this.fog;
  8900. material.shading = this.shading;
  8901. material.wireframe = this.wireframe;
  8902. material.wireframeLinewidth = this.wireframeLinewidth;
  8903. material.wireframeLinecap = this.wireframeLinecap;
  8904. material.wireframeLinejoin = this.wireframeLinejoin;
  8905. material.vertexColors = this.vertexColors;
  8906. material.skinning = this.skinning;
  8907. material.morphTargets = this.morphTargets;
  8908. material.morphNormals = this.morphNormals;
  8909. return material;
  8910. };
  8911. /**
  8912. * @author mrdoob / http://mrdoob.com/
  8913. * @author alteredq / http://alteredqualia.com/
  8914. *
  8915. * parameters = {
  8916. * color: <hex>,
  8917. * ambient: <hex>,
  8918. * emissive: <hex>,
  8919. * specular: <hex>,
  8920. * shininess: <float>,
  8921. * opacity: <float>,
  8922. *
  8923. * map: new THREE.Texture( <Image> ),
  8924. *
  8925. * lightMap: new THREE.Texture( <Image> ),
  8926. *
  8927. * bumpMap: new THREE.Texture( <Image> ),
  8928. * bumpScale: <float>,
  8929. *
  8930. * normalMap: new THREE.Texture( <Image> ),
  8931. * normalScale: <Vector2>,
  8932. *
  8933. * specularMap: new THREE.Texture( <Image> ),
  8934. *
  8935. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8936. * combine: THREE.Multiply,
  8937. * reflectivity: <float>,
  8938. * refractionRatio: <float>,
  8939. *
  8940. * shading: THREE.SmoothShading,
  8941. * blending: THREE.NormalBlending,
  8942. * depthTest: <bool>,
  8943. * depthWrite: <bool>,
  8944. *
  8945. * wireframe: <boolean>,
  8946. * wireframeLinewidth: <float>,
  8947. *
  8948. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8949. *
  8950. * skinning: <bool>,
  8951. * morphTargets: <bool>,
  8952. * morphNormals: <bool>,
  8953. *
  8954. * fog: <bool>
  8955. * }
  8956. */
  8957. THREE.MeshPhongMaterial = function ( parameters ) {
  8958. THREE.Material.call( this );
  8959. this.color = new THREE.Color( 0xffffff ); // diffuse
  8960. this.ambient = new THREE.Color( 0xffffff );
  8961. this.emissive = new THREE.Color( 0x000000 );
  8962. this.specular = new THREE.Color( 0x111111 );
  8963. this.shininess = 30;
  8964. this.metal = false;
  8965. this.wrapAround = false;
  8966. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8967. this.map = null;
  8968. this.lightMap = null;
  8969. this.bumpMap = null;
  8970. this.bumpScale = 1;
  8971. this.normalMap = null;
  8972. this.normalScale = new THREE.Vector2( 1, 1 );
  8973. this.specularMap = null;
  8974. this.envMap = null;
  8975. this.combine = THREE.MultiplyOperation;
  8976. this.reflectivity = 1;
  8977. this.refractionRatio = 0.98;
  8978. this.fog = true;
  8979. this.shading = THREE.SmoothShading;
  8980. this.wireframe = false;
  8981. this.wireframeLinewidth = 1;
  8982. this.wireframeLinecap = 'round';
  8983. this.wireframeLinejoin = 'round';
  8984. this.vertexColors = THREE.NoColors;
  8985. this.skinning = false;
  8986. this.morphTargets = false;
  8987. this.morphNormals = false;
  8988. this.setValues( parameters );
  8989. };
  8990. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  8991. THREE.MeshPhongMaterial.prototype.clone = function () {
  8992. var material = new THREE.MeshPhongMaterial();
  8993. THREE.Material.prototype.clone.call( this, material );
  8994. material.color.copy( this.color );
  8995. material.ambient.copy( this.ambient );
  8996. material.emissive.copy( this.emissive );
  8997. material.specular.copy( this.specular );
  8998. material.shininess = this.shininess;
  8999. material.metal = this.metal;
  9000. material.wrapAround = this.wrapAround;
  9001. material.wrapRGB.copy( this.wrapRGB );
  9002. material.map = this.map;
  9003. material.lightMap = this.lightMap;
  9004. material.bumpMap = this.bumpMap;
  9005. material.bumpScale = this.bumpScale;
  9006. material.normalMap = this.normalMap;
  9007. material.normalScale.copy( this.normalScale );
  9008. material.specularMap = this.specularMap;
  9009. material.envMap = this.envMap;
  9010. material.combine = this.combine;
  9011. material.reflectivity = this.reflectivity;
  9012. material.refractionRatio = this.refractionRatio;
  9013. material.fog = this.fog;
  9014. material.shading = this.shading;
  9015. material.wireframe = this.wireframe;
  9016. material.wireframeLinewidth = this.wireframeLinewidth;
  9017. material.wireframeLinecap = this.wireframeLinecap;
  9018. material.wireframeLinejoin = this.wireframeLinejoin;
  9019. material.vertexColors = this.vertexColors;
  9020. material.skinning = this.skinning;
  9021. material.morphTargets = this.morphTargets;
  9022. material.morphNormals = this.morphNormals;
  9023. return material;
  9024. };
  9025. /**
  9026. * @author mrdoob / http://mrdoob.com/
  9027. * @author alteredq / http://alteredqualia.com/
  9028. *
  9029. * parameters = {
  9030. * opacity: <float>,
  9031. *
  9032. * blending: THREE.NormalBlending,
  9033. * depthTest: <bool>,
  9034. * depthWrite: <bool>,
  9035. *
  9036. * wireframe: <boolean>,
  9037. * wireframeLinewidth: <float>
  9038. * }
  9039. */
  9040. THREE.MeshDepthMaterial = function ( parameters ) {
  9041. THREE.Material.call( this );
  9042. this.wireframe = false;
  9043. this.wireframeLinewidth = 1;
  9044. this.setValues( parameters );
  9045. };
  9046. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  9047. THREE.MeshDepthMaterial.prototype.clone = function () {
  9048. var material = new THREE.MeshDepthMaterial();
  9049. THREE.Material.prototype.clone.call( this, material );
  9050. material.wireframe = this.wireframe;
  9051. material.wireframeLinewidth = this.wireframeLinewidth;
  9052. return material;
  9053. };
  9054. /**
  9055. * @author mrdoob / http://mrdoob.com/
  9056. *
  9057. * parameters = {
  9058. * opacity: <float>,
  9059. *
  9060. * shading: THREE.FlatShading,
  9061. * blending: THREE.NormalBlending,
  9062. * depthTest: <bool>,
  9063. * depthWrite: <bool>,
  9064. *
  9065. * wireframe: <boolean>,
  9066. * wireframeLinewidth: <float>
  9067. * }
  9068. */
  9069. THREE.MeshNormalMaterial = function ( parameters ) {
  9070. THREE.Material.call( this, parameters );
  9071. this.shading = THREE.FlatShading;
  9072. this.wireframe = false;
  9073. this.wireframeLinewidth = 1;
  9074. this.morphTargets = false;
  9075. this.setValues( parameters );
  9076. };
  9077. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  9078. THREE.MeshNormalMaterial.prototype.clone = function () {
  9079. var material = new THREE.MeshNormalMaterial();
  9080. THREE.Material.prototype.clone.call( this, material );
  9081. material.shading = this.shading;
  9082. material.wireframe = this.wireframe;
  9083. material.wireframeLinewidth = this.wireframeLinewidth;
  9084. return material;
  9085. };
  9086. /**
  9087. * @author mrdoob / http://mrdoob.com/
  9088. */
  9089. THREE.MeshFaceMaterial = function ( materials ) {
  9090. this.materials = materials instanceof Array ? materials : [];
  9091. };
  9092. THREE.MeshFaceMaterial.prototype.clone = function () {
  9093. var material = new THREE.MeshFaceMaterial();
  9094. for ( var i = 0; i < this.materials.length; i ++ ) {
  9095. material.materials.push( this.materials[ i ].clone() );
  9096. }
  9097. return material;
  9098. };
  9099. /**
  9100. * @author mrdoob / http://mrdoob.com/
  9101. * @author alteredq / http://alteredqualia.com/
  9102. *
  9103. * parameters = {
  9104. * color: <hex>,
  9105. * opacity: <float>,
  9106. * map: new THREE.Texture( <Image> ),
  9107. *
  9108. * size: <float>,
  9109. *
  9110. * blending: THREE.NormalBlending,
  9111. * depthTest: <bool>,
  9112. * depthWrite: <bool>,
  9113. *
  9114. * vertexColors: <bool>,
  9115. *
  9116. * fog: <bool>
  9117. * }
  9118. */
  9119. THREE.ParticleSystemMaterial = function ( parameters ) {
  9120. THREE.Material.call( this );
  9121. this.color = new THREE.Color( 0xffffff );
  9122. this.map = null;
  9123. this.size = 1;
  9124. this.sizeAttenuation = true;
  9125. this.vertexColors = false;
  9126. this.fog = true;
  9127. this.setValues( parameters );
  9128. };
  9129. THREE.ParticleSystemMaterial.prototype = Object.create( THREE.Material.prototype );
  9130. THREE.ParticleSystemMaterial.prototype.clone = function () {
  9131. var material = new THREE.ParticleSystemMaterial();
  9132. THREE.Material.prototype.clone.call( this, material );
  9133. material.color.copy( this.color );
  9134. material.map = this.map;
  9135. material.size = this.size;
  9136. material.sizeAttenuation = this.sizeAttenuation;
  9137. material.vertexColors = this.vertexColors;
  9138. material.fog = this.fog;
  9139. return material;
  9140. };
  9141. // backwards compatibility
  9142. THREE.ParticleBasicMaterial = THREE.ParticleSystemMaterial;
  9143. /**
  9144. * @author alteredq / http://alteredqualia.com/
  9145. *
  9146. * parameters = {
  9147. * fragmentShader: <string>,
  9148. * vertexShader: <string>,
  9149. *
  9150. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  9151. *
  9152. * defines: { "label" : "value" },
  9153. *
  9154. * shading: THREE.SmoothShading,
  9155. * blending: THREE.NormalBlending,
  9156. * depthTest: <bool>,
  9157. * depthWrite: <bool>,
  9158. *
  9159. * wireframe: <boolean>,
  9160. * wireframeLinewidth: <float>,
  9161. *
  9162. * lights: <bool>,
  9163. *
  9164. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  9165. *
  9166. * skinning: <bool>,
  9167. * morphTargets: <bool>,
  9168. * morphNormals: <bool>,
  9169. *
  9170. * fog: <bool>
  9171. * }
  9172. */
  9173. THREE.ShaderMaterial = function ( parameters ) {
  9174. THREE.Material.call( this );
  9175. this.fragmentShader = "void main() {}";
  9176. this.vertexShader = "void main() {}";
  9177. this.uniforms = {};
  9178. this.defines = {};
  9179. this.attributes = null;
  9180. this.shading = THREE.SmoothShading;
  9181. this.linewidth = 1;
  9182. this.wireframe = false;
  9183. this.wireframeLinewidth = 1;
  9184. this.fog = false; // set to use scene fog
  9185. this.lights = false; // set to use scene lights
  9186. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  9187. this.skinning = false; // set to use skinning attribute streams
  9188. this.morphTargets = false; // set to use morph targets
  9189. this.morphNormals = false; // set to use morph normals
  9190. // When rendered geometry doesn't include these attributes but the material does,
  9191. // use these default values in WebGL. This avoids errors when buffer data is missing.
  9192. this.defaultAttributeValues = {
  9193. "color" : [ 1, 1, 1 ],
  9194. "uv" : [ 0, 0 ],
  9195. "uv2" : [ 0, 0 ]
  9196. };
  9197. this.index0AttributeName = undefined;
  9198. this.setValues( parameters );
  9199. };
  9200. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  9201. THREE.ShaderMaterial.prototype.clone = function () {
  9202. var material = new THREE.ShaderMaterial();
  9203. THREE.Material.prototype.clone.call( this, material );
  9204. material.fragmentShader = this.fragmentShader;
  9205. material.vertexShader = this.vertexShader;
  9206. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  9207. material.attributes = this.attributes;
  9208. material.defines = this.defines;
  9209. material.shading = this.shading;
  9210. material.wireframe = this.wireframe;
  9211. material.wireframeLinewidth = this.wireframeLinewidth;
  9212. material.fog = this.fog;
  9213. material.lights = this.lights;
  9214. material.vertexColors = this.vertexColors;
  9215. material.skinning = this.skinning;
  9216. material.morphTargets = this.morphTargets;
  9217. material.morphNormals = this.morphNormals;
  9218. return material;
  9219. };
  9220. /**
  9221. * @author mrdoob / http://mrdoob.com/
  9222. */
  9223. THREE.RawShaderMaterial = function ( parameters ) {
  9224. THREE.ShaderMaterial.call( this, parameters );
  9225. };
  9226. THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype );
  9227. THREE.RawShaderMaterial.prototype.clone = function () {
  9228. var material = new THREE.RawShaderMaterial();
  9229. THREE.ShaderMaterial.prototype.clone.call( this, material );
  9230. return material;
  9231. };
  9232. /**
  9233. * @author alteredq / http://alteredqualia.com/
  9234. *
  9235. * parameters = {
  9236. * color: <hex>,
  9237. * opacity: <float>,
  9238. * map: new THREE.Texture( <Image> ),
  9239. *
  9240. * blending: THREE.NormalBlending,
  9241. * depthTest: <bool>,
  9242. * depthWrite: <bool>,
  9243. *
  9244. * uvOffset: new THREE.Vector2(),
  9245. * uvScale: new THREE.Vector2(),
  9246. *
  9247. * fog: <bool>
  9248. * }
  9249. */
  9250. THREE.SpriteMaterial = function ( parameters ) {
  9251. THREE.Material.call( this );
  9252. // defaults
  9253. this.color = new THREE.Color( 0xffffff );
  9254. this.map = null;
  9255. this.rotation = 0;
  9256. this.fog = false;
  9257. // set parameters
  9258. this.setValues( parameters );
  9259. };
  9260. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  9261. THREE.SpriteMaterial.prototype.clone = function () {
  9262. var material = new THREE.SpriteMaterial();
  9263. THREE.Material.prototype.clone.call( this, material );
  9264. material.color.copy( this.color );
  9265. material.map = this.map;
  9266. material.rotation = this.rotation;
  9267. material.fog = this.fog;
  9268. return material;
  9269. };
  9270. /**
  9271. * @author mrdoob / http://mrdoob.com/
  9272. *
  9273. * parameters = {
  9274. * color: <hex>,
  9275. * program: <function>,
  9276. * opacity: <float>,
  9277. * blending: THREE.NormalBlending
  9278. * }
  9279. */
  9280. THREE.SpriteCanvasMaterial = function ( parameters ) {
  9281. THREE.Material.call( this );
  9282. this.color = new THREE.Color( 0xffffff );
  9283. this.program = function ( context, color ) {};
  9284. this.setValues( parameters );
  9285. };
  9286. THREE.SpriteCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  9287. THREE.SpriteCanvasMaterial.prototype.clone = function () {
  9288. var material = new THREE.SpriteCanvasMaterial();
  9289. THREE.Material.prototype.clone.call( this, material );
  9290. material.color.copy( this.color );
  9291. material.program = this.program;
  9292. return material;
  9293. };
  9294. // backwards compatibility
  9295. THREE.ParticleCanvasMaterial = THREE.SpriteCanvasMaterial;
  9296. /**
  9297. * @author mrdoob / http://mrdoob.com/
  9298. * @author alteredq / http://alteredqualia.com/
  9299. * @author szimek / https://github.com/szimek/
  9300. */
  9301. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  9302. this.id = THREE.TextureIdCount ++;
  9303. this.uuid = THREE.Math.generateUUID();
  9304. this.name = '';
  9305. this.image = image;
  9306. this.mipmaps = [];
  9307. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  9308. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  9309. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  9310. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  9311. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  9312. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  9313. this.format = format !== undefined ? format : THREE.RGBAFormat;
  9314. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  9315. this.offset = new THREE.Vector2( 0, 0 );
  9316. this.repeat = new THREE.Vector2( 1, 1 );
  9317. this.generateMipmaps = true;
  9318. this.premultiplyAlpha = false;
  9319. this.flipY = true;
  9320. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  9321. this._needsUpdate = false;
  9322. this.onUpdate = null;
  9323. };
  9324. THREE.Texture.prototype = {
  9325. constructor: THREE.Texture,
  9326. get needsUpdate () {
  9327. return this._needsUpdate;
  9328. },
  9329. set needsUpdate ( value ) {
  9330. if ( value === true ) this.update();
  9331. this._needsUpdate = value;
  9332. },
  9333. clone: function ( texture ) {
  9334. if ( texture === undefined ) texture = new THREE.Texture();
  9335. texture.image = this.image;
  9336. texture.mipmaps = this.mipmaps.slice(0);
  9337. texture.mapping = this.mapping;
  9338. texture.wrapS = this.wrapS;
  9339. texture.wrapT = this.wrapT;
  9340. texture.magFilter = this.magFilter;
  9341. texture.minFilter = this.minFilter;
  9342. texture.anisotropy = this.anisotropy;
  9343. texture.format = this.format;
  9344. texture.type = this.type;
  9345. texture.offset.copy( this.offset );
  9346. texture.repeat.copy( this.repeat );
  9347. texture.generateMipmaps = this.generateMipmaps;
  9348. texture.premultiplyAlpha = this.premultiplyAlpha;
  9349. texture.flipY = this.flipY;
  9350. texture.unpackAlignment = this.unpackAlignment;
  9351. return texture;
  9352. },
  9353. update: function () {
  9354. this.dispatchEvent( { type: 'update' } );
  9355. },
  9356. dispose: function () {
  9357. this.dispatchEvent( { type: 'dispose' } );
  9358. }
  9359. };
  9360. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  9361. THREE.TextureIdCount = 0;
  9362. /**
  9363. * @author alteredq / http://alteredqualia.com/
  9364. */
  9365. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  9366. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  9367. this.image = { width: width, height: height };
  9368. this.mipmaps = mipmaps;
  9369. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  9370. };
  9371. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  9372. THREE.CompressedTexture.prototype.clone = function () {
  9373. var texture = new THREE.CompressedTexture();
  9374. THREE.Texture.prototype.clone.call( this, texture );
  9375. return texture;
  9376. };
  9377. /**
  9378. * @author alteredq / http://alteredqualia.com/
  9379. */
  9380. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  9381. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  9382. this.image = { data: data, width: width, height: height };
  9383. };
  9384. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  9385. THREE.DataTexture.prototype.clone = function () {
  9386. var texture = new THREE.DataTexture();
  9387. THREE.Texture.prototype.clone.call( this, texture );
  9388. return texture;
  9389. };
  9390. /**
  9391. * @author alteredq / http://alteredqualia.com/
  9392. */
  9393. THREE.ParticleSystem = function ( geometry, material ) {
  9394. THREE.Object3D.call( this );
  9395. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9396. this.material = material !== undefined ? material : new THREE.ParticleSystemMaterial( { color: Math.random() * 0xffffff } );
  9397. this.sortParticles = false;
  9398. this.frustumCulled = false;
  9399. };
  9400. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  9401. THREE.ParticleSystem.prototype.clone = function ( object ) {
  9402. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  9403. object.sortParticles = this.sortParticles;
  9404. THREE.Object3D.prototype.clone.call( this, object );
  9405. return object;
  9406. };
  9407. /**
  9408. * @author mrdoob / http://mrdoob.com/
  9409. */
  9410. THREE.Line = function ( geometry, material, type ) {
  9411. THREE.Object3D.call( this );
  9412. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9413. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  9414. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  9415. };
  9416. THREE.LineStrip = 0;
  9417. THREE.LinePieces = 1;
  9418. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  9419. THREE.Line.prototype.clone = function ( object ) {
  9420. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  9421. THREE.Object3D.prototype.clone.call( this, object );
  9422. return object;
  9423. };
  9424. /**
  9425. * @author mrdoob / http://mrdoob.com/
  9426. * @author alteredq / http://alteredqualia.com/
  9427. * @author mikael emtinger / http://gomo.se/
  9428. * @author jonobr1 / http://jonobr1.com/
  9429. */
  9430. THREE.Mesh = function ( geometry, material ) {
  9431. THREE.Object3D.call( this );
  9432. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9433. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  9434. this.updateMorphTargets();
  9435. };
  9436. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  9437. THREE.Mesh.prototype.updateMorphTargets = function () {
  9438. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  9439. this.morphTargetBase = -1;
  9440. this.morphTargetForcedOrder = [];
  9441. this.morphTargetInfluences = [];
  9442. this.morphTargetDictionary = {};
  9443. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  9444. this.morphTargetInfluences.push( 0 );
  9445. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  9446. }
  9447. }
  9448. };
  9449. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  9450. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  9451. return this.morphTargetDictionary[ name ];
  9452. }
  9453. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  9454. return 0;
  9455. };
  9456. THREE.Mesh.prototype.clone = function ( object, recursive ) {
  9457. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  9458. THREE.Object3D.prototype.clone.call( this, object, recursive );
  9459. return object;
  9460. };
  9461. /**
  9462. * @author mikael emtinger / http://gomo.se/
  9463. * @author alteredq / http://alteredqualia.com/
  9464. */
  9465. THREE.Bone = function( belongsToSkin ) {
  9466. THREE.Object3D.call( this );
  9467. this.skin = belongsToSkin;
  9468. this.skinMatrix = new THREE.Matrix4();
  9469. };
  9470. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  9471. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  9472. // update local
  9473. if ( this.matrixAutoUpdate ) {
  9474. forceUpdate |= this.updateMatrix();
  9475. }
  9476. // update skin matrix
  9477. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  9478. if ( parentSkinMatrix ) {
  9479. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  9480. } else {
  9481. this.skinMatrix.copy( this.matrix );
  9482. }
  9483. this.matrixWorldNeedsUpdate = false;
  9484. forceUpdate = true;
  9485. }
  9486. // update children
  9487. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  9488. this.children[ i ].update( this.skinMatrix, forceUpdate );
  9489. }
  9490. };
  9491. /**
  9492. * @author mikael emtinger / http://gomo.se/
  9493. * @author alteredq / http://alteredqualia.com/
  9494. */
  9495. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  9496. THREE.Mesh.call( this, geometry, material );
  9497. //
  9498. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  9499. // init bones
  9500. this.identityMatrix = new THREE.Matrix4();
  9501. this.bones = [];
  9502. this.boneMatrices = [];
  9503. var b, bone, gbone, p, q, s;
  9504. if ( this.geometry && this.geometry.bones !== undefined ) {
  9505. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  9506. gbone = this.geometry.bones[ b ];
  9507. p = gbone.pos;
  9508. q = gbone.rotq;
  9509. s = gbone.scl;
  9510. bone = this.addBone();
  9511. bone.name = gbone.name;
  9512. bone.position.set( p[0], p[1], p[2] );
  9513. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  9514. if ( s !== undefined ) {
  9515. bone.scale.set( s[0], s[1], s[2] );
  9516. } else {
  9517. bone.scale.set( 1, 1, 1 );
  9518. }
  9519. }
  9520. for ( b = 0; b < this.bones.length; b ++ ) {
  9521. gbone = this.geometry.bones[ b ];
  9522. bone = this.bones[ b ];
  9523. if ( gbone.parent === -1 ) {
  9524. this.add( bone );
  9525. } else {
  9526. this.bones[ gbone.parent ].add( bone );
  9527. }
  9528. }
  9529. //
  9530. var nBones = this.bones.length;
  9531. if ( this.useVertexTexture ) {
  9532. // layout (1 matrix = 4 pixels)
  9533. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  9534. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  9535. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  9536. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  9537. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  9538. var size;
  9539. if ( nBones > 256 )
  9540. size = 64;
  9541. else if ( nBones > 64 )
  9542. size = 32;
  9543. else if ( nBones > 16 )
  9544. size = 16;
  9545. else
  9546. size = 8;
  9547. this.boneTextureWidth = size;
  9548. this.boneTextureHeight = size;
  9549. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  9550. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  9551. this.boneTexture.minFilter = THREE.NearestFilter;
  9552. this.boneTexture.magFilter = THREE.NearestFilter;
  9553. this.boneTexture.generateMipmaps = false;
  9554. this.boneTexture.flipY = false;
  9555. } else {
  9556. this.boneMatrices = new Float32Array( 16 * nBones );
  9557. }
  9558. this.pose();
  9559. }
  9560. };
  9561. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  9562. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  9563. if ( bone === undefined ) {
  9564. bone = new THREE.Bone( this );
  9565. }
  9566. this.bones.push( bone );
  9567. return bone;
  9568. };
  9569. THREE.SkinnedMesh.prototype.updateMatrixWorld = function () {
  9570. var offsetMatrix = new THREE.Matrix4();
  9571. return function ( force ) {
  9572. this.matrixAutoUpdate && this.updateMatrix();
  9573. // update matrixWorld
  9574. if ( this.matrixWorldNeedsUpdate || force ) {
  9575. if ( this.parent ) {
  9576. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9577. } else {
  9578. this.matrixWorld.copy( this.matrix );
  9579. }
  9580. this.matrixWorldNeedsUpdate = false;
  9581. force = true;
  9582. }
  9583. // update children
  9584. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  9585. var child = this.children[ i ];
  9586. if ( child instanceof THREE.Bone ) {
  9587. child.update( this.identityMatrix, false );
  9588. } else {
  9589. child.updateMatrixWorld( true );
  9590. }
  9591. }
  9592. // make a snapshot of the bones' rest position
  9593. if ( this.boneInverses == undefined ) {
  9594. this.boneInverses = [];
  9595. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9596. var inverse = new THREE.Matrix4();
  9597. inverse.getInverse( this.bones[ b ].skinMatrix );
  9598. this.boneInverses.push( inverse );
  9599. }
  9600. }
  9601. // flatten bone matrices to array
  9602. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9603. // compute the offset between the current and the original transform;
  9604. // TODO: we could get rid of this multiplication step if the skinMatrix
  9605. // was already representing the offset; however, this requires some
  9606. // major changes to the animation system
  9607. offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  9608. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  9609. }
  9610. if ( this.useVertexTexture ) {
  9611. this.boneTexture.needsUpdate = true;
  9612. }
  9613. };
  9614. }();
  9615. THREE.SkinnedMesh.prototype.pose = function () {
  9616. this.updateMatrixWorld( true );
  9617. this.normalizeSkinWeights();
  9618. };
  9619. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  9620. if ( this.geometry instanceof THREE.Geometry ) {
  9621. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  9622. var sw = this.geometry.skinWeights[ i ];
  9623. var scale = 1.0 / sw.lengthManhattan();
  9624. if ( scale !== Infinity ) {
  9625. sw.multiplyScalar( scale );
  9626. } else {
  9627. sw.set( 1 ); // this will be normalized by the shader anyway
  9628. }
  9629. }
  9630. } else {
  9631. // skinning weights assumed to be normalized for THREE.BufferGeometry
  9632. }
  9633. };
  9634. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  9635. if ( object === undefined ) {
  9636. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  9637. }
  9638. THREE.Mesh.prototype.clone.call( this, object );
  9639. return object;
  9640. };
  9641. /**
  9642. * @author alteredq / http://alteredqualia.com/
  9643. */
  9644. THREE.MorphAnimMesh = function ( geometry, material ) {
  9645. THREE.Mesh.call( this, geometry, material );
  9646. // API
  9647. this.duration = 1000; // milliseconds
  9648. this.mirroredLoop = false;
  9649. this.time = 0;
  9650. // internals
  9651. this.lastKeyframe = 0;
  9652. this.currentKeyframe = 0;
  9653. this.direction = 1;
  9654. this.directionBackwards = false;
  9655. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  9656. };
  9657. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  9658. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  9659. this.startKeyframe = start;
  9660. this.endKeyframe = end;
  9661. this.length = this.endKeyframe - this.startKeyframe + 1;
  9662. };
  9663. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  9664. this.direction = 1;
  9665. this.directionBackwards = false;
  9666. };
  9667. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  9668. this.direction = -1;
  9669. this.directionBackwards = true;
  9670. };
  9671. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  9672. var geometry = this.geometry;
  9673. if ( ! geometry.animations ) geometry.animations = {};
  9674. var firstAnimation, animations = geometry.animations;
  9675. var pattern = /([a-z]+)(\d+)/;
  9676. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  9677. var morph = geometry.morphTargets[ i ];
  9678. var parts = morph.name.match( pattern );
  9679. if ( parts && parts.length > 1 ) {
  9680. var label = parts[ 1 ];
  9681. var num = parts[ 2 ];
  9682. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  9683. var animation = animations[ label ];
  9684. if ( i < animation.start ) animation.start = i;
  9685. if ( i > animation.end ) animation.end = i;
  9686. if ( ! firstAnimation ) firstAnimation = label;
  9687. }
  9688. }
  9689. geometry.firstAnimation = firstAnimation;
  9690. };
  9691. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  9692. if ( ! this.geometry.animations ) this.geometry.animations = {};
  9693. this.geometry.animations[ label ] = { start: start, end: end };
  9694. };
  9695. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  9696. var animation = this.geometry.animations[ label ];
  9697. if ( animation ) {
  9698. this.setFrameRange( animation.start, animation.end );
  9699. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  9700. this.time = 0;
  9701. } else {
  9702. console.warn( "animation[" + label + "] undefined" );
  9703. }
  9704. };
  9705. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  9706. var frameTime = this.duration / this.length;
  9707. this.time += this.direction * delta;
  9708. if ( this.mirroredLoop ) {
  9709. if ( this.time > this.duration || this.time < 0 ) {
  9710. this.direction *= -1;
  9711. if ( this.time > this.duration ) {
  9712. this.time = this.duration;
  9713. this.directionBackwards = true;
  9714. }
  9715. if ( this.time < 0 ) {
  9716. this.time = 0;
  9717. this.directionBackwards = false;
  9718. }
  9719. }
  9720. } else {
  9721. this.time = this.time % this.duration;
  9722. if ( this.time < 0 ) this.time += this.duration;
  9723. }
  9724. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  9725. if ( keyframe !== this.currentKeyframe ) {
  9726. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  9727. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  9728. this.morphTargetInfluences[ keyframe ] = 0;
  9729. this.lastKeyframe = this.currentKeyframe;
  9730. this.currentKeyframe = keyframe;
  9731. }
  9732. var mix = ( this.time % frameTime ) / frameTime;
  9733. if ( this.directionBackwards ) {
  9734. mix = 1 - mix;
  9735. }
  9736. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  9737. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  9738. };
  9739. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  9740. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  9741. object.duration = this.duration;
  9742. object.mirroredLoop = this.mirroredLoop;
  9743. object.time = this.time;
  9744. object.lastKeyframe = this.lastKeyframe;
  9745. object.currentKeyframe = this.currentKeyframe;
  9746. object.direction = this.direction;
  9747. object.directionBackwards = this.directionBackwards;
  9748. THREE.Mesh.prototype.clone.call( this, object );
  9749. return object;
  9750. };
  9751. /**
  9752. * @author mikael emtinger / http://gomo.se/
  9753. * @author alteredq / http://alteredqualia.com/
  9754. * @author mrdoob / http://mrdoob.com/
  9755. */
  9756. THREE.LOD = function () {
  9757. THREE.Object3D.call( this );
  9758. this.objects = [];
  9759. };
  9760. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  9761. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  9762. if ( distance === undefined ) distance = 0;
  9763. distance = Math.abs( distance );
  9764. for ( var l = 0; l < this.objects.length; l ++ ) {
  9765. if ( distance < this.objects[ l ].distance ) {
  9766. break;
  9767. }
  9768. }
  9769. this.objects.splice( l, 0, { distance: distance, object: object } );
  9770. this.add( object );
  9771. };
  9772. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  9773. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9774. if ( distance < this.objects[ i ].distance ) {
  9775. break;
  9776. }
  9777. }
  9778. return this.objects[ i - 1 ].object;
  9779. };
  9780. THREE.LOD.prototype.update = function () {
  9781. var v1 = new THREE.Vector3();
  9782. var v2 = new THREE.Vector3();
  9783. return function ( camera ) {
  9784. if ( this.objects.length > 1 ) {
  9785. v1.setFromMatrixPosition( camera.matrixWorld );
  9786. v2.setFromMatrixPosition( this.matrixWorld );
  9787. var distance = v1.distanceTo( v2 );
  9788. this.objects[ 0 ].object.visible = true;
  9789. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9790. if ( distance >= this.objects[ i ].distance ) {
  9791. this.objects[ i - 1 ].object.visible = false;
  9792. this.objects[ i ].object.visible = true;
  9793. } else {
  9794. break;
  9795. }
  9796. }
  9797. for( ; i < l; i ++ ) {
  9798. this.objects[ i ].object.visible = false;
  9799. }
  9800. }
  9801. };
  9802. }();
  9803. THREE.LOD.prototype.clone = function ( object ) {
  9804. if ( object === undefined ) object = new THREE.LOD();
  9805. THREE.Object3D.prototype.clone.call( this, object );
  9806. for ( var i = 0, l = this.objects.length; i < l; i ++ ) {
  9807. var x = this.objects[i].object.clone();
  9808. x.visible = i === 0;
  9809. object.addLevel( x, this.objects[i].distance );
  9810. }
  9811. return object;
  9812. };
  9813. /**
  9814. * @author mikael emtinger / http://gomo.se/
  9815. * @author alteredq / http://alteredqualia.com/
  9816. */
  9817. THREE.Sprite = ( function () {
  9818. var vertices = new THREE.Float32Attribute( 3, 3 );
  9819. vertices.set( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0 ] );
  9820. var geometry = new THREE.BufferGeometry();
  9821. geometry.addAttribute( 'position', vertices );
  9822. return function ( material ) {
  9823. THREE.Object3D.call( this );
  9824. this.geometry = geometry;
  9825. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  9826. };
  9827. } )();
  9828. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  9829. /*
  9830. * Custom update matrix
  9831. */
  9832. THREE.Sprite.prototype.updateMatrix = function () {
  9833. this.matrix.compose( this.position, this.quaternion, this.scale );
  9834. this.matrixWorldNeedsUpdate = true;
  9835. };
  9836. THREE.Sprite.prototype.clone = function ( object ) {
  9837. if ( object === undefined ) object = new THREE.Sprite( this.material );
  9838. THREE.Object3D.prototype.clone.call( this, object );
  9839. return object;
  9840. };
  9841. // Backwards compatibility
  9842. THREE.Particle = THREE.Sprite;
  9843. /**
  9844. * @author mrdoob / http://mrdoob.com/
  9845. */
  9846. THREE.Scene = function () {
  9847. THREE.Object3D.call( this );
  9848. this.fog = null;
  9849. this.overrideMaterial = null;
  9850. this.autoUpdate = true; // checked by the renderer
  9851. this.matrixAutoUpdate = false;
  9852. this.__lights = [];
  9853. this.__objectsAdded = [];
  9854. this.__objectsRemoved = [];
  9855. };
  9856. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  9857. THREE.Scene.prototype.__addObject = function ( object ) {
  9858. if ( object instanceof THREE.Light ) {
  9859. if ( this.__lights.indexOf( object ) === - 1 ) {
  9860. this.__lights.push( object );
  9861. }
  9862. if ( object.target && object.target.parent === undefined ) {
  9863. this.add( object.target );
  9864. }
  9865. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  9866. this.__objectsAdded.push( object );
  9867. // check if previously removed
  9868. var i = this.__objectsRemoved.indexOf( object );
  9869. if ( i !== -1 ) {
  9870. this.__objectsRemoved.splice( i, 1 );
  9871. }
  9872. }
  9873. this.dispatchEvent( { type: 'objectAdded', object: object } );
  9874. object.dispatchEvent( { type: 'addedToScene', scene: this } );
  9875. for ( var c = 0; c < object.children.length; c ++ ) {
  9876. this.__addObject( object.children[ c ] );
  9877. }
  9878. };
  9879. THREE.Scene.prototype.__removeObject = function ( object ) {
  9880. if ( object instanceof THREE.Light ) {
  9881. var i = this.__lights.indexOf( object );
  9882. if ( i !== -1 ) {
  9883. this.__lights.splice( i, 1 );
  9884. }
  9885. if ( object.shadowCascadeArray ) {
  9886. for ( var x = 0; x < object.shadowCascadeArray.length; x ++ ) {
  9887. this.__removeObject( object.shadowCascadeArray[ x ] );
  9888. }
  9889. }
  9890. } else if ( !( object instanceof THREE.Camera ) ) {
  9891. this.__objectsRemoved.push( object );
  9892. // check if previously added
  9893. var i = this.__objectsAdded.indexOf( object );
  9894. if ( i !== -1 ) {
  9895. this.__objectsAdded.splice( i, 1 );
  9896. }
  9897. }
  9898. this.dispatchEvent( { type: 'objectRemoved', object: object } );
  9899. object.dispatchEvent( { type: 'removedFromScene', scene: this } );
  9900. for ( var c = 0; c < object.children.length; c ++ ) {
  9901. this.__removeObject( object.children[ c ] );
  9902. }
  9903. };
  9904. THREE.Scene.prototype.clone = function ( object ) {
  9905. if ( object === undefined ) object = new THREE.Scene();
  9906. THREE.Object3D.prototype.clone.call(this, object);
  9907. if ( this.fog !== null ) object.fog = this.fog.clone();
  9908. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  9909. object.autoUpdate = this.autoUpdate;
  9910. object.matrixAutoUpdate = this.matrixAutoUpdate;
  9911. return object;
  9912. };
  9913. /**
  9914. * @author mrdoob / http://mrdoob.com/
  9915. * @author alteredq / http://alteredqualia.com/
  9916. */
  9917. THREE.Fog = function ( color, near, far ) {
  9918. this.name = '';
  9919. this.color = new THREE.Color( color );
  9920. this.near = ( near !== undefined ) ? near : 1;
  9921. this.far = ( far !== undefined ) ? far : 1000;
  9922. };
  9923. THREE.Fog.prototype.clone = function () {
  9924. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  9925. };
  9926. /**
  9927. * @author mrdoob / http://mrdoob.com/
  9928. * @author alteredq / http://alteredqualia.com/
  9929. */
  9930. THREE.FogExp2 = function ( color, density ) {
  9931. this.name = '';
  9932. this.color = new THREE.Color( color );
  9933. this.density = ( density !== undefined ) ? density : 0.00025;
  9934. };
  9935. THREE.FogExp2.prototype.clone = function () {
  9936. return new THREE.FogExp2( this.color.getHex(), this.density );
  9937. };
  9938. /**
  9939. * @author mrdoob / http://mrdoob.com/
  9940. */
  9941. THREE.CanvasRenderer = function ( parameters ) {
  9942. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  9943. var smoothstep = THREE.Math.smoothstep;
  9944. parameters = parameters || {};
  9945. var _this = this,
  9946. _renderData, _elements, _lights,
  9947. _projector = new THREE.Projector(),
  9948. _canvas = parameters.canvas !== undefined
  9949. ? parameters.canvas
  9950. : document.createElement( 'canvas' ),
  9951. _canvasWidth = _canvas.width,
  9952. _canvasHeight = _canvas.height,
  9953. _canvasWidthHalf = Math.floor( _canvasWidth / 2 ),
  9954. _canvasHeightHalf = Math.floor( _canvasHeight / 2 ),
  9955. _context = _canvas.getContext( '2d', {
  9956. alpha: parameters.alpha === true
  9957. } ),
  9958. _clearColor = new THREE.Color( 0x000000 ),
  9959. _clearAlpha = 0,
  9960. _contextGlobalAlpha = 1,
  9961. _contextGlobalCompositeOperation = 0,
  9962. _contextStrokeStyle = null,
  9963. _contextFillStyle = null,
  9964. _contextLineWidth = null,
  9965. _contextLineCap = null,
  9966. _contextLineJoin = null,
  9967. _contextDashSize = null,
  9968. _contextGapSize = 0,
  9969. _camera,
  9970. _v1, _v2, _v3, _v4,
  9971. _v5 = new THREE.RenderableVertex(),
  9972. _v6 = new THREE.RenderableVertex(),
  9973. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  9974. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  9975. _color = new THREE.Color(),
  9976. _color1 = new THREE.Color(),
  9977. _color2 = new THREE.Color(),
  9978. _color3 = new THREE.Color(),
  9979. _color4 = new THREE.Color(),
  9980. _diffuseColor = new THREE.Color(),
  9981. _emissiveColor = new THREE.Color(),
  9982. _lightColor = new THREE.Color(),
  9983. _patterns = {},
  9984. _image, _uvs,
  9985. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  9986. _clipBox = new THREE.Box2(),
  9987. _clearBox = new THREE.Box2(),
  9988. _elemBox = new THREE.Box2(),
  9989. _ambientLight = new THREE.Color(),
  9990. _directionalLights = new THREE.Color(),
  9991. _pointLights = new THREE.Color(),
  9992. _vector3 = new THREE.Vector3(), // Needed for PointLight
  9993. _centroid = new THREE.Vector3(),
  9994. _normal = new THREE.Vector3(),
  9995. _normalViewMatrix = new THREE.Matrix3();
  9996. // dash+gap fallbacks for Firefox and everything else
  9997. if ( _context.setLineDash === undefined ) {
  9998. if ( _context.mozDash !== undefined ) {
  9999. _context.setLineDash = function ( values ) {
  10000. _context.mozDash = values[ 0 ] !== null ? values : null;
  10001. }
  10002. } else {
  10003. _context.setLineDash = function () {}
  10004. }
  10005. }
  10006. this.domElement = _canvas;
  10007. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  10008. ? parameters.devicePixelRatio
  10009. : self.devicePixelRatio !== undefined
  10010. ? self.devicePixelRatio
  10011. : 1;
  10012. this.autoClear = true;
  10013. this.sortObjects = true;
  10014. this.sortElements = true;
  10015. this.info = {
  10016. render: {
  10017. vertices: 0,
  10018. faces: 0
  10019. }
  10020. }
  10021. // WebGLRenderer compatibility
  10022. this.supportsVertexTextures = function () {};
  10023. this.setFaceCulling = function () {};
  10024. this.setSize = function ( width, height, updateStyle ) {
  10025. _canvasWidth = width * this.devicePixelRatio;
  10026. _canvasHeight = height * this.devicePixelRatio;
  10027. _canvas.width = _canvasWidth;
  10028. _canvas.height = _canvasHeight;
  10029. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  10030. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  10031. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  10032. _canvas.style.width = width + 'px';
  10033. _canvas.style.height = height + 'px';
  10034. }
  10035. _clipBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf ),
  10036. _clipBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  10037. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  10038. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  10039. _contextGlobalAlpha = 1;
  10040. _contextGlobalCompositeOperation = 0;
  10041. _contextStrokeStyle = null;
  10042. _contextFillStyle = null;
  10043. _contextLineWidth = null;
  10044. _contextLineCap = null;
  10045. _contextLineJoin = null;
  10046. this.setViewport( 0, 0, width, height );
  10047. };
  10048. this.setViewport = function ( x, y, width, height ) {
  10049. var viewportX = x * this.devicePixelRatio;
  10050. var viewportY = y * this.devicePixelRatio;
  10051. var viewportWidth = width * this.devicePixelRatio;
  10052. var viewportHeight = height * this.devicePixelRatio;
  10053. _context.setTransform( viewportWidth / _canvasWidth, 0, 0, - viewportHeight / _canvasHeight, viewportX, _canvasHeight - viewportY );
  10054. _context.translate( _canvasWidthHalf, _canvasHeightHalf );
  10055. };
  10056. this.setScissor = function () {};
  10057. this.enableScissorTest = function () {};
  10058. this.setClearColor = function ( color, alpha ) {
  10059. _clearColor.set( color );
  10060. _clearAlpha = alpha !== undefined ? alpha : 1;
  10061. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  10062. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  10063. };
  10064. this.setClearColorHex = function ( hex, alpha ) {
  10065. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  10066. this.setClearColor( hex, alpha );
  10067. };
  10068. this.getMaxAnisotropy = function () {
  10069. return 0;
  10070. };
  10071. this.clear = function () {
  10072. if ( _clearBox.empty() === false ) {
  10073. _clearBox.intersect( _clipBox );
  10074. _clearBox.expandByScalar( 2 );
  10075. if ( _clearAlpha < 1 ) {
  10076. _context.clearRect(
  10077. _clearBox.min.x | 0,
  10078. _clearBox.min.y | 0,
  10079. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  10080. ( _clearBox.max.y - _clearBox.min.y ) | 0
  10081. );
  10082. }
  10083. if ( _clearAlpha > 0 ) {
  10084. setBlending( THREE.NormalBlending );
  10085. setOpacity( 1 );
  10086. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  10087. _context.fillRect(
  10088. _clearBox.min.x | 0,
  10089. _clearBox.min.y | 0,
  10090. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  10091. ( _clearBox.max.y - _clearBox.min.y ) | 0
  10092. );
  10093. }
  10094. _clearBox.makeEmpty();
  10095. }
  10096. };
  10097. // compatibility
  10098. this.clearColor = function () {};
  10099. this.clearDepth = function () {};
  10100. this.clearStencil = function () {};
  10101. this.render = function ( scene, camera ) {
  10102. if ( camera instanceof THREE.Camera === false ) {
  10103. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  10104. return;
  10105. }
  10106. if ( this.autoClear === true ) this.clear();
  10107. _this.info.render.vertices = 0;
  10108. _this.info.render.faces = 0;
  10109. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  10110. _elements = _renderData.elements;
  10111. _lights = _renderData.lights;
  10112. _camera = camera;
  10113. _normalViewMatrix.getNormalMatrix( camera.matrixWorldInverse );
  10114. /* DEBUG
  10115. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  10116. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  10117. */
  10118. calculateLights();
  10119. for ( var e = 0, el = _elements.length; e < el; e ++ ) {
  10120. var element = _elements[ e ];
  10121. var material = element.material;
  10122. if ( material === undefined || material.opacity === 0 ) continue;
  10123. _elemBox.makeEmpty();
  10124. if ( element instanceof THREE.RenderableSprite ) {
  10125. _v1 = element;
  10126. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  10127. renderSprite( _v1, element, material );
  10128. } else if ( element instanceof THREE.RenderableLine ) {
  10129. _v1 = element.v1; _v2 = element.v2;
  10130. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  10131. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  10132. _elemBox.setFromPoints( [
  10133. _v1.positionScreen,
  10134. _v2.positionScreen
  10135. ] );
  10136. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  10137. renderLine( _v1, _v2, element, material );
  10138. }
  10139. } else if ( element instanceof THREE.RenderableFace ) {
  10140. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  10141. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  10142. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  10143. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  10144. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  10145. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  10146. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  10147. if ( material.overdraw > 0 ) {
  10148. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  10149. expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
  10150. expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
  10151. }
  10152. _elemBox.setFromPoints( [
  10153. _v1.positionScreen,
  10154. _v2.positionScreen,
  10155. _v3.positionScreen
  10156. ] );
  10157. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  10158. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  10159. }
  10160. }
  10161. /* DEBUG
  10162. setLineWidth( 1 );
  10163. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  10164. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  10165. */
  10166. _clearBox.union( _elemBox );
  10167. }
  10168. /* DEBUG
  10169. setLineWidth( 1 );
  10170. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  10171. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  10172. */
  10173. // _context.setTransform( 1, 0, 0, 1, 0, 0 );
  10174. };
  10175. //
  10176. function calculateLights() {
  10177. _ambientLight.setRGB( 0, 0, 0 );
  10178. _directionalLights.setRGB( 0, 0, 0 );
  10179. _pointLights.setRGB( 0, 0, 0 );
  10180. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  10181. var light = _lights[ l ];
  10182. var lightColor = light.color;
  10183. if ( light instanceof THREE.AmbientLight ) {
  10184. _ambientLight.add( lightColor );
  10185. } else if ( light instanceof THREE.DirectionalLight ) {
  10186. // for sprites
  10187. _directionalLights.add( lightColor );
  10188. } else if ( light instanceof THREE.PointLight ) {
  10189. // for sprites
  10190. _pointLights.add( lightColor );
  10191. }
  10192. }
  10193. }
  10194. function calculateLight( position, normal, color ) {
  10195. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  10196. var light = _lights[ l ];
  10197. _lightColor.copy( light.color );
  10198. if ( light instanceof THREE.DirectionalLight ) {
  10199. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld ).normalize();
  10200. var amount = normal.dot( lightPosition );
  10201. if ( amount <= 0 ) continue;
  10202. amount *= light.intensity;
  10203. color.add( _lightColor.multiplyScalar( amount ) );
  10204. } else if ( light instanceof THREE.PointLight ) {
  10205. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld );
  10206. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  10207. if ( amount <= 0 ) continue;
  10208. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  10209. if ( amount == 0 ) continue;
  10210. amount *= light.intensity;
  10211. color.add( _lightColor.multiplyScalar( amount ) );
  10212. }
  10213. }
  10214. }
  10215. function renderSprite( v1, element, material ) {
  10216. setOpacity( material.opacity );
  10217. setBlending( material.blending );
  10218. var scaleX = element.scale.x * _canvasWidthHalf;
  10219. var scaleY = element.scale.y * _canvasHeightHalf;
  10220. var dist = 0.5 * Math.sqrt( scaleX * scaleX + scaleY * scaleY ); // allow for rotated sprite
  10221. _elemBox.min.set( v1.x - dist, v1.y - dist );
  10222. _elemBox.max.set( v1.x + dist, v1.y + dist );
  10223. if ( material instanceof THREE.SpriteMaterial ||
  10224. material instanceof THREE.ParticleSystemMaterial ) { // Backwards compatibility
  10225. var texture = material.map;
  10226. if ( texture !== null ) {
  10227. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  10228. if ( texture.image !== undefined && texture.image.width > 0 ) {
  10229. textureToPattern( texture );
  10230. }
  10231. texture.addEventListener( 'update', onTextureUpdate );
  10232. }
  10233. var pattern = _patterns[ texture.id ];
  10234. if ( pattern !== undefined ) {
  10235. setFillStyle( pattern );
  10236. } else {
  10237. setFillStyle( 'rgba( 0, 0, 0, 1 )' );
  10238. }
  10239. //
  10240. var bitmap = texture.image;
  10241. var ox = bitmap.width * texture.offset.x;
  10242. var oy = bitmap.height * texture.offset.y;
  10243. var sx = bitmap.width * texture.repeat.x;
  10244. var sy = bitmap.height * texture.repeat.y;
  10245. var cx = scaleX / sx;
  10246. var cy = scaleY / sy;
  10247. _context.save();
  10248. _context.translate( v1.x, v1.y );
  10249. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  10250. _context.translate( - scaleX / 2, - scaleY / 2 );
  10251. _context.scale( cx, cy );
  10252. _context.translate( - ox, - oy );
  10253. _context.fillRect( ox, oy, sx, sy );
  10254. _context.restore();
  10255. } else { // no texture
  10256. setFillStyle( material.color.getStyle() );
  10257. _context.save();
  10258. _context.translate( v1.x, v1.y );
  10259. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  10260. _context.scale( scaleX, - scaleY );
  10261. _context.fillRect( - 0.5, - 0.5, 1, 1 );
  10262. _context.restore();
  10263. }
  10264. } else if ( material instanceof THREE.SpriteCanvasMaterial ) {
  10265. setStrokeStyle( material.color.getStyle() );
  10266. setFillStyle( material.color.getStyle() );
  10267. _context.save();
  10268. _context.translate( v1.x, v1.y );
  10269. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  10270. _context.scale( scaleX, scaleY );
  10271. material.program( _context );
  10272. _context.restore();
  10273. }
  10274. /* DEBUG
  10275. setStrokeStyle( 'rgb(255,255,0)' );
  10276. _context.beginPath();
  10277. _context.moveTo( v1.x - 10, v1.y );
  10278. _context.lineTo( v1.x + 10, v1.y );
  10279. _context.moveTo( v1.x, v1.y - 10 );
  10280. _context.lineTo( v1.x, v1.y + 10 );
  10281. _context.stroke();
  10282. */
  10283. }
  10284. function renderLine( v1, v2, element, material ) {
  10285. setOpacity( material.opacity );
  10286. setBlending( material.blending );
  10287. _context.beginPath();
  10288. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  10289. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  10290. if ( material instanceof THREE.LineBasicMaterial ) {
  10291. setLineWidth( material.linewidth );
  10292. setLineCap( material.linecap );
  10293. setLineJoin( material.linejoin );
  10294. if ( material.vertexColors !== THREE.VertexColors ) {
  10295. setStrokeStyle( material.color.getStyle() );
  10296. } else {
  10297. var colorStyle1 = element.vertexColors[0].getStyle();
  10298. var colorStyle2 = element.vertexColors[1].getStyle();
  10299. if ( colorStyle1 === colorStyle2 ) {
  10300. setStrokeStyle( colorStyle1 );
  10301. } else {
  10302. try {
  10303. var grad = _context.createLinearGradient(
  10304. v1.positionScreen.x,
  10305. v1.positionScreen.y,
  10306. v2.positionScreen.x,
  10307. v2.positionScreen.y
  10308. );
  10309. grad.addColorStop( 0, colorStyle1 );
  10310. grad.addColorStop( 1, colorStyle2 );
  10311. } catch ( exception ) {
  10312. grad = colorStyle1;
  10313. }
  10314. setStrokeStyle( grad );
  10315. }
  10316. }
  10317. _context.stroke();
  10318. _elemBox.expandByScalar( material.linewidth * 2 );
  10319. } else if ( material instanceof THREE.LineDashedMaterial ) {
  10320. setLineWidth( material.linewidth );
  10321. setLineCap( material.linecap );
  10322. setLineJoin( material.linejoin );
  10323. setStrokeStyle( material.color.getStyle() );
  10324. setDashAndGap( material.dashSize, material.gapSize );
  10325. _context.stroke();
  10326. _elemBox.expandByScalar( material.linewidth * 2 );
  10327. setDashAndGap( null, null );
  10328. }
  10329. }
  10330. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  10331. _this.info.render.vertices += 3;
  10332. _this.info.render.faces ++;
  10333. setOpacity( material.opacity );
  10334. setBlending( material.blending );
  10335. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  10336. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  10337. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  10338. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  10339. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  10340. _diffuseColor.copy( material.color );
  10341. _emissiveColor.copy( material.emissive );
  10342. if ( material.vertexColors === THREE.FaceColors ) {
  10343. _diffuseColor.multiply( element.color );
  10344. }
  10345. _color.copy( _ambientLight );
  10346. _centroid.copy( v1.positionWorld ).add( v2.positionWorld ).add( v3.positionWorld ).divideScalar( 3 );
  10347. calculateLight( _centroid, element.normalModel, _color );
  10348. _color.multiply( _diffuseColor ).add( _emissiveColor );
  10349. material.wireframe === true
  10350. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  10351. : fillPath( _color );
  10352. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  10353. if ( material.map !== null ) {
  10354. if ( material.map.mapping instanceof THREE.UVMapping ) {
  10355. _uvs = element.uvs;
  10356. 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 );
  10357. }
  10358. } else if ( material.envMap !== null ) {
  10359. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  10360. _normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix );
  10361. _uv1x = 0.5 * _normal.x + 0.5;
  10362. _uv1y = 0.5 * _normal.y + 0.5;
  10363. _normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix );
  10364. _uv2x = 0.5 * _normal.x + 0.5;
  10365. _uv2y = 0.5 * _normal.y + 0.5;
  10366. _normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix );
  10367. _uv3x = 0.5 * _normal.x + 0.5;
  10368. _uv3y = 0.5 * _normal.y + 0.5;
  10369. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  10370. } else if ( material.envMap.mapping instanceof THREE.SphericalRefractionMapping ) {
  10371. _normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix );
  10372. _uv1x = - 0.5 * _normal.x + 0.5;
  10373. _uv1y = - 0.5 * _normal.y + 0.5;
  10374. _normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix );
  10375. _uv2x = - 0.5 * _normal.x + 0.5;
  10376. _uv2y = - 0.5 * _normal.y + 0.5;
  10377. _normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix );
  10378. _uv3x = - 0.5 * _normal.x + 0.5;
  10379. _uv3y = - 0.5 * _normal.y + 0.5;
  10380. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  10381. }
  10382. } else {
  10383. _color.copy( material.color );
  10384. if ( material.vertexColors === THREE.FaceColors ) {
  10385. _color.multiply( element.color );
  10386. }
  10387. material.wireframe === true
  10388. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  10389. : fillPath( _color );
  10390. }
  10391. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  10392. _color.r = _color.g = _color.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _camera.near, _camera.far );
  10393. material.wireframe === true
  10394. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  10395. : fillPath( _color );
  10396. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  10397. _normal.copy( element.normalModel ).applyMatrix3( _normalViewMatrix );
  10398. _color.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  10399. material.wireframe === true
  10400. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  10401. : fillPath( _color );
  10402. } else {
  10403. _color.setRGB( 1, 1, 1 );
  10404. material.wireframe === true
  10405. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  10406. : fillPath( _color );
  10407. }
  10408. }
  10409. //
  10410. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  10411. _context.beginPath();
  10412. _context.moveTo( x0, y0 );
  10413. _context.lineTo( x1, y1 );
  10414. _context.lineTo( x2, y2 );
  10415. _context.closePath();
  10416. }
  10417. function strokePath( color, linewidth, linecap, linejoin ) {
  10418. setLineWidth( linewidth );
  10419. setLineCap( linecap );
  10420. setLineJoin( linejoin );
  10421. setStrokeStyle( color.getStyle() );
  10422. _context.stroke();
  10423. _elemBox.expandByScalar( linewidth * 2 );
  10424. }
  10425. function fillPath( color ) {
  10426. setFillStyle( color.getStyle() );
  10427. _context.fill();
  10428. }
  10429. function onTextureUpdate ( event ) {
  10430. textureToPattern( event.target );
  10431. }
  10432. function textureToPattern( texture ) {
  10433. var repeatX = texture.wrapS === THREE.RepeatWrapping;
  10434. var repeatY = texture.wrapT === THREE.RepeatWrapping;
  10435. var image = texture.image;
  10436. var canvas = document.createElement( 'canvas' );
  10437. canvas.width = image.width;
  10438. canvas.height = image.height;
  10439. var context = canvas.getContext( '2d' );
  10440. context.setTransform( 1, 0, 0, - 1, 0, image.height );
  10441. context.drawImage( image, 0, 0 );
  10442. _patterns[ texture.id ] = _context.createPattern(
  10443. canvas, repeatX === true && repeatY === true
  10444. ? 'repeat'
  10445. : repeatX === true && repeatY === false
  10446. ? 'repeat-x'
  10447. : repeatX === false && repeatY === true
  10448. ? 'repeat-y'
  10449. : 'no-repeat'
  10450. );
  10451. }
  10452. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  10453. if ( texture instanceof THREE.DataTexture ) return;
  10454. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  10455. if ( texture.image !== undefined && texture.image.width > 0 ) {
  10456. textureToPattern( texture );
  10457. }
  10458. texture.addEventListener( 'update', onTextureUpdate );
  10459. }
  10460. var pattern = _patterns[ texture.id ];
  10461. if ( pattern !== undefined ) {
  10462. setFillStyle( pattern );
  10463. } else {
  10464. setFillStyle( 'rgba(0,0,0,1)' );
  10465. _context.fill();
  10466. return;
  10467. }
  10468. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  10469. var a, b, c, d, e, f, det, idet,
  10470. offsetX = texture.offset.x / texture.repeat.x,
  10471. offsetY = texture.offset.y / texture.repeat.y,
  10472. width = texture.image.width * texture.repeat.x,
  10473. height = texture.image.height * texture.repeat.y;
  10474. u0 = ( u0 + offsetX ) * width;
  10475. v0 = ( v0 + offsetY ) * height;
  10476. u1 = ( u1 + offsetX ) * width;
  10477. v1 = ( v1 + offsetY ) * height;
  10478. u2 = ( u2 + offsetX ) * width;
  10479. v2 = ( v2 + offsetY ) * height;
  10480. x1 -= x0; y1 -= y0;
  10481. x2 -= x0; y2 -= y0;
  10482. u1 -= u0; v1 -= v0;
  10483. u2 -= u0; v2 -= v0;
  10484. det = u1 * v2 - u2 * v1;
  10485. if ( det === 0 ) return;
  10486. idet = 1 / det;
  10487. a = ( v2 * x1 - v1 * x2 ) * idet;
  10488. b = ( v2 * y1 - v1 * y2 ) * idet;
  10489. c = ( u1 * x2 - u2 * x1 ) * idet;
  10490. d = ( u1 * y2 - u2 * y1 ) * idet;
  10491. e = x0 - a * u0 - c * v0;
  10492. f = y0 - b * u0 - d * v0;
  10493. _context.save();
  10494. _context.transform( a, b, c, d, e, f );
  10495. _context.fill();
  10496. _context.restore();
  10497. }
  10498. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  10499. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  10500. var a, b, c, d, e, f, det, idet,
  10501. width = image.width - 1,
  10502. height = image.height - 1;
  10503. u0 *= width; v0 *= height;
  10504. u1 *= width; v1 *= height;
  10505. u2 *= width; v2 *= height;
  10506. x1 -= x0; y1 -= y0;
  10507. x2 -= x0; y2 -= y0;
  10508. u1 -= u0; v1 -= v0;
  10509. u2 -= u0; v2 -= v0;
  10510. det = u1 * v2 - u2 * v1;
  10511. idet = 1 / det;
  10512. a = ( v2 * x1 - v1 * x2 ) * idet;
  10513. b = ( v2 * y1 - v1 * y2 ) * idet;
  10514. c = ( u1 * x2 - u2 * x1 ) * idet;
  10515. d = ( u1 * y2 - u2 * y1 ) * idet;
  10516. e = x0 - a * u0 - c * v0;
  10517. f = y0 - b * u0 - d * v0;
  10518. _context.save();
  10519. _context.transform( a, b, c, d, e, f );
  10520. _context.clip();
  10521. _context.drawImage( image, 0, 0 );
  10522. _context.restore();
  10523. }
  10524. // Hide anti-alias gaps
  10525. function expand( v1, v2, pixels ) {
  10526. var x = v2.x - v1.x, y = v2.y - v1.y,
  10527. det = x * x + y * y, idet;
  10528. if ( det === 0 ) return;
  10529. idet = pixels / Math.sqrt( det );
  10530. x *= idet; y *= idet;
  10531. v2.x += x; v2.y += y;
  10532. v1.x -= x; v1.y -= y;
  10533. }
  10534. // Context cached methods.
  10535. function setOpacity( value ) {
  10536. if ( _contextGlobalAlpha !== value ) {
  10537. _context.globalAlpha = value;
  10538. _contextGlobalAlpha = value;
  10539. }
  10540. }
  10541. function setBlending( value ) {
  10542. if ( _contextGlobalCompositeOperation !== value ) {
  10543. if ( value === THREE.NormalBlending ) {
  10544. _context.globalCompositeOperation = 'source-over';
  10545. } else if ( value === THREE.AdditiveBlending ) {
  10546. _context.globalCompositeOperation = 'lighter';
  10547. } else if ( value === THREE.SubtractiveBlending ) {
  10548. _context.globalCompositeOperation = 'darker';
  10549. }
  10550. _contextGlobalCompositeOperation = value;
  10551. }
  10552. }
  10553. function setLineWidth( value ) {
  10554. if ( _contextLineWidth !== value ) {
  10555. _context.lineWidth = value;
  10556. _contextLineWidth = value;
  10557. }
  10558. }
  10559. function setLineCap( value ) {
  10560. // "butt", "round", "square"
  10561. if ( _contextLineCap !== value ) {
  10562. _context.lineCap = value;
  10563. _contextLineCap = value;
  10564. }
  10565. }
  10566. function setLineJoin( value ) {
  10567. // "round", "bevel", "miter"
  10568. if ( _contextLineJoin !== value ) {
  10569. _context.lineJoin = value;
  10570. _contextLineJoin = value;
  10571. }
  10572. }
  10573. function setStrokeStyle( value ) {
  10574. if ( _contextStrokeStyle !== value ) {
  10575. _context.strokeStyle = value;
  10576. _contextStrokeStyle = value;
  10577. }
  10578. }
  10579. function setFillStyle( value ) {
  10580. if ( _contextFillStyle !== value ) {
  10581. _context.fillStyle = value;
  10582. _contextFillStyle = value;
  10583. }
  10584. }
  10585. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  10586. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  10587. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  10588. _contextDashSize = dashSizeValue;
  10589. _contextGapSize = gapSizeValue;
  10590. }
  10591. }
  10592. };
  10593. /**
  10594. * Shader chunks for WebLG Shader library
  10595. *
  10596. * @author alteredq / http://alteredqualia.com/
  10597. * @author mrdoob / http://mrdoob.com/
  10598. * @author mikael emtinger / http://gomo.se/
  10599. */
  10600. THREE.ShaderChunk = {
  10601. // FOG
  10602. fog_pars_fragment: [
  10603. "#ifdef USE_FOG",
  10604. " uniform vec3 fogColor;",
  10605. " #ifdef FOG_EXP2",
  10606. " uniform float fogDensity;",
  10607. " #else",
  10608. " uniform float fogNear;",
  10609. " uniform float fogFar;",
  10610. " #endif",
  10611. "#endif"
  10612. ].join("\n"),
  10613. fog_fragment: [
  10614. "#ifdef USE_FOG",
  10615. " #ifdef USE_LOGDEPTHBUF_EXT",
  10616. " float depth = gl_FragDepthEXT / gl_FragCoord.w;",
  10617. " #else",
  10618. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10619. " #endif",
  10620. " #ifdef FOG_EXP2",
  10621. " const float LOG2 = 1.442695;",
  10622. " float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  10623. " fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  10624. " #else",
  10625. " float fogFactor = smoothstep( fogNear, fogFar, depth );",
  10626. " #endif",
  10627. " gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  10628. "#endif"
  10629. ].join("\n"),
  10630. // ENVIRONMENT MAP
  10631. envmap_pars_fragment: [
  10632. "#ifdef USE_ENVMAP",
  10633. " uniform float reflectivity;",
  10634. " uniform samplerCube envMap;",
  10635. " uniform float flipEnvMap;",
  10636. " uniform int combine;",
  10637. " #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  10638. " uniform bool useRefract;",
  10639. " uniform float refractionRatio;",
  10640. " #else",
  10641. " varying vec3 vReflect;",
  10642. " #endif",
  10643. "#endif"
  10644. ].join("\n"),
  10645. envmap_fragment: [
  10646. "#ifdef USE_ENVMAP",
  10647. " vec3 reflectVec;",
  10648. " #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  10649. " vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  10650. // http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations
  10651. // "Transforming Normal Vectors with the Inverse Transformation"
  10652. " vec3 worldNormal = normalize( vec3( vec4( normal, 0.0 ) * viewMatrix ) );",
  10653. " if ( useRefract ) {",
  10654. " reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );",
  10655. " } else { ",
  10656. " reflectVec = reflect( cameraToVertex, worldNormal );",
  10657. " }",
  10658. " #else",
  10659. " reflectVec = vReflect;",
  10660. " #endif",
  10661. " #ifdef DOUBLE_SIDED",
  10662. " float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10663. " vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  10664. " #else",
  10665. " vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  10666. " #endif",
  10667. " #ifdef GAMMA_INPUT",
  10668. " cubeColor.xyz *= cubeColor.xyz;",
  10669. " #endif",
  10670. " if ( combine == 1 ) {",
  10671. " gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  10672. " } else if ( combine == 2 ) {",
  10673. " gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  10674. " } else {",
  10675. " gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  10676. " }",
  10677. "#endif"
  10678. ].join("\n"),
  10679. envmap_pars_vertex: [
  10680. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  10681. " varying vec3 vReflect;",
  10682. " uniform float refractionRatio;",
  10683. " uniform bool useRefract;",
  10684. "#endif"
  10685. ].join("\n"),
  10686. worldpos_vertex : [
  10687. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  10688. " #ifdef USE_SKINNING",
  10689. " vec4 worldPosition = modelMatrix * skinned;",
  10690. " #endif",
  10691. " #if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  10692. " vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  10693. " #endif",
  10694. " #if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  10695. " vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  10696. " #endif",
  10697. "#endif"
  10698. ].join("\n"),
  10699. envmap_vertex : [
  10700. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  10701. " vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  10702. " worldNormal = normalize( worldNormal );",
  10703. " vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  10704. " if ( useRefract ) {",
  10705. " vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  10706. " } else {",
  10707. " vReflect = reflect( cameraToVertex, worldNormal );",
  10708. " }",
  10709. "#endif"
  10710. ].join("\n"),
  10711. // COLOR MAP (particles)
  10712. map_particle_pars_fragment: [
  10713. "#ifdef USE_MAP",
  10714. " uniform sampler2D map;",
  10715. "#endif"
  10716. ].join("\n"),
  10717. map_particle_fragment: [
  10718. "#ifdef USE_MAP",
  10719. " gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  10720. "#endif"
  10721. ].join("\n"),
  10722. // COLOR MAP (triangles)
  10723. map_pars_vertex: [
  10724. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10725. " varying vec2 vUv;",
  10726. " uniform vec4 offsetRepeat;",
  10727. "#endif"
  10728. ].join("\n"),
  10729. map_pars_fragment: [
  10730. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10731. " varying vec2 vUv;",
  10732. "#endif",
  10733. "#ifdef USE_MAP",
  10734. " uniform sampler2D map;",
  10735. "#endif"
  10736. ].join("\n"),
  10737. map_vertex: [
  10738. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10739. " vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  10740. "#endif"
  10741. ].join("\n"),
  10742. map_fragment: [
  10743. "#ifdef USE_MAP",
  10744. " vec4 texelColor = texture2D( map, vUv );",
  10745. " #ifdef GAMMA_INPUT",
  10746. " texelColor.xyz *= texelColor.xyz;",
  10747. " #endif",
  10748. " gl_FragColor = gl_FragColor * texelColor;",
  10749. "#endif"
  10750. ].join("\n"),
  10751. // LIGHT MAP
  10752. lightmap_pars_fragment: [
  10753. "#ifdef USE_LIGHTMAP",
  10754. " varying vec2 vUv2;",
  10755. " uniform sampler2D lightMap;",
  10756. "#endif"
  10757. ].join("\n"),
  10758. lightmap_pars_vertex: [
  10759. "#ifdef USE_LIGHTMAP",
  10760. " varying vec2 vUv2;",
  10761. "#endif"
  10762. ].join("\n"),
  10763. lightmap_fragment: [
  10764. "#ifdef USE_LIGHTMAP",
  10765. " gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  10766. "#endif"
  10767. ].join("\n"),
  10768. lightmap_vertex: [
  10769. "#ifdef USE_LIGHTMAP",
  10770. " vUv2 = uv2;",
  10771. "#endif"
  10772. ].join("\n"),
  10773. // BUMP MAP
  10774. bumpmap_pars_fragment: [
  10775. "#ifdef USE_BUMPMAP",
  10776. " uniform sampler2D bumpMap;",
  10777. " uniform float bumpScale;",
  10778. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  10779. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  10780. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  10781. " vec2 dHdxy_fwd() {",
  10782. " vec2 dSTdx = dFdx( vUv );",
  10783. " vec2 dSTdy = dFdy( vUv );",
  10784. " float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  10785. " float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  10786. " float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  10787. " return vec2( dBx, dBy );",
  10788. " }",
  10789. " vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  10790. " vec3 vSigmaX = dFdx( surf_pos );",
  10791. " vec3 vSigmaY = dFdy( surf_pos );",
  10792. " vec3 vN = surf_norm;", // normalized
  10793. " vec3 R1 = cross( vSigmaY, vN );",
  10794. " vec3 R2 = cross( vN, vSigmaX );",
  10795. " float fDet = dot( vSigmaX, R1 );",
  10796. " vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  10797. " return normalize( abs( fDet ) * surf_norm - vGrad );",
  10798. " }",
  10799. "#endif"
  10800. ].join("\n"),
  10801. // NORMAL MAP
  10802. normalmap_pars_fragment: [
  10803. "#ifdef USE_NORMALMAP",
  10804. " uniform sampler2D normalMap;",
  10805. " uniform vec2 normalScale;",
  10806. // Per-Pixel Tangent Space Normal Mapping
  10807. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  10808. " vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  10809. " vec3 q0 = dFdx( eye_pos.xyz );",
  10810. " vec3 q1 = dFdy( eye_pos.xyz );",
  10811. " vec2 st0 = dFdx( vUv.st );",
  10812. " vec2 st1 = dFdy( vUv.st );",
  10813. " vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  10814. " vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  10815. " vec3 N = normalize( surf_norm );",
  10816. " vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  10817. " mapN.xy = normalScale * mapN.xy;",
  10818. " mat3 tsn = mat3( S, T, N );",
  10819. " return normalize( tsn * mapN );",
  10820. " }",
  10821. "#endif"
  10822. ].join("\n"),
  10823. // SPECULAR MAP
  10824. specularmap_pars_fragment: [
  10825. "#ifdef USE_SPECULARMAP",
  10826. " uniform sampler2D specularMap;",
  10827. "#endif"
  10828. ].join("\n"),
  10829. specularmap_fragment: [
  10830. "float specularStrength;",
  10831. "#ifdef USE_SPECULARMAP",
  10832. " vec4 texelSpecular = texture2D( specularMap, vUv );",
  10833. " specularStrength = texelSpecular.r;",
  10834. "#else",
  10835. " specularStrength = 1.0;",
  10836. "#endif"
  10837. ].join("\n"),
  10838. // LIGHTS LAMBERT
  10839. lights_lambert_pars_vertex: [
  10840. "uniform vec3 ambient;",
  10841. "uniform vec3 diffuse;",
  10842. "uniform vec3 emissive;",
  10843. "uniform vec3 ambientLightColor;",
  10844. "#if MAX_DIR_LIGHTS > 0",
  10845. " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10846. " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10847. "#endif",
  10848. "#if MAX_HEMI_LIGHTS > 0",
  10849. " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10850. " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10851. " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10852. "#endif",
  10853. "#if MAX_POINT_LIGHTS > 0",
  10854. " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10855. " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10856. " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10857. "#endif",
  10858. "#if MAX_SPOT_LIGHTS > 0",
  10859. " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10860. " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10861. " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10862. " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10863. " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10864. " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10865. "#endif",
  10866. "#ifdef WRAP_AROUND",
  10867. " uniform vec3 wrapRGB;",
  10868. "#endif"
  10869. ].join("\n"),
  10870. lights_lambert_vertex: [
  10871. "vLightFront = vec3( 0.0 );",
  10872. "#ifdef DOUBLE_SIDED",
  10873. " vLightBack = vec3( 0.0 );",
  10874. "#endif",
  10875. "transformedNormal = normalize( transformedNormal );",
  10876. "#if MAX_DIR_LIGHTS > 0",
  10877. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10878. " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10879. " vec3 dirVector = normalize( lDirection.xyz );",
  10880. " float dotProduct = dot( transformedNormal, dirVector );",
  10881. " vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10882. " #ifdef DOUBLE_SIDED",
  10883. " vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10884. " #ifdef WRAP_AROUND",
  10885. " vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10886. " #endif",
  10887. " #endif",
  10888. " #ifdef WRAP_AROUND",
  10889. " vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10890. " directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  10891. " #ifdef DOUBLE_SIDED",
  10892. " directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  10893. " #endif",
  10894. " #endif",
  10895. " vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  10896. " #ifdef DOUBLE_SIDED",
  10897. " vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  10898. " #endif",
  10899. "}",
  10900. "#endif",
  10901. "#if MAX_POINT_LIGHTS > 0",
  10902. " for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10903. " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10904. " vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10905. " float lDistance = 1.0;",
  10906. " if ( pointLightDistance[ i ] > 0.0 )",
  10907. " lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10908. " lVector = normalize( lVector );",
  10909. " float dotProduct = dot( transformedNormal, lVector );",
  10910. " vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10911. " #ifdef DOUBLE_SIDED",
  10912. " vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10913. " #ifdef WRAP_AROUND",
  10914. " vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10915. " #endif",
  10916. " #endif",
  10917. " #ifdef WRAP_AROUND",
  10918. " vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10919. " pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  10920. " #ifdef DOUBLE_SIDED",
  10921. " pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  10922. " #endif",
  10923. " #endif",
  10924. " vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  10925. " #ifdef DOUBLE_SIDED",
  10926. " vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  10927. " #endif",
  10928. " }",
  10929. "#endif",
  10930. "#if MAX_SPOT_LIGHTS > 0",
  10931. " for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10932. " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10933. " vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10934. " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  10935. " if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10936. " spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10937. " float lDistance = 1.0;",
  10938. " if ( spotLightDistance[ i ] > 0.0 )",
  10939. " lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10940. " lVector = normalize( lVector );",
  10941. " float dotProduct = dot( transformedNormal, lVector );",
  10942. " vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10943. " #ifdef DOUBLE_SIDED",
  10944. " vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10945. " #ifdef WRAP_AROUND",
  10946. " vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10947. " #endif",
  10948. " #endif",
  10949. " #ifdef WRAP_AROUND",
  10950. " vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10951. " spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  10952. " #ifdef DOUBLE_SIDED",
  10953. " spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  10954. " #endif",
  10955. " #endif",
  10956. " vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  10957. " #ifdef DOUBLE_SIDED",
  10958. " vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  10959. " #endif",
  10960. " }",
  10961. " }",
  10962. "#endif",
  10963. "#if MAX_HEMI_LIGHTS > 0",
  10964. " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10965. " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10966. " vec3 lVector = normalize( lDirection.xyz );",
  10967. " float dotProduct = dot( transformedNormal, lVector );",
  10968. " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10969. " float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  10970. " vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10971. " #ifdef DOUBLE_SIDED",
  10972. " vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  10973. " #endif",
  10974. " }",
  10975. "#endif",
  10976. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  10977. "#ifdef DOUBLE_SIDED",
  10978. " vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  10979. "#endif"
  10980. ].join("\n"),
  10981. // LIGHTS PHONG
  10982. lights_phong_pars_vertex: [
  10983. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )",
  10984. " varying vec3 vWorldPosition;",
  10985. "#endif"
  10986. ].join("\n"),
  10987. lights_phong_vertex: [
  10988. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )",
  10989. " vWorldPosition = worldPosition.xyz;",
  10990. "#endif"
  10991. ].join("\n"),
  10992. lights_phong_pars_fragment: [
  10993. "uniform vec3 ambientLightColor;",
  10994. "#if MAX_DIR_LIGHTS > 0",
  10995. " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10996. " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10997. "#endif",
  10998. "#if MAX_HEMI_LIGHTS > 0",
  10999. " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  11000. " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  11001. " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  11002. "#endif",
  11003. "#if MAX_POINT_LIGHTS > 0",
  11004. " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11005. " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11006. " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11007. "#endif",
  11008. "#if MAX_SPOT_LIGHTS > 0",
  11009. " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  11010. " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  11011. " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  11012. " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  11013. " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  11014. " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  11015. "#endif",
  11016. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )",
  11017. " varying vec3 vWorldPosition;",
  11018. "#endif",
  11019. "#ifdef WRAP_AROUND",
  11020. " uniform vec3 wrapRGB;",
  11021. "#endif",
  11022. "varying vec3 vViewPosition;",
  11023. "varying vec3 vNormal;"
  11024. ].join("\n"),
  11025. lights_phong_fragment: [
  11026. "vec3 normal = normalize( vNormal );",
  11027. "vec3 viewPosition = normalize( vViewPosition );",
  11028. "#ifdef DOUBLE_SIDED",
  11029. " normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  11030. "#endif",
  11031. "#ifdef USE_NORMALMAP",
  11032. " normal = perturbNormal2Arb( -vViewPosition, normal );",
  11033. "#elif defined( USE_BUMPMAP )",
  11034. " normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  11035. "#endif",
  11036. "#if MAX_POINT_LIGHTS > 0",
  11037. " vec3 pointDiffuse = vec3( 0.0 );",
  11038. " vec3 pointSpecular = vec3( 0.0 );",
  11039. " for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11040. " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11041. " vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  11042. " float lDistance = 1.0;",
  11043. " if ( pointLightDistance[ i ] > 0.0 )",
  11044. " lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  11045. " lVector = normalize( lVector );",
  11046. // diffuse
  11047. " float dotProduct = dot( normal, lVector );",
  11048. " #ifdef WRAP_AROUND",
  11049. " float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  11050. " float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  11051. " vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11052. " #else",
  11053. " float pointDiffuseWeight = max( dotProduct, 0.0 );",
  11054. " #endif",
  11055. " pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  11056. // specular
  11057. " vec3 pointHalfVector = normalize( lVector + viewPosition );",
  11058. " float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11059. " float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  11060. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11061. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11062. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, pointHalfVector ), 0.0 ), 5.0 );",
  11063. " pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  11064. " }",
  11065. "#endif",
  11066. "#if MAX_SPOT_LIGHTS > 0",
  11067. " vec3 spotDiffuse = vec3( 0.0 );",
  11068. " vec3 spotSpecular = vec3( 0.0 );",
  11069. " for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  11070. " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  11071. " vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  11072. " float lDistance = 1.0;",
  11073. " if ( spotLightDistance[ i ] > 0.0 )",
  11074. " lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  11075. " lVector = normalize( lVector );",
  11076. " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  11077. " if ( spotEffect > spotLightAngleCos[ i ] ) {",
  11078. " spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  11079. // diffuse
  11080. " float dotProduct = dot( normal, lVector );",
  11081. " #ifdef WRAP_AROUND",
  11082. " float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  11083. " float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  11084. " vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  11085. " #else",
  11086. " float spotDiffuseWeight = max( dotProduct, 0.0 );",
  11087. " #endif",
  11088. " spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  11089. // specular
  11090. " vec3 spotHalfVector = normalize( lVector + viewPosition );",
  11091. " float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  11092. " float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  11093. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11094. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11095. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, spotHalfVector ), 0.0 ), 5.0 );",
  11096. " spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  11097. " }",
  11098. " }",
  11099. "#endif",
  11100. "#if MAX_DIR_LIGHTS > 0",
  11101. " vec3 dirDiffuse = vec3( 0.0 );",
  11102. " vec3 dirSpecular = vec3( 0.0 );" ,
  11103. " for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  11104. " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11105. " vec3 dirVector = normalize( lDirection.xyz );",
  11106. // diffuse
  11107. " float dotProduct = dot( normal, dirVector );",
  11108. " #ifdef WRAP_AROUND",
  11109. " float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  11110. " float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  11111. " vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  11112. " #else",
  11113. " float dirDiffuseWeight = max( dotProduct, 0.0 );",
  11114. " #endif",
  11115. " dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  11116. // specular
  11117. " vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11118. " float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11119. " float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  11120. /*
  11121. // fresnel term from skin shader
  11122. " const float F0 = 0.128;",
  11123. " float base = 1.0 - dot( viewPosition, dirHalfVector );",
  11124. " float exponential = pow( base, 5.0 );",
  11125. " float fresnel = exponential + F0 * ( 1.0 - exponential );",
  11126. */
  11127. /*
  11128. // fresnel term from fresnel shader
  11129. " const float mFresnelBias = 0.08;",
  11130. " const float mFresnelScale = 0.3;",
  11131. " const float mFresnelPower = 5.0;",
  11132. " float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  11133. */
  11134. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11135. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11136. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  11137. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( dirVector, dirHalfVector ), 0.0 ), 5.0 );",
  11138. " dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11139. " }",
  11140. "#endif",
  11141. "#if MAX_HEMI_LIGHTS > 0",
  11142. " vec3 hemiDiffuse = vec3( 0.0 );",
  11143. " vec3 hemiSpecular = vec3( 0.0 );" ,
  11144. " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  11145. " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  11146. " vec3 lVector = normalize( lDirection.xyz );",
  11147. // diffuse
  11148. " float dotProduct = dot( normal, lVector );",
  11149. " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  11150. " vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  11151. " hemiDiffuse += diffuse * hemiColor;",
  11152. // specular (sky light)
  11153. " vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  11154. " float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  11155. " float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  11156. // specular (ground light)
  11157. " vec3 lVectorGround = -lVector;",
  11158. " vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  11159. " float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  11160. " float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  11161. " float dotProductGround = dot( normal, lVectorGround );",
  11162. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11163. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11164. " vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, hemiHalfVectorSky ), 0.0 ), 5.0 );",
  11165. " vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 0.0 ), 5.0 );",
  11166. " hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  11167. " }",
  11168. "#endif",
  11169. "vec3 totalDiffuse = vec3( 0.0 );",
  11170. "vec3 totalSpecular = vec3( 0.0 );",
  11171. "#if MAX_DIR_LIGHTS > 0",
  11172. " totalDiffuse += dirDiffuse;",
  11173. " totalSpecular += dirSpecular;",
  11174. "#endif",
  11175. "#if MAX_HEMI_LIGHTS > 0",
  11176. " totalDiffuse += hemiDiffuse;",
  11177. " totalSpecular += hemiSpecular;",
  11178. "#endif",
  11179. "#if MAX_POINT_LIGHTS > 0",
  11180. " totalDiffuse += pointDiffuse;",
  11181. " totalSpecular += pointSpecular;",
  11182. "#endif",
  11183. "#if MAX_SPOT_LIGHTS > 0",
  11184. " totalDiffuse += spotDiffuse;",
  11185. " totalSpecular += spotSpecular;",
  11186. "#endif",
  11187. "#ifdef METAL",
  11188. " gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  11189. "#else",
  11190. " gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  11191. "#endif"
  11192. ].join("\n"),
  11193. // VERTEX COLORS
  11194. color_pars_fragment: [
  11195. "#ifdef USE_COLOR",
  11196. " varying vec3 vColor;",
  11197. "#endif"
  11198. ].join("\n"),
  11199. color_fragment: [
  11200. "#ifdef USE_COLOR",
  11201. " gl_FragColor = gl_FragColor * vec4( vColor, 1.0 );",
  11202. "#endif"
  11203. ].join("\n"),
  11204. color_pars_vertex: [
  11205. "#ifdef USE_COLOR",
  11206. " varying vec3 vColor;",
  11207. "#endif"
  11208. ].join("\n"),
  11209. color_vertex: [
  11210. "#ifdef USE_COLOR",
  11211. " #ifdef GAMMA_INPUT",
  11212. " vColor = color * color;",
  11213. " #else",
  11214. " vColor = color;",
  11215. " #endif",
  11216. "#endif"
  11217. ].join("\n"),
  11218. // SKINNING
  11219. skinning_pars_vertex: [
  11220. "#ifdef USE_SKINNING",
  11221. " #ifdef BONE_TEXTURE",
  11222. " uniform sampler2D boneTexture;",
  11223. " uniform int boneTextureWidth;",
  11224. " uniform int boneTextureHeight;",
  11225. " mat4 getBoneMatrix( const in float i ) {",
  11226. " float j = i * 4.0;",
  11227. " float x = mod( j, float( boneTextureWidth ) );",
  11228. " float y = floor( j / float( boneTextureWidth ) );",
  11229. " float dx = 1.0 / float( boneTextureWidth );",
  11230. " float dy = 1.0 / float( boneTextureHeight );",
  11231. " y = dy * ( y + 0.5 );",
  11232. " vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  11233. " vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  11234. " vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  11235. " vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  11236. " mat4 bone = mat4( v1, v2, v3, v4 );",
  11237. " return bone;",
  11238. " }",
  11239. " #else",
  11240. " uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  11241. " mat4 getBoneMatrix( const in float i ) {",
  11242. " mat4 bone = boneGlobalMatrices[ int(i) ];",
  11243. " return bone;",
  11244. " }",
  11245. " #endif",
  11246. "#endif"
  11247. ].join("\n"),
  11248. skinbase_vertex: [
  11249. "#ifdef USE_SKINNING",
  11250. " mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  11251. " mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  11252. " mat4 boneMatZ = getBoneMatrix( skinIndex.z );",
  11253. " mat4 boneMatW = getBoneMatrix( skinIndex.w );",
  11254. "#endif"
  11255. ].join("\n"),
  11256. skinning_vertex: [
  11257. "#ifdef USE_SKINNING",
  11258. " #ifdef USE_MORPHTARGETS",
  11259. " vec4 skinVertex = vec4( morphed, 1.0 );",
  11260. " #else",
  11261. " vec4 skinVertex = vec4( position, 1.0 );",
  11262. " #endif",
  11263. " vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11264. " skinned += boneMatY * skinVertex * skinWeight.y;",
  11265. " skinned += boneMatZ * skinVertex * skinWeight.z;",
  11266. " skinned += boneMatW * skinVertex * skinWeight.w;",
  11267. "#endif"
  11268. ].join("\n"),
  11269. // MORPHING
  11270. morphtarget_pars_vertex: [
  11271. "#ifdef USE_MORPHTARGETS",
  11272. " #ifndef USE_MORPHNORMALS",
  11273. " uniform float morphTargetInfluences[ 8 ];",
  11274. " #else",
  11275. " uniform float morphTargetInfluences[ 4 ];",
  11276. " #endif",
  11277. "#endif"
  11278. ].join("\n"),
  11279. morphtarget_vertex: [
  11280. "#ifdef USE_MORPHTARGETS",
  11281. " vec3 morphed = vec3( 0.0 );",
  11282. " morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  11283. " morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  11284. " morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  11285. " morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  11286. " #ifndef USE_MORPHNORMALS",
  11287. " morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  11288. " morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  11289. " morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  11290. " morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  11291. " #endif",
  11292. " morphed += position;",
  11293. "#endif"
  11294. ].join("\n"),
  11295. default_vertex : [
  11296. "vec4 mvPosition;",
  11297. "#ifdef USE_SKINNING",
  11298. " mvPosition = modelViewMatrix * skinned;",
  11299. "#endif",
  11300. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  11301. " mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  11302. "#endif",
  11303. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  11304. " mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11305. "#endif",
  11306. "gl_Position = projectionMatrix * mvPosition;"
  11307. ].join("\n"),
  11308. morphnormal_vertex: [
  11309. "#ifdef USE_MORPHNORMALS",
  11310. " vec3 morphedNormal = vec3( 0.0 );",
  11311. " morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  11312. " morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  11313. " morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  11314. " morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  11315. " morphedNormal += normal;",
  11316. "#endif"
  11317. ].join("\n"),
  11318. skinnormal_vertex: [
  11319. "#ifdef USE_SKINNING",
  11320. " mat4 skinMatrix = skinWeight.x * boneMatX;",
  11321. " skinMatrix += skinWeight.y * boneMatY;",
  11322. " skinMatrix += skinWeight.z * boneMatZ;",
  11323. " skinMatrix += skinWeight.w * boneMatW;",
  11324. " #ifdef USE_MORPHNORMALS",
  11325. " vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  11326. " #else",
  11327. " vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  11328. " #endif",
  11329. "#endif"
  11330. ].join("\n"),
  11331. defaultnormal_vertex: [
  11332. "vec3 objectNormal;",
  11333. "#ifdef USE_SKINNING",
  11334. " objectNormal = skinnedNormal.xyz;",
  11335. "#endif",
  11336. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  11337. " objectNormal = morphedNormal;",
  11338. "#endif",
  11339. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  11340. " objectNormal = normal;",
  11341. "#endif",
  11342. "#ifdef FLIP_SIDED",
  11343. " objectNormal = -objectNormal;",
  11344. "#endif",
  11345. "vec3 transformedNormal = normalMatrix * objectNormal;"
  11346. ].join("\n"),
  11347. // SHADOW MAP
  11348. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  11349. // http://spidergl.org/example.php?id=6
  11350. // http://fabiensanglard.net/shadowmapping
  11351. shadowmap_pars_fragment: [
  11352. "#ifdef USE_SHADOWMAP",
  11353. " uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  11354. " uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  11355. " uniform float shadowDarkness[ MAX_SHADOWS ];",
  11356. " uniform float shadowBias[ MAX_SHADOWS ];",
  11357. " varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  11358. " float unpackDepth( const in vec4 rgba_depth ) {",
  11359. " 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 );",
  11360. " float depth = dot( rgba_depth, bit_shift );",
  11361. " return depth;",
  11362. " }",
  11363. "#endif"
  11364. ].join("\n"),
  11365. shadowmap_fragment: [
  11366. "#ifdef USE_SHADOWMAP",
  11367. " #ifdef SHADOWMAP_DEBUG",
  11368. " vec3 frustumColors[3];",
  11369. " frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  11370. " frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  11371. " frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  11372. " #endif",
  11373. " #ifdef SHADOWMAP_CASCADE",
  11374. " int inFrustumCount = 0;",
  11375. " #endif",
  11376. " float fDepth;",
  11377. " vec3 shadowColor = vec3( 1.0 );",
  11378. " for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11379. " vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  11380. // "if ( something && something )" breaks ATI OpenGL shader compiler
  11381. // "if ( all( something, something ) )" using this instead
  11382. " bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  11383. " bool inFrustum = all( inFrustumVec );",
  11384. // don't shadow pixels outside of light frustum
  11385. // use just first frustum (for cascades)
  11386. // don't shadow pixels behind far plane of light frustum
  11387. " #ifdef SHADOWMAP_CASCADE",
  11388. " inFrustumCount += int( inFrustum );",
  11389. " bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  11390. " #else",
  11391. " bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  11392. " #endif",
  11393. " bool frustumTest = all( frustumTestVec );",
  11394. " if ( frustumTest ) {",
  11395. " shadowCoord.z += shadowBias[ i ];",
  11396. " #if defined( SHADOWMAP_TYPE_PCF )",
  11397. // Percentage-close filtering
  11398. // (9 pixel kernel)
  11399. // http://fabiensanglard.net/shadowmappingPCF/
  11400. " float shadow = 0.0;",
  11401. /*
  11402. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  11403. // must enroll loop manually
  11404. " for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  11405. " for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  11406. " vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  11407. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  11408. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  11409. " float fDepth = unpackDepth( rgbaDepth );",
  11410. " if ( fDepth < shadowCoord.z )",
  11411. " shadow += 1.0;",
  11412. " }",
  11413. " shadow /= 9.0;",
  11414. */
  11415. " const float shadowDelta = 1.0 / 9.0;",
  11416. " float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  11417. " float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  11418. " float dx0 = -1.25 * xPixelOffset;",
  11419. " float dy0 = -1.25 * yPixelOffset;",
  11420. " float dx1 = 1.25 * xPixelOffset;",
  11421. " float dy1 = 1.25 * yPixelOffset;",
  11422. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  11423. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11424. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  11425. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11426. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  11427. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11428. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  11429. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11430. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  11431. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11432. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  11433. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11434. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  11435. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11436. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  11437. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11438. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  11439. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11440. " shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  11441. " #elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  11442. // Percentage-close filtering
  11443. // (9 pixel kernel)
  11444. // http://fabiensanglard.net/shadowmappingPCF/
  11445. " float shadow = 0.0;",
  11446. " float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  11447. " float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  11448. " float dx0 = -1.0 * xPixelOffset;",
  11449. " float dy0 = -1.0 * yPixelOffset;",
  11450. " float dx1 = 1.0 * xPixelOffset;",
  11451. " float dy1 = 1.0 * yPixelOffset;",
  11452. " mat3 shadowKernel;",
  11453. " mat3 depthKernel;",
  11454. " depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  11455. " depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  11456. " depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  11457. " depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  11458. " depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  11459. " depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  11460. " depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  11461. " depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  11462. " depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  11463. " vec3 shadowZ = vec3( shadowCoord.z );",
  11464. " shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  11465. " shadowKernel[0] *= vec3(0.25);",
  11466. " shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  11467. " shadowKernel[1] *= vec3(0.25);",
  11468. " shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  11469. " shadowKernel[2] *= vec3(0.25);",
  11470. " vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  11471. " shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  11472. " shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  11473. " vec4 shadowValues;",
  11474. " shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  11475. " shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  11476. " shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  11477. " shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  11478. " shadow = dot( shadowValues, vec4( 1.0 ) );",
  11479. " shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  11480. " #else",
  11481. " vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  11482. " float fDepth = unpackDepth( rgbaDepth );",
  11483. " if ( fDepth < shadowCoord.z )",
  11484. // spot with multiple shadows is darker
  11485. " shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  11486. // spot with multiple shadows has the same color as single shadow spot
  11487. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  11488. " #endif",
  11489. " }",
  11490. " #ifdef SHADOWMAP_DEBUG",
  11491. " #ifdef SHADOWMAP_CASCADE",
  11492. " if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  11493. " #else",
  11494. " if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  11495. " #endif",
  11496. " #endif",
  11497. " }",
  11498. " #ifdef GAMMA_OUTPUT",
  11499. " shadowColor *= shadowColor;",
  11500. " #endif",
  11501. " gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  11502. "#endif"
  11503. ].join("\n"),
  11504. shadowmap_pars_vertex: [
  11505. "#ifdef USE_SHADOWMAP",
  11506. " varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  11507. " uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  11508. "#endif"
  11509. ].join("\n"),
  11510. shadowmap_vertex: [
  11511. "#ifdef USE_SHADOWMAP",
  11512. " for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11513. " vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11514. " }",
  11515. "#endif"
  11516. ].join("\n"),
  11517. // ALPHATEST
  11518. alphatest_fragment: [
  11519. "#ifdef ALPHATEST",
  11520. " if ( gl_FragColor.a < ALPHATEST ) discard;",
  11521. "#endif"
  11522. ].join("\n"),
  11523. // LINEAR SPACE
  11524. linear_to_gamma_fragment: [
  11525. "#ifdef GAMMA_OUTPUT",
  11526. " gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  11527. "#endif"
  11528. ].join("\n"),
  11529. // LOGARITHMIC DEPTH BUFFER
  11530. // http://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html
  11531. // WebGL doesn't support gl_FragDepth out of the box, unless the EXT_frag_depth extension is available. On platforms
  11532. // without EXT_frag_depth, we have to fall back on linear z-buffer in the fragment shader, which means that some long
  11533. // faces close to the camera may have issues. This can be worked around by tesselating the model more finely when
  11534. // the camera is near the surface.
  11535. logdepthbuf_pars_vertex: [
  11536. "#ifdef USE_LOGDEPTHBUF",
  11537. " #ifdef USE_LOGDEPTHBUF_EXT",
  11538. " varying float vFragDepth;",
  11539. " #endif",
  11540. " uniform float logDepthBufFC;",
  11541. "#endif",
  11542. ].join('\n'),
  11543. logdepthbuf_vertex: [
  11544. "#ifdef USE_LOGDEPTHBUF",
  11545. " gl_Position.z = log2(max(1e-6, gl_Position.w + 1.0)) * logDepthBufFC;",
  11546. " #ifdef USE_LOGDEPTHBUF_EXT",
  11547. " vFragDepth = 1.0 + gl_Position.w;",
  11548. "#else",
  11549. " gl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;",
  11550. " #endif",
  11551. "#endif"
  11552. ].join("\n"),
  11553. logdepthbuf_pars_fragment: [
  11554. "#ifdef USE_LOGDEPTHBUF",
  11555. " uniform float logDepthBufFC;",
  11556. " #ifdef USE_LOGDEPTHBUF_EXT",
  11557. " #extension GL_EXT_frag_depth : enable",
  11558. " varying float vFragDepth;",
  11559. " #endif",
  11560. "#endif"
  11561. ].join('\n'),
  11562. logdepthbuf_fragment: [
  11563. "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)",
  11564. " gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;",
  11565. "#endif"
  11566. ].join("\n")
  11567. };
  11568. /**
  11569. * Uniform Utilities
  11570. */
  11571. THREE.UniformsUtils = {
  11572. merge: function ( uniforms ) {
  11573. var u, p, tmp, merged = {};
  11574. for ( u = 0; u < uniforms.length; u ++ ) {
  11575. tmp = this.clone( uniforms[ u ] );
  11576. for ( p in tmp ) {
  11577. merged[ p ] = tmp[ p ];
  11578. }
  11579. }
  11580. return merged;
  11581. },
  11582. clone: function ( uniforms_src ) {
  11583. var u, p, parameter, parameter_src, uniforms_dst = {};
  11584. for ( u in uniforms_src ) {
  11585. uniforms_dst[ u ] = {};
  11586. for ( p in uniforms_src[ u ] ) {
  11587. parameter_src = uniforms_src[ u ][ p ];
  11588. if ( parameter_src instanceof THREE.Color ||
  11589. parameter_src instanceof THREE.Vector2 ||
  11590. parameter_src instanceof THREE.Vector3 ||
  11591. parameter_src instanceof THREE.Vector4 ||
  11592. parameter_src instanceof THREE.Matrix4 ||
  11593. parameter_src instanceof THREE.Texture ) {
  11594. uniforms_dst[ u ][ p ] = parameter_src.clone();
  11595. } else if ( parameter_src instanceof Array ) {
  11596. uniforms_dst[ u ][ p ] = parameter_src.slice();
  11597. } else {
  11598. uniforms_dst[ u ][ p ] = parameter_src;
  11599. }
  11600. }
  11601. }
  11602. return uniforms_dst;
  11603. }
  11604. };
  11605. /**
  11606. * Uniforms library for shared webgl shaders
  11607. */
  11608. THREE.UniformsLib = {
  11609. common: {
  11610. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  11611. "opacity" : { type: "f", value: 1.0 },
  11612. "map" : { type: "t", value: null },
  11613. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  11614. "lightMap" : { type: "t", value: null },
  11615. "specularMap" : { type: "t", value: null },
  11616. "envMap" : { type: "t", value: null },
  11617. "flipEnvMap" : { type: "f", value: -1 },
  11618. "useRefract" : { type: "i", value: 0 },
  11619. "reflectivity" : { type: "f", value: 1.0 },
  11620. "refractionRatio" : { type: "f", value: 0.98 },
  11621. "combine" : { type: "i", value: 0 },
  11622. "morphTargetInfluences" : { type: "f", value: 0 }
  11623. },
  11624. bump: {
  11625. "bumpMap" : { type: "t", value: null },
  11626. "bumpScale" : { type: "f", value: 1 }
  11627. },
  11628. normalmap: {
  11629. "normalMap" : { type: "t", value: null },
  11630. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  11631. },
  11632. fog : {
  11633. "fogDensity" : { type: "f", value: 0.00025 },
  11634. "fogNear" : { type: "f", value: 1 },
  11635. "fogFar" : { type: "f", value: 2000 },
  11636. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  11637. },
  11638. lights: {
  11639. "ambientLightColor" : { type: "fv", value: [] },
  11640. "directionalLightDirection" : { type: "fv", value: [] },
  11641. "directionalLightColor" : { type: "fv", value: [] },
  11642. "hemisphereLightDirection" : { type: "fv", value: [] },
  11643. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  11644. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  11645. "pointLightColor" : { type: "fv", value: [] },
  11646. "pointLightPosition" : { type: "fv", value: [] },
  11647. "pointLightDistance" : { type: "fv1", value: [] },
  11648. "spotLightColor" : { type: "fv", value: [] },
  11649. "spotLightPosition" : { type: "fv", value: [] },
  11650. "spotLightDirection" : { type: "fv", value: [] },
  11651. "spotLightDistance" : { type: "fv1", value: [] },
  11652. "spotLightAngleCos" : { type: "fv1", value: [] },
  11653. "spotLightExponent" : { type: "fv1", value: [] }
  11654. },
  11655. particle: {
  11656. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  11657. "opacity" : { type: "f", value: 1.0 },
  11658. "size" : { type: "f", value: 1.0 },
  11659. "scale" : { type: "f", value: 1.0 },
  11660. "map" : { type: "t", value: null },
  11661. "fogDensity" : { type: "f", value: 0.00025 },
  11662. "fogNear" : { type: "f", value: 1 },
  11663. "fogFar" : { type: "f", value: 2000 },
  11664. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  11665. },
  11666. shadowmap: {
  11667. "shadowMap": { type: "tv", value: [] },
  11668. "shadowMapSize": { type: "v2v", value: [] },
  11669. "shadowBias" : { type: "fv1", value: [] },
  11670. "shadowDarkness": { type: "fv1", value: [] },
  11671. "shadowMatrix" : { type: "m4v", value: [] }
  11672. }
  11673. };
  11674. /**
  11675. * Webgl Shader Library for three.js
  11676. *
  11677. * @author alteredq / http://alteredqualia.com/
  11678. * @author mrdoob / http://mrdoob.com/
  11679. * @author mikael emtinger / http://gomo.se/
  11680. */
  11681. THREE.ShaderLib = {
  11682. 'basic': {
  11683. uniforms: THREE.UniformsUtils.merge( [
  11684. THREE.UniformsLib[ "common" ],
  11685. THREE.UniformsLib[ "fog" ],
  11686. THREE.UniformsLib[ "shadowmap" ]
  11687. ] ),
  11688. vertexShader: [
  11689. THREE.ShaderChunk[ "map_pars_vertex" ],
  11690. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11691. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11692. THREE.ShaderChunk[ "color_pars_vertex" ],
  11693. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11694. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11695. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11696. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11697. "void main() {",
  11698. THREE.ShaderChunk[ "map_vertex" ],
  11699. THREE.ShaderChunk[ "lightmap_vertex" ],
  11700. THREE.ShaderChunk[ "color_vertex" ],
  11701. THREE.ShaderChunk[ "skinbase_vertex" ],
  11702. " #ifdef USE_ENVMAP",
  11703. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11704. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11705. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11706. " #endif",
  11707. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11708. THREE.ShaderChunk[ "skinning_vertex" ],
  11709. THREE.ShaderChunk[ "default_vertex" ],
  11710. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11711. THREE.ShaderChunk[ "worldpos_vertex" ],
  11712. THREE.ShaderChunk[ "envmap_vertex" ],
  11713. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11714. "}"
  11715. ].join("\n"),
  11716. fragmentShader: [
  11717. "uniform vec3 diffuse;",
  11718. "uniform float opacity;",
  11719. THREE.ShaderChunk[ "color_pars_fragment" ],
  11720. THREE.ShaderChunk[ "map_pars_fragment" ],
  11721. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11722. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11723. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11724. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11725. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11726. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11727. "void main() {",
  11728. " gl_FragColor = vec4( diffuse, opacity );",
  11729. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11730. THREE.ShaderChunk[ "map_fragment" ],
  11731. THREE.ShaderChunk[ "alphatest_fragment" ],
  11732. THREE.ShaderChunk[ "specularmap_fragment" ],
  11733. THREE.ShaderChunk[ "lightmap_fragment" ],
  11734. THREE.ShaderChunk[ "color_fragment" ],
  11735. THREE.ShaderChunk[ "envmap_fragment" ],
  11736. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11737. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11738. THREE.ShaderChunk[ "fog_fragment" ],
  11739. "}"
  11740. ].join("\n")
  11741. },
  11742. 'lambert': {
  11743. uniforms: THREE.UniformsUtils.merge( [
  11744. THREE.UniformsLib[ "common" ],
  11745. THREE.UniformsLib[ "fog" ],
  11746. THREE.UniformsLib[ "lights" ],
  11747. THREE.UniformsLib[ "shadowmap" ],
  11748. {
  11749. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  11750. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  11751. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11752. }
  11753. ] ),
  11754. vertexShader: [
  11755. "#define LAMBERT",
  11756. "varying vec3 vLightFront;",
  11757. "#ifdef DOUBLE_SIDED",
  11758. " varying vec3 vLightBack;",
  11759. "#endif",
  11760. THREE.ShaderChunk[ "map_pars_vertex" ],
  11761. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11762. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11763. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  11764. THREE.ShaderChunk[ "color_pars_vertex" ],
  11765. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11766. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11767. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11768. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11769. "void main() {",
  11770. THREE.ShaderChunk[ "map_vertex" ],
  11771. THREE.ShaderChunk[ "lightmap_vertex" ],
  11772. THREE.ShaderChunk[ "color_vertex" ],
  11773. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11774. THREE.ShaderChunk[ "skinbase_vertex" ],
  11775. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11776. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11777. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11778. THREE.ShaderChunk[ "skinning_vertex" ],
  11779. THREE.ShaderChunk[ "default_vertex" ],
  11780. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11781. THREE.ShaderChunk[ "worldpos_vertex" ],
  11782. THREE.ShaderChunk[ "envmap_vertex" ],
  11783. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  11784. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11785. "}"
  11786. ].join("\n"),
  11787. fragmentShader: [
  11788. "uniform float opacity;",
  11789. "varying vec3 vLightFront;",
  11790. "#ifdef DOUBLE_SIDED",
  11791. " varying vec3 vLightBack;",
  11792. "#endif",
  11793. THREE.ShaderChunk[ "color_pars_fragment" ],
  11794. THREE.ShaderChunk[ "map_pars_fragment" ],
  11795. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11796. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11797. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11798. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11799. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11800. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11801. "void main() {",
  11802. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  11803. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11804. THREE.ShaderChunk[ "map_fragment" ],
  11805. THREE.ShaderChunk[ "alphatest_fragment" ],
  11806. THREE.ShaderChunk[ "specularmap_fragment" ],
  11807. " #ifdef DOUBLE_SIDED",
  11808. //"float isFront = float( gl_FrontFacing );",
  11809. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  11810. " if ( gl_FrontFacing )",
  11811. " gl_FragColor.xyz *= vLightFront;",
  11812. " else",
  11813. " gl_FragColor.xyz *= vLightBack;",
  11814. " #else",
  11815. " gl_FragColor.xyz *= vLightFront;",
  11816. " #endif",
  11817. THREE.ShaderChunk[ "lightmap_fragment" ],
  11818. THREE.ShaderChunk[ "color_fragment" ],
  11819. THREE.ShaderChunk[ "envmap_fragment" ],
  11820. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11821. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11822. THREE.ShaderChunk[ "fog_fragment" ],
  11823. "}"
  11824. ].join("\n")
  11825. },
  11826. 'phong': {
  11827. uniforms: THREE.UniformsUtils.merge( [
  11828. THREE.UniformsLib[ "common" ],
  11829. THREE.UniformsLib[ "bump" ],
  11830. THREE.UniformsLib[ "normalmap" ],
  11831. THREE.UniformsLib[ "fog" ],
  11832. THREE.UniformsLib[ "lights" ],
  11833. THREE.UniformsLib[ "shadowmap" ],
  11834. {
  11835. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  11836. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  11837. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  11838. "shininess": { type: "f", value: 30 },
  11839. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11840. }
  11841. ] ),
  11842. vertexShader: [
  11843. "#define PHONG",
  11844. "varying vec3 vViewPosition;",
  11845. "varying vec3 vNormal;",
  11846. THREE.ShaderChunk[ "map_pars_vertex" ],
  11847. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11848. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11849. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  11850. THREE.ShaderChunk[ "color_pars_vertex" ],
  11851. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11852. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11853. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11854. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11855. "void main() {",
  11856. THREE.ShaderChunk[ "map_vertex" ],
  11857. THREE.ShaderChunk[ "lightmap_vertex" ],
  11858. THREE.ShaderChunk[ "color_vertex" ],
  11859. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11860. THREE.ShaderChunk[ "skinbase_vertex" ],
  11861. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11862. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11863. " vNormal = normalize( transformedNormal );",
  11864. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11865. THREE.ShaderChunk[ "skinning_vertex" ],
  11866. THREE.ShaderChunk[ "default_vertex" ],
  11867. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11868. " vViewPosition = -mvPosition.xyz;",
  11869. THREE.ShaderChunk[ "worldpos_vertex" ],
  11870. THREE.ShaderChunk[ "envmap_vertex" ],
  11871. THREE.ShaderChunk[ "lights_phong_vertex" ],
  11872. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11873. "}"
  11874. ].join("\n"),
  11875. fragmentShader: [
  11876. "uniform vec3 diffuse;",
  11877. "uniform float opacity;",
  11878. "uniform vec3 ambient;",
  11879. "uniform vec3 emissive;",
  11880. "uniform vec3 specular;",
  11881. "uniform float shininess;",
  11882. THREE.ShaderChunk[ "color_pars_fragment" ],
  11883. THREE.ShaderChunk[ "map_pars_fragment" ],
  11884. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11885. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11886. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11887. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  11888. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11889. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  11890. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  11891. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11892. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11893. "void main() {",
  11894. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  11895. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11896. THREE.ShaderChunk[ "map_fragment" ],
  11897. THREE.ShaderChunk[ "alphatest_fragment" ],
  11898. THREE.ShaderChunk[ "specularmap_fragment" ],
  11899. THREE.ShaderChunk[ "lights_phong_fragment" ],
  11900. THREE.ShaderChunk[ "lightmap_fragment" ],
  11901. THREE.ShaderChunk[ "color_fragment" ],
  11902. THREE.ShaderChunk[ "envmap_fragment" ],
  11903. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11904. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11905. THREE.ShaderChunk[ "fog_fragment" ],
  11906. "}"
  11907. ].join("\n")
  11908. },
  11909. 'particle_basic': {
  11910. uniforms: THREE.UniformsUtils.merge( [
  11911. THREE.UniformsLib[ "particle" ],
  11912. THREE.UniformsLib[ "shadowmap" ]
  11913. ] ),
  11914. vertexShader: [
  11915. "uniform float size;",
  11916. "uniform float scale;",
  11917. THREE.ShaderChunk[ "color_pars_vertex" ],
  11918. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11919. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11920. "void main() {",
  11921. THREE.ShaderChunk[ "color_vertex" ],
  11922. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11923. " #ifdef USE_SIZEATTENUATION",
  11924. " gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  11925. " #else",
  11926. " gl_PointSize = size;",
  11927. " #endif",
  11928. " gl_Position = projectionMatrix * mvPosition;",
  11929. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11930. THREE.ShaderChunk[ "worldpos_vertex" ],
  11931. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11932. "}"
  11933. ].join("\n"),
  11934. fragmentShader: [
  11935. "uniform vec3 psColor;",
  11936. "uniform float opacity;",
  11937. THREE.ShaderChunk[ "color_pars_fragment" ],
  11938. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  11939. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11940. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11941. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11942. "void main() {",
  11943. " gl_FragColor = vec4( psColor, opacity );",
  11944. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11945. THREE.ShaderChunk[ "map_particle_fragment" ],
  11946. THREE.ShaderChunk[ "alphatest_fragment" ],
  11947. THREE.ShaderChunk[ "color_fragment" ],
  11948. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11949. THREE.ShaderChunk[ "fog_fragment" ],
  11950. "}"
  11951. ].join("\n")
  11952. },
  11953. 'dashed': {
  11954. uniforms: THREE.UniformsUtils.merge( [
  11955. THREE.UniformsLib[ "common" ],
  11956. THREE.UniformsLib[ "fog" ],
  11957. {
  11958. "scale": { type: "f", value: 1 },
  11959. "dashSize": { type: "f", value: 1 },
  11960. "totalSize": { type: "f", value: 2 }
  11961. }
  11962. ] ),
  11963. vertexShader: [
  11964. "uniform float scale;",
  11965. "attribute float lineDistance;",
  11966. "varying float vLineDistance;",
  11967. THREE.ShaderChunk[ "color_pars_vertex" ],
  11968. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11969. "void main() {",
  11970. THREE.ShaderChunk[ "color_vertex" ],
  11971. " vLineDistance = scale * lineDistance;",
  11972. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11973. " gl_Position = projectionMatrix * mvPosition;",
  11974. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11975. "}"
  11976. ].join("\n"),
  11977. fragmentShader: [
  11978. "uniform vec3 diffuse;",
  11979. "uniform float opacity;",
  11980. "uniform float dashSize;",
  11981. "uniform float totalSize;",
  11982. "varying float vLineDistance;",
  11983. THREE.ShaderChunk[ "color_pars_fragment" ],
  11984. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11985. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11986. "void main() {",
  11987. " if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  11988. " discard;",
  11989. " }",
  11990. " gl_FragColor = vec4( diffuse, opacity );",
  11991. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11992. THREE.ShaderChunk[ "color_fragment" ],
  11993. THREE.ShaderChunk[ "fog_fragment" ],
  11994. "}"
  11995. ].join("\n")
  11996. },
  11997. 'depth': {
  11998. uniforms: {
  11999. "mNear": { type: "f", value: 1.0 },
  12000. "mFar" : { type: "f", value: 2000.0 },
  12001. "opacity" : { type: "f", value: 1.0 }
  12002. },
  12003. vertexShader: [
  12004. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12005. "void main() {",
  12006. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  12007. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12008. "}"
  12009. ].join("\n"),
  12010. fragmentShader: [
  12011. "uniform float mNear;",
  12012. "uniform float mFar;",
  12013. "uniform float opacity;",
  12014. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12015. "void main() {",
  12016. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12017. " #ifdef USE_LOGDEPTHBUF_EXT",
  12018. " float depth = gl_FragDepthEXT / gl_FragCoord.w;",
  12019. " #else",
  12020. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  12021. " #endif",
  12022. " float color = 1.0 - smoothstep( mNear, mFar, depth );",
  12023. " gl_FragColor = vec4( vec3( color ), opacity );",
  12024. "}"
  12025. ].join("\n")
  12026. },
  12027. 'normal': {
  12028. uniforms: {
  12029. "opacity" : { type: "f", value: 1.0 }
  12030. },
  12031. vertexShader: [
  12032. "varying vec3 vNormal;",
  12033. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  12034. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12035. "void main() {",
  12036. " vNormal = normalize( normalMatrix * normal );",
  12037. THREE.ShaderChunk[ "morphtarget_vertex" ],
  12038. THREE.ShaderChunk[ "default_vertex" ],
  12039. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12040. "}"
  12041. ].join("\n"),
  12042. fragmentShader: [
  12043. "uniform float opacity;",
  12044. "varying vec3 vNormal;",
  12045. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12046. "void main() {",
  12047. " gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  12048. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12049. "}"
  12050. ].join("\n")
  12051. },
  12052. /* -------------------------------------------------------------------------
  12053. // Normal map shader
  12054. // - Blinn-Phong
  12055. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  12056. // - point and directional lights (use with "lights: true" material option)
  12057. ------------------------------------------------------------------------- */
  12058. 'normalmap' : {
  12059. uniforms: THREE.UniformsUtils.merge( [
  12060. THREE.UniformsLib[ "fog" ],
  12061. THREE.UniformsLib[ "lights" ],
  12062. THREE.UniformsLib[ "shadowmap" ],
  12063. {
  12064. "enableAO" : { type: "i", value: 0 },
  12065. "enableDiffuse" : { type: "i", value: 0 },
  12066. "enableSpecular" : { type: "i", value: 0 },
  12067. "enableReflection": { type: "i", value: 0 },
  12068. "enableDisplacement": { type: "i", value: 0 },
  12069. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  12070. "tDiffuse" : { type: "t", value: null },
  12071. "tCube" : { type: "t", value: null },
  12072. "tNormal" : { type: "t", value: null },
  12073. "tSpecular" : { type: "t", value: null },
  12074. "tAO" : { type: "t", value: null },
  12075. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  12076. "uDisplacementBias": { type: "f", value: 0.0 },
  12077. "uDisplacementScale": { type: "f", value: 1.0 },
  12078. "diffuse": { type: "c", value: new THREE.Color( 0xffffff ) },
  12079. "specular": { type: "c", value: new THREE.Color( 0x111111 ) },
  12080. "ambient": { type: "c", value: new THREE.Color( 0xffffff ) },
  12081. "shininess": { type: "f", value: 30 },
  12082. "opacity": { type: "f", value: 1 },
  12083. "useRefract": { type: "i", value: 0 },
  12084. "refractionRatio": { type: "f", value: 0.98 },
  12085. "reflectivity": { type: "f", value: 0.5 },
  12086. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  12087. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  12088. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  12089. }
  12090. ] ),
  12091. fragmentShader: [
  12092. "uniform vec3 ambient;",
  12093. "uniform vec3 diffuse;",
  12094. "uniform vec3 specular;",
  12095. "uniform float shininess;",
  12096. "uniform float opacity;",
  12097. "uniform bool enableDiffuse;",
  12098. "uniform bool enableSpecular;",
  12099. "uniform bool enableAO;",
  12100. "uniform bool enableReflection;",
  12101. "uniform sampler2D tDiffuse;",
  12102. "uniform sampler2D tNormal;",
  12103. "uniform sampler2D tSpecular;",
  12104. "uniform sampler2D tAO;",
  12105. "uniform samplerCube tCube;",
  12106. "uniform vec2 uNormalScale;",
  12107. "uniform bool useRefract;",
  12108. "uniform float refractionRatio;",
  12109. "uniform float reflectivity;",
  12110. "varying vec3 vTangent;",
  12111. "varying vec3 vBinormal;",
  12112. "varying vec3 vNormal;",
  12113. "varying vec2 vUv;",
  12114. "uniform vec3 ambientLightColor;",
  12115. "#if MAX_DIR_LIGHTS > 0",
  12116. " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  12117. " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  12118. "#endif",
  12119. "#if MAX_HEMI_LIGHTS > 0",
  12120. " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  12121. " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  12122. " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  12123. "#endif",
  12124. "#if MAX_POINT_LIGHTS > 0",
  12125. " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  12126. " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  12127. " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  12128. "#endif",
  12129. "#if MAX_SPOT_LIGHTS > 0",
  12130. " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  12131. " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  12132. " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  12133. " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  12134. " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  12135. " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  12136. "#endif",
  12137. "#ifdef WRAP_AROUND",
  12138. " uniform vec3 wrapRGB;",
  12139. "#endif",
  12140. "varying vec3 vWorldPosition;",
  12141. "varying vec3 vViewPosition;",
  12142. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  12143. THREE.ShaderChunk[ "fog_pars_fragment" ],
  12144. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12145. "void main() {",
  12146. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12147. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  12148. " vec3 specularTex = vec3( 1.0 );",
  12149. " vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  12150. " normalTex.xy *= uNormalScale;",
  12151. " normalTex = normalize( normalTex );",
  12152. " if( enableDiffuse ) {",
  12153. " #ifdef GAMMA_INPUT",
  12154. " vec4 texelColor = texture2D( tDiffuse, vUv );",
  12155. " texelColor.xyz *= texelColor.xyz;",
  12156. " gl_FragColor = gl_FragColor * texelColor;",
  12157. " #else",
  12158. " gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  12159. " #endif",
  12160. " }",
  12161. " if( enableAO ) {",
  12162. " #ifdef GAMMA_INPUT",
  12163. " vec4 aoColor = texture2D( tAO, vUv );",
  12164. " aoColor.xyz *= aoColor.xyz;",
  12165. " gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  12166. " #else",
  12167. " gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  12168. " #endif",
  12169. " }",
  12170. " if( enableSpecular )",
  12171. " specularTex = texture2D( tSpecular, vUv ).xyz;",
  12172. " mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  12173. " vec3 finalNormal = tsb * normalTex;",
  12174. " #ifdef FLIP_SIDED",
  12175. " finalNormal = -finalNormal;",
  12176. " #endif",
  12177. " vec3 normal = normalize( finalNormal );",
  12178. " vec3 viewPosition = normalize( vViewPosition );",
  12179. // point lights
  12180. " #if MAX_POINT_LIGHTS > 0",
  12181. " vec3 pointDiffuse = vec3( 0.0 );",
  12182. " vec3 pointSpecular = vec3( 0.0 );",
  12183. " for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  12184. " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  12185. " vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  12186. " float pointDistance = 1.0;",
  12187. " if ( pointLightDistance[ i ] > 0.0 )",
  12188. " pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  12189. " pointVector = normalize( pointVector );",
  12190. // diffuse
  12191. " #ifdef WRAP_AROUND",
  12192. " float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  12193. " float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  12194. " vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  12195. " #else",
  12196. " float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  12197. " #endif",
  12198. " pointDiffuse += pointDistance * pointLightColor[ i ] * diffuse * pointDiffuseWeight;",
  12199. // specular
  12200. " vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  12201. " float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  12202. " float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  12203. // 2.0 => 2.0001 is hack to work around ANGLE bug
  12204. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  12205. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  12206. " pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  12207. " }",
  12208. " #endif",
  12209. // spot lights
  12210. " #if MAX_SPOT_LIGHTS > 0",
  12211. " vec3 spotDiffuse = vec3( 0.0 );",
  12212. " vec3 spotSpecular = vec3( 0.0 );",
  12213. " for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  12214. " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  12215. " vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  12216. " float spotDistance = 1.0;",
  12217. " if ( spotLightDistance[ i ] > 0.0 )",
  12218. " spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  12219. " spotVector = normalize( spotVector );",
  12220. " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  12221. " if ( spotEffect > spotLightAngleCos[ i ] ) {",
  12222. " spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  12223. // diffuse
  12224. " #ifdef WRAP_AROUND",
  12225. " float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  12226. " float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  12227. " vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  12228. " #else",
  12229. " float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  12230. " #endif",
  12231. " spotDiffuse += spotDistance * spotLightColor[ i ] * diffuse * spotDiffuseWeight * spotEffect;",
  12232. // specular
  12233. " vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  12234. " float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  12235. " float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  12236. // 2.0 => 2.0001 is hack to work around ANGLE bug
  12237. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  12238. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  12239. " spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  12240. " }",
  12241. " }",
  12242. " #endif",
  12243. // directional lights
  12244. " #if MAX_DIR_LIGHTS > 0",
  12245. " vec3 dirDiffuse = vec3( 0.0 );",
  12246. " vec3 dirSpecular = vec3( 0.0 );",
  12247. " for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  12248. " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  12249. " vec3 dirVector = normalize( lDirection.xyz );",
  12250. // diffuse
  12251. " #ifdef WRAP_AROUND",
  12252. " float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  12253. " float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  12254. " vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  12255. " #else",
  12256. " float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  12257. " #endif",
  12258. " dirDiffuse += directionalLightColor[ i ] * diffuse * dirDiffuseWeight;",
  12259. // specular
  12260. " vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  12261. " float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  12262. " float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  12263. // 2.0 => 2.0001 is hack to work around ANGLE bug
  12264. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  12265. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  12266. " dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  12267. " }",
  12268. " #endif",
  12269. // hemisphere lights
  12270. " #if MAX_HEMI_LIGHTS > 0",
  12271. " vec3 hemiDiffuse = vec3( 0.0 );",
  12272. " vec3 hemiSpecular = vec3( 0.0 );" ,
  12273. " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  12274. " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  12275. " vec3 lVector = normalize( lDirection.xyz );",
  12276. // diffuse
  12277. " float dotProduct = dot( normal, lVector );",
  12278. " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  12279. " vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  12280. " hemiDiffuse += diffuse * hemiColor;",
  12281. // specular (sky light)
  12282. " vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  12283. " float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  12284. " float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  12285. // specular (ground light)
  12286. " vec3 lVectorGround = -lVector;",
  12287. " vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  12288. " float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  12289. " float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  12290. " float dotProductGround = dot( normal, lVectorGround );",
  12291. // 2.0 => 2.0001 is hack to work around ANGLE bug
  12292. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  12293. " vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  12294. " vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  12295. " hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  12296. " }",
  12297. " #endif",
  12298. // all lights contribution summation
  12299. " vec3 totalDiffuse = vec3( 0.0 );",
  12300. " vec3 totalSpecular = vec3( 0.0 );",
  12301. " #if MAX_DIR_LIGHTS > 0",
  12302. " totalDiffuse += dirDiffuse;",
  12303. " totalSpecular += dirSpecular;",
  12304. " #endif",
  12305. " #if MAX_HEMI_LIGHTS > 0",
  12306. " totalDiffuse += hemiDiffuse;",
  12307. " totalSpecular += hemiSpecular;",
  12308. " #endif",
  12309. " #if MAX_POINT_LIGHTS > 0",
  12310. " totalDiffuse += pointDiffuse;",
  12311. " totalSpecular += pointSpecular;",
  12312. " #endif",
  12313. " #if MAX_SPOT_LIGHTS > 0",
  12314. " totalDiffuse += spotDiffuse;",
  12315. " totalSpecular += spotSpecular;",
  12316. " #endif",
  12317. " #ifdef METAL",
  12318. " gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  12319. " #else",
  12320. " gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  12321. " #endif",
  12322. " if ( enableReflection ) {",
  12323. " vec3 vReflect;",
  12324. " vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  12325. " if ( useRefract ) {",
  12326. " vReflect = refract( cameraToVertex, normal, refractionRatio );",
  12327. " } else {",
  12328. " vReflect = reflect( cameraToVertex, normal );",
  12329. " }",
  12330. " vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  12331. " #ifdef GAMMA_INPUT",
  12332. " cubeColor.xyz *= cubeColor.xyz;",
  12333. " #endif",
  12334. " gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * reflectivity );",
  12335. " }",
  12336. THREE.ShaderChunk[ "shadowmap_fragment" ],
  12337. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  12338. THREE.ShaderChunk[ "fog_fragment" ],
  12339. "}"
  12340. ].join("\n"),
  12341. vertexShader: [
  12342. "attribute vec4 tangent;",
  12343. "uniform vec2 uOffset;",
  12344. "uniform vec2 uRepeat;",
  12345. "uniform bool enableDisplacement;",
  12346. "#ifdef VERTEX_TEXTURES",
  12347. " uniform sampler2D tDisplacement;",
  12348. " uniform float uDisplacementScale;",
  12349. " uniform float uDisplacementBias;",
  12350. "#endif",
  12351. "varying vec3 vTangent;",
  12352. "varying vec3 vBinormal;",
  12353. "varying vec3 vNormal;",
  12354. "varying vec2 vUv;",
  12355. "varying vec3 vWorldPosition;",
  12356. "varying vec3 vViewPosition;",
  12357. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  12358. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  12359. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12360. "void main() {",
  12361. THREE.ShaderChunk[ "skinbase_vertex" ],
  12362. THREE.ShaderChunk[ "skinnormal_vertex" ],
  12363. // normal, tangent and binormal vectors
  12364. " #ifdef USE_SKINNING",
  12365. " vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  12366. " vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  12367. " vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  12368. " #else",
  12369. " vNormal = normalize( normalMatrix * normal );",
  12370. " vTangent = normalize( normalMatrix * tangent.xyz );",
  12371. " #endif",
  12372. " vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  12373. " vUv = uv * uRepeat + uOffset;",
  12374. // displacement mapping
  12375. " vec3 displacedPosition;",
  12376. " #ifdef VERTEX_TEXTURES",
  12377. " if ( enableDisplacement ) {",
  12378. " vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  12379. " float df = uDisplacementScale * dv.x + uDisplacementBias;",
  12380. " displacedPosition = position + normalize( normal ) * df;",
  12381. " } else {",
  12382. " #ifdef USE_SKINNING",
  12383. " vec4 skinVertex = vec4( position, 1.0 );",
  12384. " vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  12385. " skinned += boneMatY * skinVertex * skinWeight.y;",
  12386. " skinned += boneMatZ * skinVertex * skinWeight.z;",
  12387. " skinned += boneMatW * skinVertex * skinWeight.w;",
  12388. " displacedPosition = skinned.xyz;",
  12389. " #else",
  12390. " displacedPosition = position;",
  12391. " #endif",
  12392. " }",
  12393. " #else",
  12394. " #ifdef USE_SKINNING",
  12395. " vec4 skinVertex = vec4( position, 1.0 );",
  12396. " vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  12397. " skinned += boneMatY * skinVertex * skinWeight.y;",
  12398. " skinned += boneMatZ * skinVertex * skinWeight.z;",
  12399. " skinned += boneMatW * skinVertex * skinWeight.w;",
  12400. " displacedPosition = skinned.xyz;",
  12401. " #else",
  12402. " displacedPosition = position;",
  12403. " #endif",
  12404. " #endif",
  12405. //
  12406. " vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  12407. " vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  12408. " gl_Position = projectionMatrix * mvPosition;",
  12409. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12410. //
  12411. " vWorldPosition = worldPosition.xyz;",
  12412. " vViewPosition = -mvPosition.xyz;",
  12413. // shadows
  12414. " #ifdef USE_SHADOWMAP",
  12415. " for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  12416. " vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  12417. " }",
  12418. " #endif",
  12419. "}"
  12420. ].join("\n")
  12421. },
  12422. /* -------------------------------------------------------------------------
  12423. // Cube map shader
  12424. ------------------------------------------------------------------------- */
  12425. 'cube': {
  12426. uniforms: { "tCube": { type: "t", value: null },
  12427. "tFlip": { type: "f", value: -1 } },
  12428. vertexShader: [
  12429. "varying vec3 vWorldPosition;",
  12430. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12431. "void main() {",
  12432. " vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  12433. " vWorldPosition = worldPosition.xyz;",
  12434. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  12435. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12436. "}"
  12437. ].join("\n"),
  12438. fragmentShader: [
  12439. "uniform samplerCube tCube;",
  12440. "uniform float tFlip;",
  12441. "varying vec3 vWorldPosition;",
  12442. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12443. "void main() {",
  12444. " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  12445. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12446. "}"
  12447. ].join("\n")
  12448. },
  12449. // Depth encoding into RGBA texture
  12450. // based on SpiderGL shadow map example
  12451. // http://spidergl.org/example.php?id=6
  12452. // originally from
  12453. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  12454. // see also here:
  12455. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  12456. 'depthRGBA': {
  12457. uniforms: {},
  12458. vertexShader: [
  12459. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  12460. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  12461. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12462. "void main() {",
  12463. THREE.ShaderChunk[ "skinbase_vertex" ],
  12464. THREE.ShaderChunk[ "morphtarget_vertex" ],
  12465. THREE.ShaderChunk[ "skinning_vertex" ],
  12466. THREE.ShaderChunk[ "default_vertex" ],
  12467. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12468. "}"
  12469. ].join("\n"),
  12470. fragmentShader: [
  12471. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12472. "vec4 pack_depth( const in float depth ) {",
  12473. " const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  12474. " const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  12475. " vec4 res = mod( depth * bit_shift * vec4( 255 ), vec4( 256 ) ) / vec4( 255 );", // " vec4 res = fract( depth * bit_shift );",
  12476. " res -= res.xxyz * bit_mask;",
  12477. " return res;",
  12478. "}",
  12479. "void main() {",
  12480. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12481. " #ifdef USE_LOGDEPTHBUF_EXT",
  12482. " gl_FragData[ 0 ] = pack_depth( gl_FragDepthEXT );",
  12483. " #else",
  12484. " gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  12485. " #endif",
  12486. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  12487. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  12488. //"gl_FragData[ 0 ] = pack_depth( z );",
  12489. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  12490. "}"
  12491. ].join("\n")
  12492. }
  12493. };
  12494. /**
  12495. * @author supereggbert / http://www.paulbrunt.co.uk/
  12496. * @author mrdoob / http://mrdoob.com/
  12497. * @author alteredq / http://alteredqualia.com/
  12498. * @author szimek / https://github.com/szimek/
  12499. */
  12500. THREE.WebGLRenderer = function ( parameters ) {
  12501. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  12502. parameters = parameters || {};
  12503. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  12504. _context = parameters.context !== undefined ? parameters.context : null,
  12505. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  12506. _buffers = {},
  12507. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  12508. _depth = parameters.depth !== undefined ? parameters.depth : true,
  12509. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  12510. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  12511. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  12512. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  12513. _logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false,
  12514. _clearColor = new THREE.Color( 0x000000 ),
  12515. _clearAlpha = 0;
  12516. // public properties
  12517. this.domElement = _canvas;
  12518. this.context = null;
  12519. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  12520. ? parameters.devicePixelRatio
  12521. : self.devicePixelRatio !== undefined
  12522. ? self.devicePixelRatio
  12523. : 1;
  12524. // clearing
  12525. this.autoClear = true;
  12526. this.autoClearColor = true;
  12527. this.autoClearDepth = true;
  12528. this.autoClearStencil = true;
  12529. // scene graph
  12530. this.sortObjects = true;
  12531. this.autoUpdateObjects = true;
  12532. // physically based shading
  12533. this.gammaInput = false;
  12534. this.gammaOutput = false;
  12535. // shadow map
  12536. this.shadowMapEnabled = false;
  12537. this.shadowMapAutoUpdate = true;
  12538. this.shadowMapType = THREE.PCFShadowMap;
  12539. this.shadowMapCullFace = THREE.CullFaceFront;
  12540. this.shadowMapDebug = false;
  12541. this.shadowMapCascade = false;
  12542. // morphs
  12543. this.maxMorphTargets = 8;
  12544. this.maxMorphNormals = 4;
  12545. // flags
  12546. this.autoScaleCubemaps = true;
  12547. // custom render plugins
  12548. this.renderPluginsPre = [];
  12549. this.renderPluginsPost = [];
  12550. // info
  12551. this.info = {
  12552. memory: {
  12553. programs: 0,
  12554. geometries: 0,
  12555. textures: 0
  12556. },
  12557. render: {
  12558. calls: 0,
  12559. vertices: 0,
  12560. faces: 0,
  12561. points: 0
  12562. }
  12563. };
  12564. // internal properties
  12565. var _this = this,
  12566. _programs = [],
  12567. // internal state cache
  12568. _currentProgram = null,
  12569. _currentFramebuffer = null,
  12570. _currentMaterialId = -1,
  12571. _currentGeometryGroupHash = null,
  12572. _currentCamera = null,
  12573. _usedTextureUnits = 0,
  12574. // GL state cache
  12575. _oldDoubleSided = -1,
  12576. _oldFlipSided = -1,
  12577. _oldBlending = -1,
  12578. _oldBlendEquation = -1,
  12579. _oldBlendSrc = -1,
  12580. _oldBlendDst = -1,
  12581. _oldDepthTest = -1,
  12582. _oldDepthWrite = -1,
  12583. _oldPolygonOffset = null,
  12584. _oldPolygonOffsetFactor = null,
  12585. _oldPolygonOffsetUnits = null,
  12586. _oldLineWidth = null,
  12587. _viewportX = 0,
  12588. _viewportY = 0,
  12589. _viewportWidth = _canvas.width,
  12590. _viewportHeight = _canvas.height,
  12591. _currentWidth = 0,
  12592. _currentHeight = 0,
  12593. _newAttributes = new Uint8Array( 16 ),
  12594. _enabledAttributes = new Uint8Array( 16 ),
  12595. // frustum
  12596. _frustum = new THREE.Frustum(),
  12597. // camera matrices cache
  12598. _projScreenMatrix = new THREE.Matrix4(),
  12599. _projScreenMatrixPS = new THREE.Matrix4(),
  12600. _vector3 = new THREE.Vector3(),
  12601. // light arrays cache
  12602. _direction = new THREE.Vector3(),
  12603. _lightsNeedUpdate = true,
  12604. _lights = {
  12605. ambient: [ 0, 0, 0 ],
  12606. directional: { length: 0, colors: new Array(), positions: new Array() },
  12607. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  12608. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  12609. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  12610. };
  12611. // initialize
  12612. var _gl;
  12613. var _glExtensionTextureFloat;
  12614. var _glExtensionTextureFloatLinear;
  12615. var _glExtensionStandardDerivatives;
  12616. var _glExtensionTextureFilterAnisotropic;
  12617. var _glExtensionCompressedTextureS3TC;
  12618. var _glExtensionElementIndexUint;
  12619. var _glExtensionFragDepth;
  12620. initGL();
  12621. setDefaultGLState();
  12622. this.context = _gl;
  12623. // GPU capabilities
  12624. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  12625. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  12626. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  12627. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  12628. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  12629. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  12630. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  12631. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  12632. //
  12633. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  12634. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  12635. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  12636. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  12637. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  12638. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  12639. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  12640. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  12641. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  12642. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  12643. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  12644. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  12645. // clamp precision to maximum available
  12646. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  12647. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  12648. if ( _precision === "highp" && ! highpAvailable ) {
  12649. if ( mediumpAvailable ) {
  12650. _precision = "mediump";
  12651. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  12652. } else {
  12653. _precision = "lowp";
  12654. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  12655. }
  12656. }
  12657. if ( _precision === "mediump" && ! mediumpAvailable ) {
  12658. _precision = "lowp";
  12659. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  12660. }
  12661. // API
  12662. this.getContext = function () {
  12663. return _gl;
  12664. };
  12665. this.supportsVertexTextures = function () {
  12666. return _supportsVertexTextures;
  12667. };
  12668. this.supportsFloatTextures = function () {
  12669. return _glExtensionTextureFloat;
  12670. };
  12671. this.supportsStandardDerivatives = function () {
  12672. return _glExtensionStandardDerivatives;
  12673. };
  12674. this.supportsCompressedTextureS3TC = function () {
  12675. return _glExtensionCompressedTextureS3TC;
  12676. };
  12677. this.getMaxAnisotropy = function () {
  12678. return _maxAnisotropy;
  12679. };
  12680. this.getPrecision = function () {
  12681. return _precision;
  12682. };
  12683. this.setSize = function ( width, height, updateStyle ) {
  12684. _canvas.width = width * this.devicePixelRatio;
  12685. _canvas.height = height * this.devicePixelRatio;
  12686. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  12687. _canvas.style.width = width + 'px';
  12688. _canvas.style.height = height + 'px';
  12689. }
  12690. this.setViewport( 0, 0, width, height );
  12691. };
  12692. this.setViewport = function ( x, y, width, height ) {
  12693. _viewportX = x * this.devicePixelRatio;
  12694. _viewportY = y * this.devicePixelRatio;
  12695. _viewportWidth = width * this.devicePixelRatio;
  12696. _viewportHeight = height * this.devicePixelRatio;
  12697. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  12698. };
  12699. this.setScissor = function ( x, y, width, height ) {
  12700. _gl.scissor(
  12701. x * this.devicePixelRatio,
  12702. y * this.devicePixelRatio,
  12703. width * this.devicePixelRatio,
  12704. height * this.devicePixelRatio
  12705. );
  12706. };
  12707. this.enableScissorTest = function ( enable ) {
  12708. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  12709. };
  12710. // Clearing
  12711. this.setClearColor = function ( color, alpha ) {
  12712. _clearColor.set( color );
  12713. _clearAlpha = alpha !== undefined ? alpha : 1;
  12714. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  12715. };
  12716. this.setClearColorHex = function ( hex, alpha ) {
  12717. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  12718. this.setClearColor( hex, alpha );
  12719. };
  12720. this.getClearColor = function () {
  12721. return _clearColor;
  12722. };
  12723. this.getClearAlpha = function () {
  12724. return _clearAlpha;
  12725. };
  12726. this.clear = function ( color, depth, stencil ) {
  12727. var bits = 0;
  12728. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  12729. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  12730. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  12731. _gl.clear( bits );
  12732. };
  12733. this.clearColor = function () {
  12734. _gl.clear( _gl.COLOR_BUFFER_BIT );
  12735. };
  12736. this.clearDepth = function () {
  12737. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  12738. };
  12739. this.clearStencil = function () {
  12740. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  12741. };
  12742. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  12743. this.setRenderTarget( renderTarget );
  12744. this.clear( color, depth, stencil );
  12745. };
  12746. // Plugins
  12747. this.addPostPlugin = function ( plugin ) {
  12748. plugin.init( this );
  12749. this.renderPluginsPost.push( plugin );
  12750. };
  12751. this.addPrePlugin = function ( plugin ) {
  12752. plugin.init( this );
  12753. this.renderPluginsPre.push( plugin );
  12754. };
  12755. // Rendering
  12756. this.updateShadowMap = function ( scene, camera ) {
  12757. _currentProgram = null;
  12758. _oldBlending = -1;
  12759. _oldDepthTest = -1;
  12760. _oldDepthWrite = -1;
  12761. _currentGeometryGroupHash = -1;
  12762. _currentMaterialId = -1;
  12763. _lightsNeedUpdate = true;
  12764. _oldDoubleSided = -1;
  12765. _oldFlipSided = -1;
  12766. this.shadowMapPlugin.update( scene, camera );
  12767. };
  12768. // Internal functions
  12769. // Buffer allocation
  12770. function createParticleBuffers ( geometry ) {
  12771. geometry.__webglVertexBuffer = _gl.createBuffer();
  12772. geometry.__webglColorBuffer = _gl.createBuffer();
  12773. _this.info.memory.geometries ++;
  12774. };
  12775. function createLineBuffers ( geometry ) {
  12776. geometry.__webglVertexBuffer = _gl.createBuffer();
  12777. geometry.__webglColorBuffer = _gl.createBuffer();
  12778. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  12779. _this.info.memory.geometries ++;
  12780. };
  12781. function createMeshBuffers ( geometryGroup ) {
  12782. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  12783. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  12784. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  12785. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  12786. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  12787. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  12788. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  12789. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  12790. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  12791. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  12792. var m, ml;
  12793. if ( geometryGroup.numMorphTargets ) {
  12794. geometryGroup.__webglMorphTargetsBuffers = [];
  12795. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12796. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  12797. }
  12798. }
  12799. if ( geometryGroup.numMorphNormals ) {
  12800. geometryGroup.__webglMorphNormalsBuffers = [];
  12801. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12802. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  12803. }
  12804. }
  12805. _this.info.memory.geometries ++;
  12806. };
  12807. // Events
  12808. var onGeometryDispose = function ( event ) {
  12809. var geometry = event.target;
  12810. geometry.removeEventListener( 'dispose', onGeometryDispose );
  12811. deallocateGeometry( geometry );
  12812. };
  12813. var onTextureDispose = function ( event ) {
  12814. var texture = event.target;
  12815. texture.removeEventListener( 'dispose', onTextureDispose );
  12816. deallocateTexture( texture );
  12817. _this.info.memory.textures --;
  12818. };
  12819. var onRenderTargetDispose = function ( event ) {
  12820. var renderTarget = event.target;
  12821. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  12822. deallocateRenderTarget( renderTarget );
  12823. _this.info.memory.textures --;
  12824. };
  12825. var onMaterialDispose = function ( event ) {
  12826. var material = event.target;
  12827. material.removeEventListener( 'dispose', onMaterialDispose );
  12828. deallocateMaterial( material );
  12829. };
  12830. // Buffer deallocation
  12831. var deleteBuffers = function ( geometry ) {
  12832. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  12833. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  12834. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  12835. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  12836. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  12837. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  12838. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  12839. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  12840. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  12841. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  12842. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  12843. // custom attributes
  12844. if ( geometry.__webglCustomAttributesList !== undefined ) {
  12845. for ( var id in geometry.__webglCustomAttributesList ) {
  12846. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  12847. }
  12848. }
  12849. _this.info.memory.geometries --;
  12850. };
  12851. var deallocateGeometry = function ( geometry ) {
  12852. geometry.__webglInit = undefined;
  12853. if ( geometry instanceof THREE.BufferGeometry ) {
  12854. var attributes = geometry.attributes;
  12855. for ( var key in attributes ) {
  12856. if ( attributes[ key ].buffer !== undefined ) {
  12857. _gl.deleteBuffer( attributes[ key ].buffer );
  12858. }
  12859. }
  12860. _this.info.memory.geometries --;
  12861. } else {
  12862. if ( geometry.geometryGroups !== undefined ) {
  12863. for ( var g in geometry.geometryGroups ) {
  12864. var geometryGroup = geometry.geometryGroups[ g ];
  12865. if ( geometryGroup.numMorphTargets !== undefined ) {
  12866. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12867. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  12868. }
  12869. }
  12870. if ( geometryGroup.numMorphNormals !== undefined ) {
  12871. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12872. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  12873. }
  12874. }
  12875. deleteBuffers( geometryGroup );
  12876. }
  12877. } else {
  12878. deleteBuffers( geometry );
  12879. }
  12880. }
  12881. };
  12882. var deallocateTexture = function ( texture ) {
  12883. if ( texture.image && texture.image.__webglTextureCube ) {
  12884. // cube texture
  12885. _gl.deleteTexture( texture.image.__webglTextureCube );
  12886. } else {
  12887. // 2D texture
  12888. if ( ! texture.__webglInit ) return;
  12889. texture.__webglInit = false;
  12890. _gl.deleteTexture( texture.__webglTexture );
  12891. }
  12892. };
  12893. var deallocateRenderTarget = function ( renderTarget ) {
  12894. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  12895. _gl.deleteTexture( renderTarget.__webglTexture );
  12896. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  12897. for ( var i = 0; i < 6; i ++ ) {
  12898. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  12899. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  12900. }
  12901. } else {
  12902. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  12903. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  12904. }
  12905. };
  12906. var deallocateMaterial = function ( material ) {
  12907. var program = material.program;
  12908. if ( program === undefined ) return;
  12909. material.program = undefined;
  12910. // only deallocate GL program if this was the last use of shared program
  12911. // assumed there is only single copy of any program in the _programs list
  12912. // (that's how it's constructed)
  12913. var i, il, programInfo;
  12914. var deleteProgram = false;
  12915. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12916. programInfo = _programs[ i ];
  12917. if ( programInfo.program === program ) {
  12918. programInfo.usedTimes --;
  12919. if ( programInfo.usedTimes === 0 ) {
  12920. deleteProgram = true;
  12921. }
  12922. break;
  12923. }
  12924. }
  12925. if ( deleteProgram === true ) {
  12926. // avoid using array.splice, this is costlier than creating new array from scratch
  12927. var newPrograms = [];
  12928. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12929. programInfo = _programs[ i ];
  12930. if ( programInfo.program !== program ) {
  12931. newPrograms.push( programInfo );
  12932. }
  12933. }
  12934. _programs = newPrograms;
  12935. _gl.deleteProgram( program );
  12936. _this.info.memory.programs --;
  12937. }
  12938. };
  12939. // Buffer initialization
  12940. function initCustomAttributes ( geometry, object ) {
  12941. var nvertices = geometry.vertices.length;
  12942. var material = object.material;
  12943. if ( material.attributes ) {
  12944. if ( geometry.__webglCustomAttributesList === undefined ) {
  12945. geometry.__webglCustomAttributesList = [];
  12946. }
  12947. for ( var a in material.attributes ) {
  12948. var attribute = material.attributes[ a ];
  12949. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12950. attribute.__webglInitialized = true;
  12951. var size = 1; // "f" and "i"
  12952. if ( attribute.type === "v2" ) size = 2;
  12953. else if ( attribute.type === "v3" ) size = 3;
  12954. else if ( attribute.type === "v4" ) size = 4;
  12955. else if ( attribute.type === "c" ) size = 3;
  12956. attribute.size = size;
  12957. attribute.array = new Float32Array( nvertices * size );
  12958. attribute.buffer = _gl.createBuffer();
  12959. attribute.buffer.belongsToAttribute = a;
  12960. attribute.needsUpdate = true;
  12961. }
  12962. geometry.__webglCustomAttributesList.push( attribute );
  12963. }
  12964. }
  12965. };
  12966. function initParticleBuffers ( geometry, object ) {
  12967. var nvertices = geometry.vertices.length;
  12968. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12969. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12970. geometry.__sortArray = [];
  12971. geometry.__webglParticleCount = nvertices;
  12972. initCustomAttributes ( geometry, object );
  12973. };
  12974. function initLineBuffers ( geometry, object ) {
  12975. var nvertices = geometry.vertices.length;
  12976. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12977. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12978. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  12979. geometry.__webglLineCount = nvertices;
  12980. initCustomAttributes ( geometry, object );
  12981. };
  12982. function initMeshBuffers ( geometryGroup, object ) {
  12983. var geometry = object.geometry,
  12984. faces3 = geometryGroup.faces3,
  12985. nvertices = faces3.length * 3,
  12986. ntris = faces3.length * 1,
  12987. nlines = faces3.length * 3,
  12988. material = getBufferMaterial( object, geometryGroup ),
  12989. uvType = bufferGuessUVType( material ),
  12990. normalType = bufferGuessNormalType( material ),
  12991. vertexColorType = bufferGuessVertexColorType( material );
  12992. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  12993. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  12994. if ( normalType ) {
  12995. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  12996. }
  12997. if ( geometry.hasTangents ) {
  12998. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  12999. }
  13000. if ( vertexColorType ) {
  13001. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  13002. }
  13003. if ( uvType ) {
  13004. if ( geometry.faceVertexUvs.length > 0 ) {
  13005. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  13006. }
  13007. if ( geometry.faceVertexUvs.length > 1 ) {
  13008. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  13009. }
  13010. }
  13011. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  13012. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  13013. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  13014. }
  13015. var UintArray = _glExtensionElementIndexUint !== null && ntris > 21845 ? Uint32Array : Uint16Array; // 65535 / 3
  13016. geometryGroup.__typeArray = UintArray;
  13017. geometryGroup.__faceArray = new UintArray( ntris * 3 );
  13018. geometryGroup.__lineArray = new UintArray( nlines * 2 );
  13019. var m, ml;
  13020. if ( geometryGroup.numMorphTargets ) {
  13021. geometryGroup.__morphTargetsArrays = [];
  13022. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  13023. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  13024. }
  13025. }
  13026. if ( geometryGroup.numMorphNormals ) {
  13027. geometryGroup.__morphNormalsArrays = [];
  13028. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  13029. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  13030. }
  13031. }
  13032. geometryGroup.__webglFaceCount = ntris * 3;
  13033. geometryGroup.__webglLineCount = nlines * 2;
  13034. // custom attributes
  13035. if ( material.attributes ) {
  13036. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  13037. geometryGroup.__webglCustomAttributesList = [];
  13038. }
  13039. for ( var a in material.attributes ) {
  13040. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  13041. // attribute buffers which are correctly indexed in the setMeshBuffers function
  13042. var originalAttribute = material.attributes[ a ];
  13043. var attribute = {};
  13044. for ( var property in originalAttribute ) {
  13045. attribute[ property ] = originalAttribute[ property ];
  13046. }
  13047. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  13048. attribute.__webglInitialized = true;
  13049. var size = 1; // "f" and "i"
  13050. if( attribute.type === "v2" ) size = 2;
  13051. else if( attribute.type === "v3" ) size = 3;
  13052. else if( attribute.type === "v4" ) size = 4;
  13053. else if( attribute.type === "c" ) size = 3;
  13054. attribute.size = size;
  13055. attribute.array = new Float32Array( nvertices * size );
  13056. attribute.buffer = _gl.createBuffer();
  13057. attribute.buffer.belongsToAttribute = a;
  13058. originalAttribute.needsUpdate = true;
  13059. attribute.__original = originalAttribute;
  13060. }
  13061. geometryGroup.__webglCustomAttributesList.push( attribute );
  13062. }
  13063. }
  13064. geometryGroup.__inittedArrays = true;
  13065. };
  13066. function getBufferMaterial( object, geometryGroup ) {
  13067. return object.material instanceof THREE.MeshFaceMaterial
  13068. ? object.material.materials[ geometryGroup.materialIndex ]
  13069. : object.material;
  13070. };
  13071. function materialNeedsSmoothNormals ( material ) {
  13072. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  13073. };
  13074. function bufferGuessNormalType ( material ) {
  13075. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  13076. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  13077. return false;
  13078. }
  13079. if ( materialNeedsSmoothNormals( material ) ) {
  13080. return THREE.SmoothShading;
  13081. } else {
  13082. return THREE.FlatShading;
  13083. }
  13084. };
  13085. function bufferGuessVertexColorType( material ) {
  13086. if ( material.vertexColors ) {
  13087. return material.vertexColors;
  13088. }
  13089. return false;
  13090. };
  13091. function bufferGuessUVType( material ) {
  13092. // material must use some texture to require uvs
  13093. if ( material.map ||
  13094. material.lightMap ||
  13095. material.bumpMap ||
  13096. material.normalMap ||
  13097. material.specularMap ||
  13098. material instanceof THREE.ShaderMaterial ) {
  13099. return true;
  13100. }
  13101. return false;
  13102. };
  13103. //
  13104. function initDirectBuffers( geometry ) {
  13105. for ( var name in geometry.attributes ) {
  13106. var bufferType = ( name === "index" ) ? _gl.ELEMENT_ARRAY_BUFFER : _gl.ARRAY_BUFFER;
  13107. var attribute = geometry.attributes[ name ];
  13108. attribute.buffer = _gl.createBuffer();
  13109. _gl.bindBuffer( bufferType, attribute.buffer );
  13110. _gl.bufferData( bufferType, attribute.array, _gl.STATIC_DRAW );
  13111. }
  13112. }
  13113. // Buffer setting
  13114. function setParticleBuffers ( geometry, hint, object ) {
  13115. var v, c, vertex, offset, index, color,
  13116. vertices = geometry.vertices,
  13117. vl = vertices.length,
  13118. colors = geometry.colors,
  13119. cl = colors.length,
  13120. vertexArray = geometry.__vertexArray,
  13121. colorArray = geometry.__colorArray,
  13122. sortArray = geometry.__sortArray,
  13123. dirtyVertices = geometry.verticesNeedUpdate,
  13124. dirtyElements = geometry.elementsNeedUpdate,
  13125. dirtyColors = geometry.colorsNeedUpdate,
  13126. customAttributes = geometry.__webglCustomAttributesList,
  13127. i, il,
  13128. a, ca, cal, value,
  13129. customAttribute;
  13130. if ( object.sortParticles ) {
  13131. _projScreenMatrixPS.copy( _projScreenMatrix );
  13132. _projScreenMatrixPS.multiply( object.matrixWorld );
  13133. for ( v = 0; v < vl; v ++ ) {
  13134. vertex = vertices[ v ];
  13135. _vector3.copy( vertex );
  13136. _vector3.applyProjection( _projScreenMatrixPS );
  13137. sortArray[ v ] = [ _vector3.z, v ];
  13138. }
  13139. sortArray.sort( numericalSort );
  13140. for ( v = 0; v < vl; v ++ ) {
  13141. vertex = vertices[ sortArray[v][1] ];
  13142. offset = v * 3;
  13143. vertexArray[ offset ] = vertex.x;
  13144. vertexArray[ offset + 1 ] = vertex.y;
  13145. vertexArray[ offset + 2 ] = vertex.z;
  13146. }
  13147. for ( c = 0; c < cl; c ++ ) {
  13148. offset = c * 3;
  13149. color = colors[ sortArray[c][1] ];
  13150. colorArray[ offset ] = color.r;
  13151. colorArray[ offset + 1 ] = color.g;
  13152. colorArray[ offset + 2 ] = color.b;
  13153. }
  13154. if ( customAttributes ) {
  13155. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13156. customAttribute = customAttributes[ i ];
  13157. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  13158. offset = 0;
  13159. cal = customAttribute.value.length;
  13160. if ( customAttribute.size === 1 ) {
  13161. for ( ca = 0; ca < cal; ca ++ ) {
  13162. index = sortArray[ ca ][ 1 ];
  13163. customAttribute.array[ ca ] = customAttribute.value[ index ];
  13164. }
  13165. } else if ( customAttribute.size === 2 ) {
  13166. for ( ca = 0; ca < cal; ca ++ ) {
  13167. index = sortArray[ ca ][ 1 ];
  13168. value = customAttribute.value[ index ];
  13169. customAttribute.array[ offset ] = value.x;
  13170. customAttribute.array[ offset + 1 ] = value.y;
  13171. offset += 2;
  13172. }
  13173. } else if ( customAttribute.size === 3 ) {
  13174. if ( customAttribute.type === "c" ) {
  13175. for ( ca = 0; ca < cal; ca ++ ) {
  13176. index = sortArray[ ca ][ 1 ];
  13177. value = customAttribute.value[ index ];
  13178. customAttribute.array[ offset ] = value.r;
  13179. customAttribute.array[ offset + 1 ] = value.g;
  13180. customAttribute.array[ offset + 2 ] = value.b;
  13181. offset += 3;
  13182. }
  13183. } else {
  13184. for ( ca = 0; ca < cal; ca ++ ) {
  13185. index = sortArray[ ca ][ 1 ];
  13186. value = customAttribute.value[ index ];
  13187. customAttribute.array[ offset ] = value.x;
  13188. customAttribute.array[ offset + 1 ] = value.y;
  13189. customAttribute.array[ offset + 2 ] = value.z;
  13190. offset += 3;
  13191. }
  13192. }
  13193. } else if ( customAttribute.size === 4 ) {
  13194. for ( ca = 0; ca < cal; ca ++ ) {
  13195. index = sortArray[ ca ][ 1 ];
  13196. value = customAttribute.value[ index ];
  13197. customAttribute.array[ offset ] = value.x;
  13198. customAttribute.array[ offset + 1 ] = value.y;
  13199. customAttribute.array[ offset + 2 ] = value.z;
  13200. customAttribute.array[ offset + 3 ] = value.w;
  13201. offset += 4;
  13202. }
  13203. }
  13204. }
  13205. }
  13206. } else {
  13207. if ( dirtyVertices ) {
  13208. for ( v = 0; v < vl; v ++ ) {
  13209. vertex = vertices[ v ];
  13210. offset = v * 3;
  13211. vertexArray[ offset ] = vertex.x;
  13212. vertexArray[ offset + 1 ] = vertex.y;
  13213. vertexArray[ offset + 2 ] = vertex.z;
  13214. }
  13215. }
  13216. if ( dirtyColors ) {
  13217. for ( c = 0; c < cl; c ++ ) {
  13218. color = colors[ c ];
  13219. offset = c * 3;
  13220. colorArray[ offset ] = color.r;
  13221. colorArray[ offset + 1 ] = color.g;
  13222. colorArray[ offset + 2 ] = color.b;
  13223. }
  13224. }
  13225. if ( customAttributes ) {
  13226. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13227. customAttribute = customAttributes[ i ];
  13228. if ( customAttribute.needsUpdate &&
  13229. ( customAttribute.boundTo === undefined ||
  13230. customAttribute.boundTo === "vertices") ) {
  13231. cal = customAttribute.value.length;
  13232. offset = 0;
  13233. if ( customAttribute.size === 1 ) {
  13234. for ( ca = 0; ca < cal; ca ++ ) {
  13235. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  13236. }
  13237. } else if ( customAttribute.size === 2 ) {
  13238. for ( ca = 0; ca < cal; ca ++ ) {
  13239. value = customAttribute.value[ ca ];
  13240. customAttribute.array[ offset ] = value.x;
  13241. customAttribute.array[ offset + 1 ] = value.y;
  13242. offset += 2;
  13243. }
  13244. } else if ( customAttribute.size === 3 ) {
  13245. if ( customAttribute.type === "c" ) {
  13246. for ( ca = 0; ca < cal; ca ++ ) {
  13247. value = customAttribute.value[ ca ];
  13248. customAttribute.array[ offset ] = value.r;
  13249. customAttribute.array[ offset + 1 ] = value.g;
  13250. customAttribute.array[ offset + 2 ] = value.b;
  13251. offset += 3;
  13252. }
  13253. } else {
  13254. for ( ca = 0; ca < cal; ca ++ ) {
  13255. value = customAttribute.value[ ca ];
  13256. customAttribute.array[ offset ] = value.x;
  13257. customAttribute.array[ offset + 1 ] = value.y;
  13258. customAttribute.array[ offset + 2 ] = value.z;
  13259. offset += 3;
  13260. }
  13261. }
  13262. } else if ( customAttribute.size === 4 ) {
  13263. for ( ca = 0; ca < cal; ca ++ ) {
  13264. value = customAttribute.value[ ca ];
  13265. customAttribute.array[ offset ] = value.x;
  13266. customAttribute.array[ offset + 1 ] = value.y;
  13267. customAttribute.array[ offset + 2 ] = value.z;
  13268. customAttribute.array[ offset + 3 ] = value.w;
  13269. offset += 4;
  13270. }
  13271. }
  13272. }
  13273. }
  13274. }
  13275. }
  13276. if ( dirtyVertices || object.sortParticles ) {
  13277. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  13278. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  13279. }
  13280. if ( dirtyColors || object.sortParticles ) {
  13281. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  13282. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  13283. }
  13284. if ( customAttributes ) {
  13285. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13286. customAttribute = customAttributes[ i ];
  13287. if ( customAttribute.needsUpdate || object.sortParticles ) {
  13288. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  13289. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  13290. }
  13291. }
  13292. }
  13293. }
  13294. function setLineBuffers ( geometry, hint ) {
  13295. var v, c, d, vertex, offset, color,
  13296. vertices = geometry.vertices,
  13297. colors = geometry.colors,
  13298. lineDistances = geometry.lineDistances,
  13299. vl = vertices.length,
  13300. cl = colors.length,
  13301. dl = lineDistances.length,
  13302. vertexArray = geometry.__vertexArray,
  13303. colorArray = geometry.__colorArray,
  13304. lineDistanceArray = geometry.__lineDistanceArray,
  13305. dirtyVertices = geometry.verticesNeedUpdate,
  13306. dirtyColors = geometry.colorsNeedUpdate,
  13307. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  13308. customAttributes = geometry.__webglCustomAttributesList,
  13309. i, il,
  13310. a, ca, cal, value,
  13311. customAttribute;
  13312. if ( dirtyVertices ) {
  13313. for ( v = 0; v < vl; v ++ ) {
  13314. vertex = vertices[ v ];
  13315. offset = v * 3;
  13316. vertexArray[ offset ] = vertex.x;
  13317. vertexArray[ offset + 1 ] = vertex.y;
  13318. vertexArray[ offset + 2 ] = vertex.z;
  13319. }
  13320. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  13321. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  13322. }
  13323. if ( dirtyColors ) {
  13324. for ( c = 0; c < cl; c ++ ) {
  13325. color = colors[ c ];
  13326. offset = c * 3;
  13327. colorArray[ offset ] = color.r;
  13328. colorArray[ offset + 1 ] = color.g;
  13329. colorArray[ offset + 2 ] = color.b;
  13330. }
  13331. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  13332. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  13333. }
  13334. if ( dirtyLineDistances ) {
  13335. for ( d = 0; d < dl; d ++ ) {
  13336. lineDistanceArray[ d ] = lineDistances[ d ];
  13337. }
  13338. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  13339. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  13340. }
  13341. if ( customAttributes ) {
  13342. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13343. customAttribute = customAttributes[ i ];
  13344. if ( customAttribute.needsUpdate &&
  13345. ( customAttribute.boundTo === undefined ||
  13346. customAttribute.boundTo === "vertices" ) ) {
  13347. offset = 0;
  13348. cal = customAttribute.value.length;
  13349. if ( customAttribute.size === 1 ) {
  13350. for ( ca = 0; ca < cal; ca ++ ) {
  13351. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  13352. }
  13353. } else if ( customAttribute.size === 2 ) {
  13354. for ( ca = 0; ca < cal; ca ++ ) {
  13355. value = customAttribute.value[ ca ];
  13356. customAttribute.array[ offset ] = value.x;
  13357. customAttribute.array[ offset + 1 ] = value.y;
  13358. offset += 2;
  13359. }
  13360. } else if ( customAttribute.size === 3 ) {
  13361. if ( customAttribute.type === "c" ) {
  13362. for ( ca = 0; ca < cal; ca ++ ) {
  13363. value = customAttribute.value[ ca ];
  13364. customAttribute.array[ offset ] = value.r;
  13365. customAttribute.array[ offset + 1 ] = value.g;
  13366. customAttribute.array[ offset + 2 ] = value.b;
  13367. offset += 3;
  13368. }
  13369. } else {
  13370. for ( ca = 0; ca < cal; ca ++ ) {
  13371. value = customAttribute.value[ ca ];
  13372. customAttribute.array[ offset ] = value.x;
  13373. customAttribute.array[ offset + 1 ] = value.y;
  13374. customAttribute.array[ offset + 2 ] = value.z;
  13375. offset += 3;
  13376. }
  13377. }
  13378. } else if ( customAttribute.size === 4 ) {
  13379. for ( ca = 0; ca < cal; ca ++ ) {
  13380. value = customAttribute.value[ ca ];
  13381. customAttribute.array[ offset ] = value.x;
  13382. customAttribute.array[ offset + 1 ] = value.y;
  13383. customAttribute.array[ offset + 2 ] = value.z;
  13384. customAttribute.array[ offset + 3 ] = value.w;
  13385. offset += 4;
  13386. }
  13387. }
  13388. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  13389. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  13390. }
  13391. }
  13392. }
  13393. }
  13394. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  13395. if ( ! geometryGroup.__inittedArrays ) {
  13396. return;
  13397. }
  13398. var normalType = bufferGuessNormalType( material ),
  13399. vertexColorType = bufferGuessVertexColorType( material ),
  13400. uvType = bufferGuessUVType( material ),
  13401. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  13402. var f, fl, fi, face,
  13403. vertexNormals, faceNormal, normal,
  13404. vertexColors, faceColor,
  13405. vertexTangents,
  13406. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  13407. c1, c2, c3, c4,
  13408. sw1, sw2, sw3, sw4,
  13409. si1, si2, si3, si4,
  13410. sa1, sa2, sa3, sa4,
  13411. sb1, sb2, sb3, sb4,
  13412. m, ml, i, il,
  13413. vn, uvi, uv2i,
  13414. vk, vkl, vka,
  13415. nka, chf, faceVertexNormals,
  13416. a,
  13417. vertexIndex = 0,
  13418. offset = 0,
  13419. offset_uv = 0,
  13420. offset_uv2 = 0,
  13421. offset_face = 0,
  13422. offset_normal = 0,
  13423. offset_tangent = 0,
  13424. offset_line = 0,
  13425. offset_color = 0,
  13426. offset_skin = 0,
  13427. offset_morphTarget = 0,
  13428. offset_custom = 0,
  13429. offset_customSrc = 0,
  13430. value,
  13431. vertexArray = geometryGroup.__vertexArray,
  13432. uvArray = geometryGroup.__uvArray,
  13433. uv2Array = geometryGroup.__uv2Array,
  13434. normalArray = geometryGroup.__normalArray,
  13435. tangentArray = geometryGroup.__tangentArray,
  13436. colorArray = geometryGroup.__colorArray,
  13437. skinIndexArray = geometryGroup.__skinIndexArray,
  13438. skinWeightArray = geometryGroup.__skinWeightArray,
  13439. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  13440. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  13441. customAttributes = geometryGroup.__webglCustomAttributesList,
  13442. customAttribute,
  13443. faceArray = geometryGroup.__faceArray,
  13444. lineArray = geometryGroup.__lineArray,
  13445. geometry = object.geometry, // this is shared for all chunks
  13446. dirtyVertices = geometry.verticesNeedUpdate,
  13447. dirtyElements = geometry.elementsNeedUpdate,
  13448. dirtyUvs = geometry.uvsNeedUpdate,
  13449. dirtyNormals = geometry.normalsNeedUpdate,
  13450. dirtyTangents = geometry.tangentsNeedUpdate,
  13451. dirtyColors = geometry.colorsNeedUpdate,
  13452. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  13453. vertices = geometry.vertices,
  13454. chunk_faces3 = geometryGroup.faces3,
  13455. obj_faces = geometry.faces,
  13456. obj_uvs = geometry.faceVertexUvs[ 0 ],
  13457. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  13458. obj_colors = geometry.colors,
  13459. obj_skinIndices = geometry.skinIndices,
  13460. obj_skinWeights = geometry.skinWeights,
  13461. morphTargets = geometry.morphTargets,
  13462. morphNormals = geometry.morphNormals;
  13463. if ( dirtyVertices ) {
  13464. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13465. face = obj_faces[ chunk_faces3[ f ] ];
  13466. v1 = vertices[ face.a ];
  13467. v2 = vertices[ face.b ];
  13468. v3 = vertices[ face.c ];
  13469. vertexArray[ offset ] = v1.x;
  13470. vertexArray[ offset + 1 ] = v1.y;
  13471. vertexArray[ offset + 2 ] = v1.z;
  13472. vertexArray[ offset + 3 ] = v2.x;
  13473. vertexArray[ offset + 4 ] = v2.y;
  13474. vertexArray[ offset + 5 ] = v2.z;
  13475. vertexArray[ offset + 6 ] = v3.x;
  13476. vertexArray[ offset + 7 ] = v3.y;
  13477. vertexArray[ offset + 8 ] = v3.z;
  13478. offset += 9;
  13479. }
  13480. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13481. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  13482. }
  13483. if ( dirtyMorphTargets ) {
  13484. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  13485. offset_morphTarget = 0;
  13486. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13487. chf = chunk_faces3[ f ];
  13488. face = obj_faces[ chf ];
  13489. // morph positions
  13490. v1 = morphTargets[ vk ].vertices[ face.a ];
  13491. v2 = morphTargets[ vk ].vertices[ face.b ];
  13492. v3 = morphTargets[ vk ].vertices[ face.c ];
  13493. vka = morphTargetsArrays[ vk ];
  13494. vka[ offset_morphTarget ] = v1.x;
  13495. vka[ offset_morphTarget + 1 ] = v1.y;
  13496. vka[ offset_morphTarget + 2 ] = v1.z;
  13497. vka[ offset_morphTarget + 3 ] = v2.x;
  13498. vka[ offset_morphTarget + 4 ] = v2.y;
  13499. vka[ offset_morphTarget + 5 ] = v2.z;
  13500. vka[ offset_morphTarget + 6 ] = v3.x;
  13501. vka[ offset_morphTarget + 7 ] = v3.y;
  13502. vka[ offset_morphTarget + 8 ] = v3.z;
  13503. // morph normals
  13504. if ( material.morphNormals ) {
  13505. if ( needsSmoothNormals ) {
  13506. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  13507. n1 = faceVertexNormals.a;
  13508. n2 = faceVertexNormals.b;
  13509. n3 = faceVertexNormals.c;
  13510. } else {
  13511. n1 = morphNormals[ vk ].faceNormals[ chf ];
  13512. n2 = n1;
  13513. n3 = n1;
  13514. }
  13515. nka = morphNormalsArrays[ vk ];
  13516. nka[ offset_morphTarget ] = n1.x;
  13517. nka[ offset_morphTarget + 1 ] = n1.y;
  13518. nka[ offset_morphTarget + 2 ] = n1.z;
  13519. nka[ offset_morphTarget + 3 ] = n2.x;
  13520. nka[ offset_morphTarget + 4 ] = n2.y;
  13521. nka[ offset_morphTarget + 5 ] = n2.z;
  13522. nka[ offset_morphTarget + 6 ] = n3.x;
  13523. nka[ offset_morphTarget + 7 ] = n3.y;
  13524. nka[ offset_morphTarget + 8 ] = n3.z;
  13525. }
  13526. //
  13527. offset_morphTarget += 9;
  13528. }
  13529. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  13530. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  13531. if ( material.morphNormals ) {
  13532. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  13533. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  13534. }
  13535. }
  13536. }
  13537. if ( obj_skinWeights.length ) {
  13538. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13539. face = obj_faces[ chunk_faces3[ f ] ];
  13540. // weights
  13541. sw1 = obj_skinWeights[ face.a ];
  13542. sw2 = obj_skinWeights[ face.b ];
  13543. sw3 = obj_skinWeights[ face.c ];
  13544. skinWeightArray[ offset_skin ] = sw1.x;
  13545. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  13546. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  13547. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  13548. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  13549. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  13550. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  13551. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  13552. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  13553. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  13554. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  13555. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  13556. // indices
  13557. si1 = obj_skinIndices[ face.a ];
  13558. si2 = obj_skinIndices[ face.b ];
  13559. si3 = obj_skinIndices[ face.c ];
  13560. skinIndexArray[ offset_skin ] = si1.x;
  13561. skinIndexArray[ offset_skin + 1 ] = si1.y;
  13562. skinIndexArray[ offset_skin + 2 ] = si1.z;
  13563. skinIndexArray[ offset_skin + 3 ] = si1.w;
  13564. skinIndexArray[ offset_skin + 4 ] = si2.x;
  13565. skinIndexArray[ offset_skin + 5 ] = si2.y;
  13566. skinIndexArray[ offset_skin + 6 ] = si2.z;
  13567. skinIndexArray[ offset_skin + 7 ] = si2.w;
  13568. skinIndexArray[ offset_skin + 8 ] = si3.x;
  13569. skinIndexArray[ offset_skin + 9 ] = si3.y;
  13570. skinIndexArray[ offset_skin + 10 ] = si3.z;
  13571. skinIndexArray[ offset_skin + 11 ] = si3.w;
  13572. offset_skin += 12;
  13573. }
  13574. if ( offset_skin > 0 ) {
  13575. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13576. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  13577. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13578. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  13579. }
  13580. }
  13581. if ( dirtyColors && vertexColorType ) {
  13582. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13583. face = obj_faces[ chunk_faces3[ f ] ];
  13584. vertexColors = face.vertexColors;
  13585. faceColor = face.color;
  13586. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  13587. c1 = vertexColors[ 0 ];
  13588. c2 = vertexColors[ 1 ];
  13589. c3 = vertexColors[ 2 ];
  13590. } else {
  13591. c1 = faceColor;
  13592. c2 = faceColor;
  13593. c3 = faceColor;
  13594. }
  13595. colorArray[ offset_color ] = c1.r;
  13596. colorArray[ offset_color + 1 ] = c1.g;
  13597. colorArray[ offset_color + 2 ] = c1.b;
  13598. colorArray[ offset_color + 3 ] = c2.r;
  13599. colorArray[ offset_color + 4 ] = c2.g;
  13600. colorArray[ offset_color + 5 ] = c2.b;
  13601. colorArray[ offset_color + 6 ] = c3.r;
  13602. colorArray[ offset_color + 7 ] = c3.g;
  13603. colorArray[ offset_color + 8 ] = c3.b;
  13604. offset_color += 9;
  13605. }
  13606. if ( offset_color > 0 ) {
  13607. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13608. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  13609. }
  13610. }
  13611. if ( dirtyTangents && geometry.hasTangents ) {
  13612. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13613. face = obj_faces[ chunk_faces3[ f ] ];
  13614. vertexTangents = face.vertexTangents;
  13615. t1 = vertexTangents[ 0 ];
  13616. t2 = vertexTangents[ 1 ];
  13617. t3 = vertexTangents[ 2 ];
  13618. tangentArray[ offset_tangent ] = t1.x;
  13619. tangentArray[ offset_tangent + 1 ] = t1.y;
  13620. tangentArray[ offset_tangent + 2 ] = t1.z;
  13621. tangentArray[ offset_tangent + 3 ] = t1.w;
  13622. tangentArray[ offset_tangent + 4 ] = t2.x;
  13623. tangentArray[ offset_tangent + 5 ] = t2.y;
  13624. tangentArray[ offset_tangent + 6 ] = t2.z;
  13625. tangentArray[ offset_tangent + 7 ] = t2.w;
  13626. tangentArray[ offset_tangent + 8 ] = t3.x;
  13627. tangentArray[ offset_tangent + 9 ] = t3.y;
  13628. tangentArray[ offset_tangent + 10 ] = t3.z;
  13629. tangentArray[ offset_tangent + 11 ] = t3.w;
  13630. offset_tangent += 12;
  13631. }
  13632. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13633. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  13634. }
  13635. if ( dirtyNormals && normalType ) {
  13636. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13637. face = obj_faces[ chunk_faces3[ f ] ];
  13638. vertexNormals = face.vertexNormals;
  13639. faceNormal = face.normal;
  13640. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  13641. for ( i = 0; i < 3; i ++ ) {
  13642. vn = vertexNormals[ i ];
  13643. normalArray[ offset_normal ] = vn.x;
  13644. normalArray[ offset_normal + 1 ] = vn.y;
  13645. normalArray[ offset_normal + 2 ] = vn.z;
  13646. offset_normal += 3;
  13647. }
  13648. } else {
  13649. for ( i = 0; i < 3; i ++ ) {
  13650. normalArray[ offset_normal ] = faceNormal.x;
  13651. normalArray[ offset_normal + 1 ] = faceNormal.y;
  13652. normalArray[ offset_normal + 2 ] = faceNormal.z;
  13653. offset_normal += 3;
  13654. }
  13655. }
  13656. }
  13657. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13658. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  13659. }
  13660. if ( dirtyUvs && obj_uvs && uvType ) {
  13661. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13662. fi = chunk_faces3[ f ];
  13663. uv = obj_uvs[ fi ];
  13664. if ( uv === undefined ) continue;
  13665. for ( i = 0; i < 3; i ++ ) {
  13666. uvi = uv[ i ];
  13667. uvArray[ offset_uv ] = uvi.x;
  13668. uvArray[ offset_uv + 1 ] = uvi.y;
  13669. offset_uv += 2;
  13670. }
  13671. }
  13672. if ( offset_uv > 0 ) {
  13673. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13674. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  13675. }
  13676. }
  13677. if ( dirtyUvs && obj_uvs2 && uvType ) {
  13678. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13679. fi = chunk_faces3[ f ];
  13680. uv2 = obj_uvs2[ fi ];
  13681. if ( uv2 === undefined ) continue;
  13682. for ( i = 0; i < 3; i ++ ) {
  13683. uv2i = uv2[ i ];
  13684. uv2Array[ offset_uv2 ] = uv2i.x;
  13685. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  13686. offset_uv2 += 2;
  13687. }
  13688. }
  13689. if ( offset_uv2 > 0 ) {
  13690. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13691. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  13692. }
  13693. }
  13694. if ( dirtyElements ) {
  13695. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13696. faceArray[ offset_face ] = vertexIndex;
  13697. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  13698. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  13699. offset_face += 3;
  13700. lineArray[ offset_line ] = vertexIndex;
  13701. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  13702. lineArray[ offset_line + 2 ] = vertexIndex;
  13703. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  13704. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  13705. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  13706. offset_line += 6;
  13707. vertexIndex += 3;
  13708. }
  13709. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13710. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  13711. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13712. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  13713. }
  13714. if ( customAttributes ) {
  13715. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13716. customAttribute = customAttributes[ i ];
  13717. if ( ! customAttribute.__original.needsUpdate ) continue;
  13718. offset_custom = 0;
  13719. offset_customSrc = 0;
  13720. if ( customAttribute.size === 1 ) {
  13721. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13722. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13723. face = obj_faces[ chunk_faces3[ f ] ];
  13724. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  13725. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  13726. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  13727. offset_custom += 3;
  13728. }
  13729. } else if ( customAttribute.boundTo === "faces" ) {
  13730. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13731. value = customAttribute.value[ chunk_faces3[ f ] ];
  13732. customAttribute.array[ offset_custom ] = value;
  13733. customAttribute.array[ offset_custom + 1 ] = value;
  13734. customAttribute.array[ offset_custom + 2 ] = value;
  13735. offset_custom += 3;
  13736. }
  13737. }
  13738. } else if ( customAttribute.size === 2 ) {
  13739. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13740. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13741. face = obj_faces[ chunk_faces3[ f ] ];
  13742. v1 = customAttribute.value[ face.a ];
  13743. v2 = customAttribute.value[ face.b ];
  13744. v3 = customAttribute.value[ face.c ];
  13745. customAttribute.array[ offset_custom ] = v1.x;
  13746. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13747. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13748. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13749. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13750. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13751. offset_custom += 6;
  13752. }
  13753. } else if ( customAttribute.boundTo === "faces" ) {
  13754. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13755. value = customAttribute.value[ chunk_faces3[ f ] ];
  13756. v1 = value;
  13757. v2 = value;
  13758. v3 = value;
  13759. customAttribute.array[ offset_custom ] = v1.x;
  13760. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13761. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13762. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13763. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13764. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13765. offset_custom += 6;
  13766. }
  13767. }
  13768. } else if ( customAttribute.size === 3 ) {
  13769. var pp;
  13770. if ( customAttribute.type === "c" ) {
  13771. pp = [ "r", "g", "b" ];
  13772. } else {
  13773. pp = [ "x", "y", "z" ];
  13774. }
  13775. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13776. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13777. face = obj_faces[ chunk_faces3[ f ] ];
  13778. v1 = customAttribute.value[ face.a ];
  13779. v2 = customAttribute.value[ face.b ];
  13780. v3 = customAttribute.value[ face.c ];
  13781. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13782. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13783. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13784. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13785. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13786. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13787. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13788. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13789. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13790. offset_custom += 9;
  13791. }
  13792. } else if ( customAttribute.boundTo === "faces" ) {
  13793. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13794. value = customAttribute.value[ chunk_faces3[ f ] ];
  13795. v1 = value;
  13796. v2 = value;
  13797. v3 = value;
  13798. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13799. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13800. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13801. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13802. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13803. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13804. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13805. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13806. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13807. offset_custom += 9;
  13808. }
  13809. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13810. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13811. value = customAttribute.value[ chunk_faces3[ f ] ];
  13812. v1 = value[ 0 ];
  13813. v2 = value[ 1 ];
  13814. v3 = value[ 2 ];
  13815. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13816. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13817. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13818. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13819. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13820. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13821. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13822. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13823. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13824. offset_custom += 9;
  13825. }
  13826. }
  13827. } else if ( customAttribute.size === 4 ) {
  13828. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13829. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13830. face = obj_faces[ chunk_faces3[ f ] ];
  13831. v1 = customAttribute.value[ face.a ];
  13832. v2 = customAttribute.value[ face.b ];
  13833. v3 = customAttribute.value[ face.c ];
  13834. customAttribute.array[ offset_custom ] = v1.x;
  13835. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13836. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13837. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13838. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13839. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13840. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13841. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13842. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13843. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13844. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13845. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13846. offset_custom += 12;
  13847. }
  13848. } else if ( customAttribute.boundTo === "faces" ) {
  13849. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13850. value = customAttribute.value[ chunk_faces3[ f ] ];
  13851. v1 = value;
  13852. v2 = value;
  13853. v3 = value;
  13854. customAttribute.array[ offset_custom ] = v1.x;
  13855. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13856. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13857. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13858. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13859. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13860. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13861. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13862. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13863. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13864. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13865. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13866. offset_custom += 12;
  13867. }
  13868. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13869. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13870. value = customAttribute.value[ chunk_faces3[ f ] ];
  13871. v1 = value[ 0 ];
  13872. v2 = value[ 1 ];
  13873. v3 = value[ 2 ];
  13874. customAttribute.array[ offset_custom ] = v1.x;
  13875. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13876. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13877. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13878. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13879. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13880. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13881. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13882. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13883. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13884. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13885. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13886. offset_custom += 12;
  13887. }
  13888. }
  13889. }
  13890. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  13891. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  13892. }
  13893. }
  13894. if ( dispose ) {
  13895. delete geometryGroup.__inittedArrays;
  13896. delete geometryGroup.__colorArray;
  13897. delete geometryGroup.__normalArray;
  13898. delete geometryGroup.__tangentArray;
  13899. delete geometryGroup.__uvArray;
  13900. delete geometryGroup.__uv2Array;
  13901. delete geometryGroup.__faceArray;
  13902. delete geometryGroup.__vertexArray;
  13903. delete geometryGroup.__lineArray;
  13904. delete geometryGroup.__skinIndexArray;
  13905. delete geometryGroup.__skinWeightArray;
  13906. }
  13907. };
  13908. function setDirectBuffers( geometry, hint ) {
  13909. var attributes = geometry.attributes;
  13910. var attributeName, attributeItem;
  13911. for ( attributeName in attributes ) {
  13912. attributeItem = attributes[ attributeName ];
  13913. if ( attributeItem.needsUpdate ) {
  13914. if ( attributeName === 'index' ) {
  13915. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  13916. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  13917. } else {
  13918. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13919. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  13920. }
  13921. attributeItem.needsUpdate = false;
  13922. }
  13923. }
  13924. }
  13925. // Buffer rendering
  13926. this.renderBufferImmediate = function ( object, program, material ) {
  13927. initAttributes();
  13928. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  13929. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  13930. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  13931. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  13932. if ( object.hasPositions ) {
  13933. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  13934. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  13935. enableAttribute( program.attributes.position );
  13936. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13937. }
  13938. if ( object.hasNormals ) {
  13939. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  13940. if ( material.shading === THREE.FlatShading ) {
  13941. var nx, ny, nz,
  13942. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  13943. normalArray,
  13944. i, il = object.count * 3;
  13945. for( i = 0; i < il; i += 9 ) {
  13946. normalArray = object.normalArray;
  13947. nax = normalArray[ i ];
  13948. nay = normalArray[ i + 1 ];
  13949. naz = normalArray[ i + 2 ];
  13950. nbx = normalArray[ i + 3 ];
  13951. nby = normalArray[ i + 4 ];
  13952. nbz = normalArray[ i + 5 ];
  13953. ncx = normalArray[ i + 6 ];
  13954. ncy = normalArray[ i + 7 ];
  13955. ncz = normalArray[ i + 8 ];
  13956. nx = ( nax + nbx + ncx ) / 3;
  13957. ny = ( nay + nby + ncy ) / 3;
  13958. nz = ( naz + nbz + ncz ) / 3;
  13959. normalArray[ i ] = nx;
  13960. normalArray[ i + 1 ] = ny;
  13961. normalArray[ i + 2 ] = nz;
  13962. normalArray[ i + 3 ] = nx;
  13963. normalArray[ i + 4 ] = ny;
  13964. normalArray[ i + 5 ] = nz;
  13965. normalArray[ i + 6 ] = nx;
  13966. normalArray[ i + 7 ] = ny;
  13967. normalArray[ i + 8 ] = nz;
  13968. }
  13969. }
  13970. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13971. enableAttribute( program.attributes.normal );
  13972. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13973. }
  13974. if ( object.hasUvs && material.map ) {
  13975. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13976. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13977. enableAttribute( program.attributes.uv );
  13978. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13979. }
  13980. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13981. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13982. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13983. enableAttribute( program.attributes.color );
  13984. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13985. }
  13986. disableUnusedAttributes();
  13987. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13988. object.count = 0;
  13989. };
  13990. function setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex ) {
  13991. for ( var attributeName in programAttributes ) {
  13992. var attributePointer = programAttributes[ attributeName ];
  13993. var attributeItem = geometryAttributes[ attributeName ];
  13994. if ( attributePointer >= 0 ) {
  13995. if ( attributeItem ) {
  13996. var attributeSize = attributeItem.itemSize;
  13997. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13998. enableAttribute( attributePointer );
  13999. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  14000. } else if ( material.defaultAttributeValues ) {
  14001. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  14002. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  14003. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  14004. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  14005. }
  14006. }
  14007. }
  14008. }
  14009. disableUnusedAttributes();
  14010. }
  14011. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  14012. if ( material.visible === false ) return;
  14013. var linewidth, a, attribute;
  14014. var attributeItem, attributeName, attributePointer, attributeSize;
  14015. var program = setProgram( camera, lights, fog, material, object );
  14016. var programAttributes = program.attributes;
  14017. var geometryAttributes = geometry.attributes;
  14018. var updateBuffers = false,
  14019. wireframeBit = material.wireframe ? 1 : 0,
  14020. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  14021. if ( geometryHash !== _currentGeometryGroupHash ) {
  14022. _currentGeometryGroupHash = geometryHash;
  14023. updateBuffers = true;
  14024. }
  14025. if ( updateBuffers ) {
  14026. initAttributes();
  14027. }
  14028. // render mesh
  14029. if ( object instanceof THREE.Mesh ) {
  14030. var index = geometryAttributes[ "index" ];
  14031. if ( index ) {
  14032. // indexed triangles
  14033. var type, size;
  14034. if ( index.array instanceof Uint32Array ) {
  14035. type = _gl.UNSIGNED_INT;
  14036. size = 4;
  14037. } else {
  14038. type = _gl.UNSIGNED_SHORT;
  14039. size = 2;
  14040. }
  14041. var offsets = geometry.offsets;
  14042. if ( offsets.length === 0 ) {
  14043. if ( updateBuffers ) {
  14044. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  14045. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  14046. }
  14047. _gl.drawElements( _gl.TRIANGLES, index.array.length, type, 0 );
  14048. _this.info.render.calls ++;
  14049. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  14050. _this.info.render.faces += index.array.length / 3;
  14051. } else {
  14052. // if there is more than 1 chunk
  14053. // must set attribute pointers to use new offsets for each chunk
  14054. // even if geometry and materials didn't change
  14055. updateBuffers = true;
  14056. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  14057. var startIndex = offsets[ i ].index;
  14058. if ( updateBuffers ) {
  14059. setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex );
  14060. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  14061. }
  14062. // render indexed triangles
  14063. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, type, offsets[ i ].start * size );
  14064. _this.info.render.calls ++;
  14065. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  14066. _this.info.render.faces += offsets[ i ].count / 3;
  14067. }
  14068. }
  14069. } else {
  14070. // non-indexed triangles
  14071. if ( updateBuffers ) {
  14072. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  14073. }
  14074. var position = geometry.attributes[ "position" ];
  14075. // render non-indexed triangles
  14076. _gl.drawArrays( _gl.TRIANGLES, 0, position.array.length / 3 );
  14077. _this.info.render.calls ++;
  14078. _this.info.render.vertices += position.array.length / 3;
  14079. _this.info.render.faces += position.array.length / 9;
  14080. }
  14081. } else if ( object instanceof THREE.ParticleSystem ) {
  14082. // render particles
  14083. if ( updateBuffers ) {
  14084. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  14085. }
  14086. var position = geometryAttributes[ "position" ];
  14087. // render particles
  14088. _gl.drawArrays( _gl.POINTS, 0, position.array.length / 3 );
  14089. _this.info.render.calls ++;
  14090. _this.info.render.points += position.array.length / 3;
  14091. } else if ( object instanceof THREE.Line ) {
  14092. var mode = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  14093. setLineWidth( material.linewidth );
  14094. var index = geometryAttributes[ "index" ];
  14095. if ( index ) {
  14096. // indexed lines
  14097. var type, size;
  14098. if ( index.array instanceof Uint32Array ){
  14099. type = _gl.UNSIGNED_INT;
  14100. size = 4;
  14101. } else {
  14102. type = _gl.UNSIGNED_SHORT;
  14103. size = 2;
  14104. }
  14105. var offsets = geometry.offsets;
  14106. if ( offsets.length === 0 ) {
  14107. if ( updateBuffers ) {
  14108. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  14109. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  14110. }
  14111. _gl.drawElements( _gl.LINES, index.array.length, type, 0 ); // 2 bytes per Uint16Array
  14112. _this.info.render.calls ++;
  14113. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  14114. } else {
  14115. // if there is more than 1 chunk
  14116. // must set attribute pointers to use new offsets for each chunk
  14117. // even if geometry and materials didn't change
  14118. if ( offsets.length > 1 ) updateBuffers = true;
  14119. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  14120. var startIndex = offsets[ i ].index;
  14121. if ( updateBuffers ) {
  14122. setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex );
  14123. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  14124. }
  14125. // render indexed lines
  14126. _gl.drawElements( _gl.LINES, offsets[ i ].count, type, offsets[ i ].start * size ); // 2 bytes per Uint16Array
  14127. _this.info.render.calls ++;
  14128. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  14129. }
  14130. }
  14131. } else {
  14132. // non-indexed lines
  14133. if ( updateBuffers ) {
  14134. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  14135. }
  14136. var position = geometryAttributes[ "position" ];
  14137. _gl.drawArrays( mode, 0, position.array.length / 3 );
  14138. _this.info.render.calls ++;
  14139. _this.info.render.points += position.array.length / 3;
  14140. }
  14141. }
  14142. };
  14143. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  14144. if ( material.visible === false ) return;
  14145. var linewidth, a, attribute, i, il;
  14146. var program = setProgram( camera, lights, fog, material, object );
  14147. var attributes = program.attributes;
  14148. var updateBuffers = false,
  14149. wireframeBit = material.wireframe ? 1 : 0,
  14150. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  14151. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  14152. _currentGeometryGroupHash = geometryGroupHash;
  14153. updateBuffers = true;
  14154. }
  14155. if ( updateBuffers ) {
  14156. initAttributes();
  14157. }
  14158. // vertices
  14159. if ( !material.morphTargets && attributes.position >= 0 ) {
  14160. if ( updateBuffers ) {
  14161. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  14162. enableAttribute( attributes.position );
  14163. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  14164. }
  14165. } else {
  14166. if ( object.morphTargetBase ) {
  14167. setupMorphTargets( material, geometryGroup, object );
  14168. }
  14169. }
  14170. if ( updateBuffers ) {
  14171. // custom attributes
  14172. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  14173. if ( geometryGroup.__webglCustomAttributesList ) {
  14174. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  14175. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  14176. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  14177. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  14178. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  14179. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  14180. }
  14181. }
  14182. }
  14183. // colors
  14184. if ( attributes.color >= 0 ) {
  14185. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  14186. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  14187. enableAttribute( attributes.color );
  14188. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  14189. } else if ( material.defaultAttributeValues ) {
  14190. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  14191. }
  14192. }
  14193. // normals
  14194. if ( attributes.normal >= 0 ) {
  14195. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  14196. enableAttribute( attributes.normal );
  14197. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  14198. }
  14199. // tangents
  14200. if ( attributes.tangent >= 0 ) {
  14201. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  14202. enableAttribute( attributes.tangent );
  14203. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  14204. }
  14205. // uvs
  14206. if ( attributes.uv >= 0 ) {
  14207. if ( object.geometry.faceVertexUvs[0] ) {
  14208. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  14209. enableAttribute( attributes.uv );
  14210. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  14211. } else if ( material.defaultAttributeValues ) {
  14212. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  14213. }
  14214. }
  14215. if ( attributes.uv2 >= 0 ) {
  14216. if ( object.geometry.faceVertexUvs[1] ) {
  14217. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  14218. enableAttribute( attributes.uv2 );
  14219. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  14220. } else if ( material.defaultAttributeValues ) {
  14221. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  14222. }
  14223. }
  14224. if ( material.skinning &&
  14225. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  14226. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  14227. enableAttribute( attributes.skinIndex );
  14228. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  14229. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  14230. enableAttribute( attributes.skinWeight );
  14231. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  14232. }
  14233. // line distances
  14234. if ( attributes.lineDistance >= 0 ) {
  14235. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  14236. enableAttribute( attributes.lineDistance );
  14237. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  14238. }
  14239. }
  14240. disableUnusedAttributes();
  14241. // render mesh
  14242. if ( object instanceof THREE.Mesh ) {
  14243. var type = geometryGroup.__typeArray === Uint32Array ? _gl.UNSIGNED_INT : _gl.UNSIGNED_SHORT;
  14244. // wireframe
  14245. if ( material.wireframe ) {
  14246. setLineWidth( material.wireframeLinewidth );
  14247. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  14248. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, type, 0 );
  14249. // triangles
  14250. } else {
  14251. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  14252. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, type, 0 );
  14253. }
  14254. _this.info.render.calls ++;
  14255. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  14256. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  14257. // render lines
  14258. } else if ( object instanceof THREE.Line ) {
  14259. var mode = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  14260. setLineWidth( material.linewidth );
  14261. _gl.drawArrays( mode, 0, geometryGroup.__webglLineCount );
  14262. _this.info.render.calls ++;
  14263. // render particles
  14264. } else if ( object instanceof THREE.ParticleSystem ) {
  14265. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  14266. _this.info.render.calls ++;
  14267. _this.info.render.points += geometryGroup.__webglParticleCount;
  14268. }
  14269. };
  14270. function initAttributes() {
  14271. for ( var i = 0, l = _newAttributes.length; i < l; i ++ ) {
  14272. _newAttributes[ i ] = 0;
  14273. }
  14274. }
  14275. function enableAttribute( attribute ) {
  14276. _newAttributes[ attribute ] = 1;
  14277. if ( _enabledAttributes[ attribute ] === 0 ) {
  14278. _gl.enableVertexAttribArray( attribute );
  14279. _enabledAttributes[ attribute ] = 1;
  14280. }
  14281. }
  14282. function disableUnusedAttributes() {
  14283. for ( var i = 0, l = _enabledAttributes.length; i < l; i ++ ) {
  14284. if ( _enabledAttributes[ i ] !== _newAttributes[ i ] ) {
  14285. _gl.disableVertexAttribArray( i );
  14286. _enabledAttributes[ i ] = 0;
  14287. }
  14288. }
  14289. }
  14290. function setupMorphTargets ( material, geometryGroup, object ) {
  14291. // set base
  14292. var attributes = material.program.attributes;
  14293. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  14294. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  14295. enableAttribute( attributes.position );
  14296. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  14297. } else if ( attributes.position >= 0 ) {
  14298. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  14299. enableAttribute( attributes.position );
  14300. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  14301. }
  14302. if ( object.morphTargetForcedOrder.length ) {
  14303. // set forced order
  14304. var m = 0;
  14305. var order = object.morphTargetForcedOrder;
  14306. var influences = object.morphTargetInfluences;
  14307. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  14308. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  14309. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  14310. enableAttribute( attributes[ "morphTarget" + m ] );
  14311. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  14312. }
  14313. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  14314. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  14315. enableAttribute( attributes[ "morphNormal" + m ] );
  14316. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  14317. }
  14318. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  14319. m ++;
  14320. }
  14321. } else {
  14322. // find the most influencing
  14323. var influence, activeInfluenceIndices = [];
  14324. var influences = object.morphTargetInfluences;
  14325. var i, il = influences.length;
  14326. for ( i = 0; i < il; i ++ ) {
  14327. influence = influences[ i ];
  14328. if ( influence > 0 ) {
  14329. activeInfluenceIndices.push( [ influence, i ] );
  14330. }
  14331. }
  14332. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  14333. activeInfluenceIndices.sort( numericalSort );
  14334. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  14335. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  14336. activeInfluenceIndices.sort( numericalSort );
  14337. } else if ( activeInfluenceIndices.length === 0 ) {
  14338. activeInfluenceIndices.push( [ 0, 0 ] );
  14339. };
  14340. var influenceIndex, m = 0;
  14341. while ( m < material.numSupportedMorphTargets ) {
  14342. if ( activeInfluenceIndices[ m ] ) {
  14343. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  14344. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  14345. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  14346. enableAttribute( attributes[ "morphTarget" + m ] );
  14347. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  14348. }
  14349. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  14350. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  14351. enableAttribute( attributes[ "morphNormal" + m ] );
  14352. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  14353. }
  14354. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  14355. } else {
  14356. /*
  14357. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  14358. if ( material.morphNormals ) {
  14359. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  14360. }
  14361. */
  14362. object.__webglMorphTargetInfluences[ m ] = 0;
  14363. }
  14364. m ++;
  14365. }
  14366. }
  14367. // load updated influences uniform
  14368. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  14369. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  14370. }
  14371. };
  14372. // Sorting
  14373. function painterSortStable ( a, b ) {
  14374. if ( a.z !== b.z ) {
  14375. return b.z - a.z;
  14376. } else {
  14377. return a.id - b.id;
  14378. }
  14379. };
  14380. function numericalSort ( a, b ) {
  14381. return b[ 0 ] - a[ 0 ];
  14382. };
  14383. // Rendering
  14384. this.render = function ( scene, camera, renderTarget, forceClear ) {
  14385. if ( camera instanceof THREE.Camera === false ) {
  14386. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  14387. return;
  14388. }
  14389. var i, il,
  14390. webglObject, object,
  14391. renderList,
  14392. lights = scene.__lights,
  14393. fog = scene.fog;
  14394. // reset caching for this frame
  14395. _currentMaterialId = -1;
  14396. _lightsNeedUpdate = true;
  14397. // update scene graph
  14398. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  14399. // update camera matrices and frustum
  14400. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  14401. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  14402. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  14403. _frustum.setFromMatrix( _projScreenMatrix );
  14404. // update WebGL objects
  14405. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  14406. // custom render plugins (pre pass)
  14407. renderPlugins( this.renderPluginsPre, scene, camera );
  14408. //
  14409. _this.info.render.calls = 0;
  14410. _this.info.render.vertices = 0;
  14411. _this.info.render.faces = 0;
  14412. _this.info.render.points = 0;
  14413. this.setRenderTarget( renderTarget );
  14414. if ( this.autoClear || forceClear ) {
  14415. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  14416. }
  14417. // set matrices for regular objects (frustum culled)
  14418. renderList = scene.__webglObjects;
  14419. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  14420. webglObject = renderList[ i ];
  14421. object = webglObject.object;
  14422. webglObject.id = i;
  14423. webglObject.render = false;
  14424. if ( object.visible ) {
  14425. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  14426. setupMatrices( object, camera );
  14427. unrollBufferMaterial( webglObject );
  14428. webglObject.render = true;
  14429. if ( this.sortObjects === true ) {
  14430. if ( object.renderDepth !== null ) {
  14431. webglObject.z = object.renderDepth;
  14432. } else {
  14433. _vector3.setFromMatrixPosition( object.matrixWorld );
  14434. _vector3.applyProjection( _projScreenMatrix );
  14435. webglObject.z = _vector3.z;
  14436. }
  14437. }
  14438. }
  14439. }
  14440. }
  14441. if ( this.sortObjects ) {
  14442. renderList.sort( painterSortStable );
  14443. }
  14444. // set matrices for immediate objects
  14445. renderList = scene.__webglObjectsImmediate;
  14446. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  14447. webglObject = renderList[ i ];
  14448. object = webglObject.object;
  14449. if ( object.visible ) {
  14450. setupMatrices( object, camera );
  14451. unrollImmediateBufferMaterial( webglObject );
  14452. }
  14453. }
  14454. if ( scene.overrideMaterial ) {
  14455. var material = scene.overrideMaterial;
  14456. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  14457. this.setDepthTest( material.depthTest );
  14458. this.setDepthWrite( material.depthWrite );
  14459. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14460. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  14461. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  14462. } else {
  14463. var material = null;
  14464. // opaque pass (front-to-back order)
  14465. this.setBlending( THREE.NoBlending );
  14466. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  14467. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  14468. // transparent pass (back-to-front order)
  14469. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  14470. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  14471. }
  14472. // custom render plugins (post pass)
  14473. renderPlugins( this.renderPluginsPost, scene, camera );
  14474. // Generate mipmap if we're using any kind of mipmap filtering
  14475. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  14476. updateRenderTargetMipmap( renderTarget );
  14477. }
  14478. // Ensure depth buffer writing is enabled so it can be cleared on next render
  14479. this.setDepthTest( true );
  14480. this.setDepthWrite( true );
  14481. // _gl.finish();
  14482. };
  14483. function renderPlugins( plugins, scene, camera ) {
  14484. if ( ! plugins.length ) return;
  14485. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  14486. // reset state for plugin (to start from clean slate)
  14487. _currentProgram = null;
  14488. _currentCamera = null;
  14489. _oldBlending = -1;
  14490. _oldDepthTest = -1;
  14491. _oldDepthWrite = -1;
  14492. _oldDoubleSided = -1;
  14493. _oldFlipSided = -1;
  14494. _currentGeometryGroupHash = -1;
  14495. _currentMaterialId = -1;
  14496. _lightsNeedUpdate = true;
  14497. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  14498. // reset state after plugin (anything could have changed)
  14499. _currentProgram = null;
  14500. _currentCamera = null;
  14501. _oldBlending = -1;
  14502. _oldDepthTest = -1;
  14503. _oldDepthWrite = -1;
  14504. _oldDoubleSided = -1;
  14505. _oldFlipSided = -1;
  14506. _currentGeometryGroupHash = -1;
  14507. _currentMaterialId = -1;
  14508. _lightsNeedUpdate = true;
  14509. }
  14510. };
  14511. function renderObjects( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  14512. var webglObject, object, buffer, material, start, end, delta;
  14513. if ( reverse ) {
  14514. start = renderList.length - 1;
  14515. end = -1;
  14516. delta = -1;
  14517. } else {
  14518. start = 0;
  14519. end = renderList.length;
  14520. delta = 1;
  14521. }
  14522. for ( var i = start; i !== end; i += delta ) {
  14523. webglObject = renderList[ i ];
  14524. if ( webglObject.render ) {
  14525. object = webglObject.object;
  14526. buffer = webglObject.buffer;
  14527. if ( overrideMaterial ) {
  14528. material = overrideMaterial;
  14529. } else {
  14530. material = webglObject[ materialType ];
  14531. if ( ! material ) continue;
  14532. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  14533. _this.setDepthTest( material.depthTest );
  14534. _this.setDepthWrite( material.depthWrite );
  14535. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14536. }
  14537. _this.setMaterialFaces( material );
  14538. if ( buffer instanceof THREE.BufferGeometry ) {
  14539. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  14540. } else {
  14541. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  14542. }
  14543. }
  14544. }
  14545. };
  14546. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  14547. var webglObject, object, material, program;
  14548. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  14549. webglObject = renderList[ i ];
  14550. object = webglObject.object;
  14551. if ( object.visible ) {
  14552. if ( overrideMaterial ) {
  14553. material = overrideMaterial;
  14554. } else {
  14555. material = webglObject[ materialType ];
  14556. if ( ! material ) continue;
  14557. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  14558. _this.setDepthTest( material.depthTest );
  14559. _this.setDepthWrite( material.depthWrite );
  14560. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14561. }
  14562. _this.renderImmediateObject( camera, lights, fog, material, object );
  14563. }
  14564. }
  14565. };
  14566. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  14567. var program = setProgram( camera, lights, fog, material, object );
  14568. _currentGeometryGroupHash = -1;
  14569. _this.setMaterialFaces( material );
  14570. if ( object.immediateRenderCallback ) {
  14571. object.immediateRenderCallback( program, _gl, _frustum );
  14572. } else {
  14573. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  14574. }
  14575. };
  14576. function unrollImmediateBufferMaterial ( globject ) {
  14577. var object = globject.object,
  14578. material = object.material;
  14579. if ( material.transparent ) {
  14580. globject.transparent = material;
  14581. globject.opaque = null;
  14582. } else {
  14583. globject.opaque = material;
  14584. globject.transparent = null;
  14585. }
  14586. };
  14587. function unrollBufferMaterial ( globject ) {
  14588. var object = globject.object;
  14589. var buffer = globject.buffer;
  14590. var geometry = object.geometry;
  14591. var material = object.material;
  14592. if ( material instanceof THREE.MeshFaceMaterial ) {
  14593. var materialIndex = geometry instanceof THREE.BufferGeometry ? 0 : buffer.materialIndex;
  14594. material = material.materials[ materialIndex ];
  14595. if ( material.transparent ) {
  14596. globject.transparent = material;
  14597. globject.opaque = null;
  14598. } else {
  14599. globject.opaque = material;
  14600. globject.transparent = null;
  14601. }
  14602. } else {
  14603. if ( material ) {
  14604. if ( material.transparent ) {
  14605. globject.transparent = material;
  14606. globject.opaque = null;
  14607. } else {
  14608. globject.opaque = material;
  14609. globject.transparent = null;
  14610. }
  14611. }
  14612. }
  14613. };
  14614. // Objects refresh
  14615. this.initWebGLObjects = function ( scene ) {
  14616. if ( !scene.__webglObjects ) {
  14617. scene.__webglObjects = [];
  14618. scene.__webglObjectsImmediate = [];
  14619. scene.__webglSprites = [];
  14620. scene.__webglFlares = [];
  14621. }
  14622. while ( scene.__objectsAdded.length ) {
  14623. addObject( scene.__objectsAdded[ 0 ], scene );
  14624. scene.__objectsAdded.splice( 0, 1 );
  14625. }
  14626. while ( scene.__objectsRemoved.length ) {
  14627. removeObject( scene.__objectsRemoved[ 0 ], scene );
  14628. scene.__objectsRemoved.splice( 0, 1 );
  14629. }
  14630. // update must be called after objects adding / removal
  14631. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  14632. var object = scene.__webglObjects[ o ].object;
  14633. // TODO: Remove this hack (WebGLRenderer refactoring)
  14634. if ( object.__webglInit === undefined ) {
  14635. if ( object.__webglActive !== undefined ) {
  14636. removeObject( object, scene );
  14637. }
  14638. addObject( object, scene );
  14639. }
  14640. updateObject( object );
  14641. }
  14642. };
  14643. // Objects adding
  14644. function addObject( object, scene ) {
  14645. var g, geometry, material, geometryGroup;
  14646. if ( object.__webglInit === undefined ) {
  14647. object.__webglInit = true;
  14648. object._modelViewMatrix = new THREE.Matrix4();
  14649. object._normalMatrix = new THREE.Matrix3();
  14650. geometry = object.geometry;
  14651. if ( geometry === undefined ) {
  14652. // ImmediateRenderObject
  14653. } else if ( geometry.__webglInit === undefined ) {
  14654. geometry.__webglInit = true;
  14655. geometry.addEventListener( 'dispose', onGeometryDispose );
  14656. if ( geometry instanceof THREE.BufferGeometry ) {
  14657. initDirectBuffers( geometry );
  14658. } else if ( object instanceof THREE.Mesh ) {
  14659. material = object.material;
  14660. if ( geometry.geometryGroups === undefined ) {
  14661. geometry.makeGroups( material instanceof THREE.MeshFaceMaterial, _glExtensionElementIndexUint ? 4294967296 : 65535 );
  14662. }
  14663. // create separate VBOs per geometry chunk
  14664. for ( g in geometry.geometryGroups ) {
  14665. geometryGroup = geometry.geometryGroups[ g ];
  14666. // initialise VBO on the first access
  14667. if ( ! geometryGroup.__webglVertexBuffer ) {
  14668. createMeshBuffers( geometryGroup );
  14669. initMeshBuffers( geometryGroup, object );
  14670. geometry.verticesNeedUpdate = true;
  14671. geometry.morphTargetsNeedUpdate = true;
  14672. geometry.elementsNeedUpdate = true;
  14673. geometry.uvsNeedUpdate = true;
  14674. geometry.normalsNeedUpdate = true;
  14675. geometry.tangentsNeedUpdate = true;
  14676. geometry.colorsNeedUpdate = true;
  14677. }
  14678. }
  14679. } else if ( object instanceof THREE.Line ) {
  14680. if ( ! geometry.__webglVertexBuffer ) {
  14681. createLineBuffers( geometry );
  14682. initLineBuffers( geometry, object );
  14683. geometry.verticesNeedUpdate = true;
  14684. geometry.colorsNeedUpdate = true;
  14685. geometry.lineDistancesNeedUpdate = true;
  14686. }
  14687. } else if ( object instanceof THREE.ParticleSystem ) {
  14688. if ( ! geometry.__webglVertexBuffer ) {
  14689. createParticleBuffers( geometry );
  14690. initParticleBuffers( geometry, object );
  14691. geometry.verticesNeedUpdate = true;
  14692. geometry.colorsNeedUpdate = true;
  14693. }
  14694. }
  14695. }
  14696. }
  14697. if ( object.__webglActive === undefined ) {
  14698. if ( object instanceof THREE.Mesh ) {
  14699. geometry = object.geometry;
  14700. if ( geometry instanceof THREE.BufferGeometry ) {
  14701. addBuffer( scene.__webglObjects, geometry, object );
  14702. } else if ( geometry instanceof THREE.Geometry ) {
  14703. for ( g in geometry.geometryGroups ) {
  14704. geometryGroup = geometry.geometryGroups[ g ];
  14705. addBuffer( scene.__webglObjects, geometryGroup, object );
  14706. }
  14707. }
  14708. } else if ( object instanceof THREE.Line ||
  14709. object instanceof THREE.ParticleSystem ) {
  14710. geometry = object.geometry;
  14711. addBuffer( scene.__webglObjects, geometry, object );
  14712. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14713. addBufferImmediate( scene.__webglObjectsImmediate, object );
  14714. } else if ( object instanceof THREE.Sprite ) {
  14715. scene.__webglSprites.push( object );
  14716. } else if ( object instanceof THREE.LensFlare ) {
  14717. scene.__webglFlares.push( object );
  14718. }
  14719. object.__webglActive = true;
  14720. }
  14721. };
  14722. function addBuffer( objlist, buffer, object ) {
  14723. objlist.push(
  14724. {
  14725. id: null,
  14726. buffer: buffer,
  14727. object: object,
  14728. opaque: null,
  14729. transparent: null,
  14730. z: 0
  14731. }
  14732. );
  14733. };
  14734. function addBufferImmediate( objlist, object ) {
  14735. objlist.push(
  14736. {
  14737. id: null,
  14738. object: object,
  14739. opaque: null,
  14740. transparent: null,
  14741. z: 0
  14742. }
  14743. );
  14744. };
  14745. // Objects updates
  14746. function updateObject( object ) {
  14747. var geometry = object.geometry,
  14748. geometryGroup, customAttributesDirty, material;
  14749. if ( geometry instanceof THREE.BufferGeometry ) {
  14750. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW );
  14751. } else if ( object instanceof THREE.Mesh ) {
  14752. // check all geometry groups
  14753. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  14754. geometryGroup = geometry.geometryGroupsList[ i ];
  14755. material = getBufferMaterial( object, geometryGroup );
  14756. if ( geometry.buffersNeedUpdate ) {
  14757. initMeshBuffers( geometryGroup, object );
  14758. }
  14759. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14760. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  14761. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  14762. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  14763. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  14764. }
  14765. }
  14766. geometry.verticesNeedUpdate = false;
  14767. geometry.morphTargetsNeedUpdate = false;
  14768. geometry.elementsNeedUpdate = false;
  14769. geometry.uvsNeedUpdate = false;
  14770. geometry.normalsNeedUpdate = false;
  14771. geometry.colorsNeedUpdate = false;
  14772. geometry.tangentsNeedUpdate = false;
  14773. geometry.buffersNeedUpdate = false;
  14774. material.attributes && clearCustomAttributes( material );
  14775. } else if ( object instanceof THREE.Line ) {
  14776. material = getBufferMaterial( object, geometry );
  14777. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14778. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  14779. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  14780. }
  14781. geometry.verticesNeedUpdate = false;
  14782. geometry.colorsNeedUpdate = false;
  14783. geometry.lineDistancesNeedUpdate = false;
  14784. material.attributes && clearCustomAttributes( material );
  14785. } else if ( object instanceof THREE.ParticleSystem ) {
  14786. material = getBufferMaterial( object, geometry );
  14787. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14788. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  14789. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  14790. }
  14791. geometry.verticesNeedUpdate = false;
  14792. geometry.colorsNeedUpdate = false;
  14793. material.attributes && clearCustomAttributes( material );
  14794. }
  14795. };
  14796. // Objects updates - custom attributes check
  14797. function areCustomAttributesDirty( material ) {
  14798. for ( var a in material.attributes ) {
  14799. if ( material.attributes[ a ].needsUpdate ) return true;
  14800. }
  14801. return false;
  14802. };
  14803. function clearCustomAttributes( material ) {
  14804. for ( var a in material.attributes ) {
  14805. material.attributes[ a ].needsUpdate = false;
  14806. }
  14807. };
  14808. // Objects removal
  14809. function removeObject( object, scene ) {
  14810. if ( object instanceof THREE.Mesh ||
  14811. object instanceof THREE.ParticleSystem ||
  14812. object instanceof THREE.Line ) {
  14813. removeInstances( scene.__webglObjects, object );
  14814. } else if ( object instanceof THREE.Sprite ) {
  14815. removeInstancesDirect( scene.__webglSprites, object );
  14816. } else if ( object instanceof THREE.LensFlare ) {
  14817. removeInstancesDirect( scene.__webglFlares, object );
  14818. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14819. removeInstances( scene.__webglObjectsImmediate, object );
  14820. }
  14821. delete object.__webglActive;
  14822. };
  14823. function removeInstances( objlist, object ) {
  14824. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14825. if ( objlist[ o ].object === object ) {
  14826. objlist.splice( o, 1 );
  14827. }
  14828. }
  14829. };
  14830. function removeInstancesDirect( objlist, object ) {
  14831. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14832. if ( objlist[ o ] === object ) {
  14833. objlist.splice( o, 1 );
  14834. }
  14835. }
  14836. };
  14837. // Materials
  14838. this.initMaterial = function ( material, lights, fog, object ) {
  14839. material.addEventListener( 'dispose', onMaterialDispose );
  14840. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  14841. if ( material instanceof THREE.MeshDepthMaterial ) {
  14842. shaderID = 'depth';
  14843. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14844. shaderID = 'normal';
  14845. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  14846. shaderID = 'basic';
  14847. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14848. shaderID = 'lambert';
  14849. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14850. shaderID = 'phong';
  14851. } else if ( material instanceof THREE.LineBasicMaterial ) {
  14852. shaderID = 'basic';
  14853. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14854. shaderID = 'dashed';
  14855. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  14856. shaderID = 'particle_basic';
  14857. }
  14858. if ( shaderID ) {
  14859. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  14860. }
  14861. // heuristics to create shader parameters according to lights in the scene
  14862. // (not to blow over maxLights budget)
  14863. maxLightCount = allocateLights( lights );
  14864. maxShadows = allocateShadows( lights );
  14865. maxBones = allocateBones( object );
  14866. parameters = {
  14867. precision: _precision,
  14868. supportsVertexTextures: _supportsVertexTextures,
  14869. map: !!material.map,
  14870. envMap: !!material.envMap,
  14871. lightMap: !!material.lightMap,
  14872. bumpMap: !!material.bumpMap,
  14873. normalMap: !!material.normalMap,
  14874. specularMap: !!material.specularMap,
  14875. vertexColors: material.vertexColors,
  14876. fog: fog,
  14877. useFog: material.fog,
  14878. fogExp: fog instanceof THREE.FogExp2,
  14879. sizeAttenuation: material.sizeAttenuation,
  14880. logarithmicDepthBuffer: _logarithmicDepthBuffer,
  14881. skinning: material.skinning,
  14882. maxBones: maxBones,
  14883. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  14884. morphTargets: material.morphTargets,
  14885. morphNormals: material.morphNormals,
  14886. maxMorphTargets: this.maxMorphTargets,
  14887. maxMorphNormals: this.maxMorphNormals,
  14888. maxDirLights: maxLightCount.directional,
  14889. maxPointLights: maxLightCount.point,
  14890. maxSpotLights: maxLightCount.spot,
  14891. maxHemiLights: maxLightCount.hemi,
  14892. maxShadows: maxShadows,
  14893. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow && maxShadows > 0,
  14894. shadowMapType: this.shadowMapType,
  14895. shadowMapDebug: this.shadowMapDebug,
  14896. shadowMapCascade: this.shadowMapCascade,
  14897. alphaTest: material.alphaTest,
  14898. metal: material.metal,
  14899. wrapAround: material.wrapAround,
  14900. doubleSided: material.side === THREE.DoubleSide,
  14901. flipSided: material.side === THREE.BackSide
  14902. };
  14903. // Generate code
  14904. var chunks = [];
  14905. if ( shaderID ) {
  14906. chunks.push( shaderID );
  14907. } else {
  14908. chunks.push( material.fragmentShader );
  14909. chunks.push( material.vertexShader );
  14910. }
  14911. for ( var d in material.defines ) {
  14912. chunks.push( d );
  14913. chunks.push( material.defines[ d ] );
  14914. }
  14915. for ( var p in parameters ) {
  14916. chunks.push( p );
  14917. chunks.push( parameters[ p ] );
  14918. }
  14919. var code = chunks.join();
  14920. var program;
  14921. // Check if code has been already compiled
  14922. for ( var p = 0, pl = _programs.length; p < pl; p ++ ) {
  14923. var programInfo = _programs[ p ];
  14924. if ( programInfo.code === code ) {
  14925. program = programInfo;
  14926. program.usedTimes ++;
  14927. break;
  14928. }
  14929. }
  14930. if ( program === undefined ) {
  14931. program = new THREE.WebGLProgram( this, code, material, parameters );
  14932. _programs.push( program );
  14933. _this.info.memory.programs = _programs.length;
  14934. }
  14935. material.program = program;
  14936. var attributes = material.program.attributes;
  14937. if ( material.morphTargets ) {
  14938. material.numSupportedMorphTargets = 0;
  14939. var id, base = "morphTarget";
  14940. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  14941. id = base + i;
  14942. if ( attributes[ id ] >= 0 ) {
  14943. material.numSupportedMorphTargets ++;
  14944. }
  14945. }
  14946. }
  14947. if ( material.morphNormals ) {
  14948. material.numSupportedMorphNormals = 0;
  14949. var id, base = "morphNormal";
  14950. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  14951. id = base + i;
  14952. if ( attributes[ id ] >= 0 ) {
  14953. material.numSupportedMorphNormals ++;
  14954. }
  14955. }
  14956. }
  14957. material.uniformsList = [];
  14958. for ( u in material.uniforms ) {
  14959. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  14960. }
  14961. };
  14962. function setMaterialShaders( material, shaders ) {
  14963. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  14964. material.vertexShader = shaders.vertexShader;
  14965. material.fragmentShader = shaders.fragmentShader;
  14966. };
  14967. function setProgram( camera, lights, fog, material, object ) {
  14968. _usedTextureUnits = 0;
  14969. if ( material.needsUpdate ) {
  14970. if ( material.program ) deallocateMaterial( material );
  14971. _this.initMaterial( material, lights, fog, object );
  14972. material.needsUpdate = false;
  14973. }
  14974. if ( material.morphTargets ) {
  14975. if ( ! object.__webglMorphTargetInfluences ) {
  14976. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  14977. }
  14978. }
  14979. var refreshMaterial = false;
  14980. var program = material.program,
  14981. p_uniforms = program.uniforms,
  14982. m_uniforms = material.uniforms;
  14983. if ( program.id !== _currentProgram ) {
  14984. _gl.useProgram( program.program );
  14985. _currentProgram = program.id;
  14986. refreshMaterial = true;
  14987. }
  14988. if ( material.id !== _currentMaterialId ) {
  14989. _currentMaterialId = material.id;
  14990. refreshMaterial = true;
  14991. }
  14992. if ( refreshMaterial || camera !== _currentCamera ) {
  14993. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  14994. if ( _logarithmicDepthBuffer ) {
  14995. _gl.uniform1f(p_uniforms.logDepthBufFC, 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  14996. }
  14997. if ( camera !== _currentCamera ) _currentCamera = camera;
  14998. }
  14999. // skinning uniforms must be set even if material didn't change
  15000. // auto-setting of texture unit for bone texture must go before other textures
  15001. // not sure why, but otherwise weird things happen
  15002. if ( material.skinning ) {
  15003. if ( _supportsBoneTextures && object.useVertexTexture ) {
  15004. if ( p_uniforms.boneTexture !== null ) {
  15005. var textureUnit = getTextureUnit();
  15006. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  15007. _this.setTexture( object.boneTexture, textureUnit );
  15008. }
  15009. if ( p_uniforms.boneTextureWidth !== null ) {
  15010. _gl.uniform1i( p_uniforms.boneTextureWidth, object.boneTextureWidth );
  15011. }
  15012. if ( p_uniforms.boneTextureHeight !== null ) {
  15013. _gl.uniform1i( p_uniforms.boneTextureHeight, object.boneTextureHeight );
  15014. }
  15015. } else {
  15016. if ( p_uniforms.boneGlobalMatrices !== null ) {
  15017. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  15018. }
  15019. }
  15020. }
  15021. if ( refreshMaterial ) {
  15022. // refresh uniforms common to several materials
  15023. if ( fog && material.fog ) {
  15024. refreshUniformsFog( m_uniforms, fog );
  15025. }
  15026. if ( material instanceof THREE.MeshPhongMaterial ||
  15027. material instanceof THREE.MeshLambertMaterial ||
  15028. material.lights ) {
  15029. if ( _lightsNeedUpdate ) {
  15030. setupLights( program, lights );
  15031. _lightsNeedUpdate = false;
  15032. }
  15033. refreshUniformsLights( m_uniforms, _lights );
  15034. }
  15035. if ( material instanceof THREE.MeshBasicMaterial ||
  15036. material instanceof THREE.MeshLambertMaterial ||
  15037. material instanceof THREE.MeshPhongMaterial ) {
  15038. refreshUniformsCommon( m_uniforms, material );
  15039. }
  15040. // refresh single material specific uniforms
  15041. if ( material instanceof THREE.LineBasicMaterial ) {
  15042. refreshUniformsLine( m_uniforms, material );
  15043. } else if ( material instanceof THREE.LineDashedMaterial ) {
  15044. refreshUniformsLine( m_uniforms, material );
  15045. refreshUniformsDash( m_uniforms, material );
  15046. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  15047. refreshUniformsParticle( m_uniforms, material );
  15048. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  15049. refreshUniformsPhong( m_uniforms, material );
  15050. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  15051. refreshUniformsLambert( m_uniforms, material );
  15052. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  15053. m_uniforms.mNear.value = camera.near;
  15054. m_uniforms.mFar.value = camera.far;
  15055. m_uniforms.opacity.value = material.opacity;
  15056. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  15057. m_uniforms.opacity.value = material.opacity;
  15058. }
  15059. if ( object.receiveShadow && ! material._shadowPass ) {
  15060. refreshUniformsShadow( m_uniforms, lights );
  15061. }
  15062. // load common uniforms
  15063. loadUniformsGeneric( program, material.uniformsList );
  15064. // load material specific uniforms
  15065. // (shader material also gets them for the sake of genericity)
  15066. if ( material instanceof THREE.ShaderMaterial ||
  15067. material instanceof THREE.MeshPhongMaterial ||
  15068. material.envMap ) {
  15069. if ( p_uniforms.cameraPosition !== null ) {
  15070. _vector3.setFromMatrixPosition( camera.matrixWorld );
  15071. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  15072. }
  15073. }
  15074. if ( material instanceof THREE.MeshPhongMaterial ||
  15075. material instanceof THREE.MeshLambertMaterial ||
  15076. material instanceof THREE.ShaderMaterial ||
  15077. material.skinning ) {
  15078. if ( p_uniforms.viewMatrix !== null ) {
  15079. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  15080. }
  15081. }
  15082. }
  15083. loadUniformsMatrices( p_uniforms, object );
  15084. if ( p_uniforms.modelMatrix !== null ) {
  15085. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  15086. }
  15087. return program;
  15088. };
  15089. // Uniforms (refresh uniforms objects)
  15090. function refreshUniformsCommon ( uniforms, material ) {
  15091. uniforms.opacity.value = material.opacity;
  15092. if ( _this.gammaInput ) {
  15093. uniforms.diffuse.value.copyGammaToLinear( material.color );
  15094. } else {
  15095. uniforms.diffuse.value = material.color;
  15096. }
  15097. uniforms.map.value = material.map;
  15098. uniforms.lightMap.value = material.lightMap;
  15099. uniforms.specularMap.value = material.specularMap;
  15100. if ( material.bumpMap ) {
  15101. uniforms.bumpMap.value = material.bumpMap;
  15102. uniforms.bumpScale.value = material.bumpScale;
  15103. }
  15104. if ( material.normalMap ) {
  15105. uniforms.normalMap.value = material.normalMap;
  15106. uniforms.normalScale.value.copy( material.normalScale );
  15107. }
  15108. // uv repeat and offset setting priorities
  15109. // 1. color map
  15110. // 2. specular map
  15111. // 3. normal map
  15112. // 4. bump map
  15113. var uvScaleMap;
  15114. if ( material.map ) {
  15115. uvScaleMap = material.map;
  15116. } else if ( material.specularMap ) {
  15117. uvScaleMap = material.specularMap;
  15118. } else if ( material.normalMap ) {
  15119. uvScaleMap = material.normalMap;
  15120. } else if ( material.bumpMap ) {
  15121. uvScaleMap = material.bumpMap;
  15122. }
  15123. if ( uvScaleMap !== undefined ) {
  15124. var offset = uvScaleMap.offset;
  15125. var repeat = uvScaleMap.repeat;
  15126. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  15127. }
  15128. uniforms.envMap.value = material.envMap;
  15129. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  15130. if ( _this.gammaInput ) {
  15131. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  15132. uniforms.reflectivity.value = material.reflectivity;
  15133. } else {
  15134. uniforms.reflectivity.value = material.reflectivity;
  15135. }
  15136. uniforms.refractionRatio.value = material.refractionRatio;
  15137. uniforms.combine.value = material.combine;
  15138. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  15139. };
  15140. function refreshUniformsLine ( uniforms, material ) {
  15141. uniforms.diffuse.value = material.color;
  15142. uniforms.opacity.value = material.opacity;
  15143. };
  15144. function refreshUniformsDash ( uniforms, material ) {
  15145. uniforms.dashSize.value = material.dashSize;
  15146. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15147. uniforms.scale.value = material.scale;
  15148. };
  15149. function refreshUniformsParticle ( uniforms, material ) {
  15150. uniforms.psColor.value = material.color;
  15151. uniforms.opacity.value = material.opacity;
  15152. uniforms.size.value = material.size;
  15153. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  15154. uniforms.map.value = material.map;
  15155. };
  15156. function refreshUniformsFog ( uniforms, fog ) {
  15157. uniforms.fogColor.value = fog.color;
  15158. if ( fog instanceof THREE.Fog ) {
  15159. uniforms.fogNear.value = fog.near;
  15160. uniforms.fogFar.value = fog.far;
  15161. } else if ( fog instanceof THREE.FogExp2 ) {
  15162. uniforms.fogDensity.value = fog.density;
  15163. }
  15164. };
  15165. function refreshUniformsPhong ( uniforms, material ) {
  15166. uniforms.shininess.value = material.shininess;
  15167. if ( _this.gammaInput ) {
  15168. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  15169. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  15170. uniforms.specular.value.copyGammaToLinear( material.specular );
  15171. } else {
  15172. uniforms.ambient.value = material.ambient;
  15173. uniforms.emissive.value = material.emissive;
  15174. uniforms.specular.value = material.specular;
  15175. }
  15176. if ( material.wrapAround ) {
  15177. uniforms.wrapRGB.value.copy( material.wrapRGB );
  15178. }
  15179. };
  15180. function refreshUniformsLambert ( uniforms, material ) {
  15181. if ( _this.gammaInput ) {
  15182. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  15183. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  15184. } else {
  15185. uniforms.ambient.value = material.ambient;
  15186. uniforms.emissive.value = material.emissive;
  15187. }
  15188. if ( material.wrapAround ) {
  15189. uniforms.wrapRGB.value.copy( material.wrapRGB );
  15190. }
  15191. };
  15192. function refreshUniformsLights ( uniforms, lights ) {
  15193. uniforms.ambientLightColor.value = lights.ambient;
  15194. uniforms.directionalLightColor.value = lights.directional.colors;
  15195. uniforms.directionalLightDirection.value = lights.directional.positions;
  15196. uniforms.pointLightColor.value = lights.point.colors;
  15197. uniforms.pointLightPosition.value = lights.point.positions;
  15198. uniforms.pointLightDistance.value = lights.point.distances;
  15199. uniforms.spotLightColor.value = lights.spot.colors;
  15200. uniforms.spotLightPosition.value = lights.spot.positions;
  15201. uniforms.spotLightDistance.value = lights.spot.distances;
  15202. uniforms.spotLightDirection.value = lights.spot.directions;
  15203. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  15204. uniforms.spotLightExponent.value = lights.spot.exponents;
  15205. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  15206. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  15207. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  15208. };
  15209. function refreshUniformsShadow ( uniforms, lights ) {
  15210. if ( uniforms.shadowMatrix ) {
  15211. var j = 0;
  15212. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  15213. var light = lights[ i ];
  15214. if ( ! light.castShadow ) continue;
  15215. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  15216. uniforms.shadowMap.value[ j ] = light.shadowMap;
  15217. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  15218. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  15219. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  15220. uniforms.shadowBias.value[ j ] = light.shadowBias;
  15221. j ++;
  15222. }
  15223. }
  15224. }
  15225. };
  15226. // Uniforms (load to GPU)
  15227. function loadUniformsMatrices ( uniforms, object ) {
  15228. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  15229. if ( uniforms.normalMatrix ) {
  15230. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  15231. }
  15232. };
  15233. function getTextureUnit() {
  15234. var textureUnit = _usedTextureUnits;
  15235. if ( textureUnit >= _maxTextures ) {
  15236. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  15237. }
  15238. _usedTextureUnits += 1;
  15239. return textureUnit;
  15240. };
  15241. function loadUniformsGeneric ( program, uniforms ) {
  15242. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  15243. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  15244. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  15245. if ( !location ) continue;
  15246. uniform = uniforms[ j ][ 0 ];
  15247. type = uniform.type;
  15248. value = uniform.value;
  15249. if ( type === "i" ) { // single integer
  15250. _gl.uniform1i( location, value );
  15251. } else if ( type === "f" ) { // single float
  15252. _gl.uniform1f( location, value );
  15253. } else if ( type === "v2" ) { // single THREE.Vector2
  15254. _gl.uniform2f( location, value.x, value.y );
  15255. } else if ( type === "v3" ) { // single THREE.Vector3
  15256. _gl.uniform3f( location, value.x, value.y, value.z );
  15257. } else if ( type === "v4" ) { // single THREE.Vector4
  15258. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  15259. } else if ( type === "c" ) { // single THREE.Color
  15260. _gl.uniform3f( location, value.r, value.g, value.b );
  15261. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  15262. _gl.uniform1iv( location, value );
  15263. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  15264. _gl.uniform3iv( location, value );
  15265. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  15266. _gl.uniform1fv( location, value );
  15267. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  15268. _gl.uniform3fv( location, value );
  15269. } else if ( type === "v2v" ) { // array of THREE.Vector2
  15270. if ( uniform._array === undefined ) {
  15271. uniform._array = new Float32Array( 2 * value.length );
  15272. }
  15273. for ( i = 0, il = value.length; i < il; i ++ ) {
  15274. offset = i * 2;
  15275. uniform._array[ offset ] = value[ i ].x;
  15276. uniform._array[ offset + 1 ] = value[ i ].y;
  15277. }
  15278. _gl.uniform2fv( location, uniform._array );
  15279. } else if ( type === "v3v" ) { // array of THREE.Vector3
  15280. if ( uniform._array === undefined ) {
  15281. uniform._array = new Float32Array( 3 * value.length );
  15282. }
  15283. for ( i = 0, il = value.length; i < il; i ++ ) {
  15284. offset = i * 3;
  15285. uniform._array[ offset ] = value[ i ].x;
  15286. uniform._array[ offset + 1 ] = value[ i ].y;
  15287. uniform._array[ offset + 2 ] = value[ i ].z;
  15288. }
  15289. _gl.uniform3fv( location, uniform._array );
  15290. } else if ( type === "v4v" ) { // array of THREE.Vector4
  15291. if ( uniform._array === undefined ) {
  15292. uniform._array = new Float32Array( 4 * value.length );
  15293. }
  15294. for ( i = 0, il = value.length; i < il; i ++ ) {
  15295. offset = i * 4;
  15296. uniform._array[ offset ] = value[ i ].x;
  15297. uniform._array[ offset + 1 ] = value[ i ].y;
  15298. uniform._array[ offset + 2 ] = value[ i ].z;
  15299. uniform._array[ offset + 3 ] = value[ i ].w;
  15300. }
  15301. _gl.uniform4fv( location, uniform._array );
  15302. } else if ( type === "m4") { // single THREE.Matrix4
  15303. if ( uniform._array === undefined ) {
  15304. uniform._array = new Float32Array( 16 );
  15305. }
  15306. value.flattenToArray( uniform._array );
  15307. _gl.uniformMatrix4fv( location, false, uniform._array );
  15308. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  15309. if ( uniform._array === undefined ) {
  15310. uniform._array = new Float32Array( 16 * value.length );
  15311. }
  15312. for ( i = 0, il = value.length; i < il; i ++ ) {
  15313. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  15314. }
  15315. _gl.uniformMatrix4fv( location, false, uniform._array );
  15316. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  15317. texture = value;
  15318. textureUnit = getTextureUnit();
  15319. _gl.uniform1i( location, textureUnit );
  15320. if ( !texture ) continue;
  15321. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  15322. setCubeTexture( texture, textureUnit );
  15323. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  15324. setCubeTextureDynamic( texture, textureUnit );
  15325. } else {
  15326. _this.setTexture( texture, textureUnit );
  15327. }
  15328. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  15329. if ( uniform._array === undefined ) {
  15330. uniform._array = [];
  15331. }
  15332. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  15333. uniform._array[ i ] = getTextureUnit();
  15334. }
  15335. _gl.uniform1iv( location, uniform._array );
  15336. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  15337. texture = uniform.value[ i ];
  15338. textureUnit = uniform._array[ i ];
  15339. if ( !texture ) continue;
  15340. _this.setTexture( texture, textureUnit );
  15341. }
  15342. } else {
  15343. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  15344. }
  15345. }
  15346. };
  15347. function setupMatrices ( object, camera ) {
  15348. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  15349. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  15350. };
  15351. //
  15352. function setColorGamma( array, offset, color, intensitySq ) {
  15353. array[ offset ] = color.r * color.r * intensitySq;
  15354. array[ offset + 1 ] = color.g * color.g * intensitySq;
  15355. array[ offset + 2 ] = color.b * color.b * intensitySq;
  15356. };
  15357. function setColorLinear( array, offset, color, intensity ) {
  15358. array[ offset ] = color.r * intensity;
  15359. array[ offset + 1 ] = color.g * intensity;
  15360. array[ offset + 2 ] = color.b * intensity;
  15361. };
  15362. function setupLights ( program, lights ) {
  15363. var l, ll, light, n,
  15364. r = 0, g = 0, b = 0,
  15365. color, skyColor, groundColor,
  15366. intensity, intensitySq,
  15367. position,
  15368. distance,
  15369. zlights = _lights,
  15370. dirColors = zlights.directional.colors,
  15371. dirPositions = zlights.directional.positions,
  15372. pointColors = zlights.point.colors,
  15373. pointPositions = zlights.point.positions,
  15374. pointDistances = zlights.point.distances,
  15375. spotColors = zlights.spot.colors,
  15376. spotPositions = zlights.spot.positions,
  15377. spotDistances = zlights.spot.distances,
  15378. spotDirections = zlights.spot.directions,
  15379. spotAnglesCos = zlights.spot.anglesCos,
  15380. spotExponents = zlights.spot.exponents,
  15381. hemiSkyColors = zlights.hemi.skyColors,
  15382. hemiGroundColors = zlights.hemi.groundColors,
  15383. hemiPositions = zlights.hemi.positions,
  15384. dirLength = 0,
  15385. pointLength = 0,
  15386. spotLength = 0,
  15387. hemiLength = 0,
  15388. dirCount = 0,
  15389. pointCount = 0,
  15390. spotCount = 0,
  15391. hemiCount = 0,
  15392. dirOffset = 0,
  15393. pointOffset = 0,
  15394. spotOffset = 0,
  15395. hemiOffset = 0;
  15396. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  15397. light = lights[ l ];
  15398. if ( light.onlyShadow ) continue;
  15399. color = light.color;
  15400. intensity = light.intensity;
  15401. distance = light.distance;
  15402. if ( light instanceof THREE.AmbientLight ) {
  15403. if ( ! light.visible ) continue;
  15404. if ( _this.gammaInput ) {
  15405. r += color.r * color.r;
  15406. g += color.g * color.g;
  15407. b += color.b * color.b;
  15408. } else {
  15409. r += color.r;
  15410. g += color.g;
  15411. b += color.b;
  15412. }
  15413. } else if ( light instanceof THREE.DirectionalLight ) {
  15414. dirCount += 1;
  15415. if ( ! light.visible ) continue;
  15416. _direction.setFromMatrixPosition( light.matrixWorld );
  15417. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  15418. _direction.sub( _vector3 );
  15419. _direction.normalize();
  15420. // skip lights with undefined direction
  15421. // these create troubles in OpenGL (making pixel black)
  15422. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  15423. dirOffset = dirLength * 3;
  15424. dirPositions[ dirOffset ] = _direction.x;
  15425. dirPositions[ dirOffset + 1 ] = _direction.y;
  15426. dirPositions[ dirOffset + 2 ] = _direction.z;
  15427. if ( _this.gammaInput ) {
  15428. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  15429. } else {
  15430. setColorLinear( dirColors, dirOffset, color, intensity );
  15431. }
  15432. dirLength += 1;
  15433. } else if ( light instanceof THREE.PointLight ) {
  15434. pointCount += 1;
  15435. if ( ! light.visible ) continue;
  15436. pointOffset = pointLength * 3;
  15437. if ( _this.gammaInput ) {
  15438. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  15439. } else {
  15440. setColorLinear( pointColors, pointOffset, color, intensity );
  15441. }
  15442. _vector3.setFromMatrixPosition( light.matrixWorld );
  15443. pointPositions[ pointOffset ] = _vector3.x;
  15444. pointPositions[ pointOffset + 1 ] = _vector3.y;
  15445. pointPositions[ pointOffset + 2 ] = _vector3.z;
  15446. pointDistances[ pointLength ] = distance;
  15447. pointLength += 1;
  15448. } else if ( light instanceof THREE.SpotLight ) {
  15449. spotCount += 1;
  15450. if ( ! light.visible ) continue;
  15451. spotOffset = spotLength * 3;
  15452. if ( _this.gammaInput ) {
  15453. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  15454. } else {
  15455. setColorLinear( spotColors, spotOffset, color, intensity );
  15456. }
  15457. _vector3.setFromMatrixPosition( light.matrixWorld );
  15458. spotPositions[ spotOffset ] = _vector3.x;
  15459. spotPositions[ spotOffset + 1 ] = _vector3.y;
  15460. spotPositions[ spotOffset + 2 ] = _vector3.z;
  15461. spotDistances[ spotLength ] = distance;
  15462. _direction.copy( _vector3 );
  15463. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  15464. _direction.sub( _vector3 );
  15465. _direction.normalize();
  15466. spotDirections[ spotOffset ] = _direction.x;
  15467. spotDirections[ spotOffset + 1 ] = _direction.y;
  15468. spotDirections[ spotOffset + 2 ] = _direction.z;
  15469. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  15470. spotExponents[ spotLength ] = light.exponent;
  15471. spotLength += 1;
  15472. } else if ( light instanceof THREE.HemisphereLight ) {
  15473. hemiCount += 1;
  15474. if ( ! light.visible ) continue;
  15475. _direction.setFromMatrixPosition( light.matrixWorld );
  15476. _direction.normalize();
  15477. // skip lights with undefined direction
  15478. // these create troubles in OpenGL (making pixel black)
  15479. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  15480. hemiOffset = hemiLength * 3;
  15481. hemiPositions[ hemiOffset ] = _direction.x;
  15482. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  15483. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  15484. skyColor = light.color;
  15485. groundColor = light.groundColor;
  15486. if ( _this.gammaInput ) {
  15487. intensitySq = intensity * intensity;
  15488. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  15489. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  15490. } else {
  15491. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  15492. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  15493. }
  15494. hemiLength += 1;
  15495. }
  15496. }
  15497. // null eventual remains from removed lights
  15498. // (this is to avoid if in shader)
  15499. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  15500. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  15501. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  15502. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  15503. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  15504. zlights.directional.length = dirLength;
  15505. zlights.point.length = pointLength;
  15506. zlights.spot.length = spotLength;
  15507. zlights.hemi.length = hemiLength;
  15508. zlights.ambient[ 0 ] = r;
  15509. zlights.ambient[ 1 ] = g;
  15510. zlights.ambient[ 2 ] = b;
  15511. };
  15512. // GL state setting
  15513. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  15514. if ( cullFace === THREE.CullFaceNone ) {
  15515. _gl.disable( _gl.CULL_FACE );
  15516. } else {
  15517. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  15518. _gl.frontFace( _gl.CW );
  15519. } else {
  15520. _gl.frontFace( _gl.CCW );
  15521. }
  15522. if ( cullFace === THREE.CullFaceBack ) {
  15523. _gl.cullFace( _gl.BACK );
  15524. } else if ( cullFace === THREE.CullFaceFront ) {
  15525. _gl.cullFace( _gl.FRONT );
  15526. } else {
  15527. _gl.cullFace( _gl.FRONT_AND_BACK );
  15528. }
  15529. _gl.enable( _gl.CULL_FACE );
  15530. }
  15531. };
  15532. this.setMaterialFaces = function ( material ) {
  15533. var doubleSided = material.side === THREE.DoubleSide;
  15534. var flipSided = material.side === THREE.BackSide;
  15535. if ( _oldDoubleSided !== doubleSided ) {
  15536. if ( doubleSided ) {
  15537. _gl.disable( _gl.CULL_FACE );
  15538. } else {
  15539. _gl.enable( _gl.CULL_FACE );
  15540. }
  15541. _oldDoubleSided = doubleSided;
  15542. }
  15543. if ( _oldFlipSided !== flipSided ) {
  15544. if ( flipSided ) {
  15545. _gl.frontFace( _gl.CW );
  15546. } else {
  15547. _gl.frontFace( _gl.CCW );
  15548. }
  15549. _oldFlipSided = flipSided;
  15550. }
  15551. };
  15552. this.setDepthTest = function ( depthTest ) {
  15553. if ( _oldDepthTest !== depthTest ) {
  15554. if ( depthTest ) {
  15555. _gl.enable( _gl.DEPTH_TEST );
  15556. } else {
  15557. _gl.disable( _gl.DEPTH_TEST );
  15558. }
  15559. _oldDepthTest = depthTest;
  15560. }
  15561. };
  15562. this.setDepthWrite = function ( depthWrite ) {
  15563. if ( _oldDepthWrite !== depthWrite ) {
  15564. _gl.depthMask( depthWrite );
  15565. _oldDepthWrite = depthWrite;
  15566. }
  15567. };
  15568. function setLineWidth ( width ) {
  15569. if ( width !== _oldLineWidth ) {
  15570. _gl.lineWidth( width );
  15571. _oldLineWidth = width;
  15572. }
  15573. };
  15574. function setPolygonOffset ( polygonoffset, factor, units ) {
  15575. if ( _oldPolygonOffset !== polygonoffset ) {
  15576. if ( polygonoffset ) {
  15577. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  15578. } else {
  15579. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  15580. }
  15581. _oldPolygonOffset = polygonoffset;
  15582. }
  15583. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  15584. _gl.polygonOffset( factor, units );
  15585. _oldPolygonOffsetFactor = factor;
  15586. _oldPolygonOffsetUnits = units;
  15587. }
  15588. };
  15589. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  15590. if ( blending !== _oldBlending ) {
  15591. if ( blending === THREE.NoBlending ) {
  15592. _gl.disable( _gl.BLEND );
  15593. } else if ( blending === THREE.AdditiveBlending ) {
  15594. _gl.enable( _gl.BLEND );
  15595. _gl.blendEquation( _gl.FUNC_ADD );
  15596. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  15597. } else if ( blending === THREE.SubtractiveBlending ) {
  15598. // TODO: Find blendFuncSeparate() combination
  15599. _gl.enable( _gl.BLEND );
  15600. _gl.blendEquation( _gl.FUNC_ADD );
  15601. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  15602. } else if ( blending === THREE.MultiplyBlending ) {
  15603. // TODO: Find blendFuncSeparate() combination
  15604. _gl.enable( _gl.BLEND );
  15605. _gl.blendEquation( _gl.FUNC_ADD );
  15606. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  15607. } else if ( blending === THREE.CustomBlending ) {
  15608. _gl.enable( _gl.BLEND );
  15609. } else {
  15610. _gl.enable( _gl.BLEND );
  15611. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  15612. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  15613. }
  15614. _oldBlending = blending;
  15615. }
  15616. if ( blending === THREE.CustomBlending ) {
  15617. if ( blendEquation !== _oldBlendEquation ) {
  15618. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  15619. _oldBlendEquation = blendEquation;
  15620. }
  15621. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  15622. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  15623. _oldBlendSrc = blendSrc;
  15624. _oldBlendDst = blendDst;
  15625. }
  15626. } else {
  15627. _oldBlendEquation = null;
  15628. _oldBlendSrc = null;
  15629. _oldBlendDst = null;
  15630. }
  15631. };
  15632. // Textures
  15633. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  15634. if ( isImagePowerOfTwo ) {
  15635. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  15636. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  15637. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  15638. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  15639. } else {
  15640. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  15641. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  15642. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  15643. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  15644. }
  15645. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  15646. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  15647. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  15648. texture.__oldAnisotropy = texture.anisotropy;
  15649. }
  15650. }
  15651. };
  15652. this.setTexture = function ( texture, slot ) {
  15653. if ( texture.needsUpdate ) {
  15654. if ( ! texture.__webglInit ) {
  15655. texture.__webglInit = true;
  15656. texture.addEventListener( 'dispose', onTextureDispose );
  15657. texture.__webglTexture = _gl.createTexture();
  15658. _this.info.memory.textures ++;
  15659. }
  15660. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15661. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15662. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15663. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  15664. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  15665. var image = texture.image,
  15666. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  15667. glFormat = paramThreeToGL( texture.format ),
  15668. glType = paramThreeToGL( texture.type );
  15669. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  15670. var mipmap, mipmaps = texture.mipmaps;
  15671. if ( texture instanceof THREE.DataTexture ) {
  15672. // use manually created mipmaps if available
  15673. // if there are no manual mipmaps
  15674. // set 0 level mipmap and then use GL to generate other mipmap levels
  15675. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15676. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15677. mipmap = mipmaps[ i ];
  15678. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15679. }
  15680. texture.generateMipmaps = false;
  15681. } else {
  15682. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  15683. }
  15684. } else if ( texture instanceof THREE.CompressedTexture ) {
  15685. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15686. mipmap = mipmaps[ i ];
  15687. if ( texture.format!==THREE.RGBAFormat ) {
  15688. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15689. } else {
  15690. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15691. }
  15692. }
  15693. } else { // regular Texture (image, video, canvas)
  15694. // use manually created mipmaps if available
  15695. // if there are no manual mipmaps
  15696. // set 0 level mipmap and then use GL to generate other mipmap levels
  15697. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15698. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15699. mipmap = mipmaps[ i ];
  15700. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  15701. }
  15702. texture.generateMipmaps = false;
  15703. } else {
  15704. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  15705. }
  15706. }
  15707. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15708. texture.needsUpdate = false;
  15709. if ( texture.onUpdate ) texture.onUpdate();
  15710. } else {
  15711. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15712. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15713. }
  15714. };
  15715. function clampToMaxSize ( image, maxSize ) {
  15716. if ( image.width <= maxSize && image.height <= maxSize ) {
  15717. return image;
  15718. }
  15719. // Warning: Scaling through the canvas will only work with images that use
  15720. // premultiplied alpha.
  15721. var maxDimension = Math.max( image.width, image.height );
  15722. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  15723. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  15724. var canvas = document.createElement( 'canvas' );
  15725. canvas.width = newWidth;
  15726. canvas.height = newHeight;
  15727. var ctx = canvas.getContext( "2d" );
  15728. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  15729. return canvas;
  15730. }
  15731. function setCubeTexture ( texture, slot ) {
  15732. if ( texture.image.length === 6 ) {
  15733. if ( texture.needsUpdate ) {
  15734. if ( ! texture.image.__webglTextureCube ) {
  15735. texture.addEventListener( 'dispose', onTextureDispose );
  15736. texture.image.__webglTextureCube = _gl.createTexture();
  15737. _this.info.memory.textures ++;
  15738. }
  15739. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15740. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15741. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15742. var isCompressed = texture instanceof THREE.CompressedTexture;
  15743. var cubeImage = [];
  15744. for ( var i = 0; i < 6; i ++ ) {
  15745. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  15746. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  15747. } else {
  15748. cubeImage[ i ] = texture.image[ i ];
  15749. }
  15750. }
  15751. var image = cubeImage[ 0 ],
  15752. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  15753. glFormat = paramThreeToGL( texture.format ),
  15754. glType = paramThreeToGL( texture.type );
  15755. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  15756. for ( var i = 0; i < 6; i ++ ) {
  15757. if( !isCompressed ) {
  15758. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15759. } else {
  15760. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15761. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15762. mipmap = mipmaps[ j ];
  15763. if ( texture.format!==THREE.RGBAFormat ) {
  15764. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15765. } else {
  15766. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15767. }
  15768. }
  15769. }
  15770. }
  15771. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  15772. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15773. }
  15774. texture.needsUpdate = false;
  15775. if ( texture.onUpdate ) texture.onUpdate();
  15776. } else {
  15777. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15778. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15779. }
  15780. }
  15781. };
  15782. function setCubeTextureDynamic ( texture, slot ) {
  15783. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15784. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  15785. };
  15786. // Render targets
  15787. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  15788. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15789. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  15790. };
  15791. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  15792. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15793. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15794. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15795. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15796. /* For some reason this is not working. Defaulting to RGBA4.
  15797. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15798. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  15799. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15800. */
  15801. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15802. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15803. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15804. } else {
  15805. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15806. }
  15807. };
  15808. this.setRenderTarget = function ( renderTarget ) {
  15809. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  15810. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  15811. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  15812. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  15813. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15814. renderTarget.__webglTexture = _gl.createTexture();
  15815. _this.info.memory.textures ++;
  15816. // Setup texture, create render and frame buffers
  15817. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ),
  15818. glFormat = paramThreeToGL( renderTarget.format ),
  15819. glType = paramThreeToGL( renderTarget.type );
  15820. if ( isCube ) {
  15821. renderTarget.__webglFramebuffer = [];
  15822. renderTarget.__webglRenderbuffer = [];
  15823. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15824. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  15825. for ( var i = 0; i < 6; i ++ ) {
  15826. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15827. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  15828. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15829. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15830. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  15831. }
  15832. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15833. } else {
  15834. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  15835. if ( renderTarget.shareDepthFrom ) {
  15836. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  15837. } else {
  15838. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  15839. }
  15840. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15841. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  15842. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15843. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  15844. if ( renderTarget.shareDepthFrom ) {
  15845. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15846. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15847. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15848. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15849. }
  15850. } else {
  15851. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15852. }
  15853. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15854. }
  15855. // Release everything
  15856. if ( isCube ) {
  15857. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15858. } else {
  15859. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15860. }
  15861. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15862. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15863. }
  15864. var framebuffer, width, height, vx, vy;
  15865. if ( renderTarget ) {
  15866. if ( isCube ) {
  15867. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15868. } else {
  15869. framebuffer = renderTarget.__webglFramebuffer;
  15870. }
  15871. width = renderTarget.width;
  15872. height = renderTarget.height;
  15873. vx = 0;
  15874. vy = 0;
  15875. } else {
  15876. framebuffer = null;
  15877. width = _viewportWidth;
  15878. height = _viewportHeight;
  15879. vx = _viewportX;
  15880. vy = _viewportY;
  15881. }
  15882. if ( framebuffer !== _currentFramebuffer ) {
  15883. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15884. _gl.viewport( vx, vy, width, height );
  15885. _currentFramebuffer = framebuffer;
  15886. }
  15887. _currentWidth = width;
  15888. _currentHeight = height;
  15889. };
  15890. function updateRenderTargetMipmap ( renderTarget ) {
  15891. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15892. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15893. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15894. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15895. } else {
  15896. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15897. _gl.generateMipmap( _gl.TEXTURE_2D );
  15898. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15899. }
  15900. };
  15901. // Fallback filters for non-power-of-2 textures
  15902. function filterFallback ( f ) {
  15903. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15904. return _gl.NEAREST;
  15905. }
  15906. return _gl.LINEAR;
  15907. };
  15908. // Map three.js constants to WebGL constants
  15909. function paramThreeToGL ( p ) {
  15910. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15911. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15912. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15913. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15914. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15915. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15916. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15917. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15918. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15919. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15920. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15921. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15922. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15923. if ( p === THREE.ByteType ) return _gl.BYTE;
  15924. if ( p === THREE.ShortType ) return _gl.SHORT;
  15925. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15926. if ( p === THREE.IntType ) return _gl.INT;
  15927. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15928. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15929. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15930. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15931. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15932. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15933. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15934. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15935. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15936. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15937. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15938. if ( p === THREE.OneFactor ) return _gl.ONE;
  15939. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15940. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15941. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15942. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15943. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15944. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15945. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15946. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15947. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15948. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15949. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15950. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15951. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15952. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15953. }
  15954. return 0;
  15955. };
  15956. // Allocations
  15957. function allocateBones ( object ) {
  15958. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  15959. return 1024;
  15960. } else {
  15961. // default for when object is not specified
  15962. // ( for example when prebuilding shader
  15963. // to be used with multiple objects )
  15964. //
  15965. // - leave some extra space for other uniforms
  15966. // - limit here is ANGLE's 254 max uniform vectors
  15967. // (up to 54 should be safe)
  15968. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15969. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15970. var maxBones = nVertexMatrices;
  15971. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15972. maxBones = Math.min( object.bones.length, maxBones );
  15973. if ( maxBones < object.bones.length ) {
  15974. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  15975. }
  15976. }
  15977. return maxBones;
  15978. }
  15979. };
  15980. function allocateLights( lights ) {
  15981. var dirLights = 0;
  15982. var pointLights = 0;
  15983. var spotLights = 0;
  15984. var hemiLights = 0;
  15985. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15986. var light = lights[ l ];
  15987. if ( light.onlyShadow || light.visible === false ) continue;
  15988. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15989. if ( light instanceof THREE.PointLight ) pointLights ++;
  15990. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15991. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15992. }
  15993. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15994. };
  15995. function allocateShadows( lights ) {
  15996. var maxShadows = 0;
  15997. for ( var l = 0, ll = lights.length; l < ll; l++ ) {
  15998. var light = lights[ l ];
  15999. if ( ! light.castShadow ) continue;
  16000. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  16001. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  16002. }
  16003. return maxShadows;
  16004. };
  16005. // Initialization
  16006. function initGL() {
  16007. try {
  16008. var attributes = {
  16009. alpha: _alpha,
  16010. depth: _depth,
  16011. stencil: _stencil,
  16012. antialias: _antialias,
  16013. premultipliedAlpha: _premultipliedAlpha,
  16014. preserveDrawingBuffer: _preserveDrawingBuffer
  16015. };
  16016. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  16017. if ( _gl === null ) {
  16018. throw 'Error creating WebGL context.';
  16019. }
  16020. } catch ( error ) {
  16021. console.error( error );
  16022. }
  16023. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  16024. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  16025. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  16026. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  16027. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  16028. _glExtensionElementIndexUint = _gl.getExtension( 'OES_element_index_uint' );
  16029. if ( _glExtensionTextureFloat === null ) {
  16030. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  16031. }
  16032. if ( _glExtensionStandardDerivatives === null ) {
  16033. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  16034. }
  16035. if ( _glExtensionTextureFilterAnisotropic === null ) {
  16036. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  16037. }
  16038. if ( _glExtensionCompressedTextureS3TC === null ) {
  16039. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  16040. }
  16041. if ( _glExtensionElementIndexUint === null ) {
  16042. console.log( 'THREE.WebGLRenderer: elementindex as unsigned integer not supported.' );
  16043. }
  16044. if ( _gl.getShaderPrecisionFormat === undefined ) {
  16045. _gl.getShaderPrecisionFormat = function() {
  16046. return {
  16047. "rangeMin" : 1,
  16048. "rangeMax" : 1,
  16049. "precision" : 1
  16050. };
  16051. }
  16052. }
  16053. if ( _logarithmicDepthBuffer ) {
  16054. _glExtensionFragDepth = _gl.getExtension( 'EXT_frag_depth' );
  16055. }
  16056. };
  16057. function setDefaultGLState () {
  16058. _gl.clearColor( 0, 0, 0, 1 );
  16059. _gl.clearDepth( 1 );
  16060. _gl.clearStencil( 0 );
  16061. _gl.enable( _gl.DEPTH_TEST );
  16062. _gl.depthFunc( _gl.LEQUAL );
  16063. _gl.frontFace( _gl.CCW );
  16064. _gl.cullFace( _gl.BACK );
  16065. _gl.enable( _gl.CULL_FACE );
  16066. _gl.enable( _gl.BLEND );
  16067. _gl.blendEquation( _gl.FUNC_ADD );
  16068. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  16069. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  16070. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  16071. };
  16072. // default plugins (order is important)
  16073. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  16074. this.addPrePlugin( this.shadowMapPlugin );
  16075. this.addPostPlugin( new THREE.SpritePlugin() );
  16076. this.addPostPlugin( new THREE.LensFlarePlugin() );
  16077. };
  16078. /**
  16079. * @author szimek / https://github.com/szimek/
  16080. * @author alteredq / http://alteredqualia.com/
  16081. */
  16082. THREE.WebGLRenderTarget = function ( width, height, options ) {
  16083. this.width = width;
  16084. this.height = height;
  16085. options = options || {};
  16086. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  16087. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  16088. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  16089. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  16090. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  16091. this.offset = new THREE.Vector2( 0, 0 );
  16092. this.repeat = new THREE.Vector2( 1, 1 );
  16093. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  16094. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  16095. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  16096. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  16097. this.generateMipmaps = true;
  16098. this.shareDepthFrom = null;
  16099. };
  16100. THREE.WebGLRenderTarget.prototype = {
  16101. constructor: THREE.WebGLRenderTarget,
  16102. setSize: function ( width, height ) {
  16103. this.width = width;
  16104. this.height = height;
  16105. },
  16106. clone: function () {
  16107. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  16108. tmp.wrapS = this.wrapS;
  16109. tmp.wrapT = this.wrapT;
  16110. tmp.magFilter = this.magFilter;
  16111. tmp.minFilter = this.minFilter;
  16112. tmp.anisotropy = this.anisotropy;
  16113. tmp.offset.copy( this.offset );
  16114. tmp.repeat.copy( this.repeat );
  16115. tmp.format = this.format;
  16116. tmp.type = this.type;
  16117. tmp.depthBuffer = this.depthBuffer;
  16118. tmp.stencilBuffer = this.stencilBuffer;
  16119. tmp.generateMipmaps = this.generateMipmaps;
  16120. tmp.shareDepthFrom = this.shareDepthFrom;
  16121. return tmp;
  16122. },
  16123. dispose: function () {
  16124. this.dispatchEvent( { type: 'dispose' } );
  16125. }
  16126. };
  16127. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  16128. /**
  16129. * @author alteredq / http://alteredqualia.com
  16130. */
  16131. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  16132. THREE.WebGLRenderTarget.call( this, width, height, options );
  16133. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  16134. };
  16135. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  16136. THREE.WebGLProgram = ( function () {
  16137. var programIdCount = 0;
  16138. var generateDefines = function ( defines ) {
  16139. var value, chunk, chunks = [];
  16140. for ( var d in defines ) {
  16141. value = defines[ d ];
  16142. if ( value === false ) continue;
  16143. chunk = "#define " + d + " " + value;
  16144. chunks.push( chunk );
  16145. }
  16146. return chunks.join( "\n" );
  16147. };
  16148. var cacheUniformLocations = function ( gl, program, identifiers ) {
  16149. var uniforms = {};
  16150. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  16151. var id = identifiers[ i ];
  16152. uniforms[ id ] = gl.getUniformLocation( program, id );
  16153. }
  16154. return uniforms;
  16155. };
  16156. var cacheAttributeLocations = function ( gl, program, identifiers ) {
  16157. var attributes = {};
  16158. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  16159. var id = identifiers[ i ];
  16160. attributes[ id ] = gl.getAttribLocation( program, id );
  16161. }
  16162. return attributes;
  16163. };
  16164. return function ( renderer, code, material, parameters ) {
  16165. var _this = renderer;
  16166. var _gl = _this.context;
  16167. var fragmentShader = material.fragmentShader;
  16168. var vertexShader = material.vertexShader;
  16169. var uniforms = material.uniforms;
  16170. var attributes = material.attributes;
  16171. var defines = material.defines;
  16172. var index0AttributeName = material.index0AttributeName;
  16173. if ( index0AttributeName === undefined && parameters.morphTargets === true ) {
  16174. // programs with morphTargets displace position out of attribute 0
  16175. index0AttributeName = 'position';
  16176. }
  16177. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  16178. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  16179. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  16180. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  16181. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  16182. }
  16183. // console.log( "building new program " );
  16184. //
  16185. var customDefines = generateDefines( defines );
  16186. //
  16187. var program = _gl.createProgram();
  16188. var prefix_vertex, prefix_fragment;
  16189. if ( material instanceof THREE.RawShaderMaterial ) {
  16190. prefix_vertex = '';
  16191. prefix_fragment = '';
  16192. } else {
  16193. prefix_vertex = [
  16194. "precision " + parameters.precision + " float;",
  16195. "precision " + parameters.precision + " int;",
  16196. customDefines,
  16197. parameters.supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  16198. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  16199. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  16200. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  16201. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  16202. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  16203. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  16204. "#define MAX_SHADOWS " + parameters.maxShadows,
  16205. "#define MAX_BONES " + parameters.maxBones,
  16206. parameters.map ? "#define USE_MAP" : "",
  16207. parameters.envMap ? "#define USE_ENVMAP" : "",
  16208. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  16209. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  16210. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  16211. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  16212. parameters.vertexColors ? "#define USE_COLOR" : "",
  16213. parameters.skinning ? "#define USE_SKINNING" : "",
  16214. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  16215. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  16216. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  16217. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  16218. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  16219. parameters.flipSided ? "#define FLIP_SIDED" : "",
  16220. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  16221. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  16222. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  16223. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  16224. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  16225. parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "",
  16226. //_this._glExtensionFragDepth ? "#define USE_LOGDEPTHBUF_EXT" : "",
  16227. "uniform mat4 modelMatrix;",
  16228. "uniform mat4 modelViewMatrix;",
  16229. "uniform mat4 projectionMatrix;",
  16230. "uniform mat4 viewMatrix;",
  16231. "uniform mat3 normalMatrix;",
  16232. "uniform vec3 cameraPosition;",
  16233. "attribute vec3 position;",
  16234. "attribute vec3 normal;",
  16235. "attribute vec2 uv;",
  16236. "attribute vec2 uv2;",
  16237. "#ifdef USE_COLOR",
  16238. " attribute vec3 color;",
  16239. "#endif",
  16240. "#ifdef USE_MORPHTARGETS",
  16241. " attribute vec3 morphTarget0;",
  16242. " attribute vec3 morphTarget1;",
  16243. " attribute vec3 morphTarget2;",
  16244. " attribute vec3 morphTarget3;",
  16245. " #ifdef USE_MORPHNORMALS",
  16246. " attribute vec3 morphNormal0;",
  16247. " attribute vec3 morphNormal1;",
  16248. " attribute vec3 morphNormal2;",
  16249. " attribute vec3 morphNormal3;",
  16250. " #else",
  16251. " attribute vec3 morphTarget4;",
  16252. " attribute vec3 morphTarget5;",
  16253. " attribute vec3 morphTarget6;",
  16254. " attribute vec3 morphTarget7;",
  16255. " #endif",
  16256. "#endif",
  16257. "#ifdef USE_SKINNING",
  16258. " attribute vec4 skinIndex;",
  16259. " attribute vec4 skinWeight;",
  16260. "#endif",
  16261. ""
  16262. ].join( '\n' );
  16263. prefix_fragment = [
  16264. "precision " + parameters.precision + " float;",
  16265. "precision " + parameters.precision + " int;",
  16266. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  16267. customDefines,
  16268. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  16269. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  16270. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  16271. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  16272. "#define MAX_SHADOWS " + parameters.maxShadows,
  16273. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  16274. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  16275. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  16276. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  16277. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  16278. parameters.map ? "#define USE_MAP" : "",
  16279. parameters.envMap ? "#define USE_ENVMAP" : "",
  16280. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  16281. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  16282. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  16283. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  16284. parameters.vertexColors ? "#define USE_COLOR" : "",
  16285. parameters.metal ? "#define METAL" : "",
  16286. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  16287. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  16288. parameters.flipSided ? "#define FLIP_SIDED" : "",
  16289. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  16290. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  16291. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  16292. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  16293. parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "",
  16294. //_this._glExtensionFragDepth ? "#define USE_LOGDEPTHBUF_EXT" : "",
  16295. "uniform mat4 viewMatrix;",
  16296. "uniform vec3 cameraPosition;",
  16297. ""
  16298. ].join( '\n' );
  16299. }
  16300. var glVertexShader = new THREE.WebGLShader( _gl, _gl.VERTEX_SHADER, prefix_vertex + vertexShader );
  16301. var glFragmentShader = new THREE.WebGLShader( _gl, _gl.FRAGMENT_SHADER, prefix_fragment + fragmentShader );
  16302. _gl.attachShader( program, glVertexShader );
  16303. _gl.attachShader( program, glFragmentShader );
  16304. if ( index0AttributeName !== undefined ) {
  16305. // Force a particular attribute to index 0.
  16306. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  16307. // And, color, for example is often automatically bound to index 0 so disabling it
  16308. _gl.bindAttribLocation( program, 0, index0AttributeName );
  16309. }
  16310. _gl.linkProgram( program );
  16311. if ( _gl.getProgramParameter( program, _gl.LINK_STATUS ) === false ) {
  16312. console.error( 'Could not initialise shader' );
  16313. console.error( 'gl.VALIDATE_STATUS', _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) );
  16314. console.error( 'gl.getError()', _gl.getError() );
  16315. }
  16316. if ( _gl.getProgramInfoLog( program ) !== '' ) {
  16317. console.error( 'gl.getProgramInfoLog()', _gl.getProgramInfoLog( program ) );
  16318. }
  16319. // clean up
  16320. _gl.deleteShader( glVertexShader );
  16321. _gl.deleteShader( glFragmentShader );
  16322. // cache uniform locations
  16323. var identifiers = [
  16324. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  16325. 'morphTargetInfluences'
  16326. ];
  16327. if ( parameters.useVertexTexture ) {
  16328. identifiers.push( 'boneTexture' );
  16329. identifiers.push( 'boneTextureWidth' );
  16330. identifiers.push( 'boneTextureHeight' );
  16331. } else {
  16332. identifiers.push( 'boneGlobalMatrices' );
  16333. }
  16334. if ( parameters.logarithmicDepthBuffer ) {
  16335. identifiers.push('logDepthBufFC');
  16336. }
  16337. for ( var u in uniforms ) {
  16338. identifiers.push( u );
  16339. }
  16340. this.uniforms = cacheUniformLocations( _gl, program, identifiers );
  16341. // cache attributes locations
  16342. identifiers = [
  16343. "position", "normal", "uv", "uv2", "tangent", "color",
  16344. "skinIndex", "skinWeight", "lineDistance"
  16345. ];
  16346. for ( var i = 0; i < parameters.maxMorphTargets; i ++ ) {
  16347. identifiers.push( "morphTarget" + i );
  16348. }
  16349. for ( var i = 0; i < parameters.maxMorphNormals; i ++ ) {
  16350. identifiers.push( "morphNormal" + i );
  16351. }
  16352. for ( var a in attributes ) {
  16353. identifiers.push( a );
  16354. }
  16355. this.attributes = cacheAttributeLocations( _gl, program, identifiers );
  16356. //
  16357. this.id = programIdCount ++;
  16358. this.code = code;
  16359. this.usedTimes = 1;
  16360. this.program = program;
  16361. this.vertexShader = glVertexShader;
  16362. this.fragmentShader = glFragmentShader;
  16363. return this;
  16364. };
  16365. } )();
  16366. THREE.WebGLShader = ( function () {
  16367. var addLineNumbers = function ( string ) {
  16368. var lines = string.split( '\n' );
  16369. for ( var i = 0; i < lines.length; i ++ ) {
  16370. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  16371. }
  16372. return lines.join( '\n' );
  16373. };
  16374. return function ( gl, type, string ) {
  16375. var shader = gl.createShader( type );
  16376. gl.shaderSource( shader, string );
  16377. gl.compileShader( shader );
  16378. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  16379. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  16380. }
  16381. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  16382. console.error( 'THREE.WebGLShader:', 'gl.getShaderInfoLog()', gl.getShaderInfoLog( shader ) );
  16383. console.error( addLineNumbers( string ) );
  16384. }
  16385. return shader;
  16386. };
  16387. } )();
  16388. /**
  16389. * @author mrdoob / http://mrdoob.com/
  16390. */
  16391. THREE.RenderableVertex = function () {
  16392. this.position = new THREE.Vector3();
  16393. this.positionWorld = new THREE.Vector3();
  16394. this.positionScreen = new THREE.Vector4();
  16395. this.visible = true;
  16396. };
  16397. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  16398. this.positionWorld.copy( vertex.positionWorld );
  16399. this.positionScreen.copy( vertex.positionScreen );
  16400. };
  16401. /**
  16402. * @author mrdoob / http://mrdoob.com/
  16403. */
  16404. THREE.RenderableFace = function () {
  16405. this.id = 0;
  16406. this.v1 = new THREE.RenderableVertex();
  16407. this.v2 = new THREE.RenderableVertex();
  16408. this.v3 = new THREE.RenderableVertex();
  16409. this.normalModel = new THREE.Vector3();
  16410. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  16411. this.vertexNormalsLength = 0;
  16412. this.color = null;
  16413. this.material = null;
  16414. this.uvs = [ new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() ];
  16415. this.z = 0;
  16416. };
  16417. /**
  16418. * @author mrdoob / http://mrdoob.com/
  16419. */
  16420. THREE.RenderableObject = function () {
  16421. this.id = 0;
  16422. this.object = null;
  16423. this.z = 0;
  16424. };
  16425. /**
  16426. * @author mrdoob / http://mrdoob.com/
  16427. */
  16428. THREE.RenderableSprite = function () {
  16429. this.id = 0;
  16430. this.object = null;
  16431. this.x = 0;
  16432. this.y = 0;
  16433. this.z = 0;
  16434. this.rotation = 0;
  16435. this.scale = new THREE.Vector2();
  16436. this.material = null;
  16437. };
  16438. /**
  16439. * @author mrdoob / http://mrdoob.com/
  16440. */
  16441. THREE.RenderableLine = function () {
  16442. this.id = 0;
  16443. this.v1 = new THREE.RenderableVertex();
  16444. this.v2 = new THREE.RenderableVertex();
  16445. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  16446. this.material = null;
  16447. this.z = 0;
  16448. };
  16449. /**
  16450. * @author mrdoob / http://mrdoob.com/
  16451. * @author alteredq / http://alteredqualia.com/
  16452. */
  16453. THREE.GeometryUtils = {
  16454. // Merge two geometries or geometry and geometry from object (using object's transform)
  16455. merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) {
  16456. var matrix, normalMatrix,
  16457. vertexOffset = geometry1.vertices.length,
  16458. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  16459. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  16460. vertices1 = geometry1.vertices,
  16461. vertices2 = geometry2.vertices,
  16462. faces1 = geometry1.faces,
  16463. faces2 = geometry2.faces,
  16464. uvs1 = geometry1.faceVertexUvs[ 0 ],
  16465. uvs2 = geometry2.faceVertexUvs[ 0 ];
  16466. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  16467. if ( object2 instanceof THREE.Mesh ) {
  16468. object2.matrixAutoUpdate && object2.updateMatrix();
  16469. matrix = object2.matrix;
  16470. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  16471. }
  16472. // vertices
  16473. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  16474. var vertex = vertices2[ i ];
  16475. var vertexCopy = vertex.clone();
  16476. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  16477. vertices1.push( vertexCopy );
  16478. }
  16479. // faces
  16480. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  16481. var face = faces2[ i ], faceCopy, normal, color,
  16482. faceVertexNormals = face.vertexNormals,
  16483. faceVertexColors = face.vertexColors;
  16484. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  16485. faceCopy.normal.copy( face.normal );
  16486. if ( normalMatrix ) {
  16487. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  16488. }
  16489. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  16490. normal = faceVertexNormals[ j ].clone();
  16491. if ( normalMatrix ) {
  16492. normal.applyMatrix3( normalMatrix ).normalize();
  16493. }
  16494. faceCopy.vertexNormals.push( normal );
  16495. }
  16496. faceCopy.color.copy( face.color );
  16497. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  16498. color = faceVertexColors[ j ];
  16499. faceCopy.vertexColors.push( color.clone() );
  16500. }
  16501. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  16502. faces1.push( faceCopy );
  16503. }
  16504. // uvs
  16505. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  16506. var uv = uvs2[ i ], uvCopy = [];
  16507. if ( uv === undefined ) {
  16508. continue;
  16509. }
  16510. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  16511. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  16512. }
  16513. uvs1.push( uvCopy );
  16514. }
  16515. },
  16516. // Get random point in triangle (via barycentric coordinates)
  16517. // (uniform distribution)
  16518. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  16519. randomPointInTriangle: function () {
  16520. var vector = new THREE.Vector3();
  16521. return function ( vectorA, vectorB, vectorC ) {
  16522. var point = new THREE.Vector3();
  16523. var a = THREE.Math.random16();
  16524. var b = THREE.Math.random16();
  16525. if ( ( a + b ) > 1 ) {
  16526. a = 1 - a;
  16527. b = 1 - b;
  16528. }
  16529. var c = 1 - a - b;
  16530. point.copy( vectorA );
  16531. point.multiplyScalar( a );
  16532. vector.copy( vectorB );
  16533. vector.multiplyScalar( b );
  16534. point.add( vector );
  16535. vector.copy( vectorC );
  16536. vector.multiplyScalar( c );
  16537. point.add( vector );
  16538. return point;
  16539. };
  16540. }(),
  16541. // Get random point in face (triangle / quad)
  16542. // (uniform distribution)
  16543. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  16544. var vA, vB, vC, vD;
  16545. vA = geometry.vertices[ face.a ];
  16546. vB = geometry.vertices[ face.b ];
  16547. vC = geometry.vertices[ face.c ];
  16548. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  16549. },
  16550. // Get uniformly distributed random points in mesh
  16551. // - create array with cumulative sums of face areas
  16552. // - pick random number from 0 to total area
  16553. // - find corresponding place in area array by binary search
  16554. // - get random point in face
  16555. randomPointsInGeometry: function ( geometry, n ) {
  16556. var face, i,
  16557. faces = geometry.faces,
  16558. vertices = geometry.vertices,
  16559. il = faces.length,
  16560. totalArea = 0,
  16561. cumulativeAreas = [],
  16562. vA, vB, vC, vD;
  16563. // precompute face areas
  16564. for ( i = 0; i < il; i ++ ) {
  16565. face = faces[ i ];
  16566. vA = vertices[ face.a ];
  16567. vB = vertices[ face.b ];
  16568. vC = vertices[ face.c ];
  16569. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  16570. totalArea += face._area;
  16571. cumulativeAreas[ i ] = totalArea;
  16572. }
  16573. // binary search cumulative areas array
  16574. function binarySearchIndices( value ) {
  16575. function binarySearch( start, end ) {
  16576. // return closest larger index
  16577. // if exact number is not found
  16578. if ( end < start )
  16579. return start;
  16580. var mid = start + Math.floor( ( end - start ) / 2 );
  16581. if ( cumulativeAreas[ mid ] > value ) {
  16582. return binarySearch( start, mid - 1 );
  16583. } else if ( cumulativeAreas[ mid ] < value ) {
  16584. return binarySearch( mid + 1, end );
  16585. } else {
  16586. return mid;
  16587. }
  16588. }
  16589. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  16590. return result;
  16591. }
  16592. // pick random face weighted by face area
  16593. var r, index,
  16594. result = [];
  16595. var stats = {};
  16596. for ( i = 0; i < n; i ++ ) {
  16597. r = THREE.Math.random16() * totalArea;
  16598. index = binarySearchIndices( r );
  16599. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  16600. if ( ! stats[ index ] ) {
  16601. stats[ index ] = 1;
  16602. } else {
  16603. stats[ index ] += 1;
  16604. }
  16605. }
  16606. return result;
  16607. },
  16608. // Get triangle area (half of parallelogram)
  16609. // http://mathworld.wolfram.com/TriangleArea.html
  16610. triangleArea: function () {
  16611. var vector1 = new THREE.Vector3();
  16612. var vector2 = new THREE.Vector3();
  16613. return function ( vectorA, vectorB, vectorC ) {
  16614. vector1.subVectors( vectorB, vectorA );
  16615. vector2.subVectors( vectorC, vectorA );
  16616. vector1.cross( vector2 );
  16617. return 0.5 * vector1.length();
  16618. };
  16619. }(),
  16620. // Center geometry so that 0,0,0 is in center of bounding box
  16621. center: function ( geometry ) {
  16622. geometry.computeBoundingBox();
  16623. var bb = geometry.boundingBox;
  16624. var offset = new THREE.Vector3();
  16625. offset.addVectors( bb.min, bb.max );
  16626. offset.multiplyScalar( -0.5 );
  16627. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  16628. geometry.computeBoundingBox();
  16629. return offset;
  16630. }
  16631. };
  16632. /**
  16633. * @author alteredq / http://alteredqualia.com/
  16634. * @author mrdoob / http://mrdoob.com/
  16635. */
  16636. THREE.ImageUtils = {
  16637. crossOrigin: undefined,
  16638. loadTexture: function ( url, mapping, onLoad, onError ) {
  16639. var loader = new THREE.ImageLoader();
  16640. loader.crossOrigin = this.crossOrigin;
  16641. var texture = new THREE.Texture( undefined, mapping );
  16642. var image = loader.load( url, function () {
  16643. texture.needsUpdate = true;
  16644. if ( onLoad ) onLoad( texture );
  16645. }, undefined, function ( event ) {
  16646. if ( onError ) onError( event );
  16647. } );
  16648. texture.image = image;
  16649. texture.sourceFile = url;
  16650. return texture;
  16651. },
  16652. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  16653. var texture = new THREE.CompressedTexture();
  16654. texture.mapping = mapping;
  16655. var request = new XMLHttpRequest();
  16656. request.onload = function () {
  16657. var buffer = request.response;
  16658. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16659. texture.format = dds.format;
  16660. texture.mipmaps = dds.mipmaps;
  16661. texture.image.width = dds.width;
  16662. texture.image.height = dds.height;
  16663. // gl.generateMipmap fails for compressed textures
  16664. // mipmaps must be embedded in the DDS file
  16665. // or texture filters must not use mipmapping
  16666. texture.generateMipmaps = false;
  16667. texture.needsUpdate = true;
  16668. if ( onLoad ) onLoad( texture );
  16669. }
  16670. request.onerror = onError;
  16671. request.open( 'GET', url, true );
  16672. request.responseType = "arraybuffer";
  16673. request.send( null );
  16674. return texture;
  16675. },
  16676. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  16677. var images = [];
  16678. images.loadCount = 0;
  16679. var texture = new THREE.Texture();
  16680. texture.image = images;
  16681. if ( mapping !== undefined ) texture.mapping = mapping;
  16682. // no flipping needed for cube textures
  16683. texture.flipY = false;
  16684. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16685. var cubeImage = new Image();
  16686. images[ i ] = cubeImage;
  16687. cubeImage.onload = function () {
  16688. images.loadCount += 1;
  16689. if ( images.loadCount === 6 ) {
  16690. texture.needsUpdate = true;
  16691. if ( onLoad ) onLoad( texture );
  16692. }
  16693. };
  16694. cubeImage.onerror = onError;
  16695. cubeImage.crossOrigin = this.crossOrigin;
  16696. cubeImage.src = array[ i ];
  16697. }
  16698. return texture;
  16699. },
  16700. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  16701. var images = [];
  16702. images.loadCount = 0;
  16703. var texture = new THREE.CompressedTexture();
  16704. texture.image = images;
  16705. if ( mapping !== undefined ) texture.mapping = mapping;
  16706. // no flipping for cube textures
  16707. // (also flipping doesn't work for compressed textures )
  16708. texture.flipY = false;
  16709. // can't generate mipmaps for compressed textures
  16710. // mips must be embedded in DDS files
  16711. texture.generateMipmaps = false;
  16712. var generateCubeFaceCallback = function ( rq, img ) {
  16713. return function () {
  16714. var buffer = rq.response;
  16715. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16716. img.format = dds.format;
  16717. img.mipmaps = dds.mipmaps;
  16718. img.width = dds.width;
  16719. img.height = dds.height;
  16720. images.loadCount += 1;
  16721. if ( images.loadCount === 6 ) {
  16722. texture.format = dds.format;
  16723. texture.needsUpdate = true;
  16724. if ( onLoad ) onLoad( texture );
  16725. }
  16726. }
  16727. }
  16728. // compressed cubemap textures as 6 separate DDS files
  16729. if ( array instanceof Array ) {
  16730. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16731. var cubeImage = {};
  16732. images[ i ] = cubeImage;
  16733. var request = new XMLHttpRequest();
  16734. request.onload = generateCubeFaceCallback( request, cubeImage );
  16735. request.onerror = onError;
  16736. var url = array[ i ];
  16737. request.open( 'GET', url, true );
  16738. request.responseType = "arraybuffer";
  16739. request.send( null );
  16740. }
  16741. // compressed cubemap texture stored in a single DDS file
  16742. } else {
  16743. var url = array;
  16744. var request = new XMLHttpRequest();
  16745. request.onload = function( ) {
  16746. var buffer = request.response;
  16747. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16748. if ( dds.isCubemap ) {
  16749. var faces = dds.mipmaps.length / dds.mipmapCount;
  16750. for ( var f = 0; f < faces; f ++ ) {
  16751. images[ f ] = { mipmaps : [] };
  16752. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16753. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  16754. images[ f ].format = dds.format;
  16755. images[ f ].width = dds.width;
  16756. images[ f ].height = dds.height;
  16757. }
  16758. }
  16759. texture.format = dds.format;
  16760. texture.needsUpdate = true;
  16761. if ( onLoad ) onLoad( texture );
  16762. }
  16763. }
  16764. request.onerror = onError;
  16765. request.open( 'GET', url, true );
  16766. request.responseType = "arraybuffer";
  16767. request.send( null );
  16768. }
  16769. return texture;
  16770. },
  16771. loadDDSTexture: function ( url, mapping, onLoad, onError ) {
  16772. var images = [];
  16773. images.loadCount = 0;
  16774. var texture = new THREE.CompressedTexture();
  16775. texture.image = images;
  16776. if ( mapping !== undefined ) texture.mapping = mapping;
  16777. // no flipping for cube textures
  16778. // (also flipping doesn't work for compressed textures )
  16779. texture.flipY = false;
  16780. // can't generate mipmaps for compressed textures
  16781. // mips must be embedded in DDS files
  16782. texture.generateMipmaps = false;
  16783. {
  16784. var request = new XMLHttpRequest();
  16785. request.onload = function( ) {
  16786. var buffer = request.response;
  16787. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16788. if ( dds.isCubemap ) {
  16789. var faces = dds.mipmaps.length / dds.mipmapCount;
  16790. for ( var f = 0; f < faces; f ++ ) {
  16791. images[ f ] = { mipmaps : [] };
  16792. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16793. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  16794. images[ f ].format = dds.format;
  16795. images[ f ].width = dds.width;
  16796. images[ f ].height = dds.height;
  16797. }
  16798. }
  16799. } else {
  16800. texture.image.width = dds.width;
  16801. texture.image.height = dds.height;
  16802. texture.mipmaps = dds.mipmaps;
  16803. }
  16804. texture.format = dds.format;
  16805. texture.needsUpdate = true;
  16806. if ( onLoad ) onLoad( texture );
  16807. }
  16808. request.onerror = onError;
  16809. request.open( 'GET', url, true );
  16810. request.responseType = "arraybuffer";
  16811. request.send( null );
  16812. }
  16813. return texture;
  16814. },
  16815. parseDDS: function ( buffer, loadMipmaps ) {
  16816. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  16817. // Adapted from @toji's DDS utils
  16818. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  16819. // All values and structures referenced from:
  16820. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  16821. var DDS_MAGIC = 0x20534444;
  16822. var DDSD_CAPS = 0x1,
  16823. DDSD_HEIGHT = 0x2,
  16824. DDSD_WIDTH = 0x4,
  16825. DDSD_PITCH = 0x8,
  16826. DDSD_PIXELFORMAT = 0x1000,
  16827. DDSD_MIPMAPCOUNT = 0x20000,
  16828. DDSD_LINEARSIZE = 0x80000,
  16829. DDSD_DEPTH = 0x800000;
  16830. var DDSCAPS_COMPLEX = 0x8,
  16831. DDSCAPS_MIPMAP = 0x400000,
  16832. DDSCAPS_TEXTURE = 0x1000;
  16833. var DDSCAPS2_CUBEMAP = 0x200,
  16834. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  16835. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  16836. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  16837. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  16838. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  16839. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  16840. DDSCAPS2_VOLUME = 0x200000;
  16841. var DDPF_ALPHAPIXELS = 0x1,
  16842. DDPF_ALPHA = 0x2,
  16843. DDPF_FOURCC = 0x4,
  16844. DDPF_RGB = 0x40,
  16845. DDPF_YUV = 0x200,
  16846. DDPF_LUMINANCE = 0x20000;
  16847. function fourCCToInt32( value ) {
  16848. return value.charCodeAt(0) +
  16849. (value.charCodeAt(1) << 8) +
  16850. (value.charCodeAt(2) << 16) +
  16851. (value.charCodeAt(3) << 24);
  16852. }
  16853. function int32ToFourCC( value ) {
  16854. return String.fromCharCode(
  16855. value & 0xff,
  16856. (value >> 8) & 0xff,
  16857. (value >> 16) & 0xff,
  16858. (value >> 24) & 0xff
  16859. );
  16860. }
  16861. function loadARGBMip( buffer, dataOffset, width, height ) {
  16862. var dataLength = width*height*4;
  16863. var srcBuffer = new Uint8Array( buffer, dataOffset, dataLength );
  16864. var byteArray = new Uint8Array( dataLength );
  16865. var dst = 0;
  16866. var src = 0;
  16867. for ( var y = 0; y < height; y++ ) {
  16868. for ( var x = 0; x < width; x++ ) {
  16869. var b = srcBuffer[src]; src++;
  16870. var g = srcBuffer[src]; src++;
  16871. var r = srcBuffer[src]; src++;
  16872. var a = srcBuffer[src]; src++;
  16873. byteArray[dst] = r; dst++; //r
  16874. byteArray[dst] = g; dst++; //g
  16875. byteArray[dst] = b; dst++; //b
  16876. byteArray[dst] = a; dst++; //a
  16877. }
  16878. }
  16879. return byteArray;
  16880. }
  16881. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  16882. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  16883. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  16884. var headerLengthInt = 31; // The header length in 32 bit ints
  16885. // Offsets into the header array
  16886. var off_magic = 0;
  16887. var off_size = 1;
  16888. var off_flags = 2;
  16889. var off_height = 3;
  16890. var off_width = 4;
  16891. var off_mipmapCount = 7;
  16892. var off_pfFlags = 20;
  16893. var off_pfFourCC = 21;
  16894. var off_RGBBitCount = 22;
  16895. var off_RBitMask = 23;
  16896. var off_GBitMask = 24;
  16897. var off_BBitMask = 25;
  16898. var off_ABitMask = 26;
  16899. var off_caps = 27;
  16900. var off_caps2 = 28;
  16901. var off_caps3 = 29;
  16902. var off_caps4 = 30;
  16903. // Parse header
  16904. var header = new Int32Array( buffer, 0, headerLengthInt );
  16905. if ( header[ off_magic ] !== DDS_MAGIC ) {
  16906. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  16907. return dds;
  16908. }
  16909. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  16910. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  16911. return dds;
  16912. }
  16913. var blockBytes;
  16914. var fourCC = header[ off_pfFourCC ];
  16915. var isRGBAUncompressed = false;
  16916. switch ( fourCC ) {
  16917. case FOURCC_DXT1:
  16918. blockBytes = 8;
  16919. dds.format = THREE.RGB_S3TC_DXT1_Format;
  16920. break;
  16921. case FOURCC_DXT3:
  16922. blockBytes = 16;
  16923. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  16924. break;
  16925. case FOURCC_DXT5:
  16926. blockBytes = 16;
  16927. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  16928. break;
  16929. default:
  16930. if( header[off_RGBBitCount] ==32
  16931. && header[off_RBitMask]&0xff0000
  16932. && header[off_GBitMask]&0xff00
  16933. && header[off_BBitMask]&0xff
  16934. && header[off_ABitMask]&0xff000000 ) {
  16935. isRGBAUncompressed = true;
  16936. blockBytes = 64;
  16937. dds.format = THREE.RGBAFormat;
  16938. } else {
  16939. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  16940. return dds;
  16941. }
  16942. }
  16943. dds.mipmapCount = 1;
  16944. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  16945. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  16946. }
  16947. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  16948. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  16949. dds.width = header[ off_width ];
  16950. dds.height = header[ off_height ];
  16951. var dataOffset = header[ off_size ] + 4;
  16952. // Extract mipmaps buffers
  16953. var width = dds.width;
  16954. var height = dds.height;
  16955. var faces = dds.isCubemap ? 6 : 1;
  16956. for ( var face = 0; face < faces; face ++ ) {
  16957. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16958. if( isRGBAUncompressed ) {
  16959. var byteArray = loadARGBMip( buffer, dataOffset, width, height );
  16960. var dataLength = byteArray.length;
  16961. } else {
  16962. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  16963. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  16964. }
  16965. var mipmap = { "data": byteArray, "width": width, "height": height };
  16966. dds.mipmaps.push( mipmap );
  16967. dataOffset += dataLength;
  16968. width = Math.max( width * 0.5, 1 );
  16969. height = Math.max( height * 0.5, 1 );
  16970. }
  16971. width = dds.width;
  16972. height = dds.height;
  16973. }
  16974. return dds;
  16975. },
  16976. getNormalMap: function ( image, depth ) {
  16977. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  16978. var cross = function ( a, b ) {
  16979. 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 ] ];
  16980. }
  16981. var subtract = function ( a, b ) {
  16982. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  16983. }
  16984. var normalize = function ( a ) {
  16985. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  16986. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  16987. }
  16988. depth = depth | 1;
  16989. var width = image.width;
  16990. var height = image.height;
  16991. var canvas = document.createElement( 'canvas' );
  16992. canvas.width = width;
  16993. canvas.height = height;
  16994. var context = canvas.getContext( '2d' );
  16995. context.drawImage( image, 0, 0 );
  16996. var data = context.getImageData( 0, 0, width, height ).data;
  16997. var imageData = context.createImageData( width, height );
  16998. var output = imageData.data;
  16999. for ( var x = 0; x < width; x ++ ) {
  17000. for ( var y = 0; y < height; y ++ ) {
  17001. var ly = y - 1 < 0 ? 0 : y - 1;
  17002. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  17003. var lx = x - 1 < 0 ? 0 : x - 1;
  17004. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  17005. var points = [];
  17006. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  17007. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  17008. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  17009. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  17010. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  17011. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  17012. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  17013. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  17014. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  17015. var normals = [];
  17016. var num_points = points.length;
  17017. for ( var i = 0; i < num_points; i ++ ) {
  17018. var v1 = points[ i ];
  17019. var v2 = points[ ( i + 1 ) % num_points ];
  17020. v1 = subtract( v1, origin );
  17021. v2 = subtract( v2, origin );
  17022. normals.push( normalize( cross( v1, v2 ) ) );
  17023. }
  17024. var normal = [ 0, 0, 0 ];
  17025. for ( var i = 0; i < normals.length; i ++ ) {
  17026. normal[ 0 ] += normals[ i ][ 0 ];
  17027. normal[ 1 ] += normals[ i ][ 1 ];
  17028. normal[ 2 ] += normals[ i ][ 2 ];
  17029. }
  17030. normal[ 0 ] /= normals.length;
  17031. normal[ 1 ] /= normals.length;
  17032. normal[ 2 ] /= normals.length;
  17033. var idx = ( y * width + x ) * 4;
  17034. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  17035. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  17036. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  17037. output[ idx + 3 ] = 255;
  17038. }
  17039. }
  17040. context.putImageData( imageData, 0, 0 );
  17041. return canvas;
  17042. },
  17043. generateDataTexture: function ( width, height, color ) {
  17044. var size = width * height;
  17045. var data = new Uint8Array( 3 * size );
  17046. var r = Math.floor( color.r * 255 );
  17047. var g = Math.floor( color.g * 255 );
  17048. var b = Math.floor( color.b * 255 );
  17049. for ( var i = 0; i < size; i ++ ) {
  17050. data[ i * 3 ] = r;
  17051. data[ i * 3 + 1 ] = g;
  17052. data[ i * 3 + 2 ] = b;
  17053. }
  17054. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  17055. texture.needsUpdate = true;
  17056. return texture;
  17057. }
  17058. };
  17059. /**
  17060. * @author alteredq / http://alteredqualia.com/
  17061. */
  17062. THREE.SceneUtils = {
  17063. createMultiMaterialObject: function ( geometry, materials ) {
  17064. var group = new THREE.Object3D();
  17065. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  17066. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  17067. }
  17068. return group;
  17069. },
  17070. detach : function ( child, parent, scene ) {
  17071. child.applyMatrix( parent.matrixWorld );
  17072. parent.remove( child );
  17073. scene.add( child );
  17074. },
  17075. attach: function ( child, scene, parent ) {
  17076. var matrixWorldInverse = new THREE.Matrix4();
  17077. matrixWorldInverse.getInverse( parent.matrixWorld );
  17078. child.applyMatrix( matrixWorldInverse );
  17079. scene.remove( child );
  17080. parent.add( child );
  17081. }
  17082. };
  17083. /**
  17084. * @author zz85 / http://www.lab4games.net/zz85/blog
  17085. * @author alteredq / http://alteredqualia.com/
  17086. *
  17087. * For Text operations in three.js (See TextGeometry)
  17088. *
  17089. * It uses techniques used in:
  17090. *
  17091. * typeface.js and canvastext
  17092. * For converting fonts and rendering with javascript
  17093. * http://typeface.neocracy.org
  17094. *
  17095. * Triangulation ported from AS3
  17096. * Simple Polygon Triangulation
  17097. * http://actionsnippet.com/?p=1462
  17098. *
  17099. * A Method to triangulate shapes with holes
  17100. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  17101. *
  17102. */
  17103. THREE.FontUtils = {
  17104. faces : {},
  17105. // Just for now. face[weight][style]
  17106. face : "helvetiker",
  17107. weight: "normal",
  17108. style : "normal",
  17109. size : 150,
  17110. divisions : 10,
  17111. getFace : function() {
  17112. return this.faces[ this.face ][ this.weight ][ this.style ];
  17113. },
  17114. loadFace : function( data ) {
  17115. var family = data.familyName.toLowerCase();
  17116. var ThreeFont = this;
  17117. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  17118. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  17119. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  17120. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  17121. return data;
  17122. },
  17123. drawText : function( text ) {
  17124. var characterPts = [], allPts = [];
  17125. // RenderText
  17126. var i, p,
  17127. face = this.getFace(),
  17128. scale = this.size / face.resolution,
  17129. offset = 0,
  17130. chars = String( text ).split( '' ),
  17131. length = chars.length;
  17132. var fontPaths = [];
  17133. for ( i = 0; i < length; i ++ ) {
  17134. var path = new THREE.Path();
  17135. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  17136. offset += ret.offset;
  17137. fontPaths.push( ret.path );
  17138. }
  17139. // get the width
  17140. var width = offset / 2;
  17141. //
  17142. // for ( p = 0; p < allPts.length; p++ ) {
  17143. //
  17144. // allPts[ p ].x -= width;
  17145. //
  17146. // }
  17147. //var extract = this.extractPoints( allPts, characterPts );
  17148. //extract.contour = allPts;
  17149. //extract.paths = fontPaths;
  17150. //extract.offset = width;
  17151. return { paths : fontPaths, offset : width };
  17152. },
  17153. extractGlyphPoints : function( c, face, scale, offset, path ) {
  17154. var pts = [];
  17155. var i, i2, divisions,
  17156. outline, action, length,
  17157. scaleX, scaleY,
  17158. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  17159. laste,
  17160. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  17161. if ( !glyph ) return;
  17162. if ( glyph.o ) {
  17163. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  17164. length = outline.length;
  17165. scaleX = scale;
  17166. scaleY = scale;
  17167. for ( i = 0; i < length; ) {
  17168. action = outline[ i ++ ];
  17169. //console.log( action );
  17170. switch( action ) {
  17171. case 'm':
  17172. // Move To
  17173. x = outline[ i++ ] * scaleX + offset;
  17174. y = outline[ i++ ] * scaleY;
  17175. path.moveTo( x, y );
  17176. break;
  17177. case 'l':
  17178. // Line To
  17179. x = outline[ i++ ] * scaleX + offset;
  17180. y = outline[ i++ ] * scaleY;
  17181. path.lineTo(x,y);
  17182. break;
  17183. case 'q':
  17184. // QuadraticCurveTo
  17185. cpx = outline[ i++ ] * scaleX + offset;
  17186. cpy = outline[ i++ ] * scaleY;
  17187. cpx1 = outline[ i++ ] * scaleX + offset;
  17188. cpy1 = outline[ i++ ] * scaleY;
  17189. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  17190. laste = pts[ pts.length - 1 ];
  17191. if ( laste ) {
  17192. cpx0 = laste.x;
  17193. cpy0 = laste.y;
  17194. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  17195. var t = i2 / divisions;
  17196. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17197. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17198. }
  17199. }
  17200. break;
  17201. case 'b':
  17202. // Cubic Bezier Curve
  17203. cpx = outline[ i++ ] * scaleX + offset;
  17204. cpy = outline[ i++ ] * scaleY;
  17205. cpx1 = outline[ i++ ] * scaleX + offset;
  17206. cpy1 = outline[ i++ ] * -scaleY;
  17207. cpx2 = outline[ i++ ] * scaleX + offset;
  17208. cpy2 = outline[ i++ ] * -scaleY;
  17209. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  17210. laste = pts[ pts.length - 1 ];
  17211. if ( laste ) {
  17212. cpx0 = laste.x;
  17213. cpy0 = laste.y;
  17214. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  17215. var t = i2 / divisions;
  17216. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17217. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17218. }
  17219. }
  17220. break;
  17221. }
  17222. }
  17223. }
  17224. return { offset: glyph.ha*scale, path:path};
  17225. }
  17226. };
  17227. THREE.FontUtils.generateShapes = function( text, parameters ) {
  17228. // Parameters
  17229. parameters = parameters || {};
  17230. var size = parameters.size !== undefined ? parameters.size : 100;
  17231. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  17232. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  17233. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  17234. var style = parameters.style !== undefined ? parameters.style : "normal";
  17235. THREE.FontUtils.size = size;
  17236. THREE.FontUtils.divisions = curveSegments;
  17237. THREE.FontUtils.face = font;
  17238. THREE.FontUtils.weight = weight;
  17239. THREE.FontUtils.style = style;
  17240. // Get a Font data json object
  17241. var data = THREE.FontUtils.drawText( text );
  17242. var paths = data.paths;
  17243. var shapes = [];
  17244. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  17245. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  17246. }
  17247. return shapes;
  17248. };
  17249. /**
  17250. * This code is a quick port of code written in C++ which was submitted to
  17251. * flipcode.com by John W. Ratcliff // July 22, 2000
  17252. * See original code and more information here:
  17253. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  17254. *
  17255. * ported to actionscript by Zevan Rosser
  17256. * www.actionsnippet.com
  17257. *
  17258. * ported to javascript by Joshua Koo
  17259. * http://www.lab4games.net/zz85/blog
  17260. *
  17261. */
  17262. ( function( namespace ) {
  17263. var EPSILON = 0.0000000001;
  17264. // takes in an contour array and returns
  17265. var process = function( contour, indices ) {
  17266. var n = contour.length;
  17267. if ( n < 3 ) return null;
  17268. var result = [],
  17269. verts = [],
  17270. vertIndices = [];
  17271. /* we want a counter-clockwise polygon in verts */
  17272. var u, v, w;
  17273. if ( area( contour ) > 0.0 ) {
  17274. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  17275. } else {
  17276. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  17277. }
  17278. var nv = n;
  17279. /* remove nv - 2 vertices, creating 1 triangle every time */
  17280. var count = 2 * nv; /* error detection */
  17281. for( v = nv - 1; nv > 2; ) {
  17282. /* if we loop, it is probably a non-simple polygon */
  17283. if ( ( count-- ) <= 0 ) {
  17284. //** Triangulate: ERROR - probable bad polygon!
  17285. //throw ( "Warning, unable to triangulate polygon!" );
  17286. //return null;
  17287. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  17288. console.log( "Warning, unable to triangulate polygon!" );
  17289. if ( indices ) return vertIndices;
  17290. return result;
  17291. }
  17292. /* three consecutive vertices in current polygon, <u,v,w> */
  17293. u = v; if ( nv <= u ) u = 0; /* previous */
  17294. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  17295. w = v + 1; if ( nv <= w ) w = 0; /* next */
  17296. if ( snip( contour, u, v, w, nv, verts ) ) {
  17297. var a, b, c, s, t;
  17298. /* true names of the vertices */
  17299. a = verts[ u ];
  17300. b = verts[ v ];
  17301. c = verts[ w ];
  17302. /* output Triangle */
  17303. result.push( [ contour[ a ],
  17304. contour[ b ],
  17305. contour[ c ] ] );
  17306. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  17307. /* remove v from the remaining polygon */
  17308. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  17309. verts[ s ] = verts[ t ];
  17310. }
  17311. nv--;
  17312. /* reset error detection counter */
  17313. count = 2 * nv;
  17314. }
  17315. }
  17316. if ( indices ) return vertIndices;
  17317. return result;
  17318. };
  17319. // calculate area of the contour polygon
  17320. var area = function ( contour ) {
  17321. var n = contour.length;
  17322. var a = 0.0;
  17323. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  17324. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  17325. }
  17326. return a * 0.5;
  17327. };
  17328. var snip = function ( contour, u, v, w, n, verts ) {
  17329. var p;
  17330. var ax, ay, bx, by;
  17331. var cx, cy, px, py;
  17332. ax = contour[ verts[ u ] ].x;
  17333. ay = contour[ verts[ u ] ].y;
  17334. bx = contour[ verts[ v ] ].x;
  17335. by = contour[ verts[ v ] ].y;
  17336. cx = contour[ verts[ w ] ].x;
  17337. cy = contour[ verts[ w ] ].y;
  17338. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  17339. var aX, aY, bX, bY, cX, cY;
  17340. var apx, apy, bpx, bpy, cpx, cpy;
  17341. var cCROSSap, bCROSScp, aCROSSbp;
  17342. aX = cx - bx; aY = cy - by;
  17343. bX = ax - cx; bY = ay - cy;
  17344. cX = bx - ax; cY = by - ay;
  17345. for ( p = 0; p < n; p++ ) {
  17346. px = contour[ verts[ p ] ].x
  17347. py = contour[ verts[ p ] ].y
  17348. if ( ( (px === ax) && (py === ay) ) ||
  17349. ( (px === bx) && (py === by) ) ||
  17350. ( (px === cx) && (py === cy) ) ) continue;
  17351. apx = px - ax; apy = py - ay;
  17352. bpx = px - bx; bpy = py - by;
  17353. cpx = px - cx; cpy = py - cy;
  17354. // see if p is inside triangle abc
  17355. aCROSSbp = aX*bpy - aY*bpx;
  17356. cCROSSap = cX*apy - cY*apx;
  17357. bCROSScp = bX*cpy - bY*cpx;
  17358. if ( (aCROSSbp >= -EPSILON) && (bCROSScp >= -EPSILON) && (cCROSSap >= -EPSILON) ) return false;
  17359. }
  17360. return true;
  17361. };
  17362. namespace.Triangulate = process;
  17363. namespace.Triangulate.area = area;
  17364. return namespace;
  17365. })(THREE.FontUtils);
  17366. // To use the typeface.js face files, hook up the API
  17367. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  17368. THREE.typeface_js = self._typeface_js;
  17369. /**
  17370. * @author zz85 / http://www.lab4games.net/zz85/blog
  17371. * Extensible curve object
  17372. *
  17373. * Some common of Curve methods
  17374. * .getPoint(t), getTangent(t)
  17375. * .getPointAt(u), getTagentAt(u)
  17376. * .getPoints(), .getSpacedPoints()
  17377. * .getLength()
  17378. * .updateArcLengths()
  17379. *
  17380. * This following classes subclasses THREE.Curve:
  17381. *
  17382. * -- 2d classes --
  17383. * THREE.LineCurve
  17384. * THREE.QuadraticBezierCurve
  17385. * THREE.CubicBezierCurve
  17386. * THREE.SplineCurve
  17387. * THREE.ArcCurve
  17388. * THREE.EllipseCurve
  17389. *
  17390. * -- 3d classes --
  17391. * THREE.LineCurve3
  17392. * THREE.QuadraticBezierCurve3
  17393. * THREE.CubicBezierCurve3
  17394. * THREE.SplineCurve3
  17395. * THREE.ClosedSplineCurve3
  17396. *
  17397. * A series of curves can be represented as a THREE.CurvePath
  17398. *
  17399. **/
  17400. /**************************************************************
  17401. * Abstract Curve base class
  17402. **************************************************************/
  17403. THREE.Curve = function () {
  17404. };
  17405. // Virtual base class method to overwrite and implement in subclasses
  17406. // - t [0 .. 1]
  17407. THREE.Curve.prototype.getPoint = function ( t ) {
  17408. console.log( "Warning, getPoint() not implemented!" );
  17409. return null;
  17410. };
  17411. // Get point at relative position in curve according to arc length
  17412. // - u [0 .. 1]
  17413. THREE.Curve.prototype.getPointAt = function ( u ) {
  17414. var t = this.getUtoTmapping( u );
  17415. return this.getPoint( t );
  17416. };
  17417. // Get sequence of points using getPoint( t )
  17418. THREE.Curve.prototype.getPoints = function ( divisions ) {
  17419. if ( !divisions ) divisions = 5;
  17420. var d, pts = [];
  17421. for ( d = 0; d <= divisions; d ++ ) {
  17422. pts.push( this.getPoint( d / divisions ) );
  17423. }
  17424. return pts;
  17425. };
  17426. // Get sequence of points using getPointAt( u )
  17427. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  17428. if ( !divisions ) divisions = 5;
  17429. var d, pts = [];
  17430. for ( d = 0; d <= divisions; d ++ ) {
  17431. pts.push( this.getPointAt( d / divisions ) );
  17432. }
  17433. return pts;
  17434. };
  17435. // Get total curve arc length
  17436. THREE.Curve.prototype.getLength = function () {
  17437. var lengths = this.getLengths();
  17438. return lengths[ lengths.length - 1 ];
  17439. };
  17440. // Get list of cumulative segment lengths
  17441. THREE.Curve.prototype.getLengths = function ( divisions ) {
  17442. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  17443. if ( this.cacheArcLengths
  17444. && ( this.cacheArcLengths.length == divisions + 1 )
  17445. && !this.needsUpdate) {
  17446. //console.log( "cached", this.cacheArcLengths );
  17447. return this.cacheArcLengths;
  17448. }
  17449. this.needsUpdate = false;
  17450. var cache = [];
  17451. var current, last = this.getPoint( 0 );
  17452. var p, sum = 0;
  17453. cache.push( 0 );
  17454. for ( p = 1; p <= divisions; p ++ ) {
  17455. current = this.getPoint ( p / divisions );
  17456. sum += current.distanceTo( last );
  17457. cache.push( sum );
  17458. last = current;
  17459. }
  17460. this.cacheArcLengths = cache;
  17461. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  17462. };
  17463. THREE.Curve.prototype.updateArcLengths = function() {
  17464. this.needsUpdate = true;
  17465. this.getLengths();
  17466. };
  17467. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  17468. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  17469. var arcLengths = this.getLengths();
  17470. var i = 0, il = arcLengths.length;
  17471. var targetArcLength; // The targeted u distance value to get
  17472. if ( distance ) {
  17473. targetArcLength = distance;
  17474. } else {
  17475. targetArcLength = u * arcLengths[ il - 1 ];
  17476. }
  17477. //var time = Date.now();
  17478. // binary search for the index with largest value smaller than target u distance
  17479. var low = 0, high = il - 1, comparison;
  17480. while ( low <= high ) {
  17481. 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
  17482. comparison = arcLengths[ i ] - targetArcLength;
  17483. if ( comparison < 0 ) {
  17484. low = i + 1;
  17485. continue;
  17486. } else if ( comparison > 0 ) {
  17487. high = i - 1;
  17488. continue;
  17489. } else {
  17490. high = i;
  17491. break;
  17492. // DONE
  17493. }
  17494. }
  17495. i = high;
  17496. //console.log('b' , i, low, high, Date.now()- time);
  17497. if ( arcLengths[ i ] == targetArcLength ) {
  17498. var t = i / ( il - 1 );
  17499. return t;
  17500. }
  17501. // we could get finer grain at lengths, or use simple interpolatation between two points
  17502. var lengthBefore = arcLengths[ i ];
  17503. var lengthAfter = arcLengths[ i + 1 ];
  17504. var segmentLength = lengthAfter - lengthBefore;
  17505. // determine where we are between the 'before' and 'after' points
  17506. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  17507. // add that fractional amount to t
  17508. var t = ( i + segmentFraction ) / ( il -1 );
  17509. return t;
  17510. };
  17511. // Returns a unit vector tangent at t
  17512. // In case any sub curve does not implement its tangent derivation,
  17513. // 2 points a small delta apart will be used to find its gradient
  17514. // which seems to give a reasonable approximation
  17515. THREE.Curve.prototype.getTangent = function( t ) {
  17516. var delta = 0.0001;
  17517. var t1 = t - delta;
  17518. var t2 = t + delta;
  17519. // Capping in case of danger
  17520. if ( t1 < 0 ) t1 = 0;
  17521. if ( t2 > 1 ) t2 = 1;
  17522. var pt1 = this.getPoint( t1 );
  17523. var pt2 = this.getPoint( t2 );
  17524. var vec = pt2.clone().sub(pt1);
  17525. return vec.normalize();
  17526. };
  17527. THREE.Curve.prototype.getTangentAt = function ( u ) {
  17528. var t = this.getUtoTmapping( u );
  17529. return this.getTangent( t );
  17530. };
  17531. /**************************************************************
  17532. * Utils
  17533. **************************************************************/
  17534. THREE.Curve.Utils = {
  17535. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  17536. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  17537. },
  17538. // Puay Bing, thanks for helping with this derivative!
  17539. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  17540. return -3 * p0 * (1 - t) * (1 - t) +
  17541. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  17542. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  17543. 3 * t * t * p3;
  17544. },
  17545. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  17546. // To check if my formulas are correct
  17547. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  17548. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  17549. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  17550. var h11 = 3 * t * t - 2 * t; // t3 − t2
  17551. return h00 + h10 + h01 + h11;
  17552. },
  17553. // Catmull-Rom
  17554. interpolate: function( p0, p1, p2, p3, t ) {
  17555. var v0 = ( p2 - p0 ) * 0.5;
  17556. var v1 = ( p3 - p1 ) * 0.5;
  17557. var t2 = t * t;
  17558. var t3 = t * t2;
  17559. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17560. }
  17561. };
  17562. // TODO: Transformation for Curves?
  17563. /**************************************************************
  17564. * 3D Curves
  17565. **************************************************************/
  17566. // A Factory method for creating new curve subclasses
  17567. THREE.Curve.create = function ( constructor, getPointFunc ) {
  17568. constructor.prototype = Object.create( THREE.Curve.prototype );
  17569. constructor.prototype.getPoint = getPointFunc;
  17570. return constructor;
  17571. };
  17572. /**
  17573. * @author zz85 / http://www.lab4games.net/zz85/blog
  17574. *
  17575. **/
  17576. /**************************************************************
  17577. * Curved Path - a curve path is simply a array of connected
  17578. * curves, but retains the api of a curve
  17579. **************************************************************/
  17580. THREE.CurvePath = function () {
  17581. this.curves = [];
  17582. this.bends = [];
  17583. this.autoClose = false; // Automatically closes the path
  17584. };
  17585. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  17586. THREE.CurvePath.prototype.add = function ( curve ) {
  17587. this.curves.push( curve );
  17588. };
  17589. THREE.CurvePath.prototype.checkConnection = function() {
  17590. // TODO
  17591. // If the ending of curve is not connected to the starting
  17592. // or the next curve, then, this is not a real path
  17593. };
  17594. THREE.CurvePath.prototype.closePath = function() {
  17595. // TODO Test
  17596. // and verify for vector3 (needs to implement equals)
  17597. // Add a line curve if start and end of lines are not connected
  17598. var startPoint = this.curves[0].getPoint(0);
  17599. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  17600. if (!startPoint.equals(endPoint)) {
  17601. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  17602. }
  17603. };
  17604. // To get accurate point with reference to
  17605. // entire path distance at time t,
  17606. // following has to be done:
  17607. // 1. Length of each sub path have to be known
  17608. // 2. Locate and identify type of curve
  17609. // 3. Get t for the curve
  17610. // 4. Return curve.getPointAt(t')
  17611. THREE.CurvePath.prototype.getPoint = function( t ) {
  17612. var d = t * this.getLength();
  17613. var curveLengths = this.getCurveLengths();
  17614. var i = 0, diff, curve;
  17615. // To think about boundaries points.
  17616. while ( i < curveLengths.length ) {
  17617. if ( curveLengths[ i ] >= d ) {
  17618. diff = curveLengths[ i ] - d;
  17619. curve = this.curves[ i ];
  17620. var u = 1 - diff / curve.getLength();
  17621. return curve.getPointAt( u );
  17622. break;
  17623. }
  17624. i ++;
  17625. }
  17626. return null;
  17627. // loop where sum != 0, sum > d , sum+1 <d
  17628. };
  17629. /*
  17630. THREE.CurvePath.prototype.getTangent = function( t ) {
  17631. };*/
  17632. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  17633. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  17634. // getPoint() depends on getLength
  17635. THREE.CurvePath.prototype.getLength = function() {
  17636. var lens = this.getCurveLengths();
  17637. return lens[ lens.length - 1 ];
  17638. };
  17639. // Compute lengths and cache them
  17640. // We cannot overwrite getLengths() because UtoT mapping uses it.
  17641. THREE.CurvePath.prototype.getCurveLengths = function() {
  17642. // We use cache values if curves and cache array are same length
  17643. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  17644. return this.cacheLengths;
  17645. };
  17646. // Get length of subsurve
  17647. // Push sums into cached array
  17648. var lengths = [], sums = 0;
  17649. var i, il = this.curves.length;
  17650. for ( i = 0; i < il; i ++ ) {
  17651. sums += this.curves[ i ].getLength();
  17652. lengths.push( sums );
  17653. }
  17654. this.cacheLengths = lengths;
  17655. return lengths;
  17656. };
  17657. // Returns min and max coordinates
  17658. THREE.CurvePath.prototype.getBoundingBox = function () {
  17659. var points = this.getPoints();
  17660. var maxX, maxY, maxZ;
  17661. var minX, minY, minZ;
  17662. maxX = maxY = Number.NEGATIVE_INFINITY;
  17663. minX = minY = Number.POSITIVE_INFINITY;
  17664. var p, i, il, sum;
  17665. var v3 = points[0] instanceof THREE.Vector3;
  17666. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  17667. for ( i = 0, il = points.length; i < il; i ++ ) {
  17668. p = points[ i ];
  17669. if ( p.x > maxX ) maxX = p.x;
  17670. else if ( p.x < minX ) minX = p.x;
  17671. if ( p.y > maxY ) maxY = p.y;
  17672. else if ( p.y < minY ) minY = p.y;
  17673. if ( v3 ) {
  17674. if ( p.z > maxZ ) maxZ = p.z;
  17675. else if ( p.z < minZ ) minZ = p.z;
  17676. }
  17677. sum.add( p );
  17678. }
  17679. var ret = {
  17680. minX: minX,
  17681. minY: minY,
  17682. maxX: maxX,
  17683. maxY: maxY
  17684. };
  17685. if ( v3 ) {
  17686. ret.maxZ = maxZ;
  17687. ret.minZ = minZ;
  17688. }
  17689. return ret;
  17690. };
  17691. /**************************************************************
  17692. * Create Geometries Helpers
  17693. **************************************************************/
  17694. /// Generate geometry from path points (for Line or ParticleSystem objects)
  17695. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  17696. var pts = this.getPoints( divisions, true );
  17697. return this.createGeometry( pts );
  17698. };
  17699. // Generate geometry from equidistance sampling along the path
  17700. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  17701. var pts = this.getSpacedPoints( divisions, true );
  17702. return this.createGeometry( pts );
  17703. };
  17704. THREE.CurvePath.prototype.createGeometry = function( points ) {
  17705. var geometry = new THREE.Geometry();
  17706. for ( var i = 0; i < points.length; i ++ ) {
  17707. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  17708. }
  17709. return geometry;
  17710. };
  17711. /**************************************************************
  17712. * Bend / Wrap Helper Methods
  17713. **************************************************************/
  17714. // Wrap path / Bend modifiers?
  17715. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  17716. this.bends.push( bendpath );
  17717. };
  17718. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  17719. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  17720. var i, il;
  17721. if ( !bends ) {
  17722. bends = this.bends;
  17723. }
  17724. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17725. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17726. }
  17727. return oldPts;
  17728. };
  17729. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  17730. var oldPts = this.getSpacedPoints( segments );
  17731. var i, il;
  17732. if ( !bends ) {
  17733. bends = this.bends;
  17734. }
  17735. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17736. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17737. }
  17738. return oldPts;
  17739. };
  17740. // This returns getPoints() bend/wrapped around the contour of a path.
  17741. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  17742. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  17743. var bounds = this.getBoundingBox();
  17744. var i, il, p, oldX, oldY, xNorm;
  17745. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  17746. p = oldPts[ i ];
  17747. oldX = p.x;
  17748. oldY = p.y;
  17749. xNorm = oldX / bounds.maxX;
  17750. // If using actual distance, for length > path, requires line extrusions
  17751. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  17752. xNorm = path.getUtoTmapping( xNorm, oldX );
  17753. // check for out of bounds?
  17754. var pathPt = path.getPoint( xNorm );
  17755. var normal = path.getTangent( xNorm );
  17756. normal.set( -normal.y, normal.x ).multiplyScalar( oldY );
  17757. p.x = pathPt.x + normal.x;
  17758. p.y = pathPt.y + normal.y;
  17759. }
  17760. return oldPts;
  17761. };
  17762. /**
  17763. * @author alteredq / http://alteredqualia.com/
  17764. */
  17765. THREE.Gyroscope = function () {
  17766. THREE.Object3D.call( this );
  17767. };
  17768. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  17769. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  17770. this.matrixAutoUpdate && this.updateMatrix();
  17771. // update matrixWorld
  17772. if ( this.matrixWorldNeedsUpdate || force ) {
  17773. if ( this.parent ) {
  17774. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  17775. this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld );
  17776. this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject );
  17777. this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld );
  17778. } else {
  17779. this.matrixWorld.copy( this.matrix );
  17780. }
  17781. this.matrixWorldNeedsUpdate = false;
  17782. force = true;
  17783. }
  17784. // update children
  17785. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  17786. this.children[ i ].updateMatrixWorld( force );
  17787. }
  17788. };
  17789. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  17790. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  17791. THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion();
  17792. THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion();
  17793. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  17794. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  17795. /**
  17796. * @author zz85 / http://www.lab4games.net/zz85/blog
  17797. * Creates free form 2d path using series of points, lines or curves.
  17798. *
  17799. **/
  17800. THREE.Path = function ( points ) {
  17801. THREE.CurvePath.call(this);
  17802. this.actions = [];
  17803. if ( points ) {
  17804. this.fromPoints( points );
  17805. }
  17806. };
  17807. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  17808. THREE.PathActions = {
  17809. MOVE_TO: 'moveTo',
  17810. LINE_TO: 'lineTo',
  17811. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  17812. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  17813. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  17814. ARC: 'arc', // Circle
  17815. ELLIPSE: 'ellipse'
  17816. };
  17817. // TODO Clean up PATH API
  17818. // Create path using straight lines to connect all points
  17819. // - vectors: array of Vector2
  17820. THREE.Path.prototype.fromPoints = function ( vectors ) {
  17821. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  17822. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  17823. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  17824. };
  17825. };
  17826. // startPath() endPath()?
  17827. THREE.Path.prototype.moveTo = function ( x, y ) {
  17828. var args = Array.prototype.slice.call( arguments );
  17829. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  17830. };
  17831. THREE.Path.prototype.lineTo = function ( x, y ) {
  17832. var args = Array.prototype.slice.call( arguments );
  17833. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17834. var x0 = lastargs[ lastargs.length - 2 ];
  17835. var y0 = lastargs[ lastargs.length - 1 ];
  17836. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  17837. this.curves.push( curve );
  17838. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  17839. };
  17840. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  17841. var args = Array.prototype.slice.call( arguments );
  17842. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17843. var x0 = lastargs[ lastargs.length - 2 ];
  17844. var y0 = lastargs[ lastargs.length - 1 ];
  17845. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  17846. new THREE.Vector2( aCPx, aCPy ),
  17847. new THREE.Vector2( aX, aY ) );
  17848. this.curves.push( curve );
  17849. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  17850. };
  17851. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  17852. aCP2x, aCP2y,
  17853. aX, aY ) {
  17854. var args = Array.prototype.slice.call( arguments );
  17855. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17856. var x0 = lastargs[ lastargs.length - 2 ];
  17857. var y0 = lastargs[ lastargs.length - 1 ];
  17858. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  17859. new THREE.Vector2( aCP1x, aCP1y ),
  17860. new THREE.Vector2( aCP2x, aCP2y ),
  17861. new THREE.Vector2( aX, aY ) );
  17862. this.curves.push( curve );
  17863. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  17864. };
  17865. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  17866. var args = Array.prototype.slice.call( arguments );
  17867. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17868. var x0 = lastargs[ lastargs.length - 2 ];
  17869. var y0 = lastargs[ lastargs.length - 1 ];
  17870. //---
  17871. var npts = [ new THREE.Vector2( x0, y0 ) ];
  17872. Array.prototype.push.apply( npts, pts );
  17873. var curve = new THREE.SplineCurve( npts );
  17874. this.curves.push( curve );
  17875. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  17876. };
  17877. // FUTURE: Change the API or follow canvas API?
  17878. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  17879. aStartAngle, aEndAngle, aClockwise ) {
  17880. var lastargs = this.actions[ this.actions.length - 1].args;
  17881. var x0 = lastargs[ lastargs.length - 2 ];
  17882. var y0 = lastargs[ lastargs.length - 1 ];
  17883. this.absarc(aX + x0, aY + y0, aRadius,
  17884. aStartAngle, aEndAngle, aClockwise );
  17885. };
  17886. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  17887. aStartAngle, aEndAngle, aClockwise ) {
  17888. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17889. };
  17890. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  17891. aStartAngle, aEndAngle, aClockwise ) {
  17892. var lastargs = this.actions[ this.actions.length - 1].args;
  17893. var x0 = lastargs[ lastargs.length - 2 ];
  17894. var y0 = lastargs[ lastargs.length - 1 ];
  17895. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  17896. aStartAngle, aEndAngle, aClockwise );
  17897. };
  17898. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  17899. aStartAngle, aEndAngle, aClockwise ) {
  17900. var args = Array.prototype.slice.call( arguments );
  17901. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  17902. aStartAngle, aEndAngle, aClockwise );
  17903. this.curves.push( curve );
  17904. var lastPoint = curve.getPoint(1);
  17905. args.push(lastPoint.x);
  17906. args.push(lastPoint.y);
  17907. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17908. };
  17909. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17910. if ( ! divisions ) divisions = 40;
  17911. var points = [];
  17912. for ( var i = 0; i < divisions; i ++ ) {
  17913. points.push( this.getPoint( i / divisions ) );
  17914. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17915. }
  17916. // if ( closedPath ) {
  17917. //
  17918. // points.push( points[ 0 ] );
  17919. //
  17920. // }
  17921. return points;
  17922. };
  17923. /* Return an array of vectors based on contour of the path */
  17924. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17925. if (this.useSpacedPoints) {
  17926. console.log('tata');
  17927. return this.getSpacedPoints( divisions, closedPath );
  17928. }
  17929. divisions = divisions || 12;
  17930. var points = [];
  17931. var i, il, item, action, args;
  17932. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17933. laste, j,
  17934. t, tx, ty;
  17935. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17936. item = this.actions[ i ];
  17937. action = item.action;
  17938. args = item.args;
  17939. switch( action ) {
  17940. case THREE.PathActions.MOVE_TO:
  17941. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17942. break;
  17943. case THREE.PathActions.LINE_TO:
  17944. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17945. break;
  17946. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17947. cpx = args[ 2 ];
  17948. cpy = args[ 3 ];
  17949. cpx1 = args[ 0 ];
  17950. cpy1 = args[ 1 ];
  17951. if ( points.length > 0 ) {
  17952. laste = points[ points.length - 1 ];
  17953. cpx0 = laste.x;
  17954. cpy0 = laste.y;
  17955. } else {
  17956. laste = this.actions[ i - 1 ].args;
  17957. cpx0 = laste[ laste.length - 2 ];
  17958. cpy0 = laste[ laste.length - 1 ];
  17959. }
  17960. for ( j = 1; j <= divisions; j ++ ) {
  17961. t = j / divisions;
  17962. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17963. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17964. points.push( new THREE.Vector2( tx, ty ) );
  17965. }
  17966. break;
  17967. case THREE.PathActions.BEZIER_CURVE_TO:
  17968. cpx = args[ 4 ];
  17969. cpy = args[ 5 ];
  17970. cpx1 = args[ 0 ];
  17971. cpy1 = args[ 1 ];
  17972. cpx2 = args[ 2 ];
  17973. cpy2 = args[ 3 ];
  17974. if ( points.length > 0 ) {
  17975. laste = points[ points.length - 1 ];
  17976. cpx0 = laste.x;
  17977. cpy0 = laste.y;
  17978. } else {
  17979. laste = this.actions[ i - 1 ].args;
  17980. cpx0 = laste[ laste.length - 2 ];
  17981. cpy0 = laste[ laste.length - 1 ];
  17982. }
  17983. for ( j = 1; j <= divisions; j ++ ) {
  17984. t = j / divisions;
  17985. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17986. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17987. points.push( new THREE.Vector2( tx, ty ) );
  17988. }
  17989. break;
  17990. case THREE.PathActions.CSPLINE_THRU:
  17991. laste = this.actions[ i - 1 ].args;
  17992. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17993. var spts = [ last ];
  17994. var n = divisions * args[ 0 ].length;
  17995. spts = spts.concat( args[ 0 ] );
  17996. var spline = new THREE.SplineCurve( spts );
  17997. for ( j = 1; j <= n; j ++ ) {
  17998. points.push( spline.getPointAt( j / n ) ) ;
  17999. }
  18000. break;
  18001. case THREE.PathActions.ARC:
  18002. var aX = args[ 0 ], aY = args[ 1 ],
  18003. aRadius = args[ 2 ],
  18004. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  18005. aClockwise = !!args[ 5 ];
  18006. var deltaAngle = aEndAngle - aStartAngle;
  18007. var angle;
  18008. var tdivisions = divisions * 2;
  18009. for ( j = 1; j <= tdivisions; j ++ ) {
  18010. t = j / tdivisions;
  18011. if ( ! aClockwise ) {
  18012. t = 1 - t;
  18013. }
  18014. angle = aStartAngle + t * deltaAngle;
  18015. tx = aX + aRadius * Math.cos( angle );
  18016. ty = aY + aRadius * Math.sin( angle );
  18017. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  18018. points.push( new THREE.Vector2( tx, ty ) );
  18019. }
  18020. //console.log(points);
  18021. break;
  18022. case THREE.PathActions.ELLIPSE:
  18023. var aX = args[ 0 ], aY = args[ 1 ],
  18024. xRadius = args[ 2 ],
  18025. yRadius = args[ 3 ],
  18026. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  18027. aClockwise = !!args[ 6 ];
  18028. var deltaAngle = aEndAngle - aStartAngle;
  18029. var angle;
  18030. var tdivisions = divisions * 2;
  18031. for ( j = 1; j <= tdivisions; j ++ ) {
  18032. t = j / tdivisions;
  18033. if ( ! aClockwise ) {
  18034. t = 1 - t;
  18035. }
  18036. angle = aStartAngle + t * deltaAngle;
  18037. tx = aX + xRadius * Math.cos( angle );
  18038. ty = aY + yRadius * Math.sin( angle );
  18039. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  18040. points.push( new THREE.Vector2( tx, ty ) );
  18041. }
  18042. //console.log(points);
  18043. break;
  18044. } // end switch
  18045. }
  18046. // Normalize to remove the closing point by default.
  18047. var lastPoint = points[ points.length - 1];
  18048. var EPSILON = 0.0000000001;
  18049. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  18050. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  18051. points.splice( points.length - 1, 1);
  18052. if ( closedPath ) {
  18053. points.push( points[ 0 ] );
  18054. }
  18055. return points;
  18056. };
  18057. // Breaks path into shapes
  18058. THREE.Path.prototype.toShapes = function( isCCW ) {
  18059. function isPointInsidePolygon( inPt, inPolygon ) {
  18060. var EPSILON = 0.0000000001;
  18061. var polyLen = inPolygon.length;
  18062. // inPt on polygon contour => immediate success or
  18063. // toggling of inside/outside at every single! intersection point of an edge
  18064. // with the horizontal line through inPt, left of inPt
  18065. // not counting lowerY endpoints of edges and whole edges on that line
  18066. var inside = false;
  18067. for( var p = polyLen - 1, q = 0; q < polyLen; p = q++ ) {
  18068. var edgeLowPt = inPolygon[ p ];
  18069. var edgeHighPt = inPolygon[ q ];
  18070. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  18071. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  18072. if ( Math.abs(edgeDy) > EPSILON ) { // not parallel
  18073. if ( edgeDy < 0 ) {
  18074. edgeLowPt = inPolygon[ q ]; edgeDx = -edgeDx;
  18075. edgeHighPt = inPolygon[ p ]; edgeDy = -edgeDy;
  18076. }
  18077. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  18078. if ( inPt.y == edgeLowPt.y ) {
  18079. if ( inPt.x == edgeLowPt.x ) return true; // inPt is on contour ?
  18080. // continue; // no intersection or edgeLowPt => doesn't count !!!
  18081. } else {
  18082. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  18083. if ( perpEdge == 0 ) return true; // inPt is on contour ?
  18084. if ( perpEdge < 0 ) continue;
  18085. inside = !inside; // true intersection left of inPt
  18086. }
  18087. } else { // parallel or colinear
  18088. if ( inPt.y != edgeLowPt.y ) continue; // parallel
  18089. // egde lies on the same horizontal line as inPt
  18090. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  18091. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  18092. // continue;
  18093. }
  18094. }
  18095. return inside;
  18096. }
  18097. var i, il, item, action, args;
  18098. var subPaths = [], lastPath = new THREE.Path();
  18099. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  18100. item = this.actions[ i ];
  18101. args = item.args;
  18102. action = item.action;
  18103. if ( action == THREE.PathActions.MOVE_TO ) {
  18104. if ( lastPath.actions.length != 0 ) {
  18105. subPaths.push( lastPath );
  18106. lastPath = new THREE.Path();
  18107. }
  18108. }
  18109. lastPath[ action ].apply( lastPath, args );
  18110. }
  18111. if ( lastPath.actions.length != 0 ) {
  18112. subPaths.push( lastPath );
  18113. }
  18114. // console.log(subPaths);
  18115. if ( subPaths.length == 0 ) return [];
  18116. var solid, tmpPath, tmpShape, shapes = [];
  18117. if ( subPaths.length == 1) {
  18118. tmpPath = subPaths[0];
  18119. tmpShape = new THREE.Shape();
  18120. tmpShape.actions = tmpPath.actions;
  18121. tmpShape.curves = tmpPath.curves;
  18122. shapes.push( tmpShape );
  18123. return shapes;
  18124. }
  18125. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  18126. holesFirst = isCCW ? !holesFirst : holesFirst;
  18127. // console.log("Holes first", holesFirst);
  18128. var betterShapeHoles = [];
  18129. var newShapes = [];
  18130. var newShapeHoles = [];
  18131. var mainIdx = 0;
  18132. var tmpPoints;
  18133. newShapes[mainIdx] = undefined;
  18134. newShapeHoles[mainIdx] = [];
  18135. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  18136. tmpPath = subPaths[ i ];
  18137. tmpPoints = tmpPath.getPoints();
  18138. solid = THREE.Shape.Utils.isClockWise( tmpPoints );
  18139. solid = isCCW ? !solid : solid;
  18140. if ( solid ) {
  18141. if ( (! holesFirst ) && ( newShapes[mainIdx] ) ) mainIdx++;
  18142. newShapes[mainIdx] = { s: new THREE.Shape(), p: tmpPoints };
  18143. newShapes[mainIdx].s.actions = tmpPath.actions;
  18144. newShapes[mainIdx].s.curves = tmpPath.curves;
  18145. if ( holesFirst ) mainIdx++;
  18146. newShapeHoles[mainIdx] = [];
  18147. //console.log('cw', i);
  18148. } else {
  18149. newShapeHoles[mainIdx].push( { h: tmpPath, p: tmpPoints[0] } );
  18150. //console.log('ccw', i);
  18151. }
  18152. }
  18153. if ( newShapes.length > 1 ) {
  18154. var ambigious = false;
  18155. var toChange = [];
  18156. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) {
  18157. betterShapeHoles[sIdx] = [];
  18158. }
  18159. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) {
  18160. var sh = newShapes[sIdx];
  18161. var sho = newShapeHoles[sIdx];
  18162. for (var hIdx = 0; hIdx < sho.length; hIdx++ ) {
  18163. var ho = sho[hIdx];
  18164. var hole_unassigned = true;
  18165. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++ ) {
  18166. if ( isPointInsidePolygon( ho.p, newShapes[s2Idx].p ) ) {
  18167. if ( sIdx != s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  18168. if ( hole_unassigned ) {
  18169. hole_unassigned = false;
  18170. betterShapeHoles[s2Idx].push( ho );
  18171. } else {
  18172. ambigious = true;
  18173. }
  18174. }
  18175. }
  18176. if ( hole_unassigned ) { betterShapeHoles[sIdx].push( ho ); }
  18177. }
  18178. }
  18179. // console.log("ambigious: ", ambigious);
  18180. if ( toChange.length > 0 ) {
  18181. // console.log("to change: ", toChange);
  18182. if (! ambigious) newShapeHoles = betterShapeHoles;
  18183. }
  18184. }
  18185. var tmpHoles, j, jl;
  18186. for ( i = 0, il = newShapes.length; i < il; i ++ ) {
  18187. tmpShape = newShapes[i].s;
  18188. shapes.push( tmpShape );
  18189. tmpHoles = newShapeHoles[i];
  18190. for ( j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  18191. tmpShape.holes.push( tmpHoles[j].h );
  18192. }
  18193. }
  18194. //console.log("shape", shapes);
  18195. return shapes;
  18196. };
  18197. /**
  18198. * @author zz85 / http://www.lab4games.net/zz85/blog
  18199. * Defines a 2d shape plane using paths.
  18200. **/
  18201. // STEP 1 Create a path.
  18202. // STEP 2 Turn path into shape.
  18203. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  18204. // STEP 3a - Extract points from each shape, turn to vertices
  18205. // STEP 3b - Triangulate each shape, add faces.
  18206. THREE.Shape = function () {
  18207. THREE.Path.apply( this, arguments );
  18208. this.holes = [];
  18209. };
  18210. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  18211. // Convenience method to return ExtrudeGeometry
  18212. THREE.Shape.prototype.extrude = function ( options ) {
  18213. var extruded = new THREE.ExtrudeGeometry( this, options );
  18214. return extruded;
  18215. };
  18216. // Convenience method to return ShapeGeometry
  18217. THREE.Shape.prototype.makeGeometry = function ( options ) {
  18218. var geometry = new THREE.ShapeGeometry( this, options );
  18219. return geometry;
  18220. };
  18221. // Get points of holes
  18222. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  18223. var i, il = this.holes.length, holesPts = [];
  18224. for ( i = 0; i < il; i ++ ) {
  18225. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  18226. }
  18227. return holesPts;
  18228. };
  18229. // Get points of holes (spaced by regular distance)
  18230. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  18231. var i, il = this.holes.length, holesPts = [];
  18232. for ( i = 0; i < il; i ++ ) {
  18233. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  18234. }
  18235. return holesPts;
  18236. };
  18237. // Get points of shape and holes (keypoints based on segments parameter)
  18238. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  18239. return {
  18240. shape: this.getTransformedPoints( divisions ),
  18241. holes: this.getPointsHoles( divisions )
  18242. };
  18243. };
  18244. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  18245. if (this.useSpacedPoints) {
  18246. return this.extractAllSpacedPoints(divisions);
  18247. }
  18248. return this.extractAllPoints(divisions);
  18249. };
  18250. //
  18251. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  18252. //
  18253. // return {
  18254. //
  18255. // shape: this.transform( bend, divisions ),
  18256. // holes: this.getPointsHoles( divisions, bend )
  18257. //
  18258. // };
  18259. //
  18260. // };
  18261. // Get points of shape and holes (spaced by regular distance)
  18262. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  18263. return {
  18264. shape: this.getTransformedSpacedPoints( divisions ),
  18265. holes: this.getSpacedPointsHoles( divisions )
  18266. };
  18267. };
  18268. /**************************************************************
  18269. * Utils
  18270. **************************************************************/
  18271. THREE.Shape.Utils = {
  18272. triangulateShape: function ( contour, holes ) {
  18273. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  18274. // inOtherPt needs to be colinear to the inSegment
  18275. if ( inSegPt1.x != inSegPt2.x ) {
  18276. if ( inSegPt1.x < inSegPt2.x ) {
  18277. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  18278. } else {
  18279. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  18280. }
  18281. } else {
  18282. if ( inSegPt1.y < inSegPt2.y ) {
  18283. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  18284. } else {
  18285. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  18286. }
  18287. }
  18288. }
  18289. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  18290. var EPSILON = 0.0000000001;
  18291. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  18292. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  18293. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  18294. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  18295. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  18296. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  18297. if ( Math.abs(limit) > EPSILON ) { // not parallel
  18298. var perpSeg2;
  18299. if ( limit > 0 ) {
  18300. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  18301. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  18302. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  18303. } else {
  18304. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  18305. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  18306. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  18307. }
  18308. // i.e. to reduce rounding errors
  18309. // intersection at endpoint of segment#1?
  18310. if ( perpSeg2 == 0 ) {
  18311. if ( ( inExcludeAdjacentSegs ) &&
  18312. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  18313. return [ inSeg1Pt1 ];
  18314. }
  18315. if ( perpSeg2 == limit ) {
  18316. if ( ( inExcludeAdjacentSegs ) &&
  18317. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  18318. return [ inSeg1Pt2 ];
  18319. }
  18320. // intersection at endpoint of segment#2?
  18321. if ( perpSeg1 == 0 ) return [ inSeg2Pt1 ];
  18322. if ( perpSeg1 == limit ) return [ inSeg2Pt2 ];
  18323. // return real intersection point
  18324. var factorSeg1 = perpSeg2 / limit;
  18325. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  18326. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  18327. } else { // parallel or colinear
  18328. if ( ( perpSeg1 != 0 ) ||
  18329. ( seg2dy * seg1seg2dx != seg2dx * seg1seg2dy ) ) return [];
  18330. // they are collinear or degenerate
  18331. var seg1Pt = ( (seg1dx == 0) && (seg1dy == 0) ); // segment1 ist just a point?
  18332. var seg2Pt = ( (seg2dx == 0) && (seg2dy == 0) ); // segment2 ist just a point?
  18333. // both segments are points
  18334. if ( seg1Pt && seg2Pt ) {
  18335. if ( (inSeg1Pt1.x != inSeg2Pt1.x) ||
  18336. (inSeg1Pt1.y != inSeg2Pt1.y) ) return []; // they are distinct points
  18337. return [ inSeg1Pt1 ]; // they are the same point
  18338. }
  18339. // segment#1 is a single point
  18340. if ( seg1Pt ) {
  18341. if (! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  18342. return [ inSeg1Pt1 ];
  18343. }
  18344. // segment#2 is a single point
  18345. if ( seg2Pt ) {
  18346. if (! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  18347. return [ inSeg2Pt1 ];
  18348. }
  18349. // they are collinear segments, which might overlap
  18350. var seg1min, seg1max, seg1minVal, seg1maxVal;
  18351. var seg2min, seg2max, seg2minVal, seg2maxVal;
  18352. if (seg1dx != 0) { // the segments are NOT on a vertical line
  18353. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  18354. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  18355. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  18356. } else {
  18357. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  18358. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  18359. }
  18360. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  18361. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  18362. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  18363. } else {
  18364. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  18365. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  18366. }
  18367. } else { // the segments are on a vertical line
  18368. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  18369. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  18370. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  18371. } else {
  18372. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  18373. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  18374. }
  18375. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  18376. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  18377. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  18378. } else {
  18379. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  18380. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  18381. }
  18382. }
  18383. if ( seg1minVal <= seg2minVal ) {
  18384. if ( seg1maxVal < seg2minVal ) return [];
  18385. if ( seg1maxVal == seg2minVal ) {
  18386. if ( inExcludeAdjacentSegs ) return [];
  18387. return [ seg2min ];
  18388. }
  18389. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  18390. return [ seg2min, seg2max ];
  18391. } else {
  18392. if ( seg1minVal > seg2maxVal ) return [];
  18393. if ( seg1minVal == seg2maxVal ) {
  18394. if ( inExcludeAdjacentSegs ) return [];
  18395. return [ seg1min ];
  18396. }
  18397. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  18398. return [ seg1min, seg2max ];
  18399. }
  18400. }
  18401. }
  18402. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  18403. // The order of legs is important
  18404. var EPSILON = 0.0000000001;
  18405. // translation of all points, so that Vertex is at (0,0)
  18406. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  18407. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  18408. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  18409. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  18410. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  18411. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  18412. if ( Math.abs(from2toAngle) > EPSILON ) { // angle != 180 deg.
  18413. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  18414. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  18415. if ( from2toAngle > 0 ) { // main angle < 180 deg.
  18416. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  18417. } else { // main angle > 180 deg.
  18418. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  18419. }
  18420. } else { // angle == 180 deg.
  18421. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  18422. return ( from2otherAngle > 0 );
  18423. }
  18424. }
  18425. function removeHoles( contour, holes ) {
  18426. var shape = contour.concat(); // work on this shape
  18427. var hole;
  18428. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  18429. // Check if hole point lies within angle around shape point
  18430. var lastShapeIdx = shape.length - 1;
  18431. var prevShapeIdx = inShapeIdx - 1;
  18432. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  18433. var nextShapeIdx = inShapeIdx + 1;
  18434. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  18435. var insideAngle = isPointInsideAngle( shape[inShapeIdx], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[inHoleIdx] );
  18436. if (! insideAngle ) {
  18437. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  18438. return false;
  18439. }
  18440. // Check if shape point lies within angle around hole point
  18441. var lastHoleIdx = hole.length - 1;
  18442. var prevHoleIdx = inHoleIdx - 1;
  18443. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  18444. var nextHoleIdx = inHoleIdx + 1;
  18445. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  18446. insideAngle = isPointInsideAngle( hole[inHoleIdx], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[inShapeIdx] );
  18447. if (! insideAngle ) {
  18448. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  18449. return false;
  18450. }
  18451. return true;
  18452. }
  18453. function intersectsShapeEdge( inShapePt, inHolePt ) {
  18454. // checks for intersections with shape edges
  18455. var sIdx, nextIdx, intersection;
  18456. for ( sIdx = 0; sIdx < shape.length; sIdx++ ) {
  18457. nextIdx = sIdx+1; nextIdx %= shape.length;
  18458. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[sIdx], shape[nextIdx], true );
  18459. if ( intersection.length > 0 ) return true;
  18460. }
  18461. return false;
  18462. }
  18463. var indepHoles = [];
  18464. function intersectsHoleEdge( inShapePt, inHolePt ) {
  18465. // checks for intersections with hole edges
  18466. var ihIdx, chkHole,
  18467. hIdx, nextIdx, intersection;
  18468. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx++ ) {
  18469. chkHole = holes[indepHoles[ihIdx]];
  18470. for ( hIdx = 0; hIdx < chkHole.length; hIdx++ ) {
  18471. nextIdx = hIdx+1; nextIdx %= chkHole.length;
  18472. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[hIdx], chkHole[nextIdx], true );
  18473. if ( intersection.length > 0 ) return true;
  18474. }
  18475. }
  18476. return false;
  18477. }
  18478. var holeIndex, shapeIndex,
  18479. shapePt, holePt,
  18480. holeIdx, cutKey, failedCuts = [],
  18481. tmpShape1, tmpShape2,
  18482. tmpHole1, tmpHole2;
  18483. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  18484. indepHoles.push( h );
  18485. }
  18486. var minShapeIndex = 0;
  18487. var counter = indepHoles.length * 2;
  18488. while ( indepHoles.length > 0 ) {
  18489. counter --;
  18490. if ( counter < 0 ) {
  18491. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  18492. break;
  18493. }
  18494. // search for shape-vertex and hole-vertex,
  18495. // which can be connected without intersections
  18496. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex++ ) {
  18497. shapePt = shape[ shapeIndex ];
  18498. holeIndex = -1;
  18499. // search for hole which can be reached without intersections
  18500. for ( var h = 0; h < indepHoles.length; h ++ ) {
  18501. holeIdx = indepHoles[h];
  18502. // prevent multiple checks
  18503. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  18504. if ( failedCuts[cutKey] !== undefined ) continue;
  18505. hole = holes[holeIdx];
  18506. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  18507. holePt = hole[ h2 ];
  18508. if (! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  18509. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  18510. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  18511. holeIndex = h2;
  18512. indepHoles.splice(h,1);
  18513. tmpShape1 = shape.slice( 0, shapeIndex+1 );
  18514. tmpShape2 = shape.slice( shapeIndex );
  18515. tmpHole1 = hole.slice( holeIndex );
  18516. tmpHole2 = hole.slice( 0, holeIndex+1 );
  18517. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  18518. minShapeIndex = shapeIndex;
  18519. // Debug only, to show the selected cuts
  18520. // glob_CutLines.push( [ shapePt, holePt ] );
  18521. break;
  18522. }
  18523. if ( holeIndex >= 0 ) break; // hole-vertex found
  18524. failedCuts[cutKey] = true; // remember failure
  18525. }
  18526. if ( holeIndex >= 0 ) break; // hole-vertex found
  18527. }
  18528. }
  18529. return shape; /* shape with no holes */
  18530. }
  18531. var i, il, f, face,
  18532. key, index,
  18533. allPointsMap = {};
  18534. // 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.
  18535. var allpoints = contour.concat();
  18536. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  18537. Array.prototype.push.apply( allpoints, holes[h] );
  18538. }
  18539. //console.log( "allpoints",allpoints, allpoints.length );
  18540. // prepare all points map
  18541. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  18542. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  18543. if ( allPointsMap[ key ] !== undefined ) {
  18544. console.log( "Duplicate point", key );
  18545. }
  18546. allPointsMap[ key ] = i;
  18547. }
  18548. // remove holes by cutting paths to holes and adding them to the shape
  18549. var shapeWithoutHoles = removeHoles( contour, holes );
  18550. var triangles = THREE.FontUtils.Triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  18551. //console.log( "triangles",triangles, triangles.length );
  18552. // check all face vertices against all points map
  18553. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  18554. face = triangles[ i ];
  18555. for ( f = 0; f < 3; f ++ ) {
  18556. key = face[ f ].x + ":" + face[ f ].y;
  18557. index = allPointsMap[ key ];
  18558. if ( index !== undefined ) {
  18559. face[ f ] = index;
  18560. }
  18561. }
  18562. }
  18563. return triangles.concat();
  18564. },
  18565. isClockWise: function ( pts ) {
  18566. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  18567. },
  18568. // Bezier Curves formulas obtained from
  18569. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  18570. // Quad Bezier Functions
  18571. b2p0: function ( t, p ) {
  18572. var k = 1 - t;
  18573. return k * k * p;
  18574. },
  18575. b2p1: function ( t, p ) {
  18576. return 2 * ( 1 - t ) * t * p;
  18577. },
  18578. b2p2: function ( t, p ) {
  18579. return t * t * p;
  18580. },
  18581. b2: function ( t, p0, p1, p2 ) {
  18582. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  18583. },
  18584. // Cubic Bezier Functions
  18585. b3p0: function ( t, p ) {
  18586. var k = 1 - t;
  18587. return k * k * k * p;
  18588. },
  18589. b3p1: function ( t, p ) {
  18590. var k = 1 - t;
  18591. return 3 * k * k * t * p;
  18592. },
  18593. b3p2: function ( t, p ) {
  18594. var k = 1 - t;
  18595. return 3 * k * t * t * p;
  18596. },
  18597. b3p3: function ( t, p ) {
  18598. return t * t * t * p;
  18599. },
  18600. b3: function ( t, p0, p1, p2, p3 ) {
  18601. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  18602. }
  18603. };
  18604. /**************************************************************
  18605. * Line
  18606. **************************************************************/
  18607. THREE.LineCurve = function ( v1, v2 ) {
  18608. this.v1 = v1;
  18609. this.v2 = v2;
  18610. };
  18611. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  18612. THREE.LineCurve.prototype.getPoint = function ( t ) {
  18613. var point = this.v2.clone().sub(this.v1);
  18614. point.multiplyScalar( t ).add( this.v1 );
  18615. return point;
  18616. };
  18617. // Line curve is linear, so we can overwrite default getPointAt
  18618. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  18619. return this.getPoint( u );
  18620. };
  18621. THREE.LineCurve.prototype.getTangent = function( t ) {
  18622. var tangent = this.v2.clone().sub(this.v1);
  18623. return tangent.normalize();
  18624. };
  18625. /**************************************************************
  18626. * Quadratic Bezier curve
  18627. **************************************************************/
  18628. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  18629. this.v0 = v0;
  18630. this.v1 = v1;
  18631. this.v2 = v2;
  18632. };
  18633. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  18634. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  18635. var tx, ty;
  18636. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  18637. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  18638. return new THREE.Vector2( tx, ty );
  18639. };
  18640. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  18641. var tx, ty;
  18642. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  18643. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  18644. // returns unit vector
  18645. var tangent = new THREE.Vector2( tx, ty );
  18646. tangent.normalize();
  18647. return tangent;
  18648. };
  18649. /**************************************************************
  18650. * Cubic Bezier curve
  18651. **************************************************************/
  18652. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  18653. this.v0 = v0;
  18654. this.v1 = v1;
  18655. this.v2 = v2;
  18656. this.v3 = v3;
  18657. };
  18658. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  18659. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  18660. var tx, ty;
  18661. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18662. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18663. return new THREE.Vector2( tx, ty );
  18664. };
  18665. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  18666. var tx, ty;
  18667. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18668. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18669. var tangent = new THREE.Vector2( tx, ty );
  18670. tangent.normalize();
  18671. return tangent;
  18672. };
  18673. /**************************************************************
  18674. * Spline curve
  18675. **************************************************************/
  18676. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  18677. this.points = (points == undefined) ? [] : points;
  18678. };
  18679. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  18680. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  18681. var v = new THREE.Vector2();
  18682. var c = [];
  18683. var points = this.points, point, intPoint, weight;
  18684. point = ( points.length - 1 ) * t;
  18685. intPoint = Math.floor( point );
  18686. weight = point - intPoint;
  18687. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18688. c[ 1 ] = intPoint;
  18689. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  18690. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  18691. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  18692. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  18693. return v;
  18694. };
  18695. /**************************************************************
  18696. * Ellipse curve
  18697. **************************************************************/
  18698. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) {
  18699. this.aX = aX;
  18700. this.aY = aY;
  18701. this.xRadius = xRadius;
  18702. this.yRadius = yRadius;
  18703. this.aStartAngle = aStartAngle;
  18704. this.aEndAngle = aEndAngle;
  18705. this.aClockwise = aClockwise;
  18706. };
  18707. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  18708. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  18709. var angle;
  18710. var deltaAngle = this.aEndAngle - this.aStartAngle;
  18711. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  18712. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  18713. if ( this.aClockwise === true ) {
  18714. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  18715. } else {
  18716. angle = this.aStartAngle + t * deltaAngle;
  18717. }
  18718. var tx = this.aX + this.xRadius * Math.cos( angle );
  18719. var ty = this.aY + this.yRadius * Math.sin( angle );
  18720. return new THREE.Vector2( tx, ty );
  18721. };
  18722. /**************************************************************
  18723. * Arc curve
  18724. **************************************************************/
  18725. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18726. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18727. };
  18728. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  18729. /**************************************************************
  18730. * Line3D
  18731. **************************************************************/
  18732. THREE.LineCurve3 = THREE.Curve.create(
  18733. function ( v1, v2 ) {
  18734. this.v1 = v1;
  18735. this.v2 = v2;
  18736. },
  18737. function ( t ) {
  18738. var r = new THREE.Vector3();
  18739. r.subVectors( this.v2, this.v1 ); // diff
  18740. r.multiplyScalar( t );
  18741. r.add( this.v1 );
  18742. return r;
  18743. }
  18744. );
  18745. /**************************************************************
  18746. * Quadratic Bezier 3D curve
  18747. **************************************************************/
  18748. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  18749. function ( v0, v1, v2 ) {
  18750. this.v0 = v0;
  18751. this.v1 = v1;
  18752. this.v2 = v2;
  18753. },
  18754. function ( t ) {
  18755. var tx, ty, tz;
  18756. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  18757. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  18758. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  18759. return new THREE.Vector3( tx, ty, tz );
  18760. }
  18761. );
  18762. /**************************************************************
  18763. * Cubic Bezier 3D curve
  18764. **************************************************************/
  18765. THREE.CubicBezierCurve3 = THREE.Curve.create(
  18766. function ( v0, v1, v2, v3 ) {
  18767. this.v0 = v0;
  18768. this.v1 = v1;
  18769. this.v2 = v2;
  18770. this.v3 = v3;
  18771. },
  18772. function ( t ) {
  18773. var tx, ty, tz;
  18774. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18775. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18776. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  18777. return new THREE.Vector3( tx, ty, tz );
  18778. }
  18779. );
  18780. /**************************************************************
  18781. * Spline 3D curve
  18782. **************************************************************/
  18783. THREE.SplineCurve3 = THREE.Curve.create(
  18784. function ( points /* array of Vector3 */) {
  18785. this.points = (points == undefined) ? [] : points;
  18786. },
  18787. function ( t ) {
  18788. var v = new THREE.Vector3();
  18789. var c = [];
  18790. var points = this.points, point, intPoint, weight;
  18791. point = ( points.length - 1 ) * t;
  18792. intPoint = Math.floor( point );
  18793. weight = point - intPoint;
  18794. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18795. c[ 1 ] = intPoint;
  18796. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18797. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18798. var pt0 = points[ c[0] ],
  18799. pt1 = points[ c[1] ],
  18800. pt2 = points[ c[2] ],
  18801. pt3 = points[ c[3] ];
  18802. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  18803. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  18804. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  18805. return v;
  18806. }
  18807. );
  18808. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  18809. // var v = new THREE.Vector3();
  18810. // var c = [];
  18811. // var points = this.points, point, intPoint, weight;
  18812. // point = ( points.length - 1 ) * t;
  18813. // intPoint = Math.floor( point );
  18814. // weight = point - intPoint;
  18815. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18816. // c[ 1 ] = intPoint;
  18817. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18818. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18819. // var pt0 = points[ c[0] ],
  18820. // pt1 = points[ c[1] ],
  18821. // pt2 = points[ c[2] ],
  18822. // pt3 = points[ c[3] ];
  18823. // // t = weight;
  18824. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  18825. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  18826. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  18827. // return v;
  18828. // }
  18829. /**************************************************************
  18830. * Closed Spline 3D curve
  18831. **************************************************************/
  18832. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  18833. function ( points /* array of Vector3 */) {
  18834. this.points = (points == undefined) ? [] : points;
  18835. },
  18836. function ( t ) {
  18837. var v = new THREE.Vector3();
  18838. var c = [];
  18839. var points = this.points, point, intPoint, weight;
  18840. point = ( points.length - 0 ) * t;
  18841. // This needs to be from 0-length +1
  18842. intPoint = Math.floor( point );
  18843. weight = point - intPoint;
  18844. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  18845. c[ 0 ] = ( intPoint - 1 ) % points.length;
  18846. c[ 1 ] = ( intPoint ) % points.length;
  18847. c[ 2 ] = ( intPoint + 1 ) % points.length;
  18848. c[ 3 ] = ( intPoint + 2 ) % points.length;
  18849. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  18850. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  18851. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  18852. return v;
  18853. }
  18854. );
  18855. /**
  18856. * @author mikael emtinger / http://gomo.se/
  18857. */
  18858. THREE.AnimationHandler = ( function () {
  18859. var playing = [];
  18860. var library = {};
  18861. var that = {};
  18862. that.update = function ( deltaTimeMS ) {
  18863. for ( var i = 0; i < playing.length; i ++ ) {
  18864. playing[ i ].update( deltaTimeMS );
  18865. }
  18866. };
  18867. that.addToUpdate = function ( animation ) {
  18868. if ( playing.indexOf( animation ) === -1 ) {
  18869. playing.push( animation );
  18870. }
  18871. };
  18872. that.removeFromUpdate = function ( animation ) {
  18873. var index = playing.indexOf( animation );
  18874. if ( index !== -1 ) {
  18875. playing.splice( index, 1 );
  18876. }
  18877. };
  18878. that.add = function ( data ) {
  18879. if ( library[ data.name ] !== undefined ) {
  18880. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  18881. }
  18882. library[ data.name ] = data;
  18883. initData( data );
  18884. };
  18885. that.remove = function ( name ) {
  18886. if ( library[ name ] === undefined ) {
  18887. console.log( "THREE.AnimationHandler.add: Warning! " + name + " doesn't exists in library. Doing nothing." );
  18888. }
  18889. library[ name ] = undefined;
  18890. };
  18891. that.get = function ( name ) {
  18892. if ( typeof name === "string" ) {
  18893. if ( library[ name ] ) {
  18894. return library[ name ];
  18895. } else {
  18896. return null;
  18897. }
  18898. } else {
  18899. // todo: add simple tween library
  18900. }
  18901. };
  18902. that.parse = function ( root ) {
  18903. // setup hierarchy
  18904. var hierarchy = [];
  18905. if ( root instanceof THREE.SkinnedMesh ) {
  18906. for ( var b = 0; b < root.bones.length; b++ ) {
  18907. hierarchy.push( root.bones[ b ] );
  18908. }
  18909. } else {
  18910. parseRecurseHierarchy( root, hierarchy );
  18911. }
  18912. return hierarchy;
  18913. };
  18914. var parseRecurseHierarchy = function ( root, hierarchy ) {
  18915. hierarchy.push( root );
  18916. for ( var c = 0; c < root.children.length; c++ )
  18917. parseRecurseHierarchy( root.children[ c ], hierarchy );
  18918. }
  18919. var initData = function ( data ) {
  18920. if ( data.initialized === true )
  18921. return;
  18922. // loop through all keys
  18923. for ( var h = 0; h < data.hierarchy.length; h ++ ) {
  18924. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18925. // remove minus times
  18926. if ( data.hierarchy[ h ].keys[ k ].time < 0 ) {
  18927. data.hierarchy[ h ].keys[ k ].time = 0;
  18928. }
  18929. // create quaternions
  18930. if ( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  18931. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  18932. var quat = data.hierarchy[ h ].keys[ k ].rot;
  18933. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion().fromArray( quat );
  18934. }
  18935. }
  18936. // prepare morph target keys
  18937. if ( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  18938. // get all used
  18939. var usedMorphTargets = {};
  18940. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18941. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18942. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  18943. usedMorphTargets[ morphTargetName ] = -1;
  18944. }
  18945. }
  18946. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  18947. // set all used on all frames
  18948. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18949. var influences = {};
  18950. for ( var morphTargetName in usedMorphTargets ) {
  18951. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18952. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  18953. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  18954. break;
  18955. }
  18956. }
  18957. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  18958. influences[ morphTargetName ] = 0;
  18959. }
  18960. }
  18961. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  18962. }
  18963. }
  18964. // remove all keys that are on the same time
  18965. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18966. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  18967. data.hierarchy[ h ].keys.splice( k, 1 );
  18968. k --;
  18969. }
  18970. }
  18971. // set index
  18972. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18973. data.hierarchy[ h ].keys[ k ].index = k;
  18974. }
  18975. }
  18976. data.initialized = true;
  18977. };
  18978. // interpolation types
  18979. that.LINEAR = 0;
  18980. that.CATMULLROM = 1;
  18981. that.CATMULLROM_FORWARD = 2;
  18982. return that;
  18983. }() );
  18984. /**
  18985. * @author mikael emtinger / http://gomo.se/
  18986. * @author mrdoob / http://mrdoob.com/
  18987. * @author alteredq / http://alteredqualia.com/
  18988. */
  18989. THREE.Animation = function ( root, name ) {
  18990. this.root = root;
  18991. this.data = THREE.AnimationHandler.get( name );
  18992. this.hierarchy = THREE.AnimationHandler.parse( root );
  18993. this.currentTime = 0;
  18994. this.timeScale = 1;
  18995. this.isPlaying = false;
  18996. this.isPaused = true;
  18997. this.loop = true;
  18998. this.interpolationType = THREE.AnimationHandler.LINEAR;
  18999. };
  19000. THREE.Animation.prototype.play = function ( startTime ) {
  19001. this.currentTime = startTime !== undefined ? startTime : 0;
  19002. if ( this.isPlaying === false ) {
  19003. this.isPlaying = true;
  19004. this.reset();
  19005. this.update( 0 );
  19006. }
  19007. this.isPaused = false;
  19008. THREE.AnimationHandler.addToUpdate( this );
  19009. };
  19010. THREE.Animation.prototype.pause = function() {
  19011. if ( this.isPaused === true ) {
  19012. THREE.AnimationHandler.addToUpdate( this );
  19013. } else {
  19014. THREE.AnimationHandler.removeFromUpdate( this );
  19015. }
  19016. this.isPaused = !this.isPaused;
  19017. };
  19018. THREE.Animation.prototype.stop = function() {
  19019. this.isPlaying = false;
  19020. this.isPaused = false;
  19021. THREE.AnimationHandler.removeFromUpdate( this );
  19022. };
  19023. THREE.Animation.prototype.reset = function () {
  19024. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  19025. var object = this.hierarchy[ h ];
  19026. object.matrixAutoUpdate = true;
  19027. if ( object.animationCache === undefined ) {
  19028. object.animationCache = {};
  19029. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  19030. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  19031. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  19032. }
  19033. var prevKey = object.animationCache.prevKey;
  19034. var nextKey = object.animationCache.nextKey;
  19035. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  19036. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  19037. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  19038. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  19039. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  19040. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  19041. }
  19042. };
  19043. THREE.Animation.prototype.update = (function(){
  19044. var points = [];
  19045. var target = new THREE.Vector3();
  19046. // Catmull-Rom spline
  19047. var interpolateCatmullRom = function ( points, scale ) {
  19048. var c = [], v3 = [],
  19049. point, intPoint, weight, w2, w3,
  19050. pa, pb, pc, pd;
  19051. point = ( points.length - 1 ) * scale;
  19052. intPoint = Math.floor( point );
  19053. weight = point - intPoint;
  19054. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  19055. c[ 1 ] = intPoint;
  19056. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  19057. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  19058. pa = points[ c[ 0 ] ];
  19059. pb = points[ c[ 1 ] ];
  19060. pc = points[ c[ 2 ] ];
  19061. pd = points[ c[ 3 ] ];
  19062. w2 = weight * weight;
  19063. w3 = weight * w2;
  19064. v3[ 0 ] = interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  19065. v3[ 1 ] = interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  19066. v3[ 2 ] = interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  19067. return v3;
  19068. };
  19069. var interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  19070. var v0 = ( p2 - p0 ) * 0.5,
  19071. v1 = ( p3 - p1 ) * 0.5;
  19072. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  19073. };
  19074. return function ( delta ) {
  19075. if ( this.isPlaying === false ) return;
  19076. this.currentTime += delta * this.timeScale;
  19077. //
  19078. var vector;
  19079. var types = [ "pos", "rot", "scl" ];
  19080. var duration = this.data.length;
  19081. if ( this.loop === true && this.currentTime > duration ) {
  19082. this.currentTime %= duration;
  19083. this.reset();
  19084. } else if ( this.loop === false && this.currentTime > duration ) {
  19085. this.stop();
  19086. return;
  19087. }
  19088. this.currentTime = Math.min( this.currentTime, duration );
  19089. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  19090. var object = this.hierarchy[ h ];
  19091. var animationCache = object.animationCache;
  19092. // loop through pos/rot/scl
  19093. for ( var t = 0; t < 3; t ++ ) {
  19094. // get keys
  19095. var type = types[ t ];
  19096. var prevKey = animationCache.prevKey[ type ];
  19097. var nextKey = animationCache.nextKey[ type ];
  19098. if ( nextKey.time <= this.currentTime ) {
  19099. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  19100. nextKey = this.getNextKeyWith( type, h, 1 );
  19101. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  19102. prevKey = nextKey;
  19103. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  19104. }
  19105. animationCache.prevKey[ type ] = prevKey;
  19106. animationCache.nextKey[ type ] = nextKey;
  19107. }
  19108. object.matrixAutoUpdate = true;
  19109. object.matrixWorldNeedsUpdate = true;
  19110. var scale = ( this.currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  19111. var prevXYZ = prevKey[ type ];
  19112. var nextXYZ = nextKey[ type ];
  19113. if ( scale < 0 ) scale = 0;
  19114. if ( scale > 1 ) scale = 1;
  19115. // interpolate
  19116. if ( type === "pos" ) {
  19117. vector = object.position;
  19118. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  19119. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  19120. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  19121. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  19122. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  19123. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  19124. points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  19125. points[ 1 ] = prevXYZ;
  19126. points[ 2 ] = nextXYZ;
  19127. points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  19128. scale = scale * 0.33 + 0.33;
  19129. var currentPoint = interpolateCatmullRom( points, scale );
  19130. vector.x = currentPoint[ 0 ];
  19131. vector.y = currentPoint[ 1 ];
  19132. vector.z = currentPoint[ 2 ];
  19133. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  19134. var forwardPoint = interpolateCatmullRom( points, scale * 1.01 );
  19135. target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  19136. target.sub( vector );
  19137. target.y = 0;
  19138. target.normalize();
  19139. var angle = Math.atan2( target.x, target.z );
  19140. object.rotation.set( 0, angle, 0 );
  19141. }
  19142. }
  19143. } else if ( type === "rot" ) {
  19144. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  19145. } else if ( type === "scl" ) {
  19146. vector = object.scale;
  19147. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  19148. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  19149. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  19150. }
  19151. }
  19152. }
  19153. };
  19154. })();
  19155. // Get next key with
  19156. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  19157. var keys = this.data.hierarchy[ h ].keys;
  19158. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  19159. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  19160. key = key < keys.length - 1 ? key : keys.length - 1;
  19161. } else {
  19162. key = key % keys.length;
  19163. }
  19164. for ( ; key < keys.length; key++ ) {
  19165. if ( keys[ key ][ type ] !== undefined ) {
  19166. return keys[ key ];
  19167. }
  19168. }
  19169. return this.data.hierarchy[ h ].keys[ 0 ];
  19170. };
  19171. // Get previous key with
  19172. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  19173. var keys = this.data.hierarchy[ h ].keys;
  19174. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  19175. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  19176. key = key > 0 ? key : 0;
  19177. } else {
  19178. key = key >= 0 ? key : key + keys.length;
  19179. }
  19180. for ( ; key >= 0; key -- ) {
  19181. if ( keys[ key ][ type ] !== undefined ) {
  19182. return keys[ key ];
  19183. }
  19184. }
  19185. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  19186. };
  19187. /**
  19188. * @author mikael emtinger / http://gomo.se/
  19189. * @author mrdoob / http://mrdoob.com/
  19190. * @author alteredq / http://alteredqualia.com/
  19191. * @author khang duong
  19192. * @author erik kitson
  19193. */
  19194. THREE.KeyFrameAnimation = function ( root, data ) {
  19195. this.root = root;
  19196. this.data = THREE.AnimationHandler.get( data );
  19197. this.hierarchy = THREE.AnimationHandler.parse( root );
  19198. this.currentTime = 0;
  19199. this.timeScale = 0.001;
  19200. this.isPlaying = false;
  19201. this.isPaused = true;
  19202. this.loop = true;
  19203. // initialize to first keyframes
  19204. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  19205. var keys = this.data.hierarchy[h].keys,
  19206. sids = this.data.hierarchy[h].sids,
  19207. obj = this.hierarchy[h];
  19208. if ( keys.length && sids ) {
  19209. for ( var s = 0; s < sids.length; s++ ) {
  19210. var sid = sids[ s ],
  19211. next = this.getNextKeyWith( sid, h, 0 );
  19212. if ( next ) {
  19213. next.apply( sid );
  19214. }
  19215. }
  19216. obj.matrixAutoUpdate = false;
  19217. this.data.hierarchy[h].node.updateMatrix();
  19218. obj.matrixWorldNeedsUpdate = true;
  19219. }
  19220. }
  19221. };
  19222. // Play
  19223. THREE.KeyFrameAnimation.prototype.play = function ( startTime ) {
  19224. this.currentTime = startTime !== undefined ? startTime : 0;
  19225. if ( this.isPlaying === false ) {
  19226. this.isPlaying = true;
  19227. // reset key cache
  19228. var h, hl = this.hierarchy.length,
  19229. object,
  19230. node;
  19231. for ( h = 0; h < hl; h++ ) {
  19232. object = this.hierarchy[ h ];
  19233. node = this.data.hierarchy[ h ];
  19234. if ( node.animationCache === undefined ) {
  19235. node.animationCache = {};
  19236. node.animationCache.prevKey = null;
  19237. node.animationCache.nextKey = null;
  19238. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  19239. }
  19240. var keys = this.data.hierarchy[h].keys;
  19241. if (keys.length) {
  19242. node.animationCache.prevKey = keys[ 0 ];
  19243. node.animationCache.nextKey = keys[ 1 ];
  19244. this.startTime = Math.min( keys[0].time, this.startTime );
  19245. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  19246. }
  19247. }
  19248. this.update( 0 );
  19249. }
  19250. this.isPaused = false;
  19251. THREE.AnimationHandler.addToUpdate( this );
  19252. };
  19253. // Pause
  19254. THREE.KeyFrameAnimation.prototype.pause = function() {
  19255. if( this.isPaused ) {
  19256. THREE.AnimationHandler.addToUpdate( this );
  19257. } else {
  19258. THREE.AnimationHandler.removeFromUpdate( this );
  19259. }
  19260. this.isPaused = !this.isPaused;
  19261. };
  19262. // Stop
  19263. THREE.KeyFrameAnimation.prototype.stop = function() {
  19264. this.isPlaying = false;
  19265. this.isPaused = false;
  19266. THREE.AnimationHandler.removeFromUpdate( this );
  19267. // reset JIT matrix and remove cache
  19268. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  19269. var obj = this.hierarchy[ h ];
  19270. var node = this.data.hierarchy[ h ];
  19271. if ( node.animationCache !== undefined ) {
  19272. var original = node.animationCache.originalMatrix;
  19273. if( obj instanceof THREE.Bone ) {
  19274. original.copy( obj.skinMatrix );
  19275. obj.skinMatrix = original;
  19276. } else {
  19277. original.copy( obj.matrix );
  19278. obj.matrix = original;
  19279. }
  19280. delete node.animationCache;
  19281. }
  19282. }
  19283. };
  19284. // Update
  19285. THREE.KeyFrameAnimation.prototype.update = function ( delta ) {
  19286. if ( this.isPlaying === false ) return;
  19287. this.currentTime += delta * this.timeScale;
  19288. //
  19289. var duration = this.data.length;
  19290. if ( this.loop === true && this.currentTime > duration ) {
  19291. this.currentTime %= duration;
  19292. }
  19293. this.currentTime = Math.min( this.currentTime, duration );
  19294. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  19295. var object = this.hierarchy[ h ];
  19296. var node = this.data.hierarchy[ h ];
  19297. var keys = node.keys,
  19298. animationCache = node.animationCache;
  19299. if ( keys.length ) {
  19300. var prevKey = animationCache.prevKey;
  19301. var nextKey = animationCache.nextKey;
  19302. if ( nextKey.time <= this.currentTime ) {
  19303. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  19304. prevKey = nextKey;
  19305. nextKey = keys[ prevKey.index + 1 ];
  19306. }
  19307. animationCache.prevKey = prevKey;
  19308. animationCache.nextKey = nextKey;
  19309. }
  19310. if ( nextKey.time >= this.currentTime ) {
  19311. prevKey.interpolate( nextKey, this.currentTime );
  19312. } else {
  19313. prevKey.interpolate( nextKey, nextKey.time );
  19314. }
  19315. this.data.hierarchy[ h ].node.updateMatrix();
  19316. object.matrixWorldNeedsUpdate = true;
  19317. }
  19318. }
  19319. };
  19320. // Get next key with
  19321. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  19322. var keys = this.data.hierarchy[ h ].keys;
  19323. key = key % keys.length;
  19324. for ( ; key < keys.length; key++ ) {
  19325. if ( keys[ key ].hasTarget( sid ) ) {
  19326. return keys[ key ];
  19327. }
  19328. }
  19329. return keys[ 0 ];
  19330. };
  19331. // Get previous key with
  19332. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  19333. var keys = this.data.hierarchy[ h ].keys;
  19334. key = key >= 0 ? key : key + keys.length;
  19335. for ( ; key >= 0; key-- ) {
  19336. if ( keys[ key ].hasTarget( sid ) ) {
  19337. return keys[ key ];
  19338. }
  19339. }
  19340. return keys[ keys.length - 1 ];
  19341. };
  19342. /**
  19343. * @author mrdoob / http://mrdoob.com
  19344. */
  19345. THREE.MorphAnimation = function ( mesh ) {
  19346. this.mesh = mesh;
  19347. this.frames = mesh.morphTargetInfluences.length;
  19348. this.currentTime = 0;
  19349. this.duration = 1000;
  19350. this.loop = true;
  19351. this.isPlaying = false;
  19352. };
  19353. THREE.MorphAnimation.prototype = {
  19354. play: function () {
  19355. this.isPlaying = true;
  19356. },
  19357. pause: function () {
  19358. this.isPlaying = false;
  19359. },
  19360. update: ( function () {
  19361. var lastFrame = 0;
  19362. var currentFrame = 0;
  19363. return function ( delta ) {
  19364. if ( this.isPlaying === false ) return;
  19365. this.currentTime += delta;
  19366. if ( this.loop === true && this.currentTime > this.duration ) {
  19367. this.currentTime %= this.duration;
  19368. }
  19369. this.currentTime = Math.min( this.currentTime, this.duration );
  19370. var interpolation = this.duration / this.frames;
  19371. var frame = Math.floor( this.currentTime / interpolation );
  19372. if ( frame != currentFrame ) {
  19373. this.mesh.morphTargetInfluences[ lastFrame ] = 0;
  19374. this.mesh.morphTargetInfluences[ currentFrame ] = 1;
  19375. this.mesh.morphTargetInfluences[ frame ] = 0;
  19376. lastFrame = currentFrame;
  19377. currentFrame = frame;
  19378. }
  19379. this.mesh.morphTargetInfluences[ frame ] = ( this.currentTime % interpolation ) / interpolation;
  19380. this.mesh.morphTargetInfluences[ lastFrame ] = 1 - this.mesh.morphTargetInfluences[ frame ];
  19381. }
  19382. } )()
  19383. };
  19384. /**
  19385. * Camera for rendering cube maps
  19386. * - renders scene into axis-aligned cube
  19387. *
  19388. * @author alteredq / http://alteredqualia.com/
  19389. */
  19390. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  19391. THREE.Object3D.call( this );
  19392. var fov = 90, aspect = 1;
  19393. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19394. cameraPX.up.set( 0, -1, 0 );
  19395. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  19396. this.add( cameraPX );
  19397. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19398. cameraNX.up.set( 0, -1, 0 );
  19399. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  19400. this.add( cameraNX );
  19401. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19402. cameraPY.up.set( 0, 0, 1 );
  19403. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  19404. this.add( cameraPY );
  19405. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19406. cameraNY.up.set( 0, 0, -1 );
  19407. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  19408. this.add( cameraNY );
  19409. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19410. cameraPZ.up.set( 0, -1, 0 );
  19411. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  19412. this.add( cameraPZ );
  19413. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19414. cameraNZ.up.set( 0, -1, 0 );
  19415. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  19416. this.add( cameraNZ );
  19417. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  19418. this.updateCubeMap = function ( renderer, scene ) {
  19419. var renderTarget = this.renderTarget;
  19420. var generateMipmaps = renderTarget.generateMipmaps;
  19421. renderTarget.generateMipmaps = false;
  19422. renderTarget.activeCubeFace = 0;
  19423. renderer.render( scene, cameraPX, renderTarget );
  19424. renderTarget.activeCubeFace = 1;
  19425. renderer.render( scene, cameraNX, renderTarget );
  19426. renderTarget.activeCubeFace = 2;
  19427. renderer.render( scene, cameraPY, renderTarget );
  19428. renderTarget.activeCubeFace = 3;
  19429. renderer.render( scene, cameraNY, renderTarget );
  19430. renderTarget.activeCubeFace = 4;
  19431. renderer.render( scene, cameraPZ, renderTarget );
  19432. renderTarget.generateMipmaps = generateMipmaps;
  19433. renderTarget.activeCubeFace = 5;
  19434. renderer.render( scene, cameraNZ, renderTarget );
  19435. };
  19436. };
  19437. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  19438. /**
  19439. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  19440. *
  19441. * A general perpose camera, for setting FOV, Lens Focal Length,
  19442. * and switching between perspective and orthographic views easily.
  19443. * Use this only if you do not wish to manage
  19444. * both a Orthographic and Perspective Camera
  19445. *
  19446. */
  19447. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  19448. THREE.Camera.call( this );
  19449. this.fov = fov;
  19450. this.left = -width / 2;
  19451. this.right = width / 2
  19452. this.top = height / 2;
  19453. this.bottom = -height / 2;
  19454. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  19455. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  19456. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  19457. this.zoom = 1;
  19458. this.toPerspective();
  19459. var aspect = width/height;
  19460. };
  19461. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  19462. THREE.CombinedCamera.prototype.toPerspective = function () {
  19463. // Switches to the Perspective Camera
  19464. this.near = this.cameraP.near;
  19465. this.far = this.cameraP.far;
  19466. this.cameraP.fov = this.fov / this.zoom ;
  19467. this.cameraP.updateProjectionMatrix();
  19468. this.projectionMatrix = this.cameraP.projectionMatrix;
  19469. this.inPerspectiveMode = true;
  19470. this.inOrthographicMode = false;
  19471. };
  19472. THREE.CombinedCamera.prototype.toOrthographic = function () {
  19473. // Switches to the Orthographic camera estimating viewport from Perspective
  19474. var fov = this.fov;
  19475. var aspect = this.cameraP.aspect;
  19476. var near = this.cameraP.near;
  19477. var far = this.cameraP.far;
  19478. // The size that we set is the mid plane of the viewing frustum
  19479. var hyperfocus = ( near + far ) / 2;
  19480. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  19481. var planeHeight = 2 * halfHeight;
  19482. var planeWidth = planeHeight * aspect;
  19483. var halfWidth = planeWidth / 2;
  19484. halfHeight /= this.zoom;
  19485. halfWidth /= this.zoom;
  19486. this.cameraO.left = -halfWidth;
  19487. this.cameraO.right = halfWidth;
  19488. this.cameraO.top = halfHeight;
  19489. this.cameraO.bottom = -halfHeight;
  19490. // this.cameraO.left = -farHalfWidth;
  19491. // this.cameraO.right = farHalfWidth;
  19492. // this.cameraO.top = farHalfHeight;
  19493. // this.cameraO.bottom = -farHalfHeight;
  19494. // this.cameraO.left = this.left / this.zoom;
  19495. // this.cameraO.right = this.right / this.zoom;
  19496. // this.cameraO.top = this.top / this.zoom;
  19497. // this.cameraO.bottom = this.bottom / this.zoom;
  19498. this.cameraO.updateProjectionMatrix();
  19499. this.near = this.cameraO.near;
  19500. this.far = this.cameraO.far;
  19501. this.projectionMatrix = this.cameraO.projectionMatrix;
  19502. this.inPerspectiveMode = false;
  19503. this.inOrthographicMode = true;
  19504. };
  19505. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  19506. this.cameraP.aspect = width / height;
  19507. this.left = -width / 2;
  19508. this.right = width / 2
  19509. this.top = height / 2;
  19510. this.bottom = -height / 2;
  19511. };
  19512. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  19513. this.fov = fov;
  19514. if ( this.inPerspectiveMode ) {
  19515. this.toPerspective();
  19516. } else {
  19517. this.toOrthographic();
  19518. }
  19519. };
  19520. // For mantaining similar API with PerspectiveCamera
  19521. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  19522. if ( this.inPerspectiveMode ) {
  19523. this.toPerspective();
  19524. } else {
  19525. this.toPerspective();
  19526. this.toOrthographic();
  19527. }
  19528. };
  19529. /*
  19530. * Uses Focal Length (in mm) to estimate and set FOV
  19531. * 35mm (fullframe) camera is used if frame size is not specified;
  19532. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  19533. */
  19534. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  19535. if ( frameHeight === undefined ) frameHeight = 24;
  19536. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  19537. this.setFov( fov );
  19538. return fov;
  19539. };
  19540. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  19541. this.zoom = zoom;
  19542. if ( this.inPerspectiveMode ) {
  19543. this.toPerspective();
  19544. } else {
  19545. this.toOrthographic();
  19546. }
  19547. };
  19548. THREE.CombinedCamera.prototype.toFrontView = function() {
  19549. this.rotation.x = 0;
  19550. this.rotation.y = 0;
  19551. this.rotation.z = 0;
  19552. // should we be modifing the matrix instead?
  19553. this.rotationAutoUpdate = false;
  19554. };
  19555. THREE.CombinedCamera.prototype.toBackView = function() {
  19556. this.rotation.x = 0;
  19557. this.rotation.y = Math.PI;
  19558. this.rotation.z = 0;
  19559. this.rotationAutoUpdate = false;
  19560. };
  19561. THREE.CombinedCamera.prototype.toLeftView = function() {
  19562. this.rotation.x = 0;
  19563. this.rotation.y = - Math.PI / 2;
  19564. this.rotation.z = 0;
  19565. this.rotationAutoUpdate = false;
  19566. };
  19567. THREE.CombinedCamera.prototype.toRightView = function() {
  19568. this.rotation.x = 0;
  19569. this.rotation.y = Math.PI / 2;
  19570. this.rotation.z = 0;
  19571. this.rotationAutoUpdate = false;
  19572. };
  19573. THREE.CombinedCamera.prototype.toTopView = function() {
  19574. this.rotation.x = - Math.PI / 2;
  19575. this.rotation.y = 0;
  19576. this.rotation.z = 0;
  19577. this.rotationAutoUpdate = false;
  19578. };
  19579. THREE.CombinedCamera.prototype.toBottomView = function() {
  19580. this.rotation.x = Math.PI / 2;
  19581. this.rotation.y = 0;
  19582. this.rotation.z = 0;
  19583. this.rotationAutoUpdate = false;
  19584. };
  19585. /**
  19586. * @author mrdoob / http://mrdoob.com/
  19587. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  19588. */
  19589. THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  19590. THREE.Geometry.call( this );
  19591. this.parameters = {
  19592. width: width,
  19593. height: height,
  19594. depth: depth,
  19595. widthSegments: widthSegments,
  19596. heightSegments: heightSegments,
  19597. depthSegments: depthSegments
  19598. };
  19599. this.widthSegments = widthSegments || 1;
  19600. this.heightSegments = heightSegments || 1;
  19601. this.depthSegments = depthSegments || 1;
  19602. var scope = this;
  19603. var width_half = width / 2;
  19604. var height_half = height / 2;
  19605. var depth_half = depth / 2;
  19606. buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, 0 ); // px
  19607. buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, 1 ); // nx
  19608. buildPlane( 'x', 'z', 1, 1, width, depth, height_half, 2 ); // py
  19609. buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, 3 ); // ny
  19610. buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, 4 ); // pz
  19611. buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, 5 ); // nz
  19612. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  19613. var w, ix, iy,
  19614. gridX = scope.widthSegments,
  19615. gridY = scope.heightSegments,
  19616. width_half = width / 2,
  19617. height_half = height / 2,
  19618. offset = scope.vertices.length;
  19619. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  19620. w = 'z';
  19621. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  19622. w = 'y';
  19623. gridY = scope.depthSegments;
  19624. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  19625. w = 'x';
  19626. gridX = scope.depthSegments;
  19627. }
  19628. var gridX1 = gridX + 1,
  19629. gridY1 = gridY + 1,
  19630. segment_width = width / gridX,
  19631. segment_height = height / gridY,
  19632. normal = new THREE.Vector3();
  19633. normal[ w ] = depth > 0 ? 1 : - 1;
  19634. for ( iy = 0; iy < gridY1; iy ++ ) {
  19635. for ( ix = 0; ix < gridX1; ix ++ ) {
  19636. var vector = new THREE.Vector3();
  19637. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  19638. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  19639. vector[ w ] = depth;
  19640. scope.vertices.push( vector );
  19641. }
  19642. }
  19643. for ( iy = 0; iy < gridY; iy++ ) {
  19644. for ( ix = 0; ix < gridX; ix++ ) {
  19645. var a = ix + gridX1 * iy;
  19646. var b = ix + gridX1 * ( iy + 1 );
  19647. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  19648. var d = ( ix + 1 ) + gridX1 * iy;
  19649. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  19650. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  19651. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  19652. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  19653. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  19654. face.normal.copy( normal );
  19655. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19656. face.materialIndex = materialIndex;
  19657. scope.faces.push( face );
  19658. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19659. face = new THREE.Face3( b + offset, c + offset, d + offset );
  19660. face.normal.copy( normal );
  19661. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19662. face.materialIndex = materialIndex;
  19663. scope.faces.push( face );
  19664. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19665. }
  19666. }
  19667. }
  19668. this.mergeVertices();
  19669. };
  19670. THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19671. /**
  19672. * @author hughes
  19673. * @author mrdoob / http://mrdoob.com/
  19674. */
  19675. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  19676. this.parameters = {
  19677. radius: radius,
  19678. segments: segments,
  19679. thetaStart: thetaStart,
  19680. thetaLength: thetaLength
  19681. };
  19682. radius = radius || 50;
  19683. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  19684. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19685. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19686. //
  19687. var elements = segments + 2;
  19688. var indices = new Uint16Array( segments * 3 );
  19689. var vertices = new Float32Array( elements * 3 );
  19690. var normals = new Float32Array( elements * 3 );
  19691. var uvs = new Float32Array( elements * 2 );
  19692. // center
  19693. normals[ 2 ] = 1;
  19694. uvs[ 0 ] = 0.5;
  19695. uvs[ 1 ] = 0.5;
  19696. var offset = 0, offset2 = 2, offset3 = 3;
  19697. for ( var i = 0; i <= segments; i ++ ) {
  19698. var segment = thetaStart + i / segments * thetaLength;
  19699. var x = radius * Math.cos( segment );
  19700. var y = radius * Math.sin( segment );
  19701. vertices[ offset3 ] = x;
  19702. vertices[ offset3 + 1 ] = y;
  19703. normals[ offset3 + 2 ] = 1;
  19704. uvs[ offset2 ] = ( x / radius + 1 ) / 2;
  19705. uvs[ offset2 + 1 ] = ( y / radius + 1 ) / 2;
  19706. offset2 += 2;
  19707. offset3 += 3;
  19708. //
  19709. indices[ offset ] = 0;
  19710. indices[ offset + 1 ] = i + 1;
  19711. indices[ offset + 2 ] = i + 2;
  19712. offset += 3;
  19713. }
  19714. THREE.IndexedGeometry2.call( this, indices, vertices, normals, uvs );
  19715. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19716. };
  19717. THREE.CircleGeometry.prototype = Object.create( THREE.IndexedGeometry2.prototype );
  19718. // DEPRECATED
  19719. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  19720. console.warn( 'DEPRECATED: THREE.CubeGeometry is deprecated. Use THREE.BoxGeometry instead.' );
  19721. return new THREE.BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments );
  19722. };
  19723. /**
  19724. * @author mrdoob / http://mrdoob.com/
  19725. */
  19726. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
  19727. THREE.Geometry.call( this );
  19728. this.parameters = {
  19729. radiusTop: radiusTop,
  19730. radiusBottom: radiusBottom,
  19731. height: height,
  19732. radialSegments: radialSegments,
  19733. heightSegments: heightSegments,
  19734. openEnded: openEnded
  19735. };
  19736. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  19737. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  19738. height = height !== undefined ? height : 100;
  19739. radialSegments = radialSegments || 8;
  19740. heightSegments = heightSegments || 1;
  19741. openEnded = openEnded !== undefined ? openEnded : false;
  19742. var heightHalf = height / 2;
  19743. var x, y, vertices = [], uvs = [];
  19744. for ( y = 0; y <= heightSegments; y ++ ) {
  19745. var verticesRow = [];
  19746. var uvsRow = [];
  19747. var v = y / heightSegments;
  19748. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  19749. for ( x = 0; x <= radialSegments; x ++ ) {
  19750. var u = x / radialSegments;
  19751. var vertex = new THREE.Vector3();
  19752. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  19753. vertex.y = - v * height + heightHalf;
  19754. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  19755. this.vertices.push( vertex );
  19756. verticesRow.push( this.vertices.length - 1 );
  19757. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19758. }
  19759. vertices.push( verticesRow );
  19760. uvs.push( uvsRow );
  19761. }
  19762. var tanTheta = ( radiusBottom - radiusTop ) / height;
  19763. var na, nb;
  19764. for ( x = 0; x < radialSegments; x ++ ) {
  19765. if ( radiusTop !== 0 ) {
  19766. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  19767. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  19768. } else {
  19769. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  19770. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  19771. }
  19772. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  19773. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  19774. for ( y = 0; y < heightSegments; y ++ ) {
  19775. var v1 = vertices[ y ][ x ];
  19776. var v2 = vertices[ y + 1 ][ x ];
  19777. var v3 = vertices[ y + 1 ][ x + 1 ];
  19778. var v4 = vertices[ y ][ x + 1 ];
  19779. var n1 = na.clone();
  19780. var n2 = na.clone();
  19781. var n3 = nb.clone();
  19782. var n4 = nb.clone();
  19783. var uv1 = uvs[ y ][ x ].clone();
  19784. var uv2 = uvs[ y + 1 ][ x ].clone();
  19785. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  19786. var uv4 = uvs[ y ][ x + 1 ].clone();
  19787. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19788. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19789. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  19790. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  19791. }
  19792. }
  19793. // top cap
  19794. if ( openEnded === false && radiusTop > 0 ) {
  19795. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  19796. for ( x = 0; x < radialSegments; x ++ ) {
  19797. var v1 = vertices[ 0 ][ x ];
  19798. var v2 = vertices[ 0 ][ x + 1 ];
  19799. var v3 = this.vertices.length - 1;
  19800. var n1 = new THREE.Vector3( 0, 1, 0 );
  19801. var n2 = new THREE.Vector3( 0, 1, 0 );
  19802. var n3 = new THREE.Vector3( 0, 1, 0 );
  19803. var uv1 = uvs[ 0 ][ x ].clone();
  19804. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  19805. var uv3 = new THREE.Vector2( uv2.x, 0 );
  19806. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19807. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19808. }
  19809. }
  19810. // bottom cap
  19811. if ( openEnded === false && radiusBottom > 0 ) {
  19812. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  19813. for ( x = 0; x < radialSegments; x ++ ) {
  19814. var v1 = vertices[ y ][ x + 1 ];
  19815. var v2 = vertices[ y ][ x ];
  19816. var v3 = this.vertices.length - 1;
  19817. var n1 = new THREE.Vector3( 0, - 1, 0 );
  19818. var n2 = new THREE.Vector3( 0, - 1, 0 );
  19819. var n3 = new THREE.Vector3( 0, - 1, 0 );
  19820. var uv1 = uvs[ y ][ x + 1 ].clone();
  19821. var uv2 = uvs[ y ][ x ].clone();
  19822. var uv3 = new THREE.Vector2( uv2.x, 1 );
  19823. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19824. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19825. }
  19826. }
  19827. this.computeFaceNormals();
  19828. }
  19829. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19830. /**
  19831. * @author zz85 / http://www.lab4games.net/zz85/blog
  19832. *
  19833. * Creates extruded geometry from a path shape.
  19834. *
  19835. * parameters = {
  19836. *
  19837. * curveSegments: <int>, // number of points on the curves
  19838. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  19839. * amount: <int>, // Depth to extrude the shape
  19840. *
  19841. * bevelEnabled: <bool>, // turn on bevel
  19842. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19843. * bevelSize: <float>, // how far from shape outline is bevel
  19844. * bevelSegments: <int>, // number of bevel layers
  19845. *
  19846. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  19847. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  19848. *
  19849. * material: <int> // material index for front and back faces
  19850. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  19851. * uvGenerator: <Object> // object that provides UV generator functions
  19852. *
  19853. * }
  19854. **/
  19855. THREE.ExtrudeGeometry = function ( shapes, options ) {
  19856. if ( typeof( shapes ) === "undefined" ) {
  19857. shapes = [];
  19858. return;
  19859. }
  19860. THREE.Geometry.call( this );
  19861. shapes = shapes instanceof Array ? shapes : [ shapes ];
  19862. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19863. this.addShapeList( shapes, options );
  19864. this.computeFaceNormals();
  19865. // can't really use automatic vertex normals
  19866. // as then front and back sides get smoothed too
  19867. // should do separate smoothing just for sides
  19868. //this.computeVertexNormals();
  19869. //console.log( "took", ( Date.now() - startTime ) );
  19870. };
  19871. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19872. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19873. var sl = shapes.length;
  19874. for ( var s = 0; s < sl; s ++ ) {
  19875. var shape = shapes[ s ];
  19876. this.addShape( shape, options );
  19877. }
  19878. };
  19879. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  19880. var amount = options.amount !== undefined ? options.amount : 100;
  19881. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  19882. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  19883. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19884. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  19885. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19886. var steps = options.steps !== undefined ? options.steps : 1;
  19887. var extrudePath = options.extrudePath;
  19888. var extrudePts, extrudeByPath = false;
  19889. var material = options.material;
  19890. var extrudeMaterial = options.extrudeMaterial;
  19891. // Use default WorldUVGenerator if no UV generators are specified.
  19892. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  19893. var shapebb = this.shapebb;
  19894. //shapebb = shape.getBoundingBox();
  19895. var splineTube, binormal, normal, position2;
  19896. if ( extrudePath ) {
  19897. extrudePts = extrudePath.getSpacedPoints( steps );
  19898. extrudeByPath = true;
  19899. bevelEnabled = false; // bevels not supported for path extrusion
  19900. // SETUP TNB variables
  19901. // Reuse TNB from TubeGeomtry for now.
  19902. // TODO1 - have a .isClosed in spline?
  19903. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  19904. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19905. binormal = new THREE.Vector3();
  19906. normal = new THREE.Vector3();
  19907. position2 = new THREE.Vector3();
  19908. }
  19909. // Safeguards if bevels are not enabled
  19910. if ( ! bevelEnabled ) {
  19911. bevelSegments = 0;
  19912. bevelThickness = 0;
  19913. bevelSize = 0;
  19914. }
  19915. // Variables initalization
  19916. var ahole, h, hl; // looping of holes
  19917. var scope = this;
  19918. var bevelPoints = [];
  19919. var shapesOffset = this.vertices.length;
  19920. var shapePoints = shape.extractPoints( curveSegments );
  19921. var vertices = shapePoints.shape;
  19922. var holes = shapePoints.holes;
  19923. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  19924. if ( reverse ) {
  19925. vertices = vertices.reverse();
  19926. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19927. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19928. ahole = holes[ h ];
  19929. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  19930. holes[ h ] = ahole.reverse();
  19931. }
  19932. }
  19933. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  19934. }
  19935. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  19936. /* Vertices */
  19937. var contour = vertices; // vertices has all points but contour has only points of circumference
  19938. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19939. ahole = holes[ h ];
  19940. vertices = vertices.concat( ahole );
  19941. }
  19942. function scalePt2 ( pt, vec, size ) {
  19943. if ( !vec ) console.log( "die" );
  19944. return vec.clone().multiplyScalar( size ).add( pt );
  19945. }
  19946. var b, bs, t, z,
  19947. vert, vlen = vertices.length,
  19948. face, flen = faces.length,
  19949. cont, clen = contour.length;
  19950. // Find directions for point movement
  19951. var RAD_TO_DEGREES = 180 / Math.PI;
  19952. function getBevelVec( inPt, inPrev, inNext ) {
  19953. var EPSILON = 0.0000000001;
  19954. var sign = THREE.Math.sign;
  19955. // computes for inPt the corresponding point inPt' on a new contour
  19956. // shiftet by 1 unit (length of normalized vector) to the left
  19957. // if we walk along contour clockwise, this new contour is outside the old one
  19958. //
  19959. // inPt' is the intersection of the two lines parallel to the two
  19960. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19961. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  19962. // good reading for geometry algorithms (here: line-line intersection)
  19963. // http://geomalgorithms.com/a05-_intersect-1.html
  19964. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  19965. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  19966. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  19967. // check for colinear edges
  19968. var colinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19969. if ( Math.abs( colinear0 ) > EPSILON ) { // not colinear
  19970. // length of vectors for normalizing
  19971. var v_prev_len = Math.sqrt( v_prev_lensq );
  19972. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  19973. // shift adjacent points by unit vectors to the left
  19974. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  19975. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  19976. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  19977. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  19978. // scaling factor for v_prev to intersection point
  19979. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  19980. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  19981. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19982. // vector from inPt to intersection point
  19983. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  19984. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  19985. // Don't normalize!, otherwise sharp corners become ugly
  19986. // but prevent crazy spikes
  19987. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y )
  19988. if ( v_trans_lensq <= 2 ) {
  19989. return new THREE.Vector2( v_trans_x, v_trans_y );
  19990. } else {
  19991. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  19992. }
  19993. } else { // handle special case of colinear edges
  19994. var direction_eq = false; // assumes: opposite
  19995. if ( v_prev_x > EPSILON ) {
  19996. if ( v_next_x > EPSILON ) { direction_eq = true; }
  19997. } else {
  19998. if ( v_prev_x < -EPSILON ) {
  19999. if ( v_next_x < -EPSILON ) { direction_eq = true; }
  20000. } else {
  20001. if ( sign(v_prev_y) == sign(v_next_y) ) { direction_eq = true; }
  20002. }
  20003. }
  20004. if ( direction_eq ) {
  20005. // console.log("Warning: lines are a straight sequence");
  20006. v_trans_x = -v_prev_y;
  20007. v_trans_y = v_prev_x;
  20008. shrink_by = Math.sqrt( v_prev_lensq );
  20009. } else {
  20010. // console.log("Warning: lines are a straight spike");
  20011. v_trans_x = v_prev_x;
  20012. v_trans_y = v_prev_y;
  20013. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  20014. }
  20015. }
  20016. return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  20017. }
  20018. var contourMovements = [];
  20019. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  20020. if ( j === il ) j = 0;
  20021. if ( k === il ) k = 0;
  20022. // (j)---(i)---(k)
  20023. // console.log('i,j,k', i, j , k)
  20024. var pt_i = contour[ i ];
  20025. var pt_j = contour[ j ];
  20026. var pt_k = contour[ k ];
  20027. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  20028. }
  20029. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  20030. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20031. ahole = holes[ h ];
  20032. oneHoleMovements = [];
  20033. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  20034. if ( j === il ) j = 0;
  20035. if ( k === il ) k = 0;
  20036. // (j)---(i)---(k)
  20037. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  20038. }
  20039. holesMovements.push( oneHoleMovements );
  20040. verticesMovements = verticesMovements.concat( oneHoleMovements );
  20041. }
  20042. // Loop bevelSegments, 1 for the front, 1 for the back
  20043. for ( b = 0; b < bevelSegments; b ++ ) {
  20044. //for ( b = bevelSegments; b > 0; b -- ) {
  20045. t = b / bevelSegments;
  20046. z = bevelThickness * ( 1 - t );
  20047. //z = bevelThickness * t;
  20048. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  20049. //bs = bevelSize * t ; // linear
  20050. // contract shape
  20051. for ( i = 0, il = contour.length; i < il; i ++ ) {
  20052. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  20053. v( vert.x, vert.y, - z );
  20054. }
  20055. // expand holes
  20056. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  20057. ahole = holes[ h ];
  20058. oneHoleMovements = holesMovements[ h ];
  20059. for ( i = 0, il = ahole.length; i < il; i++ ) {
  20060. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  20061. v( vert.x, vert.y, -z );
  20062. }
  20063. }
  20064. }
  20065. bs = bevelSize;
  20066. // Back facing vertices
  20067. for ( i = 0; i < vlen; i ++ ) {
  20068. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  20069. if ( !extrudeByPath ) {
  20070. v( vert.x, vert.y, 0 );
  20071. } else {
  20072. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  20073. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  20074. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  20075. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  20076. v( position2.x, position2.y, position2.z );
  20077. }
  20078. }
  20079. // Add stepped vertices...
  20080. // Including front facing vertices
  20081. var s;
  20082. for ( s = 1; s <= steps; s ++ ) {
  20083. for ( i = 0; i < vlen; i ++ ) {
  20084. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  20085. if ( !extrudeByPath ) {
  20086. v( vert.x, vert.y, amount / steps * s );
  20087. } else {
  20088. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  20089. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  20090. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  20091. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  20092. v( position2.x, position2.y, position2.z );
  20093. }
  20094. }
  20095. }
  20096. // Add bevel segments planes
  20097. //for ( b = 1; b <= bevelSegments; b ++ ) {
  20098. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  20099. t = b / bevelSegments;
  20100. z = bevelThickness * ( 1 - t );
  20101. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  20102. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  20103. // contract shape
  20104. for ( i = 0, il = contour.length; i < il; i ++ ) {
  20105. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  20106. v( vert.x, vert.y, amount + z );
  20107. }
  20108. // expand holes
  20109. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20110. ahole = holes[ h ];
  20111. oneHoleMovements = holesMovements[ h ];
  20112. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  20113. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  20114. if ( !extrudeByPath ) {
  20115. v( vert.x, vert.y, amount + z );
  20116. } else {
  20117. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  20118. }
  20119. }
  20120. }
  20121. }
  20122. /* Faces */
  20123. // Top and bottom faces
  20124. buildLidFaces();
  20125. // Sides faces
  20126. buildSideFaces();
  20127. ///// Internal functions
  20128. function buildLidFaces() {
  20129. if ( bevelEnabled ) {
  20130. var layer = 0 ; // steps + 1
  20131. var offset = vlen * layer;
  20132. // Bottom faces
  20133. for ( i = 0; i < flen; i ++ ) {
  20134. face = faces[ i ];
  20135. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  20136. }
  20137. layer = steps + bevelSegments * 2;
  20138. offset = vlen * layer;
  20139. // Top faces
  20140. for ( i = 0; i < flen; i ++ ) {
  20141. face = faces[ i ];
  20142. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  20143. }
  20144. } else {
  20145. // Bottom faces
  20146. for ( i = 0; i < flen; i++ ) {
  20147. face = faces[ i ];
  20148. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  20149. }
  20150. // Top faces
  20151. for ( i = 0; i < flen; i ++ ) {
  20152. face = faces[ i ];
  20153. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  20154. }
  20155. }
  20156. }
  20157. // Create faces for the z-sides of the shape
  20158. function buildSideFaces() {
  20159. var layeroffset = 0;
  20160. sidewalls( contour, layeroffset );
  20161. layeroffset += contour.length;
  20162. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20163. ahole = holes[ h ];
  20164. sidewalls( ahole, layeroffset );
  20165. //, true
  20166. layeroffset += ahole.length;
  20167. }
  20168. }
  20169. function sidewalls( contour, layeroffset ) {
  20170. var j, k;
  20171. i = contour.length;
  20172. while ( --i >= 0 ) {
  20173. j = i;
  20174. k = i - 1;
  20175. if ( k < 0 ) k = contour.length - 1;
  20176. //console.log('b', i,j, i-1, k,vertices.length);
  20177. var s = 0, sl = steps + bevelSegments * 2;
  20178. for ( s = 0; s < sl; s ++ ) {
  20179. var slen1 = vlen * s;
  20180. var slen2 = vlen * ( s + 1 );
  20181. var a = layeroffset + j + slen1,
  20182. b = layeroffset + k + slen1,
  20183. c = layeroffset + k + slen2,
  20184. d = layeroffset + j + slen2;
  20185. f4( a, b, c, d, contour, s, sl, j, k );
  20186. }
  20187. }
  20188. }
  20189. function v( x, y, z ) {
  20190. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  20191. }
  20192. function f3( a, b, c, isBottom ) {
  20193. a += shapesOffset;
  20194. b += shapesOffset;
  20195. c += shapesOffset;
  20196. // normal, color, material
  20197. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  20198. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  20199. scope.faceVertexUvs[ 0 ].push( uvs );
  20200. }
  20201. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  20202. a += shapesOffset;
  20203. b += shapesOffset;
  20204. c += shapesOffset;
  20205. d += shapesOffset;
  20206. scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) );
  20207. scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) );
  20208. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  20209. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  20210. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  20211. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  20212. }
  20213. };
  20214. THREE.ExtrudeGeometry.WorldUVGenerator = {
  20215. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  20216. var ax = geometry.vertices[ indexA ].x,
  20217. ay = geometry.vertices[ indexA ].y,
  20218. bx = geometry.vertices[ indexB ].x,
  20219. by = geometry.vertices[ indexB ].y,
  20220. cx = geometry.vertices[ indexC ].x,
  20221. cy = geometry.vertices[ indexC ].y;
  20222. return [
  20223. new THREE.Vector2( ax, ay ),
  20224. new THREE.Vector2( bx, by ),
  20225. new THREE.Vector2( cx, cy )
  20226. ];
  20227. },
  20228. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  20229. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  20230. },
  20231. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  20232. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  20233. contourIndex1, contourIndex2 ) {
  20234. var ax = geometry.vertices[ indexA ].x,
  20235. ay = geometry.vertices[ indexA ].y,
  20236. az = geometry.vertices[ indexA ].z,
  20237. bx = geometry.vertices[ indexB ].x,
  20238. by = geometry.vertices[ indexB ].y,
  20239. bz = geometry.vertices[ indexB ].z,
  20240. cx = geometry.vertices[ indexC ].x,
  20241. cy = geometry.vertices[ indexC ].y,
  20242. cz = geometry.vertices[ indexC ].z,
  20243. dx = geometry.vertices[ indexD ].x,
  20244. dy = geometry.vertices[ indexD ].y,
  20245. dz = geometry.vertices[ indexD ].z;
  20246. if ( Math.abs( ay - by ) < 0.01 ) {
  20247. return [
  20248. new THREE.Vector2( ax, 1 - az ),
  20249. new THREE.Vector2( bx, 1 - bz ),
  20250. new THREE.Vector2( cx, 1 - cz ),
  20251. new THREE.Vector2( dx, 1 - dz )
  20252. ];
  20253. } else {
  20254. return [
  20255. new THREE.Vector2( ay, 1 - az ),
  20256. new THREE.Vector2( by, 1 - bz ),
  20257. new THREE.Vector2( cy, 1 - cz ),
  20258. new THREE.Vector2( dy, 1 - dz )
  20259. ];
  20260. }
  20261. }
  20262. };
  20263. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  20264. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  20265. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  20266. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  20267. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  20268. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  20269. /**
  20270. * @author jonobr1 / http://jonobr1.com
  20271. *
  20272. * Creates a one-sided polygonal geometry from a path shape. Similar to
  20273. * ExtrudeGeometry.
  20274. *
  20275. * parameters = {
  20276. *
  20277. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  20278. *
  20279. * material: <int> // material index for front and back faces
  20280. * uvGenerator: <Object> // object that provides UV generator functions
  20281. *
  20282. * }
  20283. **/
  20284. THREE.ShapeGeometry = function ( shapes, options ) {
  20285. THREE.Geometry.call( this );
  20286. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  20287. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  20288. this.addShapeList( shapes, options );
  20289. this.computeFaceNormals();
  20290. };
  20291. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20292. /**
  20293. * Add an array of shapes to THREE.ShapeGeometry.
  20294. */
  20295. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  20296. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  20297. this.addShape( shapes[ i ], options );
  20298. }
  20299. return this;
  20300. };
  20301. /**
  20302. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  20303. */
  20304. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  20305. if ( options === undefined ) options = {};
  20306. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  20307. var material = options.material;
  20308. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  20309. var shapebb = this.shapebb;
  20310. //
  20311. var i, l, hole, s;
  20312. var shapesOffset = this.vertices.length;
  20313. var shapePoints = shape.extractPoints( curveSegments );
  20314. var vertices = shapePoints.shape;
  20315. var holes = shapePoints.holes;
  20316. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  20317. if ( reverse ) {
  20318. vertices = vertices.reverse();
  20319. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  20320. for ( i = 0, l = holes.length; i < l; i++ ) {
  20321. hole = holes[ i ];
  20322. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  20323. holes[ i ] = hole.reverse();
  20324. }
  20325. }
  20326. reverse = false;
  20327. }
  20328. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  20329. // Vertices
  20330. var contour = vertices;
  20331. for ( i = 0, l = holes.length; i < l; i++ ) {
  20332. hole = holes[ i ];
  20333. vertices = vertices.concat( hole );
  20334. }
  20335. //
  20336. var vert, vlen = vertices.length;
  20337. var face, flen = faces.length;
  20338. var cont, clen = contour.length;
  20339. for ( i = 0; i < vlen; i++ ) {
  20340. vert = vertices[ i ];
  20341. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  20342. }
  20343. for ( i = 0; i < flen; i++ ) {
  20344. face = faces[ i ];
  20345. var a = face[ 0 ] + shapesOffset;
  20346. var b = face[ 1 ] + shapesOffset;
  20347. var c = face[ 2 ] + shapesOffset;
  20348. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  20349. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  20350. }
  20351. };
  20352. /**
  20353. * @author astrodud / http://astrodud.isgreat.org/
  20354. * @author zz85 / https://github.com/zz85
  20355. * @author bhouston / http://exocortex.com
  20356. */
  20357. // points - to create a closed torus, one must use a set of points
  20358. // like so: [ a, b, c, d, a ], see first is the same as last.
  20359. // segments - the number of circumference segments to create
  20360. // phiStart - the starting radian
  20361. // phiLength - the radian (0 to 2*PI) range of the lathed section
  20362. // 2*pi is a closed lathe, less than 2PI is a portion.
  20363. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  20364. THREE.Geometry.call( this );
  20365. segments = segments || 12;
  20366. phiStart = phiStart || 0;
  20367. phiLength = phiLength || 2 * Math.PI;
  20368. var inversePointLength = 1.0 / ( points.length - 1 );
  20369. var inverseSegments = 1.0 / segments;
  20370. for ( var i = 0, il = segments; i <= il; i ++ ) {
  20371. var phi = phiStart + i * inverseSegments * phiLength;
  20372. var c = Math.cos( phi ),
  20373. s = Math.sin( phi );
  20374. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  20375. var pt = points[ j ];
  20376. var vertex = new THREE.Vector3();
  20377. vertex.x = c * pt.x - s * pt.y;
  20378. vertex.y = s * pt.x + c * pt.y;
  20379. vertex.z = pt.z;
  20380. this.vertices.push( vertex );
  20381. }
  20382. }
  20383. var np = points.length;
  20384. for ( var i = 0, il = segments; i < il; i ++ ) {
  20385. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  20386. var base = j + np * i;
  20387. var a = base;
  20388. var b = base + np;
  20389. var c = base + 1 + np;
  20390. var d = base + 1;
  20391. var u0 = i * inverseSegments;
  20392. var v0 = j * inversePointLength;
  20393. var u1 = u0 + inverseSegments;
  20394. var v1 = v0 + inversePointLength;
  20395. this.faces.push( new THREE.Face3( a, b, d ) );
  20396. this.faceVertexUvs[ 0 ].push( [
  20397. new THREE.Vector2( u0, v0 ),
  20398. new THREE.Vector2( u1, v0 ),
  20399. new THREE.Vector2( u0, v1 )
  20400. ] );
  20401. this.faces.push( new THREE.Face3( b, c, d ) );
  20402. this.faceVertexUvs[ 0 ].push( [
  20403. new THREE.Vector2( u1, v0 ),
  20404. new THREE.Vector2( u1, v1 ),
  20405. new THREE.Vector2( u0, v1 )
  20406. ] );
  20407. }
  20408. }
  20409. this.mergeVertices();
  20410. this.computeFaceNormals();
  20411. this.computeVertexNormals();
  20412. };
  20413. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20414. /**
  20415. * @author mrdoob / http://mrdoob.com/
  20416. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  20417. */
  20418. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  20419. this.parameters = {
  20420. width: width,
  20421. height: height,
  20422. widthSegments: widthSegments,
  20423. heightSegments: heightSegments
  20424. };
  20425. var width_half = width / 2;
  20426. var height_half = height / 2;
  20427. var gridX = widthSegments || 1;
  20428. var gridY = heightSegments || 1;
  20429. var gridX1 = gridX + 1;
  20430. var gridY1 = gridY + 1;
  20431. var segment_width = width / gridX;
  20432. var segment_height = height / gridY;
  20433. var vertices = new Float32Array( gridX1 * gridY1 * 3 );
  20434. var normals = new Float32Array( gridX1 * gridY1 * 3 );
  20435. var uvs = new Float32Array( gridX1 * gridY1 * 2 );
  20436. var offset = 0;
  20437. var offset2 = 0;
  20438. for ( var iy = 0; iy < gridY1; iy ++ ) {
  20439. var y = iy * segment_height - height_half;
  20440. for ( var ix = 0; ix < gridX1; ix ++ ) {
  20441. var x = ix * segment_width - width_half;
  20442. vertices[ offset ] = x;
  20443. vertices[ offset + 1 ] = - y;
  20444. normals[ offset + 2 ] = 1;
  20445. uvs[ offset2 ] = ix / gridX;
  20446. uvs[ offset2 + 1 ] = 1 - ( iy / gridY );
  20447. offset += 3;
  20448. offset2 += 2;
  20449. }
  20450. }
  20451. offset = 0;
  20452. var indices = new ( vertices.length > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 );
  20453. for ( var iy = 0; iy < gridY; iy ++ ) {
  20454. for ( var ix = 0; ix < gridX; ix ++ ) {
  20455. var a = ix + gridX1 * iy;
  20456. var b = ix + gridX1 * ( iy + 1 );
  20457. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  20458. var d = ( ix + 1 ) + gridX1 * iy;
  20459. indices[ offset ] = a;
  20460. indices[ offset + 1 ] = b;
  20461. indices[ offset + 2 ] = d;
  20462. indices[ offset + 3 ] = b;
  20463. indices[ offset + 4 ] = c;
  20464. indices[ offset + 5 ] = d;
  20465. offset += 6;
  20466. }
  20467. }
  20468. THREE.IndexedGeometry2.call( this, indices, vertices, normals, uvs );
  20469. };
  20470. THREE.PlaneGeometry.prototype = Object.create( THREE.IndexedGeometry2.prototype );
  20471. /**
  20472. * @author Kaleb Murphy
  20473. */
  20474. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  20475. THREE.Geometry.call( this );
  20476. innerRadius = innerRadius || 0;
  20477. outerRadius = outerRadius || 50;
  20478. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  20479. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  20480. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  20481. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  20482. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  20483. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  20484. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  20485. var vertex = new THREE.Vector3();
  20486. var segment = thetaStart + o / thetaSegments * thetaLength;
  20487. vertex.x = radius * Math.cos( segment );
  20488. vertex.y = radius * Math.sin( segment );
  20489. this.vertices.push( vertex );
  20490. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  20491. }
  20492. radius += radiusStep;
  20493. }
  20494. var n = new THREE.Vector3( 0, 0, 1 );
  20495. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  20496. var thetaSegment = i * thetaSegments;
  20497. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  20498. var segment = o + thetaSegment;
  20499. var v1 = segment + i;
  20500. var v2 = segment + thetaSegments + i;
  20501. var v3 = segment + thetaSegments + 1 + i;
  20502. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  20503. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  20504. v1 = segment + i;
  20505. v2 = segment + thetaSegments + 1 + i;
  20506. v3 = segment + 1 + i;
  20507. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  20508. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  20509. }
  20510. }
  20511. this.computeFaceNormals();
  20512. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20513. };
  20514. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20515. /**
  20516. * @author mrdoob / http://mrdoob.com/
  20517. */
  20518. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  20519. THREE.Geometry.call( this );
  20520. this.parameters = {
  20521. radius: radius,
  20522. widthSegments: widthSegments,
  20523. heightSegments: heightSegments,
  20524. phiStart: phiStart,
  20525. phiLength: phiLength,
  20526. thetaStart: thetaStart,
  20527. thetaLength: thetaLength
  20528. };
  20529. radius = radius || 50;
  20530. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  20531. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  20532. phiStart = phiStart !== undefined ? phiStart : 0;
  20533. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  20534. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  20535. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  20536. var x, y, vertices = [], uvs = [];
  20537. for ( y = 0; y <= heightSegments; y ++ ) {
  20538. var verticesRow = [];
  20539. var uvsRow = [];
  20540. for ( x = 0; x <= widthSegments; x ++ ) {
  20541. var u = x / widthSegments;
  20542. var v = y / heightSegments;
  20543. var vertex = new THREE.Vector3();
  20544. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20545. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  20546. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20547. this.vertices.push( vertex );
  20548. verticesRow.push( this.vertices.length - 1 );
  20549. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  20550. }
  20551. vertices.push( verticesRow );
  20552. uvs.push( uvsRow );
  20553. }
  20554. for ( y = 0; y < heightSegments; y ++ ) {
  20555. for ( x = 0; x < widthSegments; x ++ ) {
  20556. var v1 = vertices[ y ][ x + 1 ];
  20557. var v2 = vertices[ y ][ x ];
  20558. var v3 = vertices[ y + 1 ][ x ];
  20559. var v4 = vertices[ y + 1 ][ x + 1 ];
  20560. var n1 = this.vertices[ v1 ].clone().normalize();
  20561. var n2 = this.vertices[ v2 ].clone().normalize();
  20562. var n3 = this.vertices[ v3 ].clone().normalize();
  20563. var n4 = this.vertices[ v4 ].clone().normalize();
  20564. var uv1 = uvs[ y ][ x + 1 ].clone();
  20565. var uv2 = uvs[ y ][ x ].clone();
  20566. var uv3 = uvs[ y + 1 ][ x ].clone();
  20567. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  20568. if ( Math.abs( this.vertices[ v1 ].y ) === radius ) {
  20569. uv1.x = ( uv1.x + uv2.x ) / 2;
  20570. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  20571. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  20572. } else if ( Math.abs( this.vertices[ v3 ].y ) === radius ) {
  20573. uv3.x = ( uv3.x + uv4.x ) / 2;
  20574. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  20575. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  20576. } else {
  20577. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  20578. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  20579. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  20580. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  20581. }
  20582. }
  20583. }
  20584. this.computeFaceNormals();
  20585. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20586. };
  20587. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20588. /**
  20589. * @author zz85 / http://www.lab4games.net/zz85/blog
  20590. * @author alteredq / http://alteredqualia.com/
  20591. *
  20592. * For creating 3D text geometry in three.js
  20593. *
  20594. * Text = 3D Text
  20595. *
  20596. * parameters = {
  20597. * size: <float>, // size of the text
  20598. * height: <float>, // thickness to extrude text
  20599. * curveSegments: <int>, // number of points on the curves
  20600. *
  20601. * font: <string>, // font name
  20602. * weight: <string>, // font weight (normal, bold)
  20603. * style: <string>, // font style (normal, italics)
  20604. *
  20605. * bevelEnabled: <bool>, // turn on bevel
  20606. * bevelThickness: <float>, // how deep into text bevel goes
  20607. * bevelSize: <float>, // how far from text outline is bevel
  20608. * }
  20609. *
  20610. */
  20611. /* Usage Examples
  20612. // TextGeometry wrapper
  20613. var text3d = new TextGeometry( text, options );
  20614. // Complete manner
  20615. var textShapes = THREE.FontUtils.generateShapes( text, options );
  20616. var text3d = new ExtrudeGeometry( textShapes, options );
  20617. */
  20618. THREE.TextGeometry = function ( text, parameters ) {
  20619. parameters = parameters || {};
  20620. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  20621. // translate parameters to ExtrudeGeometry API
  20622. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  20623. // defaults
  20624. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  20625. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  20626. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  20627. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  20628. };
  20629. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  20630. /**
  20631. * @author oosmoxiecode
  20632. * @author mrdoob / http://mrdoob.com/
  20633. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  20634. */
  20635. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  20636. THREE.Geometry.call( this );
  20637. this.parameters = {
  20638. radius: radius,
  20639. tube: tube,
  20640. radialSegments: radialSegments,
  20641. tubularSegments: tubularSegments,
  20642. arc: arc
  20643. };
  20644. radius = radius || 100;
  20645. tube = tube || 40;
  20646. radialSegments = radialSegments || 8;
  20647. tubularSegments = tubularSegments || 6;
  20648. arc = arc || Math.PI * 2;
  20649. var center = new THREE.Vector3(), uvs = [], normals = [];
  20650. for ( var j = 0; j <= radialSegments; j ++ ) {
  20651. for ( var i = 0; i <= tubularSegments; i ++ ) {
  20652. var u = i / tubularSegments * arc;
  20653. var v = j / radialSegments * Math.PI * 2;
  20654. center.x = radius * Math.cos( u );
  20655. center.y = radius * Math.sin( u );
  20656. var vertex = new THREE.Vector3();
  20657. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  20658. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  20659. vertex.z = tube * Math.sin( v );
  20660. this.vertices.push( vertex );
  20661. uvs.push( new THREE.Vector2( i / tubularSegments, j / radialSegments ) );
  20662. normals.push( vertex.clone().sub( center ).normalize() );
  20663. }
  20664. }
  20665. for ( var j = 1; j <= radialSegments; j ++ ) {
  20666. for ( var i = 1; i <= tubularSegments; i ++ ) {
  20667. var a = ( tubularSegments + 1 ) * j + i - 1;
  20668. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  20669. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  20670. var d = ( tubularSegments + 1 ) * j + i;
  20671. var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
  20672. this.faces.push( face );
  20673. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  20674. face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
  20675. this.faces.push( face );
  20676. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  20677. }
  20678. }
  20679. this.computeFaceNormals();
  20680. };
  20681. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20682. /**
  20683. * @author oosmoxiecode
  20684. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  20685. */
  20686. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  20687. THREE.Geometry.call( this );
  20688. this.parameters = {
  20689. radius: radius,
  20690. tube: tube,
  20691. radialSegments: radialSegments,
  20692. tubularSegments: tubularSegments,
  20693. p: p,
  20694. q: q,
  20695. heightScale: heightScale
  20696. };
  20697. radius = radius || 100;
  20698. tube = tube || 40;
  20699. radialSegments = radialSegments || 64;
  20700. tubularSegments = tubularSegments || 8;
  20701. p = p || 2;
  20702. q = q || 3;
  20703. heightScale = heightScale || 1;
  20704. var grid = new Array( radialSegments );
  20705. var tang = new THREE.Vector3();
  20706. var n = new THREE.Vector3();
  20707. var bitan = new THREE.Vector3();
  20708. for ( var i = 0; i < radialSegments; ++ i ) {
  20709. grid[ i ] = new Array( tubularSegments );
  20710. var u = i / radialSegments * 2 * p * Math.PI;
  20711. var p1 = getPos( u, q, p, radius, heightScale );
  20712. var p2 = getPos( u + 0.01, q, p, radius, heightScale );
  20713. tang.subVectors( p2, p1 );
  20714. n.addVectors( p2, p1 );
  20715. bitan.crossVectors( tang, n );
  20716. n.crossVectors( bitan, tang );
  20717. bitan.normalize();
  20718. n.normalize();
  20719. for ( var j = 0; j < tubularSegments; ++ j ) {
  20720. var v = j / tubularSegments * 2 * Math.PI;
  20721. var cx = - tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20722. var cy = tube * Math.sin( v );
  20723. var pos = new THREE.Vector3();
  20724. pos.x = p1.x + cx * n.x + cy * bitan.x;
  20725. pos.y = p1.y + cx * n.y + cy * bitan.y;
  20726. pos.z = p1.z + cx * n.z + cy * bitan.z;
  20727. grid[ i ][ j ] = this.vertices.push( pos ) - 1;
  20728. }
  20729. }
  20730. for ( var i = 0; i < radialSegments; ++ i ) {
  20731. for ( var j = 0; j < tubularSegments; ++ j ) {
  20732. var ip = ( i + 1 ) % radialSegments;
  20733. var jp = ( j + 1 ) % tubularSegments;
  20734. var a = grid[ i ][ j ];
  20735. var b = grid[ ip ][ j ];
  20736. var c = grid[ ip ][ jp ];
  20737. var d = grid[ i ][ jp ];
  20738. var uva = new THREE.Vector2( i / radialSegments, j / tubularSegments );
  20739. var uvb = new THREE.Vector2( ( i + 1 ) / radialSegments, j / tubularSegments );
  20740. var uvc = new THREE.Vector2( ( i + 1 ) / radialSegments, ( j + 1 ) / tubularSegments );
  20741. var uvd = new THREE.Vector2( i / radialSegments, ( j + 1 ) / tubularSegments );
  20742. this.faces.push( new THREE.Face3( a, b, d ) );
  20743. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  20744. this.faces.push( new THREE.Face3( b, c, d ) );
  20745. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  20746. }
  20747. }
  20748. this.computeFaceNormals();
  20749. this.computeVertexNormals();
  20750. function getPos( u, in_q, in_p, radius, heightScale ) {
  20751. var cu = Math.cos( u );
  20752. var su = Math.sin( u );
  20753. var quOverP = in_q / in_p * u;
  20754. var cs = Math.cos( quOverP );
  20755. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  20756. var ty = radius * ( 2 + cs ) * su * 0.5;
  20757. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  20758. return new THREE.Vector3( tx, ty, tz );
  20759. }
  20760. };
  20761. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20762. /**
  20763. * @author WestLangley / https://github.com/WestLangley
  20764. * @author zz85 / https://github.com/zz85
  20765. * @author miningold / https://github.com/miningold
  20766. *
  20767. * Modified from the TorusKnotGeometry by @oosmoxiecode
  20768. *
  20769. * Creates a tube which extrudes along a 3d spline
  20770. *
  20771. * Uses parallel transport frames as described in
  20772. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20773. */
  20774. THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed ) {
  20775. THREE.Geometry.call( this );
  20776. this.parameters = {
  20777. path: path,
  20778. segments: segments,
  20779. radius: radius,
  20780. radialSegments: radialSegments,
  20781. closed: closed
  20782. };
  20783. segments = segments || 64;
  20784. radius = radius || 1;
  20785. radialSegments = radialSegments || 8;
  20786. closed = closed || false;
  20787. var grid = [];
  20788. var scope = this,
  20789. tangent,
  20790. normal,
  20791. binormal,
  20792. numpoints = segments + 1,
  20793. x, y, z,
  20794. tx, ty, tz,
  20795. u, v,
  20796. cx, cy,
  20797. pos, pos2 = new THREE.Vector3(),
  20798. i, j,
  20799. ip, jp,
  20800. a, b, c, d,
  20801. uva, uvb, uvc, uvd;
  20802. var frames = new THREE.TubeGeometry.FrenetFrames( path, segments, closed ),
  20803. tangents = frames.tangents,
  20804. normals = frames.normals,
  20805. binormals = frames.binormals;
  20806. // proxy internals
  20807. this.tangents = tangents;
  20808. this.normals = normals;
  20809. this.binormals = binormals;
  20810. function vert( x, y, z ) {
  20811. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  20812. }
  20813. // consruct the grid
  20814. for ( i = 0; i < numpoints; i++ ) {
  20815. grid[ i ] = [];
  20816. u = i / ( numpoints - 1 );
  20817. pos = path.getPointAt( u );
  20818. tangent = tangents[ i ];
  20819. normal = normals[ i ];
  20820. binormal = binormals[ i ];
  20821. for ( j = 0; j < radialSegments; j++ ) {
  20822. v = j / radialSegments * 2 * Math.PI;
  20823. cx = -radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20824. cy = radius * Math.sin( v );
  20825. pos2.copy( pos );
  20826. pos2.x += cx * normal.x + cy * binormal.x;
  20827. pos2.y += cx * normal.y + cy * binormal.y;
  20828. pos2.z += cx * normal.z + cy * binormal.z;
  20829. grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  20830. }
  20831. }
  20832. // construct the mesh
  20833. for ( i = 0; i < segments; i++ ) {
  20834. for ( j = 0; j < radialSegments; j++ ) {
  20835. ip = ( closed ) ? (i + 1) % segments : i + 1;
  20836. jp = (j + 1) % radialSegments;
  20837. a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  20838. b = grid[ ip ][ j ];
  20839. c = grid[ ip ][ jp ];
  20840. d = grid[ i ][ jp ];
  20841. uva = new THREE.Vector2( i / segments, j / radialSegments );
  20842. uvb = new THREE.Vector2( ( i + 1 ) / segments, j / radialSegments );
  20843. uvc = new THREE.Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments );
  20844. uvd = new THREE.Vector2( i / segments, ( j + 1 ) / radialSegments );
  20845. this.faces.push( new THREE.Face3( a, b, d ) );
  20846. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  20847. this.faces.push( new THREE.Face3( b, c, d ) );
  20848. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  20849. }
  20850. }
  20851. this.computeFaceNormals();
  20852. this.computeVertexNormals();
  20853. };
  20854. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20855. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  20856. THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) {
  20857. var tangent = new THREE.Vector3(),
  20858. normal = new THREE.Vector3(),
  20859. binormal = new THREE.Vector3(),
  20860. tangents = [],
  20861. normals = [],
  20862. binormals = [],
  20863. vec = new THREE.Vector3(),
  20864. mat = new THREE.Matrix4(),
  20865. numpoints = segments + 1,
  20866. theta,
  20867. epsilon = 0.0001,
  20868. smallest,
  20869. tx, ty, tz,
  20870. i, u, v;
  20871. // expose internals
  20872. this.tangents = tangents;
  20873. this.normals = normals;
  20874. this.binormals = binormals;
  20875. // compute the tangent vectors for each segment on the path
  20876. for ( i = 0; i < numpoints; i++ ) {
  20877. u = i / ( numpoints - 1 );
  20878. tangents[ i ] = path.getTangentAt( u );
  20879. tangents[ i ].normalize();
  20880. }
  20881. initialNormal3();
  20882. function initialNormal1(lastBinormal) {
  20883. // fixed start binormal. Has dangers of 0 vectors
  20884. normals[ 0 ] = new THREE.Vector3();
  20885. binormals[ 0 ] = new THREE.Vector3();
  20886. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  20887. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  20888. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20889. }
  20890. function initialNormal2() {
  20891. // This uses the Frenet-Serret formula for deriving binormal
  20892. var t2 = path.getTangentAt( epsilon );
  20893. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  20894. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  20895. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  20896. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20897. }
  20898. function initialNormal3() {
  20899. // select an initial normal vector perpenicular to the first tangent vector,
  20900. // and in the direction of the smallest tangent xyz component
  20901. normals[ 0 ] = new THREE.Vector3();
  20902. binormals[ 0 ] = new THREE.Vector3();
  20903. smallest = Number.MAX_VALUE;
  20904. tx = Math.abs( tangents[ 0 ].x );
  20905. ty = Math.abs( tangents[ 0 ].y );
  20906. tz = Math.abs( tangents[ 0 ].z );
  20907. if ( tx <= smallest ) {
  20908. smallest = tx;
  20909. normal.set( 1, 0, 0 );
  20910. }
  20911. if ( ty <= smallest ) {
  20912. smallest = ty;
  20913. normal.set( 0, 1, 0 );
  20914. }
  20915. if ( tz <= smallest ) {
  20916. normal.set( 0, 0, 1 );
  20917. }
  20918. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20919. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20920. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20921. }
  20922. // compute the slowly-varying normal and binormal vectors for each segment on the path
  20923. for ( i = 1; i < numpoints; i++ ) {
  20924. normals[ i ] = normals[ i-1 ].clone();
  20925. binormals[ i ] = binormals[ i-1 ].clone();
  20926. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  20927. if ( vec.length() > epsilon ) {
  20928. vec.normalize();
  20929. theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  20930. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20931. }
  20932. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20933. }
  20934. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20935. if ( closed ) {
  20936. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), -1, 1 ) );
  20937. theta /= ( numpoints - 1 );
  20938. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  20939. theta = -theta;
  20940. }
  20941. for ( i = 1; i < numpoints; i++ ) {
  20942. // twist a little...
  20943. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20944. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20945. }
  20946. }
  20947. };
  20948. /**
  20949. * @author clockworkgeek / https://github.com/clockworkgeek
  20950. * @author timothypratley / https://github.com/timothypratley
  20951. * @author WestLangley / http://github.com/WestLangley
  20952. */
  20953. THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) {
  20954. THREE.Geometry.call( this );
  20955. radius = radius || 1;
  20956. detail = detail || 0;
  20957. var that = this;
  20958. for ( var i = 0, l = vertices.length; i < l; i += 3 ) {
  20959. prepare( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  20960. }
  20961. var midpoints = [], p = this.vertices;
  20962. var faces = [];
  20963. for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) {
  20964. var v1 = p[ indices[ i ] ];
  20965. var v2 = p[ indices[ i + 1 ] ];
  20966. var v3 = p[ indices[ i + 2 ] ];
  20967. faces[ j ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20968. }
  20969. var centroid = new THREE.Vector3();
  20970. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20971. subdivide( faces[ i ], detail );
  20972. }
  20973. // Handle case when face straddles the seam
  20974. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  20975. var uvs = this.faceVertexUvs[ 0 ][ i ];
  20976. var x0 = uvs[ 0 ].x;
  20977. var x1 = uvs[ 1 ].x;
  20978. var x2 = uvs[ 2 ].x;
  20979. var max = Math.max( x0, Math.max( x1, x2 ) );
  20980. var min = Math.min( x0, Math.min( x1, x2 ) );
  20981. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  20982. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  20983. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  20984. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  20985. }
  20986. }
  20987. // Apply radius
  20988. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  20989. this.vertices[ i ].multiplyScalar( radius );
  20990. }
  20991. // Merge vertices
  20992. this.mergeVertices();
  20993. this.computeFaceNormals();
  20994. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20995. // Project vector onto sphere's surface
  20996. function prepare( vector ) {
  20997. var vertex = vector.normalize().clone();
  20998. vertex.index = that.vertices.push( vertex ) - 1;
  20999. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  21000. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  21001. var v = inclination( vector ) / Math.PI + 0.5;
  21002. vertex.uv = new THREE.Vector2( u, 1 - v );
  21003. return vertex;
  21004. }
  21005. // Approximate a curved face with recursively sub-divided triangles.
  21006. function make( v1, v2, v3 ) {
  21007. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  21008. that.faces.push( face );
  21009. centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  21010. var azi = azimuth( centroid );
  21011. that.faceVertexUvs[ 0 ].push( [
  21012. correctUV( v1.uv, v1, azi ),
  21013. correctUV( v2.uv, v2, azi ),
  21014. correctUV( v3.uv, v3, azi )
  21015. ] );
  21016. }
  21017. // Analytically subdivide a face to the required detail level.
  21018. function subdivide( face, detail ) {
  21019. var cols = Math.pow(2, detail);
  21020. var cells = Math.pow(4, detail);
  21021. var a = prepare( that.vertices[ face.a ] );
  21022. var b = prepare( that.vertices[ face.b ] );
  21023. var c = prepare( that.vertices[ face.c ] );
  21024. var v = [];
  21025. // Construct all of the vertices for this subdivision.
  21026. for ( var i = 0 ; i <= cols; i ++ ) {
  21027. v[ i ] = [];
  21028. var aj = prepare( a.clone().lerp( c, i / cols ) );
  21029. var bj = prepare( b.clone().lerp( c, i / cols ) );
  21030. var rows = cols - i;
  21031. for ( var j = 0; j <= rows; j ++) {
  21032. if ( j == 0 && i == cols ) {
  21033. v[ i ][ j ] = aj;
  21034. } else {
  21035. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  21036. }
  21037. }
  21038. }
  21039. // Construct all of the faces.
  21040. for ( var i = 0; i < cols ; i ++ ) {
  21041. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  21042. var k = Math.floor( j / 2 );
  21043. if ( j % 2 == 0 ) {
  21044. make(
  21045. v[ i ][ k + 1],
  21046. v[ i + 1 ][ k ],
  21047. v[ i ][ k ]
  21048. );
  21049. } else {
  21050. make(
  21051. v[ i ][ k + 1 ],
  21052. v[ i + 1][ k + 1],
  21053. v[ i + 1 ][ k ]
  21054. );
  21055. }
  21056. }
  21057. }
  21058. }
  21059. // Angle around the Y axis, counter-clockwise when looking from above.
  21060. function azimuth( vector ) {
  21061. return Math.atan2( vector.z, -vector.x );
  21062. }
  21063. // Angle above the XZ plane.
  21064. function inclination( vector ) {
  21065. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  21066. }
  21067. // Texture fixing helper. Spheres have some odd behaviours.
  21068. function correctUV( uv, vector, azimuth ) {
  21069. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  21070. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  21071. return uv.clone();
  21072. }
  21073. };
  21074. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21075. /**
  21076. * @author timothypratley / https://github.com/timothypratley
  21077. */
  21078. THREE.IcosahedronGeometry = function ( radius, detail ) {
  21079. this.parameters = {
  21080. radius: radius,
  21081. detail: detail
  21082. };
  21083. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21084. var vertices = [
  21085. -1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  21086. 0, -1, t, 0, 1, t, 0, -1, -t, 0, 1, -t,
  21087. t, 0, -1, t, 0, 1, -t, 0, -1, -t, 0, 1
  21088. ];
  21089. var indices = [
  21090. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  21091. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  21092. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  21093. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  21094. ];
  21095. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  21096. };
  21097. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21098. /**
  21099. * @author timothypratley / https://github.com/timothypratley
  21100. */
  21101. THREE.OctahedronGeometry = function ( radius, detail ) {
  21102. this.parameters = {
  21103. radius: radius,
  21104. detail: detail
  21105. };
  21106. var vertices = [
  21107. 1, 0, 0, -1, 0, 0, 0, 1, 0, 0,-1, 0, 0, 0, 1, 0, 0,-1
  21108. ];
  21109. var indices = [
  21110. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  21111. ];
  21112. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  21113. };
  21114. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21115. /**
  21116. * @author timothypratley / https://github.com/timothypratley
  21117. */
  21118. THREE.TetrahedronGeometry = function ( radius, detail ) {
  21119. var vertices = [
  21120. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  21121. ];
  21122. var indices = [
  21123. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  21124. ];
  21125. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  21126. };
  21127. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21128. /**
  21129. * @author zz85 / https://github.com/zz85
  21130. * Parametric Surfaces Geometry
  21131. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  21132. *
  21133. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  21134. *
  21135. */
  21136. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  21137. THREE.Geometry.call( this );
  21138. var verts = this.vertices;
  21139. var faces = this.faces;
  21140. var uvs = this.faceVertexUvs[ 0 ];
  21141. var i, il, j, p;
  21142. var u, v;
  21143. var stackCount = stacks + 1;
  21144. var sliceCount = slices + 1;
  21145. for ( i = 0; i <= stacks; i ++ ) {
  21146. v = i / stacks;
  21147. for ( j = 0; j <= slices; j ++ ) {
  21148. u = j / slices;
  21149. p = func( u, v );
  21150. verts.push( p );
  21151. }
  21152. }
  21153. var a, b, c, d;
  21154. var uva, uvb, uvc, uvd;
  21155. for ( i = 0; i < stacks; i ++ ) {
  21156. for ( j = 0; j < slices; j ++ ) {
  21157. a = i * sliceCount + j;
  21158. b = i * sliceCount + j + 1;
  21159. c = (i + 1) * sliceCount + j + 1;
  21160. d = (i + 1) * sliceCount + j;
  21161. uva = new THREE.Vector2( j / slices, i / stacks );
  21162. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  21163. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  21164. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  21165. faces.push( new THREE.Face3( a, b, d ) );
  21166. uvs.push( [ uva, uvb, uvd ] );
  21167. faces.push( new THREE.Face3( b, c, d ) );
  21168. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  21169. }
  21170. }
  21171. // console.log(this);
  21172. // magic bullet
  21173. // var diff = this.mergeVertices();
  21174. // console.log('removed ', diff, ' vertices by merging');
  21175. this.computeFaceNormals();
  21176. this.computeVertexNormals();
  21177. };
  21178. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21179. /**
  21180. * @author sroucheray / http://sroucheray.org/
  21181. * @author mrdoob / http://mrdoob.com/
  21182. */
  21183. THREE.AxisHelper = function ( size ) {
  21184. size = size || 1;
  21185. var geometry = new THREE.Geometry();
  21186. geometry.vertices.push(
  21187. new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ),
  21188. new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ),
  21189. new THREE.Vector3(), new THREE.Vector3( 0, 0, size )
  21190. );
  21191. geometry.colors.push(
  21192. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  21193. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  21194. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  21195. );
  21196. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  21197. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  21198. };
  21199. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  21200. /**
  21201. * @author WestLangley / http://github.com/WestLangley
  21202. * @author zz85 / http://github.com/zz85
  21203. * @author bhouston / http://exocortex.com
  21204. *
  21205. * Creates an arrow for visualizing directions
  21206. *
  21207. * Parameters:
  21208. * dir - Vector3
  21209. * origin - Vector3
  21210. * length - Number
  21211. * hex - color in hex value
  21212. * headLength - Number
  21213. * headWidth - Number
  21214. */
  21215. THREE.ArrowHelper = function ( dir, origin, length, hex, headLength, headWidth ) {
  21216. // dir is assumed to be normalized
  21217. THREE.Object3D.call( this );
  21218. if ( hex === undefined ) hex = 0xffff00;
  21219. if ( length === undefined ) length = 1;
  21220. if ( headLength === undefined ) headLength = 0.2 * length;
  21221. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  21222. this.position = origin;
  21223. var lineGeometry = new THREE.Geometry();
  21224. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  21225. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  21226. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  21227. this.line.matrixAutoUpdate = false;
  21228. this.add( this.line );
  21229. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  21230. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  21231. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  21232. this.cone.matrixAutoUpdate = false;
  21233. this.add( this.cone );
  21234. this.setDirection( dir );
  21235. this.setLength( length, headLength, headWidth );
  21236. };
  21237. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  21238. THREE.ArrowHelper.prototype.setDirection = function () {
  21239. var axis = new THREE.Vector3();
  21240. var radians;
  21241. return function ( dir ) {
  21242. // dir is assumed to be normalized
  21243. if ( dir.y > 0.99999 ) {
  21244. this.quaternion.set( 0, 0, 0, 1 );
  21245. } else if ( dir.y < - 0.99999 ) {
  21246. this.quaternion.set( 1, 0, 0, 0 );
  21247. } else {
  21248. axis.set( dir.z, 0, - dir.x ).normalize();
  21249. radians = Math.acos( dir.y );
  21250. this.quaternion.setFromAxisAngle( axis, radians );
  21251. }
  21252. };
  21253. }();
  21254. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  21255. if ( headLength === undefined ) headLength = 0.2 * length;
  21256. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  21257. this.line.scale.set( 1, length, 1 );
  21258. this.line.updateMatrix();
  21259. this.cone.scale.set( headWidth, headLength, headWidth );
  21260. this.cone.position.y = length;
  21261. this.cone.updateMatrix();
  21262. };
  21263. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  21264. this.line.material.color.setHex( hex );
  21265. this.cone.material.color.setHex( hex );
  21266. };
  21267. /**
  21268. * @author mrdoob / http://mrdoob.com/
  21269. */
  21270. THREE.BoxHelper = function ( object ) {
  21271. // 5____4
  21272. // 1/___0/|
  21273. // | 6__|_7
  21274. // 2/___3/
  21275. var vertices = [
  21276. new THREE.Vector3( 1, 1, 1 ),
  21277. new THREE.Vector3( - 1, 1, 1 ),
  21278. new THREE.Vector3( - 1, - 1, 1 ),
  21279. new THREE.Vector3( 1, - 1, 1 ),
  21280. new THREE.Vector3( 1, 1, - 1 ),
  21281. new THREE.Vector3( - 1, 1, - 1 ),
  21282. new THREE.Vector3( - 1, - 1, - 1 ),
  21283. new THREE.Vector3( 1, - 1, - 1 )
  21284. ];
  21285. this.vertices = vertices;
  21286. // TODO: Wouldn't be nice if Line had .segments?
  21287. var geometry = new THREE.Geometry();
  21288. geometry.vertices.push(
  21289. vertices[ 0 ], vertices[ 1 ],
  21290. vertices[ 1 ], vertices[ 2 ],
  21291. vertices[ 2 ], vertices[ 3 ],
  21292. vertices[ 3 ], vertices[ 0 ],
  21293. vertices[ 4 ], vertices[ 5 ],
  21294. vertices[ 5 ], vertices[ 6 ],
  21295. vertices[ 6 ], vertices[ 7 ],
  21296. vertices[ 7 ], vertices[ 4 ],
  21297. vertices[ 0 ], vertices[ 4 ],
  21298. vertices[ 1 ], vertices[ 5 ],
  21299. vertices[ 2 ], vertices[ 6 ],
  21300. vertices[ 3 ], vertices[ 7 ]
  21301. );
  21302. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  21303. if ( object !== undefined ) {
  21304. this.update( object );
  21305. }
  21306. };
  21307. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  21308. THREE.BoxHelper.prototype.update = function ( object ) {
  21309. var geometry = object.geometry;
  21310. if ( geometry.boundingBox === null ) {
  21311. geometry.computeBoundingBox();
  21312. }
  21313. var min = geometry.boundingBox.min;
  21314. var max = geometry.boundingBox.max;
  21315. var vertices = this.vertices;
  21316. vertices[ 0 ].set( max.x, max.y, max.z );
  21317. vertices[ 1 ].set( min.x, max.y, max.z );
  21318. vertices[ 2 ].set( min.x, min.y, max.z );
  21319. vertices[ 3 ].set( max.x, min.y, max.z );
  21320. vertices[ 4 ].set( max.x, max.y, min.z );
  21321. vertices[ 5 ].set( min.x, max.y, min.z );
  21322. vertices[ 6 ].set( min.x, min.y, min.z );
  21323. vertices[ 7 ].set( max.x, min.y, min.z );
  21324. this.geometry.computeBoundingSphere();
  21325. this.geometry.verticesNeedUpdate = true;
  21326. this.matrixAutoUpdate = false;
  21327. this.matrixWorld = object.matrixWorld;
  21328. };
  21329. /**
  21330. * @author WestLangley / http://github.com/WestLangley
  21331. */
  21332. // a helper to show the world-axis-aligned bounding box for an object
  21333. THREE.BoundingBoxHelper = function ( object, hex ) {
  21334. var color = ( hex !== undefined ) ? hex : 0x888888;
  21335. this.object = object;
  21336. this.box = new THREE.Box3();
  21337. THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  21338. };
  21339. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  21340. THREE.BoundingBoxHelper.prototype.update = function () {
  21341. this.box.setFromObject( this.object );
  21342. this.box.size( this.scale );
  21343. this.box.center( this.position );
  21344. };
  21345. /**
  21346. * @author alteredq / http://alteredqualia.com/
  21347. *
  21348. * - shows frustum, line of sight and up of the camera
  21349. * - suitable for fast updates
  21350. * - based on frustum visualization in lightgl.js shadowmap example
  21351. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  21352. */
  21353. THREE.CameraHelper = function ( camera ) {
  21354. var geometry = new THREE.Geometry();
  21355. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  21356. var pointMap = {};
  21357. // colors
  21358. var hexFrustum = 0xffaa00;
  21359. var hexCone = 0xff0000;
  21360. var hexUp = 0x00aaff;
  21361. var hexTarget = 0xffffff;
  21362. var hexCross = 0x333333;
  21363. // near
  21364. addLine( "n1", "n2", hexFrustum );
  21365. addLine( "n2", "n4", hexFrustum );
  21366. addLine( "n4", "n3", hexFrustum );
  21367. addLine( "n3", "n1", hexFrustum );
  21368. // far
  21369. addLine( "f1", "f2", hexFrustum );
  21370. addLine( "f2", "f4", hexFrustum );
  21371. addLine( "f4", "f3", hexFrustum );
  21372. addLine( "f3", "f1", hexFrustum );
  21373. // sides
  21374. addLine( "n1", "f1", hexFrustum );
  21375. addLine( "n2", "f2", hexFrustum );
  21376. addLine( "n3", "f3", hexFrustum );
  21377. addLine( "n4", "f4", hexFrustum );
  21378. // cone
  21379. addLine( "p", "n1", hexCone );
  21380. addLine( "p", "n2", hexCone );
  21381. addLine( "p", "n3", hexCone );
  21382. addLine( "p", "n4", hexCone );
  21383. // up
  21384. addLine( "u1", "u2", hexUp );
  21385. addLine( "u2", "u3", hexUp );
  21386. addLine( "u3", "u1", hexUp );
  21387. // target
  21388. addLine( "c", "t", hexTarget );
  21389. addLine( "p", "c", hexCross );
  21390. // cross
  21391. addLine( "cn1", "cn2", hexCross );
  21392. addLine( "cn3", "cn4", hexCross );
  21393. addLine( "cf1", "cf2", hexCross );
  21394. addLine( "cf3", "cf4", hexCross );
  21395. function addLine( a, b, hex ) {
  21396. addPoint( a, hex );
  21397. addPoint( b, hex );
  21398. }
  21399. function addPoint( id, hex ) {
  21400. geometry.vertices.push( new THREE.Vector3() );
  21401. geometry.colors.push( new THREE.Color( hex ) );
  21402. if ( pointMap[ id ] === undefined ) {
  21403. pointMap[ id ] = [];
  21404. }
  21405. pointMap[ id ].push( geometry.vertices.length - 1 );
  21406. }
  21407. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  21408. this.camera = camera;
  21409. this.matrixWorld = camera.matrixWorld;
  21410. this.matrixAutoUpdate = false;
  21411. this.pointMap = pointMap;
  21412. this.update();
  21413. };
  21414. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  21415. THREE.CameraHelper.prototype.update = function () {
  21416. var vector = new THREE.Vector3();
  21417. var camera = new THREE.Camera();
  21418. var projector = new THREE.Projector();
  21419. return function () {
  21420. var scope = this;
  21421. var w = 1, h = 1;
  21422. // we need just camera projection matrix
  21423. // world matrix must be identity
  21424. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  21425. // center / target
  21426. setPoint( "c", 0, 0, -1 );
  21427. setPoint( "t", 0, 0, 1 );
  21428. // near
  21429. setPoint( "n1", -w, -h, -1 );
  21430. setPoint( "n2", w, -h, -1 );
  21431. setPoint( "n3", -w, h, -1 );
  21432. setPoint( "n4", w, h, -1 );
  21433. // far
  21434. setPoint( "f1", -w, -h, 1 );
  21435. setPoint( "f2", w, -h, 1 );
  21436. setPoint( "f3", -w, h, 1 );
  21437. setPoint( "f4", w, h, 1 );
  21438. // up
  21439. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  21440. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  21441. setPoint( "u3", 0, h * 2, -1 );
  21442. // cross
  21443. setPoint( "cf1", -w, 0, 1 );
  21444. setPoint( "cf2", w, 0, 1 );
  21445. setPoint( "cf3", 0, -h, 1 );
  21446. setPoint( "cf4", 0, h, 1 );
  21447. setPoint( "cn1", -w, 0, -1 );
  21448. setPoint( "cn2", w, 0, -1 );
  21449. setPoint( "cn3", 0, -h, -1 );
  21450. setPoint( "cn4", 0, h, -1 );
  21451. function setPoint( point, x, y, z ) {
  21452. vector.set( x, y, z );
  21453. projector.unprojectVector( vector, camera );
  21454. var points = scope.pointMap[ point ];
  21455. if ( points !== undefined ) {
  21456. for ( var i = 0, il = points.length; i < il; i ++ ) {
  21457. scope.geometry.vertices[ points[ i ] ].copy( vector );
  21458. }
  21459. }
  21460. }
  21461. this.geometry.verticesNeedUpdate = true;
  21462. };
  21463. }();
  21464. /**
  21465. * @author alteredq / http://alteredqualia.com/
  21466. * @author mrdoob / http://mrdoob.com/
  21467. * @author WestLangley / http://github.com/WestLangley
  21468. */
  21469. THREE.DirectionalLightHelper = function ( light, size ) {
  21470. THREE.Object3D.call( this );
  21471. this.light = light;
  21472. this.light.updateMatrixWorld();
  21473. this.matrixWorld = light.matrixWorld;
  21474. this.matrixAutoUpdate = false;
  21475. size = size || 1;
  21476. var geometry = new THREE.Geometry();
  21477. geometry.vertices.push(
  21478. new THREE.Vector3( - size, size, 0 ),
  21479. new THREE.Vector3( size, size, 0 ),
  21480. new THREE.Vector3( size, - size, 0 ),
  21481. new THREE.Vector3( - size, - size, 0 ),
  21482. new THREE.Vector3( - size, size, 0 )
  21483. );
  21484. var material = new THREE.LineBasicMaterial( { fog: false } );
  21485. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21486. this.lightPlane = new THREE.Line( geometry, material );
  21487. this.add( this.lightPlane );
  21488. geometry = new THREE.Geometry();
  21489. geometry.vertices.push(
  21490. new THREE.Vector3(),
  21491. new THREE.Vector3()
  21492. );
  21493. material = new THREE.LineBasicMaterial( { fog: false } );
  21494. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21495. this.targetLine = new THREE.Line( geometry, material );
  21496. this.add( this.targetLine );
  21497. this.update();
  21498. };
  21499. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21500. THREE.DirectionalLightHelper.prototype.dispose = function () {
  21501. this.lightPlane.geometry.dispose();
  21502. this.lightPlane.material.dispose();
  21503. this.targetLine.geometry.dispose();
  21504. this.targetLine.material.dispose();
  21505. };
  21506. THREE.DirectionalLightHelper.prototype.update = function () {
  21507. var v1 = new THREE.Vector3();
  21508. var v2 = new THREE.Vector3();
  21509. var v3 = new THREE.Vector3();
  21510. return function () {
  21511. v1.setFromMatrixPosition( this.light.matrixWorld );
  21512. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  21513. v3.subVectors( v2, v1 );
  21514. this.lightPlane.lookAt( v3 );
  21515. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21516. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  21517. this.targetLine.geometry.verticesNeedUpdate = true;
  21518. this.targetLine.material.color.copy( this.lightPlane.material.color );
  21519. }
  21520. }();
  21521. /**
  21522. * @author WestLangley / http://github.com/WestLangley
  21523. */
  21524. THREE.EdgesHelper = function ( object, hex ) {
  21525. var color = ( hex !== undefined ) ? hex : 0xffffff;
  21526. var edge = [ 0, 0 ], hash = {};
  21527. var sortFunction = function ( a, b ) { return a - b };
  21528. var keys = [ 'a', 'b', 'c' ];
  21529. var geometry = new THREE.BufferGeometry();
  21530. var geometry2 = object.geometry.clone();
  21531. geometry2.mergeVertices();
  21532. geometry2.computeFaceNormals();
  21533. var vertices = geometry2.vertices;
  21534. var faces = geometry2.faces;
  21535. var numEdges = 0;
  21536. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21537. var face = faces[ i ];
  21538. for ( var j = 0; j < 3; j ++ ) {
  21539. edge[ 0 ] = face[ keys[ j ] ];
  21540. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  21541. edge.sort( sortFunction );
  21542. var key = edge.toString();
  21543. if ( hash[ key ] === undefined ) {
  21544. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  21545. numEdges ++;
  21546. } else {
  21547. hash[ key ].face2 = i;
  21548. }
  21549. }
  21550. }
  21551. geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2, 3 ) );
  21552. var coords = geometry.attributes.position.array;
  21553. var index = 0;
  21554. for ( var key in hash ) {
  21555. var h = hash[ key ];
  21556. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) < 0.9999 ) { // hardwired const OK
  21557. var vertex = vertices[ h.vert1 ];
  21558. coords[ index ++ ] = vertex.x;
  21559. coords[ index ++ ] = vertex.y;
  21560. coords[ index ++ ] = vertex.z;
  21561. vertex = vertices[ h.vert2 ];
  21562. coords[ index ++ ] = vertex.x;
  21563. coords[ index ++ ] = vertex.y;
  21564. coords[ index ++ ] = vertex.z;
  21565. }
  21566. }
  21567. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  21568. this.matrixAutoUpdate = false;
  21569. this.matrixWorld = object.matrixWorld;
  21570. };
  21571. THREE.EdgesHelper.prototype = Object.create( THREE.Line.prototype );
  21572. /**
  21573. * @author mrdoob / http://mrdoob.com/
  21574. * @author WestLangley / http://github.com/WestLangley
  21575. */
  21576. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  21577. this.object = object;
  21578. this.size = ( size !== undefined ) ? size : 1;
  21579. var color = ( hex !== undefined ) ? hex : 0xffff00;
  21580. var width = ( linewidth !== undefined ) ? linewidth : 1;
  21581. var geometry = new THREE.Geometry();
  21582. var faces = this.object.geometry.faces;
  21583. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21584. geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() );
  21585. }
  21586. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21587. this.matrixAutoUpdate = false;
  21588. this.normalMatrix = new THREE.Matrix3();
  21589. this.update();
  21590. };
  21591. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  21592. THREE.FaceNormalsHelper.prototype.update = function () {
  21593. var vertices = this.geometry.vertices;
  21594. var object = this.object;
  21595. var objectVertices = object.geometry.vertices;
  21596. var objectFaces = object.geometry.faces;
  21597. var objectWorldMatrix = object.matrixWorld;
  21598. object.updateMatrixWorld( true );
  21599. this.normalMatrix.getNormalMatrix( objectWorldMatrix );
  21600. for ( var i = 0, i2 = 0, l = objectFaces.length; i < l; i ++, i2 += 2 ) {
  21601. var face = objectFaces[ i ];
  21602. vertices[ i2 ].copy( objectVertices[ face.a ] )
  21603. .add( objectVertices[ face.b ] )
  21604. .add( objectVertices[ face.c ] )
  21605. .divideScalar( 3 )
  21606. .applyMatrix4( objectWorldMatrix );
  21607. vertices[ i2 + 1 ].copy( face.normal )
  21608. .applyMatrix3( this.normalMatrix )
  21609. .normalize()
  21610. .multiplyScalar( this.size )
  21611. .add( vertices[ i2 ] );
  21612. }
  21613. this.geometry.verticesNeedUpdate = true;
  21614. return this;
  21615. };
  21616. /**
  21617. * @author mrdoob / http://mrdoob.com/
  21618. */
  21619. THREE.GridHelper = function ( size, step ) {
  21620. var geometry = new THREE.Geometry();
  21621. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  21622. this.color1 = new THREE.Color( 0x444444 );
  21623. this.color2 = new THREE.Color( 0x888888 );
  21624. for ( var i = - size; i <= size; i += step ) {
  21625. geometry.vertices.push(
  21626. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  21627. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  21628. );
  21629. var color = i === 0 ? this.color1 : this.color2;
  21630. geometry.colors.push( color, color, color, color );
  21631. }
  21632. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  21633. };
  21634. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  21635. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  21636. this.color1.set( colorCenterLine );
  21637. this.color2.set( colorGrid );
  21638. this.geometry.colorsNeedUpdate = true;
  21639. }
  21640. /**
  21641. * @author alteredq / http://alteredqualia.com/
  21642. * @author mrdoob / http://mrdoob.com/
  21643. */
  21644. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  21645. THREE.Object3D.call( this );
  21646. this.light = light;
  21647. this.light.updateMatrixWorld();
  21648. this.matrixWorld = light.matrixWorld;
  21649. this.matrixAutoUpdate = false;
  21650. this.colors = [ new THREE.Color(), new THREE.Color() ];
  21651. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21652. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  21653. for ( var i = 0, il = 8; i < il; i ++ ) {
  21654. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  21655. }
  21656. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  21657. this.lightSphere = new THREE.Mesh( geometry, material );
  21658. this.add( this.lightSphere );
  21659. this.update();
  21660. };
  21661. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21662. THREE.HemisphereLightHelper.prototype.dispose = function () {
  21663. this.lightSphere.geometry.dispose();
  21664. this.lightSphere.material.dispose();
  21665. };
  21666. THREE.HemisphereLightHelper.prototype.update = function () {
  21667. var vector = new THREE.Vector3();
  21668. return function () {
  21669. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  21670. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  21671. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  21672. this.lightSphere.geometry.colorsNeedUpdate = true;
  21673. }
  21674. }();
  21675. /**
  21676. * @author alteredq / http://alteredqualia.com/
  21677. * @author mrdoob / http://mrdoob.com/
  21678. */
  21679. THREE.PointLightHelper = function ( light, sphereSize ) {
  21680. this.light = light;
  21681. this.light.updateMatrixWorld();
  21682. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21683. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  21684. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21685. THREE.Mesh.call( this, geometry, material );
  21686. this.matrixWorld = this.light.matrixWorld;
  21687. this.matrixAutoUpdate = false;
  21688. /*
  21689. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  21690. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  21691. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  21692. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  21693. var d = light.distance;
  21694. if ( d === 0.0 ) {
  21695. this.lightDistance.visible = false;
  21696. } else {
  21697. this.lightDistance.scale.set( d, d, d );
  21698. }
  21699. this.add( this.lightDistance );
  21700. */
  21701. };
  21702. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  21703. THREE.PointLightHelper.prototype.dispose = function () {
  21704. this.geometry.dispose();
  21705. this.material.dispose();
  21706. };
  21707. THREE.PointLightHelper.prototype.update = function () {
  21708. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21709. /*
  21710. var d = this.light.distance;
  21711. if ( d === 0.0 ) {
  21712. this.lightDistance.visible = false;
  21713. } else {
  21714. this.lightDistance.visible = true;
  21715. this.lightDistance.scale.set( d, d, d );
  21716. }
  21717. */
  21718. };
  21719. /**
  21720. * @author alteredq / http://alteredqualia.com/
  21721. * @author mrdoob / http://mrdoob.com/
  21722. * @author WestLangley / http://github.com/WestLangley
  21723. */
  21724. THREE.SpotLightHelper = function ( light ) {
  21725. THREE.Object3D.call( this );
  21726. this.light = light;
  21727. this.light.updateMatrixWorld();
  21728. this.matrixWorld = light.matrixWorld;
  21729. this.matrixAutoUpdate = false;
  21730. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  21731. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
  21732. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  21733. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  21734. this.cone = new THREE.Mesh( geometry, material );
  21735. this.add( this.cone );
  21736. this.update();
  21737. };
  21738. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21739. THREE.SpotLightHelper.prototype.dispose = function () {
  21740. this.cone.geometry.dispose();
  21741. this.cone.material.dispose();
  21742. };
  21743. THREE.SpotLightHelper.prototype.update = function () {
  21744. var vector = new THREE.Vector3();
  21745. var vector2 = new THREE.Vector3();
  21746. return function () {
  21747. var coneLength = this.light.distance ? this.light.distance : 10000;
  21748. var coneWidth = coneLength * Math.tan( this.light.angle );
  21749. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  21750. vector.setFromMatrixPosition( this.light.matrixWorld );
  21751. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  21752. this.cone.lookAt( vector2.sub( vector ) );
  21753. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21754. };
  21755. }();
  21756. /**
  21757. * @author mrdoob / http://mrdoob.com/
  21758. * @author WestLangley / http://github.com/WestLangley
  21759. */
  21760. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  21761. this.object = object;
  21762. this.size = ( size !== undefined ) ? size : 1;
  21763. var color = ( hex !== undefined ) ? hex : 0xff0000;
  21764. var width = ( linewidth !== undefined ) ? linewidth : 1;
  21765. var geometry = new THREE.Geometry();
  21766. var vertices = object.geometry.vertices;
  21767. var faces = object.geometry.faces;
  21768. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21769. var face = faces[ i ];
  21770. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21771. geometry.vertices.push( new THREE.Vector3() );
  21772. geometry.vertices.push( new THREE.Vector3() );
  21773. }
  21774. }
  21775. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21776. this.matrixAutoUpdate = false;
  21777. this.normalMatrix = new THREE.Matrix3();
  21778. this.update();
  21779. };
  21780. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  21781. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  21782. var v1 = new THREE.Vector3();
  21783. return function( object ) {
  21784. var keys = [ 'a', 'b', 'c', 'd' ];
  21785. this.object.updateMatrixWorld( true );
  21786. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  21787. var vertices = this.geometry.vertices;
  21788. var verts = this.object.geometry.vertices;
  21789. var faces = this.object.geometry.faces;
  21790. var worldMatrix = this.object.matrixWorld;
  21791. var idx = 0;
  21792. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21793. var face = faces[ i ];
  21794. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21795. var vertexId = face[ keys[ j ] ];
  21796. var vertex = verts[ vertexId ];
  21797. var normal = face.vertexNormals[ j ];
  21798. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21799. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  21800. v1.add( vertices[ idx ] );
  21801. idx = idx + 1;
  21802. vertices[ idx ].copy( v1 );
  21803. idx = idx + 1;
  21804. }
  21805. }
  21806. this.geometry.verticesNeedUpdate = true;
  21807. return this;
  21808. }
  21809. }());
  21810. /**
  21811. * @author mrdoob / http://mrdoob.com/
  21812. * @author WestLangley / http://github.com/WestLangley
  21813. */
  21814. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  21815. this.object = object;
  21816. this.size = ( size !== undefined ) ? size : 1;
  21817. var color = ( hex !== undefined ) ? hex : 0x0000ff;
  21818. var width = ( linewidth !== undefined ) ? linewidth : 1;
  21819. var geometry = new THREE.Geometry();
  21820. var vertices = object.geometry.vertices;
  21821. var faces = object.geometry.faces;
  21822. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21823. var face = faces[ i ];
  21824. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21825. geometry.vertices.push( new THREE.Vector3() );
  21826. geometry.vertices.push( new THREE.Vector3() );
  21827. }
  21828. }
  21829. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21830. this.matrixAutoUpdate = false;
  21831. this.update();
  21832. };
  21833. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  21834. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  21835. var v1 = new THREE.Vector3();
  21836. return function( object ) {
  21837. var keys = [ 'a', 'b', 'c', 'd' ];
  21838. this.object.updateMatrixWorld( true );
  21839. var vertices = this.geometry.vertices;
  21840. var verts = this.object.geometry.vertices;
  21841. var faces = this.object.geometry.faces;
  21842. var worldMatrix = this.object.matrixWorld;
  21843. var idx = 0;
  21844. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21845. var face = faces[ i ];
  21846. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21847. var vertexId = face[ keys[ j ] ];
  21848. var vertex = verts[ vertexId ];
  21849. var tangent = face.vertexTangents[ j ];
  21850. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21851. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  21852. v1.add( vertices[ idx ] );
  21853. idx = idx + 1;
  21854. vertices[ idx ].copy( v1 );
  21855. idx = idx + 1;
  21856. }
  21857. }
  21858. this.geometry.verticesNeedUpdate = true;
  21859. return this;
  21860. }
  21861. }());
  21862. /**
  21863. * @author mrdoob / http://mrdoob.com/
  21864. */
  21865. THREE.WireframeHelper = function ( object, hex ) {
  21866. var color = ( hex !== undefined ) ? hex : 0xffffff;
  21867. var edge = [ 0, 0 ], hash = {};
  21868. var sortFunction = function ( a, b ) { return a - b };
  21869. var keys = [ 'a', 'b', 'c' ];
  21870. var geometry = new THREE.BufferGeometry();
  21871. if ( object.geometry instanceof THREE.Geometry ) {
  21872. var vertices = object.geometry.vertices;
  21873. var faces = object.geometry.faces;
  21874. var numEdges = 0;
  21875. // allocate maximal size
  21876. var edges = new Uint32Array( 6 * faces.length );
  21877. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21878. var face = faces[ i ];
  21879. for ( var j = 0; j < 3; j ++ ) {
  21880. edge[ 0 ] = face[ keys[ j ] ];
  21881. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  21882. edge.sort( sortFunction );
  21883. var key = edge.toString();
  21884. if ( hash[ key ] === undefined ) {
  21885. edges[ 2 * numEdges ] = edge[ 0 ];
  21886. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  21887. hash[ key ] = true;
  21888. numEdges ++;
  21889. }
  21890. }
  21891. }
  21892. geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2, 3 ) );
  21893. var coords = geometry.attributes.position.array;
  21894. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  21895. for ( var j = 0; j < 2; j ++ ) {
  21896. var vertex = vertices[ edges [ 2 * i + j] ];
  21897. var index = 6 * i + 3 * j;
  21898. coords[ index + 0 ] = vertex.x;
  21899. coords[ index + 1 ] = vertex.y;
  21900. coords[ index + 2 ] = vertex.z;
  21901. }
  21902. }
  21903. } else if ( object.geometry instanceof THREE.BufferGeometry && object.geometry.attributes.index !== undefined ) { // indexed BufferGeometry
  21904. var vertices = object.geometry.attributes.position.array;
  21905. var indices = object.geometry.attributes.index.array;
  21906. var offsets = object.geometry.offsets;
  21907. var numEdges = 0;
  21908. // allocate maximal size
  21909. var edges = new Uint32Array( 2 * indices.length );
  21910. for ( var o = 0, ol = offsets.length; o < ol; ++ o ) {
  21911. var start = offsets[ o ].start;
  21912. var count = offsets[ o ].count;
  21913. var index = offsets[ o ].index;
  21914. for ( var i = start, il = start + count; i < il; i += 3 ) {
  21915. for ( var j = 0; j < 3; j ++ ) {
  21916. edge[ 0 ] = index + indices[ i + j ];
  21917. edge[ 1 ] = index + indices[ i + ( j + 1 ) % 3 ];
  21918. edge.sort( sortFunction );
  21919. var key = edge.toString();
  21920. if ( hash[ key ] === undefined ) {
  21921. edges[ 2 * numEdges ] = edge[ 0 ];
  21922. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  21923. hash[ key ] = true;
  21924. numEdges ++;
  21925. }
  21926. }
  21927. }
  21928. }
  21929. geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2, 3 ) );
  21930. var coords = geometry.attributes.position.array;
  21931. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  21932. for ( var j = 0; j < 2; j ++ ) {
  21933. var index = 6 * i + 3 * j;
  21934. var index2 = 3 * edges[ 2 * i + j];
  21935. coords[ index + 0 ] = vertices[ index2 ];
  21936. coords[ index + 1 ] = vertices[ index2 + 1 ];
  21937. coords[ index + 2 ] = vertices[ index2 + 2 ];
  21938. }
  21939. }
  21940. } else if ( object.geometry instanceof THREE.BufferGeometry ) { // non-indexed BufferGeometry
  21941. var vertices = object.geometry.attributes.position.array;
  21942. var numEdges = vertices.length / 3;
  21943. var numTris = numEdges / 3;
  21944. geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2, 3 ) );
  21945. var coords = geometry.attributes.position.array;
  21946. for ( var i = 0, l = numTris; i < l; i ++ ) {
  21947. for ( var j = 0; j < 3; j ++ ) {
  21948. var index = 18 * i + 6 * j;
  21949. var index1 = 9 * i + 3 * j;
  21950. coords[ index + 0 ] = vertices[ index1 ];
  21951. coords[ index + 1 ] = vertices[ index1 + 1 ];
  21952. coords[ index + 2 ] = vertices[ index1 + 2 ];
  21953. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  21954. coords[ index + 3 ] = vertices[ index2 ];
  21955. coords[ index + 4 ] = vertices[ index2 + 1 ];
  21956. coords[ index + 5 ] = vertices[ index2 + 2 ];
  21957. }
  21958. }
  21959. }
  21960. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  21961. this.matrixAutoUpdate = false;
  21962. this.matrixWorld = object.matrixWorld;
  21963. };
  21964. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  21965. /**
  21966. * @author alteredq / http://alteredqualia.com/
  21967. */
  21968. THREE.ImmediateRenderObject = function () {
  21969. THREE.Object3D.call( this );
  21970. this.render = function ( renderCallback ) { };
  21971. };
  21972. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  21973. /**
  21974. * @author mikael emtinger / http://gomo.se/
  21975. * @author alteredq / http://alteredqualia.com/
  21976. */
  21977. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  21978. THREE.Object3D.call( this );
  21979. this.lensFlares = [];
  21980. this.positionScreen = new THREE.Vector3();
  21981. this.customUpdateCallback = undefined;
  21982. if( texture !== undefined ) {
  21983. this.add( texture, size, distance, blending, color );
  21984. }
  21985. };
  21986. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  21987. /*
  21988. * Add: adds another flare
  21989. */
  21990. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  21991. if( size === undefined ) size = -1;
  21992. if( distance === undefined ) distance = 0;
  21993. if( opacity === undefined ) opacity = 1;
  21994. if( color === undefined ) color = new THREE.Color( 0xffffff );
  21995. if( blending === undefined ) blending = THREE.NormalBlending;
  21996. distance = Math.min( distance, Math.max( 0, distance ) );
  21997. this.lensFlares.push( { texture: texture, // THREE.Texture
  21998. size: size, // size in pixels (-1 = use texture.width)
  21999. distance: distance, // distance (0-1) from light source (0=at light source)
  22000. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  22001. scale: 1, // scale
  22002. rotation: 1, // rotation
  22003. opacity: opacity, // opacity
  22004. color: color, // color
  22005. blending: blending } ); // blending
  22006. };
  22007. /*
  22008. * Update lens flares update positions on all flares based on the screen position
  22009. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  22010. */
  22011. THREE.LensFlare.prototype.updateLensFlares = function () {
  22012. var f, fl = this.lensFlares.length;
  22013. var flare;
  22014. var vecX = -this.positionScreen.x * 2;
  22015. var vecY = -this.positionScreen.y * 2;
  22016. for( f = 0; f < fl; f ++ ) {
  22017. flare = this.lensFlares[ f ];
  22018. flare.x = this.positionScreen.x + vecX * flare.distance;
  22019. flare.y = this.positionScreen.y + vecY * flare.distance;
  22020. flare.wantedRotation = flare.x * Math.PI * 0.25;
  22021. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  22022. }
  22023. };
  22024. /**
  22025. * @author alteredq / http://alteredqualia.com/
  22026. */
  22027. THREE.MorphBlendMesh = function( geometry, material ) {
  22028. THREE.Mesh.call( this, geometry, material );
  22029. this.animationsMap = {};
  22030. this.animationsList = [];
  22031. // prepare default animation
  22032. // (all frames played together in 1 second)
  22033. var numFrames = this.geometry.morphTargets.length;
  22034. var name = "__default";
  22035. var startFrame = 0;
  22036. var endFrame = numFrames - 1;
  22037. var fps = numFrames / 1;
  22038. this.createAnimation( name, startFrame, endFrame, fps );
  22039. this.setAnimationWeight( name, 1 );
  22040. };
  22041. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  22042. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  22043. var animation = {
  22044. startFrame: start,
  22045. endFrame: end,
  22046. length: end - start + 1,
  22047. fps: fps,
  22048. duration: ( end - start ) / fps,
  22049. lastFrame: 0,
  22050. currentFrame: 0,
  22051. active: false,
  22052. time: 0,
  22053. direction: 1,
  22054. weight: 1,
  22055. directionBackwards: false,
  22056. mirroredLoop: false
  22057. };
  22058. this.animationsMap[ name ] = animation;
  22059. this.animationsList.push( animation );
  22060. };
  22061. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  22062. var pattern = /([a-z]+)(\d+)/;
  22063. var firstAnimation, frameRanges = {};
  22064. var geometry = this.geometry;
  22065. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  22066. var morph = geometry.morphTargets[ i ];
  22067. var chunks = morph.name.match( pattern );
  22068. if ( chunks && chunks.length > 1 ) {
  22069. var name = chunks[ 1 ];
  22070. var num = chunks[ 2 ];
  22071. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  22072. var range = frameRanges[ name ];
  22073. if ( i < range.start ) range.start = i;
  22074. if ( i > range.end ) range.end = i;
  22075. if ( ! firstAnimation ) firstAnimation = name;
  22076. }
  22077. }
  22078. for ( var name in frameRanges ) {
  22079. var range = frameRanges[ name ];
  22080. this.createAnimation( name, range.start, range.end, fps );
  22081. }
  22082. this.firstAnimation = firstAnimation;
  22083. };
  22084. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  22085. var animation = this.animationsMap[ name ];
  22086. if ( animation ) {
  22087. animation.direction = 1;
  22088. animation.directionBackwards = false;
  22089. }
  22090. };
  22091. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  22092. var animation = this.animationsMap[ name ];
  22093. if ( animation ) {
  22094. animation.direction = -1;
  22095. animation.directionBackwards = true;
  22096. }
  22097. };
  22098. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  22099. var animation = this.animationsMap[ name ];
  22100. if ( animation ) {
  22101. animation.fps = fps;
  22102. animation.duration = ( animation.end - animation.start ) / animation.fps;
  22103. }
  22104. };
  22105. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  22106. var animation = this.animationsMap[ name ];
  22107. if ( animation ) {
  22108. animation.duration = duration;
  22109. animation.fps = ( animation.end - animation.start ) / animation.duration;
  22110. }
  22111. };
  22112. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  22113. var animation = this.animationsMap[ name ];
  22114. if ( animation ) {
  22115. animation.weight = weight;
  22116. }
  22117. };
  22118. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  22119. var animation = this.animationsMap[ name ];
  22120. if ( animation ) {
  22121. animation.time = time;
  22122. }
  22123. };
  22124. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  22125. var time = 0;
  22126. var animation = this.animationsMap[ name ];
  22127. if ( animation ) {
  22128. time = animation.time;
  22129. }
  22130. return time;
  22131. };
  22132. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  22133. var duration = -1;
  22134. var animation = this.animationsMap[ name ];
  22135. if ( animation ) {
  22136. duration = animation.duration;
  22137. }
  22138. return duration;
  22139. };
  22140. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  22141. var animation = this.animationsMap[ name ];
  22142. if ( animation ) {
  22143. animation.time = 0;
  22144. animation.active = true;
  22145. } else {
  22146. console.warn( "animation[" + name + "] undefined" );
  22147. }
  22148. };
  22149. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  22150. var animation = this.animationsMap[ name ];
  22151. if ( animation ) {
  22152. animation.active = false;
  22153. }
  22154. };
  22155. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  22156. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  22157. var animation = this.animationsList[ i ];
  22158. if ( ! animation.active ) continue;
  22159. var frameTime = animation.duration / animation.length;
  22160. animation.time += animation.direction * delta;
  22161. if ( animation.mirroredLoop ) {
  22162. if ( animation.time > animation.duration || animation.time < 0 ) {
  22163. animation.direction *= -1;
  22164. if ( animation.time > animation.duration ) {
  22165. animation.time = animation.duration;
  22166. animation.directionBackwards = true;
  22167. }
  22168. if ( animation.time < 0 ) {
  22169. animation.time = 0;
  22170. animation.directionBackwards = false;
  22171. }
  22172. }
  22173. } else {
  22174. animation.time = animation.time % animation.duration;
  22175. if ( animation.time < 0 ) animation.time += animation.duration;
  22176. }
  22177. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  22178. var weight = animation.weight;
  22179. if ( keyframe !== animation.currentFrame ) {
  22180. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  22181. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  22182. this.morphTargetInfluences[ keyframe ] = 0;
  22183. animation.lastFrame = animation.currentFrame;
  22184. animation.currentFrame = keyframe;
  22185. }
  22186. var mix = ( animation.time % frameTime ) / frameTime;
  22187. if ( animation.directionBackwards ) mix = 1 - mix;
  22188. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  22189. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  22190. }
  22191. };
  22192. /**
  22193. * @author mikael emtinger / http://gomo.se/
  22194. * @author alteredq / http://alteredqualia.com/
  22195. */
  22196. THREE.LensFlarePlugin = function () {
  22197. var _gl, _renderer, _precision, _lensFlare = {};
  22198. this.init = function ( renderer ) {
  22199. _gl = renderer.context;
  22200. _renderer = renderer;
  22201. _precision = renderer.getPrecision();
  22202. _lensFlare.vertices = new Float32Array( 8 + 8 );
  22203. _lensFlare.faces = new Uint16Array( 6 );
  22204. var i = 0;
  22205. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  22206. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  22207. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  22208. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  22209. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  22210. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  22211. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  22212. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  22213. i = 0;
  22214. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  22215. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  22216. // buffers
  22217. _lensFlare.vertexBuffer = _gl.createBuffer();
  22218. _lensFlare.elementBuffer = _gl.createBuffer();
  22219. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  22220. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  22221. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  22222. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  22223. // textures
  22224. _lensFlare.tempTexture = _gl.createTexture();
  22225. _lensFlare.occlusionTexture = _gl.createTexture();
  22226. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  22227. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  22228. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  22229. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  22230. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  22231. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  22232. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  22233. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  22234. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  22235. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  22236. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  22237. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  22238. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  22239. _lensFlare.hasVertexTexture = false;
  22240. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  22241. } else {
  22242. _lensFlare.hasVertexTexture = true;
  22243. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  22244. }
  22245. _lensFlare.attributes = {};
  22246. _lensFlare.uniforms = {};
  22247. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  22248. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  22249. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  22250. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  22251. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  22252. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  22253. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  22254. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  22255. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  22256. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  22257. };
  22258. /*
  22259. * Render lens flares
  22260. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  22261. * reads these back and calculates occlusion.
  22262. * Then _lensFlare.update_lensFlares() is called to re-position and
  22263. * update transparency of flares. Then they are rendered.
  22264. *
  22265. */
  22266. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  22267. var flares = scene.__webglFlares,
  22268. nFlares = flares.length;
  22269. if ( ! nFlares ) return;
  22270. var tempPosition = new THREE.Vector3();
  22271. var invAspect = viewportHeight / viewportWidth,
  22272. halfViewportWidth = viewportWidth * 0.5,
  22273. halfViewportHeight = viewportHeight * 0.5;
  22274. var size = 16 / viewportHeight,
  22275. scale = new THREE.Vector2( size * invAspect, size );
  22276. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  22277. screenPositionPixels = new THREE.Vector2( 1, 1 );
  22278. var uniforms = _lensFlare.uniforms,
  22279. attributes = _lensFlare.attributes;
  22280. // set _lensFlare program and reset blending
  22281. _gl.useProgram( _lensFlare.program );
  22282. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  22283. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  22284. // loop through all lens flares to update their occlusion and positions
  22285. // setup gl and common used attribs/unforms
  22286. _gl.uniform1i( uniforms.occlusionMap, 0 );
  22287. _gl.uniform1i( uniforms.map, 1 );
  22288. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  22289. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  22290. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  22291. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  22292. _gl.disable( _gl.CULL_FACE );
  22293. _gl.depthMask( false );
  22294. var i, j, jl, flare, sprite;
  22295. for ( i = 0; i < nFlares; i ++ ) {
  22296. size = 16 / viewportHeight;
  22297. scale.set( size * invAspect, size );
  22298. // calc object screen position
  22299. flare = flares[ i ];
  22300. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  22301. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  22302. tempPosition.applyProjection( camera.projectionMatrix );
  22303. // setup arrays for gl programs
  22304. screenPosition.copy( tempPosition )
  22305. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  22306. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  22307. // screen cull
  22308. if ( _lensFlare.hasVertexTexture || (
  22309. screenPositionPixels.x > 0 &&
  22310. screenPositionPixels.x < viewportWidth &&
  22311. screenPositionPixels.y > 0 &&
  22312. screenPositionPixels.y < viewportHeight ) ) {
  22313. // save current RGB to temp texture
  22314. _gl.activeTexture( _gl.TEXTURE1 );
  22315. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  22316. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  22317. // render pink quad
  22318. _gl.uniform1i( uniforms.renderType, 0 );
  22319. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  22320. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  22321. _gl.disable( _gl.BLEND );
  22322. _gl.enable( _gl.DEPTH_TEST );
  22323. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  22324. // copy result to occlusionMap
  22325. _gl.activeTexture( _gl.TEXTURE0 );
  22326. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  22327. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  22328. // restore graphics
  22329. _gl.uniform1i( uniforms.renderType, 1 );
  22330. _gl.disable( _gl.DEPTH_TEST );
  22331. _gl.activeTexture( _gl.TEXTURE1 );
  22332. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  22333. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  22334. // update object positions
  22335. flare.positionScreen.copy( screenPosition )
  22336. if ( flare.customUpdateCallback ) {
  22337. flare.customUpdateCallback( flare );
  22338. } else {
  22339. flare.updateLensFlares();
  22340. }
  22341. // render flares
  22342. _gl.uniform1i( uniforms.renderType, 2 );
  22343. _gl.enable( _gl.BLEND );
  22344. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  22345. sprite = flare.lensFlares[ j ];
  22346. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  22347. screenPosition.x = sprite.x;
  22348. screenPosition.y = sprite.y;
  22349. screenPosition.z = sprite.z;
  22350. size = sprite.size * sprite.scale / viewportHeight;
  22351. scale.x = size * invAspect;
  22352. scale.y = size;
  22353. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  22354. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  22355. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  22356. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  22357. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  22358. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  22359. _renderer.setTexture( sprite.texture, 1 );
  22360. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  22361. }
  22362. }
  22363. }
  22364. }
  22365. // restore gl
  22366. _gl.enable( _gl.CULL_FACE );
  22367. _gl.enable( _gl.DEPTH_TEST );
  22368. _gl.depthMask( true );
  22369. };
  22370. function createProgram ( shader, precision ) {
  22371. var program = _gl.createProgram();
  22372. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  22373. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  22374. var prefix = "precision " + precision + " float;\n";
  22375. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  22376. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  22377. _gl.compileShader( fragmentShader );
  22378. _gl.compileShader( vertexShader );
  22379. _gl.attachShader( program, fragmentShader );
  22380. _gl.attachShader( program, vertexShader );
  22381. _gl.linkProgram( program );
  22382. return program;
  22383. };
  22384. };
  22385. /**
  22386. * @author alteredq / http://alteredqualia.com/
  22387. */
  22388. THREE.ShadowMapPlugin = function () {
  22389. var _gl,
  22390. _renderer,
  22391. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  22392. _frustum = new THREE.Frustum(),
  22393. _projScreenMatrix = new THREE.Matrix4(),
  22394. _min = new THREE.Vector3(),
  22395. _max = new THREE.Vector3(),
  22396. _matrixPosition = new THREE.Vector3();
  22397. this.init = function ( renderer ) {
  22398. _gl = renderer.context;
  22399. _renderer = renderer;
  22400. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  22401. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  22402. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  22403. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  22404. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  22405. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  22406. _depthMaterial._shadowPass = true;
  22407. _depthMaterialMorph._shadowPass = true;
  22408. _depthMaterialSkin._shadowPass = true;
  22409. _depthMaterialMorphSkin._shadowPass = true;
  22410. };
  22411. this.render = function ( scene, camera ) {
  22412. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  22413. this.update( scene, camera );
  22414. };
  22415. this.update = function ( scene, camera ) {
  22416. var i, il, j, jl, n,
  22417. shadowMap, shadowMatrix, shadowCamera,
  22418. program, buffer, material,
  22419. webglObject, object, light,
  22420. renderList,
  22421. lights = [],
  22422. k = 0,
  22423. fog = null;
  22424. // set GL state for depth map
  22425. _gl.clearColor( 1, 1, 1, 1 );
  22426. _gl.disable( _gl.BLEND );
  22427. _gl.enable( _gl.CULL_FACE );
  22428. _gl.frontFace( _gl.CCW );
  22429. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  22430. _gl.cullFace( _gl.FRONT );
  22431. } else {
  22432. _gl.cullFace( _gl.BACK );
  22433. }
  22434. _renderer.setDepthTest( true );
  22435. // preprocess lights
  22436. // - skip lights that are not casting shadows
  22437. // - create virtual lights for cascaded shadow maps
  22438. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  22439. light = scene.__lights[ i ];
  22440. if ( ! light.castShadow ) continue;
  22441. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  22442. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  22443. var virtualLight;
  22444. if ( ! light.shadowCascadeArray[ n ] ) {
  22445. virtualLight = createVirtualLight( light, n );
  22446. virtualLight.originalCamera = camera;
  22447. var gyro = new THREE.Gyroscope();
  22448. gyro.position.copy( light.shadowCascadeOffset );
  22449. gyro.add( virtualLight );
  22450. gyro.add( virtualLight.target );
  22451. camera.add( gyro );
  22452. light.shadowCascadeArray[ n ] = virtualLight;
  22453. console.log( "Created virtualLight", virtualLight );
  22454. } else {
  22455. virtualLight = light.shadowCascadeArray[ n ];
  22456. }
  22457. updateVirtualLight( light, n );
  22458. lights[ k ] = virtualLight;
  22459. k ++;
  22460. }
  22461. } else {
  22462. lights[ k ] = light;
  22463. k ++;
  22464. }
  22465. }
  22466. // render depth map
  22467. for ( i = 0, il = lights.length; i < il; i ++ ) {
  22468. light = lights[ i ];
  22469. if ( ! light.shadowMap ) {
  22470. var shadowFilter = THREE.LinearFilter;
  22471. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  22472. shadowFilter = THREE.NearestFilter;
  22473. }
  22474. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  22475. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  22476. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  22477. light.shadowMatrix = new THREE.Matrix4();
  22478. }
  22479. if ( ! light.shadowCamera ) {
  22480. if ( light instanceof THREE.SpotLight ) {
  22481. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  22482. } else if ( light instanceof THREE.DirectionalLight ) {
  22483. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  22484. } else {
  22485. console.error( "Unsupported light type for shadow" );
  22486. continue;
  22487. }
  22488. scene.add( light.shadowCamera );
  22489. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  22490. }
  22491. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  22492. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  22493. light.shadowCamera.add( light.cameraHelper );
  22494. }
  22495. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  22496. updateShadowCamera( camera, light );
  22497. }
  22498. shadowMap = light.shadowMap;
  22499. shadowMatrix = light.shadowMatrix;
  22500. shadowCamera = light.shadowCamera;
  22501. shadowCamera.position.setFromMatrixPosition( light.matrixWorld );
  22502. _matrixPosition.setFromMatrixPosition( light.target.matrixWorld );
  22503. shadowCamera.lookAt( _matrixPosition );
  22504. shadowCamera.updateMatrixWorld();
  22505. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  22506. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  22507. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  22508. // compute shadow matrix
  22509. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  22510. 0.0, 0.5, 0.0, 0.5,
  22511. 0.0, 0.0, 0.5, 0.5,
  22512. 0.0, 0.0, 0.0, 1.0 );
  22513. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  22514. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  22515. // update camera matrices and frustum
  22516. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  22517. _frustum.setFromMatrix( _projScreenMatrix );
  22518. // render shadow map
  22519. _renderer.setRenderTarget( shadowMap );
  22520. _renderer.clear();
  22521. // set object matrices & frustum culling
  22522. renderList = scene.__webglObjects;
  22523. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22524. webglObject = renderList[ j ];
  22525. object = webglObject.object;
  22526. webglObject.render = false;
  22527. if ( object.visible && object.castShadow ) {
  22528. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  22529. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  22530. webglObject.render = true;
  22531. }
  22532. }
  22533. }
  22534. // render regular objects
  22535. var objectMaterial, useMorphing, useSkinning;
  22536. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22537. webglObject = renderList[ j ];
  22538. if ( webglObject.render ) {
  22539. object = webglObject.object;
  22540. buffer = webglObject.buffer;
  22541. // culling is overriden globally for all objects
  22542. // while rendering depth map
  22543. // need to deal with MeshFaceMaterial somehow
  22544. // in that case just use the first of material.materials for now
  22545. // (proper solution would require to break objects by materials
  22546. // similarly to regular rendering and then set corresponding
  22547. // depth materials per each chunk instead of just once per object)
  22548. objectMaterial = getObjectMaterial( object );
  22549. useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  22550. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  22551. if ( object.customDepthMaterial ) {
  22552. material = object.customDepthMaterial;
  22553. } else if ( useSkinning ) {
  22554. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  22555. } else if ( useMorphing ) {
  22556. material = _depthMaterialMorph;
  22557. } else {
  22558. material = _depthMaterial;
  22559. }
  22560. if ( buffer instanceof THREE.BufferGeometry ) {
  22561. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  22562. } else {
  22563. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  22564. }
  22565. }
  22566. }
  22567. // set matrices and render immediate objects
  22568. renderList = scene.__webglObjectsImmediate;
  22569. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22570. webglObject = renderList[ j ];
  22571. object = webglObject.object;
  22572. if ( object.visible && object.castShadow ) {
  22573. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  22574. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  22575. }
  22576. }
  22577. }
  22578. // restore GL state
  22579. var clearColor = _renderer.getClearColor(),
  22580. clearAlpha = _renderer.getClearAlpha();
  22581. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  22582. _gl.enable( _gl.BLEND );
  22583. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  22584. _gl.cullFace( _gl.BACK );
  22585. }
  22586. };
  22587. function createVirtualLight( light, cascade ) {
  22588. var virtualLight = new THREE.DirectionalLight();
  22589. virtualLight.isVirtual = true;
  22590. virtualLight.onlyShadow = true;
  22591. virtualLight.castShadow = true;
  22592. virtualLight.shadowCameraNear = light.shadowCameraNear;
  22593. virtualLight.shadowCameraFar = light.shadowCameraFar;
  22594. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  22595. virtualLight.shadowCameraRight = light.shadowCameraRight;
  22596. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  22597. virtualLight.shadowCameraTop = light.shadowCameraTop;
  22598. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  22599. virtualLight.shadowDarkness = light.shadowDarkness;
  22600. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  22601. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  22602. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  22603. virtualLight.pointsWorld = [];
  22604. virtualLight.pointsFrustum = [];
  22605. var pointsWorld = virtualLight.pointsWorld,
  22606. pointsFrustum = virtualLight.pointsFrustum;
  22607. for ( var i = 0; i < 8; i ++ ) {
  22608. pointsWorld[ i ] = new THREE.Vector3();
  22609. pointsFrustum[ i ] = new THREE.Vector3();
  22610. }
  22611. var nearZ = light.shadowCascadeNearZ[ cascade ];
  22612. var farZ = light.shadowCascadeFarZ[ cascade ];
  22613. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  22614. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  22615. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  22616. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  22617. pointsFrustum[ 4 ].set( -1, -1, farZ );
  22618. pointsFrustum[ 5 ].set( 1, -1, farZ );
  22619. pointsFrustum[ 6 ].set( -1, 1, farZ );
  22620. pointsFrustum[ 7 ].set( 1, 1, farZ );
  22621. return virtualLight;
  22622. }
  22623. // Synchronize virtual light with the original light
  22624. function updateVirtualLight( light, cascade ) {
  22625. var virtualLight = light.shadowCascadeArray[ cascade ];
  22626. virtualLight.position.copy( light.position );
  22627. virtualLight.target.position.copy( light.target.position );
  22628. virtualLight.lookAt( virtualLight.target );
  22629. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  22630. virtualLight.shadowDarkness = light.shadowDarkness;
  22631. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  22632. var nearZ = light.shadowCascadeNearZ[ cascade ];
  22633. var farZ = light.shadowCascadeFarZ[ cascade ];
  22634. var pointsFrustum = virtualLight.pointsFrustum;
  22635. pointsFrustum[ 0 ].z = nearZ;
  22636. pointsFrustum[ 1 ].z = nearZ;
  22637. pointsFrustum[ 2 ].z = nearZ;
  22638. pointsFrustum[ 3 ].z = nearZ;
  22639. pointsFrustum[ 4 ].z = farZ;
  22640. pointsFrustum[ 5 ].z = farZ;
  22641. pointsFrustum[ 6 ].z = farZ;
  22642. pointsFrustum[ 7 ].z = farZ;
  22643. }
  22644. // Fit shadow camera's ortho frustum to camera frustum
  22645. function updateShadowCamera( camera, light ) {
  22646. var shadowCamera = light.shadowCamera,
  22647. pointsFrustum = light.pointsFrustum,
  22648. pointsWorld = light.pointsWorld;
  22649. _min.set( Infinity, Infinity, Infinity );
  22650. _max.set( -Infinity, -Infinity, -Infinity );
  22651. for ( var i = 0; i < 8; i ++ ) {
  22652. var p = pointsWorld[ i ];
  22653. p.copy( pointsFrustum[ i ] );
  22654. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  22655. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  22656. if ( p.x < _min.x ) _min.x = p.x;
  22657. if ( p.x > _max.x ) _max.x = p.x;
  22658. if ( p.y < _min.y ) _min.y = p.y;
  22659. if ( p.y > _max.y ) _max.y = p.y;
  22660. if ( p.z < _min.z ) _min.z = p.z;
  22661. if ( p.z > _max.z ) _max.z = p.z;
  22662. }
  22663. shadowCamera.left = _min.x;
  22664. shadowCamera.right = _max.x;
  22665. shadowCamera.top = _max.y;
  22666. shadowCamera.bottom = _min.y;
  22667. // can't really fit near/far
  22668. //shadowCamera.near = _min.z;
  22669. //shadowCamera.far = _max.z;
  22670. shadowCamera.updateProjectionMatrix();
  22671. }
  22672. // For the moment just ignore objects that have multiple materials with different animation methods
  22673. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  22674. function getObjectMaterial( object ) {
  22675. return object.material instanceof THREE.MeshFaceMaterial
  22676. ? object.material.materials[ 0 ]
  22677. : object.material;
  22678. };
  22679. };
  22680. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  22681. /**
  22682. * @author mikael emtinger / http://gomo.se/
  22683. * @author alteredq / http://alteredqualia.com/
  22684. */
  22685. THREE.SpritePlugin = function () {
  22686. var _gl, _renderer, _texture;
  22687. var vertices, faces, vertexBuffer, elementBuffer;
  22688. var program, attributes, uniforms;
  22689. this.init = function ( renderer ) {
  22690. _gl = renderer.context;
  22691. _renderer = renderer;
  22692. vertices = new Float32Array( [
  22693. - 0.5, - 0.5, 0, 0,
  22694. 0.5, - 0.5, 1, 0,
  22695. 0.5, 0.5, 1, 1,
  22696. - 0.5, 0.5, 0, 1
  22697. ] );
  22698. faces = new Uint16Array( [
  22699. 0, 1, 2,
  22700. 0, 2, 3
  22701. ] );
  22702. vertexBuffer = _gl.createBuffer();
  22703. elementBuffer = _gl.createBuffer();
  22704. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  22705. _gl.bufferData( _gl.ARRAY_BUFFER, vertices, _gl.STATIC_DRAW );
  22706. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  22707. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faces, _gl.STATIC_DRAW );
  22708. program = createProgram();
  22709. attributes = {
  22710. position: _gl.getAttribLocation ( program, 'position' ),
  22711. uv: _gl.getAttribLocation ( program, 'uv' )
  22712. };
  22713. uniforms = {
  22714. uvOffset: _gl.getUniformLocation( program, 'uvOffset' ),
  22715. uvScale: _gl.getUniformLocation( program, 'uvScale' ),
  22716. rotation: _gl.getUniformLocation( program, 'rotation' ),
  22717. scale: _gl.getUniformLocation( program, 'scale' ),
  22718. color: _gl.getUniformLocation( program, 'color' ),
  22719. map: _gl.getUniformLocation( program, 'map' ),
  22720. opacity: _gl.getUniformLocation( program, 'opacity' ),
  22721. modelViewMatrix: _gl.getUniformLocation( program, 'modelViewMatrix' ),
  22722. projectionMatrix: _gl.getUniformLocation( program, 'projectionMatrix' ),
  22723. fogType: _gl.getUniformLocation( program, 'fogType' ),
  22724. fogDensity: _gl.getUniformLocation( program, 'fogDensity' ),
  22725. fogNear: _gl.getUniformLocation( program, 'fogNear' ),
  22726. fogFar: _gl.getUniformLocation( program, 'fogFar' ),
  22727. fogColor: _gl.getUniformLocation( program, 'fogColor' ),
  22728. alphaTest: _gl.getUniformLocation( program, 'alphaTest' )
  22729. };
  22730. var canvas = document.createElement( 'canvas' );
  22731. canvas.width = 8;
  22732. canvas.height = 8;
  22733. var context = canvas.getContext( '2d' );
  22734. context.fillStyle = '#ffffff';
  22735. context.fillRect( 0, 0, canvas.width, canvas.height );
  22736. _texture = new THREE.Texture( canvas );
  22737. _texture.needsUpdate = true;
  22738. };
  22739. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  22740. var sprites = scene.__webglSprites,
  22741. nSprites = sprites.length;
  22742. if ( ! nSprites ) return;
  22743. // setup gl
  22744. _gl.useProgram( program );
  22745. _gl.enableVertexAttribArray( attributes.position );
  22746. _gl.enableVertexAttribArray( attributes.uv );
  22747. _gl.disable( _gl.CULL_FACE );
  22748. _gl.enable( _gl.BLEND );
  22749. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  22750. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  22751. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  22752. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  22753. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  22754. _gl.activeTexture( _gl.TEXTURE0 );
  22755. _gl.uniform1i( uniforms.map, 0 );
  22756. var oldFogType = 0;
  22757. var sceneFogType = 0;
  22758. var fog = scene.fog;
  22759. if ( fog ) {
  22760. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  22761. if ( fog instanceof THREE.Fog ) {
  22762. _gl.uniform1f( uniforms.fogNear, fog.near );
  22763. _gl.uniform1f( uniforms.fogFar, fog.far );
  22764. _gl.uniform1i( uniforms.fogType, 1 );
  22765. oldFogType = 1;
  22766. sceneFogType = 1;
  22767. } else if ( fog instanceof THREE.FogExp2 ) {
  22768. _gl.uniform1f( uniforms.fogDensity, fog.density );
  22769. _gl.uniform1i( uniforms.fogType, 2 );
  22770. oldFogType = 2;
  22771. sceneFogType = 2;
  22772. }
  22773. } else {
  22774. _gl.uniform1i( uniforms.fogType, 0 );
  22775. oldFogType = 0;
  22776. sceneFogType = 0;
  22777. }
  22778. // update positions and sort
  22779. var i, sprite, material, fogType, scale = [];
  22780. for( i = 0; i < nSprites; i ++ ) {
  22781. sprite = sprites[ i ];
  22782. material = sprite.material;
  22783. if ( sprite.visible === false ) continue;
  22784. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  22785. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  22786. }
  22787. sprites.sort( painterSortStable );
  22788. // render all sprites
  22789. for( i = 0; i < nSprites; i ++ ) {
  22790. sprite = sprites[ i ];
  22791. if ( sprite.visible === false ) continue;
  22792. material = sprite.material;
  22793. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  22794. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  22795. scale[ 0 ] = sprite.scale.x;
  22796. scale[ 1 ] = sprite.scale.y;
  22797. if ( scene.fog && material.fog ) {
  22798. fogType = sceneFogType;
  22799. } else {
  22800. fogType = 0;
  22801. }
  22802. if ( oldFogType !== fogType ) {
  22803. _gl.uniform1i( uniforms.fogType, fogType );
  22804. oldFogType = fogType;
  22805. }
  22806. if ( material.map !== null ) {
  22807. _gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  22808. _gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  22809. } else {
  22810. _gl.uniform2f( uniforms.uvOffset, 0, 0 );
  22811. _gl.uniform2f( uniforms.uvScale, 1, 1 );
  22812. }
  22813. _gl.uniform1f( uniforms.opacity, material.opacity );
  22814. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  22815. _gl.uniform1f( uniforms.rotation, material.rotation );
  22816. _gl.uniform2fv( uniforms.scale, scale );
  22817. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  22818. _renderer.setDepthTest( material.depthTest );
  22819. _renderer.setDepthWrite( material.depthWrite );
  22820. if ( material.map && material.map.image && material.map.image.width ) {
  22821. _renderer.setTexture( material.map, 0 );
  22822. } else {
  22823. _renderer.setTexture( _texture, 0 );
  22824. }
  22825. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  22826. }
  22827. // restore gl
  22828. _gl.enable( _gl.CULL_FACE );
  22829. };
  22830. function createProgram () {
  22831. var program = _gl.createProgram();
  22832. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  22833. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  22834. _gl.shaderSource( vertexShader, [
  22835. 'precision ' + _renderer.getPrecision() + ' float;',
  22836. 'uniform mat4 modelViewMatrix;',
  22837. 'uniform mat4 projectionMatrix;',
  22838. 'uniform float rotation;',
  22839. 'uniform vec2 scale;',
  22840. 'uniform vec2 uvOffset;',
  22841. 'uniform vec2 uvScale;',
  22842. 'attribute vec2 position;',
  22843. 'attribute vec2 uv;',
  22844. 'varying vec2 vUV;',
  22845. 'void main() {',
  22846. 'vUV = uvOffset + uv * uvScale;',
  22847. 'vec2 alignedPosition = position * scale;',
  22848. 'vec2 rotatedPosition;',
  22849. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  22850. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  22851. 'vec4 finalPosition;',
  22852. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  22853. 'finalPosition.xy += rotatedPosition;',
  22854. 'finalPosition = projectionMatrix * finalPosition;',
  22855. 'gl_Position = finalPosition;',
  22856. '}'
  22857. ].join( '\n' ) );
  22858. _gl.shaderSource( fragmentShader, [
  22859. 'precision ' + _renderer.getPrecision() + ' float;',
  22860. 'uniform vec3 color;',
  22861. 'uniform sampler2D map;',
  22862. 'uniform float opacity;',
  22863. 'uniform int fogType;',
  22864. 'uniform vec3 fogColor;',
  22865. 'uniform float fogDensity;',
  22866. 'uniform float fogNear;',
  22867. 'uniform float fogFar;',
  22868. 'uniform float alphaTest;',
  22869. 'varying vec2 vUV;',
  22870. 'void main() {',
  22871. 'vec4 texture = texture2D( map, vUV );',
  22872. 'if ( texture.a < alphaTest ) discard;',
  22873. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  22874. 'if ( fogType > 0 ) {',
  22875. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  22876. 'float fogFactor = 0.0;',
  22877. 'if ( fogType == 1 ) {',
  22878. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  22879. '} else {',
  22880. 'const float LOG2 = 1.442695;',
  22881. 'float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  22882. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  22883. '}',
  22884. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  22885. '}',
  22886. '}'
  22887. ].join( '\n' ) );
  22888. _gl.compileShader( vertexShader );
  22889. _gl.compileShader( fragmentShader );
  22890. _gl.attachShader( program, vertexShader );
  22891. _gl.attachShader( program, fragmentShader );
  22892. _gl.linkProgram( program );
  22893. return program;
  22894. };
  22895. function painterSortStable ( a, b ) {
  22896. if ( a.z !== b.z ) {
  22897. return b.z - a.z;
  22898. } else {
  22899. return b.id - a.id;
  22900. }
  22901. };
  22902. };
  22903. /**
  22904. * @author alteredq / http://alteredqualia.com/
  22905. */
  22906. THREE.DepthPassPlugin = function () {
  22907. this.enabled = false;
  22908. this.renderTarget = null;
  22909. var _gl,
  22910. _renderer,
  22911. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  22912. _frustum = new THREE.Frustum(),
  22913. _projScreenMatrix = new THREE.Matrix4();
  22914. this.init = function ( renderer ) {
  22915. _gl = renderer.context;
  22916. _renderer = renderer;
  22917. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  22918. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  22919. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  22920. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  22921. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  22922. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  22923. _depthMaterial._shadowPass = true;
  22924. _depthMaterialMorph._shadowPass = true;
  22925. _depthMaterialSkin._shadowPass = true;
  22926. _depthMaterialMorphSkin._shadowPass = true;
  22927. };
  22928. this.render = function ( scene, camera ) {
  22929. if ( ! this.enabled ) return;
  22930. this.update( scene, camera );
  22931. };
  22932. this.update = function ( scene, camera ) {
  22933. var i, il, j, jl, n,
  22934. program, buffer, material,
  22935. webglObject, object, light,
  22936. renderList,
  22937. fog = null;
  22938. // set GL state for depth map
  22939. _gl.clearColor( 1, 1, 1, 1 );
  22940. _gl.disable( _gl.BLEND );
  22941. _renderer.setDepthTest( true );
  22942. // update scene
  22943. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  22944. // update camera matrices and frustum
  22945. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  22946. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  22947. _frustum.setFromMatrix( _projScreenMatrix );
  22948. // render depth map
  22949. _renderer.setRenderTarget( this.renderTarget );
  22950. _renderer.clear();
  22951. // set object matrices & frustum culling
  22952. renderList = scene.__webglObjects;
  22953. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22954. webglObject = renderList[ j ];
  22955. object = webglObject.object;
  22956. webglObject.render = false;
  22957. if ( object.visible ) {
  22958. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  22959. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22960. webglObject.render = true;
  22961. }
  22962. }
  22963. }
  22964. // render regular objects
  22965. var objectMaterial, useMorphing, useSkinning;
  22966. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22967. webglObject = renderList[ j ];
  22968. if ( webglObject.render ) {
  22969. object = webglObject.object;
  22970. buffer = webglObject.buffer;
  22971. // todo: create proper depth material for particles
  22972. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  22973. objectMaterial = getObjectMaterial( object );
  22974. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  22975. useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  22976. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  22977. if ( object.customDepthMaterial ) {
  22978. material = object.customDepthMaterial;
  22979. } else if ( useSkinning ) {
  22980. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  22981. } else if ( useMorphing ) {
  22982. material = _depthMaterialMorph;
  22983. } else {
  22984. material = _depthMaterial;
  22985. }
  22986. if ( buffer instanceof THREE.BufferGeometry ) {
  22987. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  22988. } else {
  22989. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  22990. }
  22991. }
  22992. }
  22993. // set matrices and render immediate objects
  22994. renderList = scene.__webglObjectsImmediate;
  22995. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22996. webglObject = renderList[ j ];
  22997. object = webglObject.object;
  22998. if ( object.visible ) {
  22999. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  23000. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  23001. }
  23002. }
  23003. // restore GL state
  23004. var clearColor = _renderer.getClearColor(),
  23005. clearAlpha = _renderer.getClearAlpha();
  23006. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  23007. _gl.enable( _gl.BLEND );
  23008. };
  23009. // For the moment just ignore objects that have multiple materials with different animation methods
  23010. // Only the first material will be taken into account for deciding which depth material to use
  23011. function getObjectMaterial( object ) {
  23012. return object.material instanceof THREE.MeshFaceMaterial
  23013. ? object.material.materials[ 0 ]
  23014. : object.material;
  23015. };
  23016. };
  23017. /**
  23018. * @author mikael emtinger / http://gomo.se/
  23019. */
  23020. THREE.ShaderFlares = {
  23021. 'lensFlareVertexTexture': {
  23022. vertexShader: [
  23023. "uniform lowp int renderType;",
  23024. "uniform vec3 screenPosition;",
  23025. "uniform vec2 scale;",
  23026. "uniform float rotation;",
  23027. "uniform sampler2D occlusionMap;",
  23028. "attribute vec2 position;",
  23029. "attribute vec2 uv;",
  23030. "varying vec2 vUV;",
  23031. "varying float vVisibility;",
  23032. "void main() {",
  23033. "vUV = uv;",
  23034. "vec2 pos = position;",
  23035. "if( renderType == 2 ) {",
  23036. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  23037. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  23038. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  23039. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  23040. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  23041. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  23042. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  23043. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  23044. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  23045. "vVisibility = visibility.r / 9.0;",
  23046. "vVisibility *= 1.0 - visibility.g / 9.0;",
  23047. "vVisibility *= visibility.b / 9.0;",
  23048. "vVisibility *= 1.0 - visibility.a / 9.0;",
  23049. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  23050. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  23051. "}",
  23052. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  23053. "}"
  23054. ].join( "\n" ),
  23055. fragmentShader: [
  23056. "uniform lowp int renderType;",
  23057. "uniform sampler2D map;",
  23058. "uniform float opacity;",
  23059. "uniform vec3 color;",
  23060. "varying vec2 vUV;",
  23061. "varying float vVisibility;",
  23062. "void main() {",
  23063. // pink square
  23064. "if( renderType == 0 ) {",
  23065. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  23066. // restore
  23067. "} else if( renderType == 1 ) {",
  23068. "gl_FragColor = texture2D( map, vUV );",
  23069. // flare
  23070. "} else {",
  23071. "vec4 texture = texture2D( map, vUV );",
  23072. "texture.a *= opacity * vVisibility;",
  23073. "gl_FragColor = texture;",
  23074. "gl_FragColor.rgb *= color;",
  23075. "}",
  23076. "}"
  23077. ].join( "\n" )
  23078. },
  23079. 'lensFlare': {
  23080. vertexShader: [
  23081. "uniform lowp int renderType;",
  23082. "uniform vec3 screenPosition;",
  23083. "uniform vec2 scale;",
  23084. "uniform float rotation;",
  23085. "attribute vec2 position;",
  23086. "attribute vec2 uv;",
  23087. "varying vec2 vUV;",
  23088. "void main() {",
  23089. "vUV = uv;",
  23090. "vec2 pos = position;",
  23091. "if( renderType == 2 ) {",
  23092. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  23093. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  23094. "}",
  23095. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  23096. "}"
  23097. ].join( "\n" ),
  23098. fragmentShader: [
  23099. "precision mediump float;",
  23100. "uniform lowp int renderType;",
  23101. "uniform sampler2D map;",
  23102. "uniform sampler2D occlusionMap;",
  23103. "uniform float opacity;",
  23104. "uniform vec3 color;",
  23105. "varying vec2 vUV;",
  23106. "void main() {",
  23107. // pink square
  23108. "if( renderType == 0 ) {",
  23109. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  23110. // restore
  23111. "} else if( renderType == 1 ) {",
  23112. "gl_FragColor = texture2D( map, vUV );",
  23113. // flare
  23114. "} else {",
  23115. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  23116. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  23117. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  23118. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  23119. "visibility = ( 1.0 - visibility / 4.0 );",
  23120. "vec4 texture = texture2D( map, vUV );",
  23121. "texture.a *= opacity * visibility;",
  23122. "gl_FragColor = texture;",
  23123. "gl_FragColor.rgb *= color;",
  23124. "}",
  23125. "}"
  23126. ].join( "\n" )
  23127. }
  23128. };
粤ICP备19079148号