three.js 824 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001
  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. _euler: undefined,
  401. _updateEuler: function ( callback ) {
  402. if ( this._euler !== undefined ) {
  403. this._euler.setFromQuaternion( this, undefined, false );
  404. }
  405. },
  406. get x () {
  407. return this._x;
  408. },
  409. set x ( value ) {
  410. this._x = value;
  411. this._updateEuler();
  412. },
  413. get y () {
  414. return this._y;
  415. },
  416. set y ( value ) {
  417. this._y = value;
  418. this._updateEuler();
  419. },
  420. get z () {
  421. return this._z;
  422. },
  423. set z ( value ) {
  424. this._z = value;
  425. this._updateEuler();
  426. },
  427. get w () {
  428. return this._w;
  429. },
  430. set w ( value ) {
  431. this._w = value;
  432. this._updateEuler();
  433. },
  434. set: function ( x, y, z, w ) {
  435. this._x = x;
  436. this._y = y;
  437. this._z = z;
  438. this._w = w;
  439. this._updateEuler();
  440. return this;
  441. },
  442. copy: function ( quaternion ) {
  443. this._x = quaternion._x;
  444. this._y = quaternion._y;
  445. this._z = quaternion._z;
  446. this._w = quaternion._w;
  447. this._updateEuler();
  448. return this;
  449. },
  450. setFromEuler: function ( euler, update ) {
  451. if ( euler instanceof THREE.Euler === false ) {
  452. throw new Error( 'ERROR: Quaternion\'s .setFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  453. }
  454. // http://www.mathworks.com/matlabcentral/fileexchange/
  455. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  456. // content/SpinCalc.m
  457. var c1 = Math.cos( euler._x / 2 );
  458. var c2 = Math.cos( euler._y / 2 );
  459. var c3 = Math.cos( euler._z / 2 );
  460. var s1 = Math.sin( euler._x / 2 );
  461. var s2 = Math.sin( euler._y / 2 );
  462. var s3 = Math.sin( euler._z / 2 );
  463. if ( euler.order === 'XYZ' ) {
  464. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  465. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  466. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  467. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  468. } else if ( euler.order === 'YXZ' ) {
  469. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  470. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  471. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  472. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  473. } else if ( euler.order === 'ZXY' ) {
  474. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  475. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  476. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  477. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  478. } else if ( euler.order === 'ZYX' ) {
  479. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  480. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  481. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  482. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  483. } else if ( euler.order === 'YZX' ) {
  484. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  485. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  486. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  487. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  488. } else if ( euler.order === 'XZY' ) {
  489. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  490. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  491. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  492. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  493. }
  494. if ( update !== false ) this._updateEuler();
  495. return this;
  496. },
  497. setFromAxisAngle: function ( axis, angle ) {
  498. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  499. // axis have to be normalized
  500. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  501. this._x = axis.x * s;
  502. this._y = axis.y * s;
  503. this._z = axis.z * s;
  504. this._w = Math.cos( halfAngle );
  505. this._updateEuler();
  506. return this;
  507. },
  508. setFromRotationMatrix: function ( m ) {
  509. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  510. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  511. var te = m.elements,
  512. m11 = te[0], m12 = te[4], m13 = te[8],
  513. m21 = te[1], m22 = te[5], m23 = te[9],
  514. m31 = te[2], m32 = te[6], m33 = te[10],
  515. trace = m11 + m22 + m33,
  516. s;
  517. if ( trace > 0 ) {
  518. s = 0.5 / Math.sqrt( trace + 1.0 );
  519. this._w = 0.25 / s;
  520. this._x = ( m32 - m23 ) * s;
  521. this._y = ( m13 - m31 ) * s;
  522. this._z = ( m21 - m12 ) * s;
  523. } else if ( m11 > m22 && m11 > m33 ) {
  524. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  525. this._w = (m32 - m23 ) / s;
  526. this._x = 0.25 * s;
  527. this._y = (m12 + m21 ) / s;
  528. this._z = (m13 + m31 ) / s;
  529. } else if ( m22 > m33 ) {
  530. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  531. this._w = (m13 - m31 ) / s;
  532. this._x = (m12 + m21 ) / s;
  533. this._y = 0.25 * s;
  534. this._z = (m23 + m32 ) / s;
  535. } else {
  536. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  537. this._w = ( m21 - m12 ) / s;
  538. this._x = ( m13 + m31 ) / s;
  539. this._y = ( m23 + m32 ) / s;
  540. this._z = 0.25 * s;
  541. }
  542. this._updateEuler();
  543. return this;
  544. },
  545. inverse: function () {
  546. this.conjugate().normalize();
  547. return this;
  548. },
  549. conjugate: function () {
  550. this._x *= -1;
  551. this._y *= -1;
  552. this._z *= -1;
  553. this._updateEuler();
  554. return this;
  555. },
  556. lengthSq: function () {
  557. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  558. },
  559. length: function () {
  560. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  561. },
  562. normalize: function () {
  563. var l = this.length();
  564. if ( l === 0 ) {
  565. this._x = 0;
  566. this._y = 0;
  567. this._z = 0;
  568. this._w = 1;
  569. } else {
  570. l = 1 / l;
  571. this._x = this._x * l;
  572. this._y = this._y * l;
  573. this._z = this._z * l;
  574. this._w = this._w * l;
  575. }
  576. return this;
  577. },
  578. multiply: function ( q, p ) {
  579. if ( p !== undefined ) {
  580. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  581. return this.multiplyQuaternions( q, p );
  582. }
  583. return this.multiplyQuaternions( this, q );
  584. },
  585. multiplyQuaternions: function ( a, b ) {
  586. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  587. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  588. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  589. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  590. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  591. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  592. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  593. this._updateEuler();
  594. return this;
  595. },
  596. multiplyVector3: function ( vector ) {
  597. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  598. return vector.applyQuaternion( this );
  599. },
  600. slerp: function ( qb, t ) {
  601. var x = this._x, y = this._y, z = this._z, w = this._w;
  602. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  603. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  604. if ( cosHalfTheta < 0 ) {
  605. this._w = -qb._w;
  606. this._x = -qb._x;
  607. this._y = -qb._y;
  608. this._z = -qb._z;
  609. cosHalfTheta = -cosHalfTheta;
  610. } else {
  611. this.copy( qb );
  612. }
  613. if ( cosHalfTheta >= 1.0 ) {
  614. this._w = w;
  615. this._x = x;
  616. this._y = y;
  617. this._z = z;
  618. return this;
  619. }
  620. var halfTheta = Math.acos( cosHalfTheta );
  621. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  622. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  623. this._w = 0.5 * ( w + this._w );
  624. this._x = 0.5 * ( x + this._x );
  625. this._y = 0.5 * ( y + this._y );
  626. this._z = 0.5 * ( z + this._z );
  627. return this;
  628. }
  629. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  630. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  631. this._w = ( w * ratioA + this._w * ratioB );
  632. this._x = ( x * ratioA + this._x * ratioB );
  633. this._y = ( y * ratioA + this._y * ratioB );
  634. this._z = ( z * ratioA + this._z * ratioB );
  635. this._updateEuler();
  636. return this;
  637. },
  638. equals: function ( quaternion ) {
  639. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  640. },
  641. fromArray: function ( array ) {
  642. this._x = array[ 0 ];
  643. this._y = array[ 1 ];
  644. this._z = array[ 2 ];
  645. this._w = array[ 3 ];
  646. this._updateEuler();
  647. return this;
  648. },
  649. toArray: function () {
  650. return [ this._x, this._y, this._z, this._w ];
  651. },
  652. clone: function () {
  653. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  654. }
  655. };
  656. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  657. return qm.copy( qa ).slerp( qb, t );
  658. }
  659. /**
  660. * @author mrdoob / http://mrdoob.com/
  661. * @author philogb / http://blog.thejit.org/
  662. * @author egraether / http://egraether.com/
  663. * @author zz85 / http://www.lab4games.net/zz85/blog
  664. */
  665. THREE.Vector2 = function ( x, y ) {
  666. this.x = x || 0;
  667. this.y = y || 0;
  668. };
  669. THREE.Vector2.prototype = {
  670. constructor: THREE.Vector2,
  671. set: function ( x, y ) {
  672. this.x = x;
  673. this.y = y;
  674. return this;
  675. },
  676. setX: function ( x ) {
  677. this.x = x;
  678. return this;
  679. },
  680. setY: function ( y ) {
  681. this.y = y;
  682. return this;
  683. },
  684. setComponent: function ( index, value ) {
  685. switch ( index ) {
  686. case 0: this.x = value; break;
  687. case 1: this.y = value; break;
  688. default: throw new Error( "index is out of range: " + index );
  689. }
  690. },
  691. getComponent: function ( index ) {
  692. switch ( index ) {
  693. case 0: return this.x;
  694. case 1: return this.y;
  695. default: throw new Error( "index is out of range: " + index );
  696. }
  697. },
  698. copy: function ( v ) {
  699. this.x = v.x;
  700. this.y = v.y;
  701. return this;
  702. },
  703. add: function ( v, w ) {
  704. if ( w !== undefined ) {
  705. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  706. return this.addVectors( v, w );
  707. }
  708. this.x += v.x;
  709. this.y += v.y;
  710. return this;
  711. },
  712. addVectors: function ( a, b ) {
  713. this.x = a.x + b.x;
  714. this.y = a.y + b.y;
  715. return this;
  716. },
  717. addScalar: function ( s ) {
  718. this.x += s;
  719. this.y += s;
  720. return this;
  721. },
  722. sub: function ( v, w ) {
  723. if ( w !== undefined ) {
  724. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  725. return this.subVectors( v, w );
  726. }
  727. this.x -= v.x;
  728. this.y -= v.y;
  729. return this;
  730. },
  731. subVectors: function ( a, b ) {
  732. this.x = a.x - b.x;
  733. this.y = a.y - b.y;
  734. return this;
  735. },
  736. multiplyScalar: function ( s ) {
  737. this.x *= s;
  738. this.y *= s;
  739. return this;
  740. },
  741. divideScalar: function ( scalar ) {
  742. if ( scalar !== 0 ) {
  743. var invScalar = 1 / scalar;
  744. this.x *= invScalar;
  745. this.y *= invScalar;
  746. } else {
  747. this.x = 0;
  748. this.y = 0;
  749. }
  750. return this;
  751. },
  752. min: function ( v ) {
  753. if ( this.x > v.x ) {
  754. this.x = v.x;
  755. }
  756. if ( this.y > v.y ) {
  757. this.y = v.y;
  758. }
  759. return this;
  760. },
  761. max: function ( v ) {
  762. if ( this.x < v.x ) {
  763. this.x = v.x;
  764. }
  765. if ( this.y < v.y ) {
  766. this.y = v.y;
  767. }
  768. return this;
  769. },
  770. clamp: function ( min, max ) {
  771. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  772. if ( this.x < min.x ) {
  773. this.x = min.x;
  774. } else if ( this.x > max.x ) {
  775. this.x = max.x;
  776. }
  777. if ( this.y < min.y ) {
  778. this.y = min.y;
  779. } else if ( this.y > max.y ) {
  780. this.y = max.y;
  781. }
  782. return this;
  783. },
  784. clampScalar: ( function () {
  785. var min, max;
  786. return function ( minVal, maxVal ) {
  787. if ( min === undefined ) {
  788. min = new THREE.Vector2();
  789. max = new THREE.Vector2();
  790. }
  791. min.set( minVal, minVal );
  792. max.set( maxVal, maxVal );
  793. return this.clamp( min, max );
  794. };
  795. } )(),
  796. floor: function () {
  797. this.x = Math.floor( this.x );
  798. this.y = Math.floor( this.y );
  799. return this;
  800. },
  801. ceil: function () {
  802. this.x = Math.ceil( this.x );
  803. this.y = Math.ceil( this.y );
  804. return this;
  805. },
  806. round: function () {
  807. this.x = Math.round( this.x );
  808. this.y = Math.round( this.y );
  809. return this;
  810. },
  811. roundToZero: function () {
  812. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  813. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  814. return this;
  815. },
  816. negate: function () {
  817. return this.multiplyScalar( - 1 );
  818. },
  819. dot: function ( v ) {
  820. return this.x * v.x + this.y * v.y;
  821. },
  822. lengthSq: function () {
  823. return this.x * this.x + this.y * this.y;
  824. },
  825. length: function () {
  826. return Math.sqrt( this.x * this.x + this.y * this.y );
  827. },
  828. normalize: function () {
  829. return this.divideScalar( this.length() );
  830. },
  831. distanceTo: function ( v ) {
  832. return Math.sqrt( this.distanceToSquared( v ) );
  833. },
  834. distanceToSquared: function ( v ) {
  835. var dx = this.x - v.x, dy = this.y - v.y;
  836. return dx * dx + dy * dy;
  837. },
  838. setLength: function ( l ) {
  839. var oldLength = this.length();
  840. if ( oldLength !== 0 && l !== oldLength ) {
  841. this.multiplyScalar( l / oldLength );
  842. }
  843. return this;
  844. },
  845. lerp: function ( v, alpha ) {
  846. this.x += ( v.x - this.x ) * alpha;
  847. this.y += ( v.y - this.y ) * alpha;
  848. return this;
  849. },
  850. equals: function( v ) {
  851. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  852. },
  853. fromArray: function ( array ) {
  854. this.x = array[ 0 ];
  855. this.y = array[ 1 ];
  856. return this;
  857. },
  858. toArray: function () {
  859. return [ this.x, this.y ];
  860. },
  861. clone: function () {
  862. return new THREE.Vector2( this.x, this.y );
  863. }
  864. };
  865. /**
  866. * @author mrdoob / http://mrdoob.com/
  867. * @author *kile / http://kile.stravaganza.org/
  868. * @author philogb / http://blog.thejit.org/
  869. * @author mikael emtinger / http://gomo.se/
  870. * @author egraether / http://egraether.com/
  871. * @author WestLangley / http://github.com/WestLangley
  872. */
  873. THREE.Vector3 = function ( x, y, z ) {
  874. this.x = x || 0;
  875. this.y = y || 0;
  876. this.z = z || 0;
  877. };
  878. THREE.Vector3.prototype = {
  879. constructor: THREE.Vector3,
  880. set: function ( x, y, z ) {
  881. this.x = x;
  882. this.y = y;
  883. this.z = z;
  884. return this;
  885. },
  886. setX: function ( x ) {
  887. this.x = x;
  888. return this;
  889. },
  890. setY: function ( y ) {
  891. this.y = y;
  892. return this;
  893. },
  894. setZ: function ( z ) {
  895. this.z = z;
  896. return this;
  897. },
  898. setComponent: function ( index, value ) {
  899. switch ( index ) {
  900. case 0: this.x = value; break;
  901. case 1: this.y = value; break;
  902. case 2: this.z = value; break;
  903. default: throw new Error( "index is out of range: " + index );
  904. }
  905. },
  906. getComponent: function ( index ) {
  907. switch ( index ) {
  908. case 0: return this.x;
  909. case 1: return this.y;
  910. case 2: return this.z;
  911. default: throw new Error( "index is out of range: " + index );
  912. }
  913. },
  914. copy: function ( v ) {
  915. this.x = v.x;
  916. this.y = v.y;
  917. this.z = v.z;
  918. return this;
  919. },
  920. add: function ( v, w ) {
  921. if ( w !== undefined ) {
  922. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  923. return this.addVectors( v, w );
  924. }
  925. this.x += v.x;
  926. this.y += v.y;
  927. this.z += v.z;
  928. return this;
  929. },
  930. addScalar: function ( s ) {
  931. this.x += s;
  932. this.y += s;
  933. this.z += s;
  934. return this;
  935. },
  936. addVectors: function ( a, b ) {
  937. this.x = a.x + b.x;
  938. this.y = a.y + b.y;
  939. this.z = a.z + b.z;
  940. return this;
  941. },
  942. sub: function ( v, w ) {
  943. if ( w !== undefined ) {
  944. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  945. return this.subVectors( v, w );
  946. }
  947. this.x -= v.x;
  948. this.y -= v.y;
  949. this.z -= v.z;
  950. return this;
  951. },
  952. subVectors: function ( a, b ) {
  953. this.x = a.x - b.x;
  954. this.y = a.y - b.y;
  955. this.z = a.z - b.z;
  956. return this;
  957. },
  958. multiply: function ( v, w ) {
  959. if ( w !== undefined ) {
  960. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  961. return this.multiplyVectors( v, w );
  962. }
  963. this.x *= v.x;
  964. this.y *= v.y;
  965. this.z *= v.z;
  966. return this;
  967. },
  968. multiplyScalar: function ( scalar ) {
  969. this.x *= scalar;
  970. this.y *= scalar;
  971. this.z *= scalar;
  972. return this;
  973. },
  974. multiplyVectors: function ( a, b ) {
  975. this.x = a.x * b.x;
  976. this.y = a.y * b.y;
  977. this.z = a.z * b.z;
  978. return this;
  979. },
  980. applyEuler: function () {
  981. var quaternion;
  982. return function ( euler ) {
  983. if ( euler instanceof THREE.Euler === false ) {
  984. console.error( 'ERROR: Vector3\'s .applyEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  985. }
  986. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  987. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  988. return this;
  989. };
  990. }(),
  991. applyAxisAngle: function () {
  992. var quaternion;
  993. return function ( axis, angle ) {
  994. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  995. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  996. return this;
  997. };
  998. }(),
  999. applyMatrix3: function ( m ) {
  1000. var x = this.x;
  1001. var y = this.y;
  1002. var z = this.z;
  1003. var e = m.elements;
  1004. this.x = e[0] * x + e[3] * y + e[6] * z;
  1005. this.y = e[1] * x + e[4] * y + e[7] * z;
  1006. this.z = e[2] * x + e[5] * y + e[8] * z;
  1007. return this;
  1008. },
  1009. applyMatrix4: function ( m ) {
  1010. // input: THREE.Matrix4 affine matrix
  1011. var x = this.x, y = this.y, z = this.z;
  1012. var e = m.elements;
  1013. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  1014. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  1015. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  1016. return this;
  1017. },
  1018. applyProjection: function ( m ) {
  1019. // input: THREE.Matrix4 projection matrix
  1020. var x = this.x, y = this.y, z = this.z;
  1021. var e = m.elements;
  1022. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  1023. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  1024. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  1025. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  1026. return this;
  1027. },
  1028. applyQuaternion: function ( q ) {
  1029. var x = this.x;
  1030. var y = this.y;
  1031. var z = this.z;
  1032. var qx = q.x;
  1033. var qy = q.y;
  1034. var qz = q.z;
  1035. var qw = q.w;
  1036. // calculate quat * vector
  1037. var ix = qw * x + qy * z - qz * y;
  1038. var iy = qw * y + qz * x - qx * z;
  1039. var iz = qw * z + qx * y - qy * x;
  1040. var iw = -qx * x - qy * y - qz * z;
  1041. // calculate result * inverse quat
  1042. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  1043. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  1044. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  1045. return this;
  1046. },
  1047. transformDirection: function ( m ) {
  1048. // input: THREE.Matrix4 affine matrix
  1049. // vector interpreted as a direction
  1050. var x = this.x, y = this.y, z = this.z;
  1051. var e = m.elements;
  1052. this.x = e[0] * x + e[4] * y + e[8] * z;
  1053. this.y = e[1] * x + e[5] * y + e[9] * z;
  1054. this.z = e[2] * x + e[6] * y + e[10] * z;
  1055. this.normalize();
  1056. return this;
  1057. },
  1058. divide: function ( v ) {
  1059. this.x /= v.x;
  1060. this.y /= v.y;
  1061. this.z /= v.z;
  1062. return this;
  1063. },
  1064. divideScalar: function ( scalar ) {
  1065. if ( scalar !== 0 ) {
  1066. var invScalar = 1 / scalar;
  1067. this.x *= invScalar;
  1068. this.y *= invScalar;
  1069. this.z *= invScalar;
  1070. } else {
  1071. this.x = 0;
  1072. this.y = 0;
  1073. this.z = 0;
  1074. }
  1075. return this;
  1076. },
  1077. min: function ( v ) {
  1078. if ( this.x > v.x ) {
  1079. this.x = v.x;
  1080. }
  1081. if ( this.y > v.y ) {
  1082. this.y = v.y;
  1083. }
  1084. if ( this.z > v.z ) {
  1085. this.z = v.z;
  1086. }
  1087. return this;
  1088. },
  1089. max: function ( v ) {
  1090. if ( this.x < v.x ) {
  1091. this.x = v.x;
  1092. }
  1093. if ( this.y < v.y ) {
  1094. this.y = v.y;
  1095. }
  1096. if ( this.z < v.z ) {
  1097. this.z = v.z;
  1098. }
  1099. return this;
  1100. },
  1101. clamp: function ( min, max ) {
  1102. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1103. if ( this.x < min.x ) {
  1104. this.x = min.x;
  1105. } else if ( this.x > max.x ) {
  1106. this.x = max.x;
  1107. }
  1108. if ( this.y < min.y ) {
  1109. this.y = min.y;
  1110. } else if ( this.y > max.y ) {
  1111. this.y = max.y;
  1112. }
  1113. if ( this.z < min.z ) {
  1114. this.z = min.z;
  1115. } else if ( this.z > max.z ) {
  1116. this.z = max.z;
  1117. }
  1118. return this;
  1119. },
  1120. clampScalar: ( function () {
  1121. var min, max;
  1122. return function ( minVal, maxVal ) {
  1123. if ( min === undefined ) {
  1124. min = new THREE.Vector3();
  1125. max = new THREE.Vector3();
  1126. }
  1127. min.set( minVal, minVal, minVal );
  1128. max.set( maxVal, maxVal, maxVal );
  1129. return this.clamp( min, max );
  1130. };
  1131. } )(),
  1132. floor: function () {
  1133. this.x = Math.floor( this.x );
  1134. this.y = Math.floor( this.y );
  1135. this.z = Math.floor( this.z );
  1136. return this;
  1137. },
  1138. ceil: function () {
  1139. this.x = Math.ceil( this.x );
  1140. this.y = Math.ceil( this.y );
  1141. this.z = Math.ceil( this.z );
  1142. return this;
  1143. },
  1144. round: function () {
  1145. this.x = Math.round( this.x );
  1146. this.y = Math.round( this.y );
  1147. this.z = Math.round( this.z );
  1148. return this;
  1149. },
  1150. roundToZero: function () {
  1151. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1152. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1153. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1154. return this;
  1155. },
  1156. negate: function () {
  1157. return this.multiplyScalar( - 1 );
  1158. },
  1159. dot: function ( v ) {
  1160. return this.x * v.x + this.y * v.y + this.z * v.z;
  1161. },
  1162. lengthSq: function () {
  1163. return this.x * this.x + this.y * this.y + this.z * this.z;
  1164. },
  1165. length: function () {
  1166. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1167. },
  1168. lengthManhattan: function () {
  1169. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1170. },
  1171. normalize: function () {
  1172. return this.divideScalar( this.length() );
  1173. },
  1174. setLength: function ( l ) {
  1175. var oldLength = this.length();
  1176. if ( oldLength !== 0 && l !== oldLength ) {
  1177. this.multiplyScalar( l / oldLength );
  1178. }
  1179. return this;
  1180. },
  1181. lerp: function ( v, alpha ) {
  1182. this.x += ( v.x - this.x ) * alpha;
  1183. this.y += ( v.y - this.y ) * alpha;
  1184. this.z += ( v.z - this.z ) * alpha;
  1185. return this;
  1186. },
  1187. cross: function ( v, w ) {
  1188. if ( w !== undefined ) {
  1189. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1190. return this.crossVectors( v, w );
  1191. }
  1192. var x = this.x, y = this.y, z = this.z;
  1193. this.x = y * v.z - z * v.y;
  1194. this.y = z * v.x - x * v.z;
  1195. this.z = x * v.y - y * v.x;
  1196. return this;
  1197. },
  1198. crossVectors: function ( a, b ) {
  1199. var ax = a.x, ay = a.y, az = a.z;
  1200. var bx = b.x, by = b.y, bz = b.z;
  1201. this.x = ay * bz - az * by;
  1202. this.y = az * bx - ax * bz;
  1203. this.z = ax * by - ay * bx;
  1204. return this;
  1205. },
  1206. projectOnVector: function () {
  1207. var v1, dot;
  1208. return function ( vector ) {
  1209. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1210. v1.copy( vector ).normalize();
  1211. dot = this.dot( v1 );
  1212. return this.copy( v1 ).multiplyScalar( dot );
  1213. };
  1214. }(),
  1215. projectOnPlane: function () {
  1216. var v1;
  1217. return function ( planeNormal ) {
  1218. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1219. v1.copy( this ).projectOnVector( planeNormal );
  1220. return this.sub( v1 );
  1221. }
  1222. }(),
  1223. reflect: function () {
  1224. // reflect incident vector off plane orthogonal to normal
  1225. // normal is assumed to have unit length
  1226. var v1;
  1227. return function ( normal ) {
  1228. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1229. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1230. }
  1231. }(),
  1232. angleTo: function ( v ) {
  1233. var theta = this.dot( v ) / ( this.length() * v.length() );
  1234. // clamp, to handle numerical problems
  1235. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1236. },
  1237. distanceTo: function ( v ) {
  1238. return Math.sqrt( this.distanceToSquared( v ) );
  1239. },
  1240. distanceToSquared: function ( v ) {
  1241. var dx = this.x - v.x;
  1242. var dy = this.y - v.y;
  1243. var dz = this.z - v.z;
  1244. return dx * dx + dy * dy + dz * dz;
  1245. },
  1246. setEulerFromRotationMatrix: function ( m, order ) {
  1247. console.error( "REMOVED: Vector3\'s setEulerFromRotationMatrix has been removed in favor of Euler.setFromRotationMatrix(), please update your code.");
  1248. },
  1249. setEulerFromQuaternion: function ( q, order ) {
  1250. console.error( "REMOVED: Vector3\'s setEulerFromQuaternion: has been removed in favor of Euler.setFromQuaternion(), please update your code.");
  1251. },
  1252. getPositionFromMatrix: function ( m ) {
  1253. console.warn( "DEPRECATED: Vector3\'s .getPositionFromMatrix() has been renamed to .setFromMatrixPosition(). Please update your code." );
  1254. return this.setFromMatrixPosition( m );
  1255. },
  1256. getScaleFromMatrix: function ( m ) {
  1257. console.warn( "DEPRECATED: Vector3\'s .getScaleFromMatrix() has been renamed to .setFromMatrixScale(). Please update your code." );
  1258. return this.setFromMatrixScale( m );
  1259. },
  1260. getColumnFromMatrix: function ( index, matrix ) {
  1261. console.warn( "DEPRECATED: Vector3\'s .getColumnFromMatrix() has been renamed to .setFromMatrixColumn(). Please update your code." );
  1262. return this.setFromMatrixColumn( index, matrix );
  1263. },
  1264. setFromMatrixPosition: function ( m ) {
  1265. this.x = m.elements[ 12 ];
  1266. this.y = m.elements[ 13 ];
  1267. this.z = m.elements[ 14 ];
  1268. return this;
  1269. },
  1270. setFromMatrixScale: function ( m ) {
  1271. var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
  1272. var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
  1273. var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
  1274. this.x = sx;
  1275. this.y = sy;
  1276. this.z = sz;
  1277. return this;
  1278. },
  1279. setFromMatrixColumn: function ( index, matrix ) {
  1280. var offset = index * 4;
  1281. var me = matrix.elements;
  1282. this.x = me[ offset ];
  1283. this.y = me[ offset + 1 ];
  1284. this.z = me[ offset + 2 ];
  1285. return this;
  1286. },
  1287. equals: function ( v ) {
  1288. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1289. },
  1290. fromArray: function ( array ) {
  1291. this.x = array[ 0 ];
  1292. this.y = array[ 1 ];
  1293. this.z = array[ 2 ];
  1294. return this;
  1295. },
  1296. toArray: function () {
  1297. return [ this.x, this.y, this.z ];
  1298. },
  1299. clone: function () {
  1300. return new THREE.Vector3( this.x, this.y, this.z );
  1301. }
  1302. };
  1303. /**
  1304. * @author supereggbert / http://www.paulbrunt.co.uk/
  1305. * @author philogb / http://blog.thejit.org/
  1306. * @author mikael emtinger / http://gomo.se/
  1307. * @author egraether / http://egraether.com/
  1308. * @author WestLangley / http://github.com/WestLangley
  1309. */
  1310. THREE.Vector4 = function ( x, y, z, w ) {
  1311. this.x = x || 0;
  1312. this.y = y || 0;
  1313. this.z = z || 0;
  1314. this.w = ( w !== undefined ) ? w : 1;
  1315. };
  1316. THREE.Vector4.prototype = {
  1317. constructor: THREE.Vector4,
  1318. set: function ( x, y, z, w ) {
  1319. this.x = x;
  1320. this.y = y;
  1321. this.z = z;
  1322. this.w = w;
  1323. return this;
  1324. },
  1325. setX: function ( x ) {
  1326. this.x = x;
  1327. return this;
  1328. },
  1329. setY: function ( y ) {
  1330. this.y = y;
  1331. return this;
  1332. },
  1333. setZ: function ( z ) {
  1334. this.z = z;
  1335. return this;
  1336. },
  1337. setW: function ( w ) {
  1338. this.w = w;
  1339. return this;
  1340. },
  1341. setComponent: function ( index, value ) {
  1342. switch ( index ) {
  1343. case 0: this.x = value; break;
  1344. case 1: this.y = value; break;
  1345. case 2: this.z = value; break;
  1346. case 3: this.w = value; break;
  1347. default: throw new Error( "index is out of range: " + index );
  1348. }
  1349. },
  1350. getComponent: function ( index ) {
  1351. switch ( index ) {
  1352. case 0: return this.x;
  1353. case 1: return this.y;
  1354. case 2: return this.z;
  1355. case 3: return this.w;
  1356. default: throw new Error( "index is out of range: " + index );
  1357. }
  1358. },
  1359. copy: function ( v ) {
  1360. this.x = v.x;
  1361. this.y = v.y;
  1362. this.z = v.z;
  1363. this.w = ( v.w !== undefined ) ? v.w : 1;
  1364. return this;
  1365. },
  1366. add: function ( v, w ) {
  1367. if ( w !== undefined ) {
  1368. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1369. return this.addVectors( v, w );
  1370. }
  1371. this.x += v.x;
  1372. this.y += v.y;
  1373. this.z += v.z;
  1374. this.w += v.w;
  1375. return this;
  1376. },
  1377. addScalar: function ( s ) {
  1378. this.x += s;
  1379. this.y += s;
  1380. this.z += s;
  1381. this.w += s;
  1382. return this;
  1383. },
  1384. addVectors: function ( a, b ) {
  1385. this.x = a.x + b.x;
  1386. this.y = a.y + b.y;
  1387. this.z = a.z + b.z;
  1388. this.w = a.w + b.w;
  1389. return this;
  1390. },
  1391. sub: function ( v, w ) {
  1392. if ( w !== undefined ) {
  1393. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1394. return this.subVectors( v, w );
  1395. }
  1396. this.x -= v.x;
  1397. this.y -= v.y;
  1398. this.z -= v.z;
  1399. this.w -= v.w;
  1400. return this;
  1401. },
  1402. subVectors: function ( a, b ) {
  1403. this.x = a.x - b.x;
  1404. this.y = a.y - b.y;
  1405. this.z = a.z - b.z;
  1406. this.w = a.w - b.w;
  1407. return this;
  1408. },
  1409. multiplyScalar: function ( scalar ) {
  1410. this.x *= scalar;
  1411. this.y *= scalar;
  1412. this.z *= scalar;
  1413. this.w *= scalar;
  1414. return this;
  1415. },
  1416. applyMatrix4: function ( m ) {
  1417. var x = this.x;
  1418. var y = this.y;
  1419. var z = this.z;
  1420. var w = this.w;
  1421. var e = m.elements;
  1422. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1423. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1424. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1425. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1426. return this;
  1427. },
  1428. divideScalar: function ( scalar ) {
  1429. if ( scalar !== 0 ) {
  1430. var invScalar = 1 / scalar;
  1431. this.x *= invScalar;
  1432. this.y *= invScalar;
  1433. this.z *= invScalar;
  1434. this.w *= invScalar;
  1435. } else {
  1436. this.x = 0;
  1437. this.y = 0;
  1438. this.z = 0;
  1439. this.w = 1;
  1440. }
  1441. return this;
  1442. },
  1443. setAxisAngleFromQuaternion: function ( q ) {
  1444. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1445. // q is assumed to be normalized
  1446. this.w = 2 * Math.acos( q.w );
  1447. var s = Math.sqrt( 1 - q.w * q.w );
  1448. if ( s < 0.0001 ) {
  1449. this.x = 1;
  1450. this.y = 0;
  1451. this.z = 0;
  1452. } else {
  1453. this.x = q.x / s;
  1454. this.y = q.y / s;
  1455. this.z = q.z / s;
  1456. }
  1457. return this;
  1458. },
  1459. setAxisAngleFromRotationMatrix: function ( m ) {
  1460. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1461. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1462. var angle, x, y, z, // variables for result
  1463. epsilon = 0.01, // margin to allow for rounding errors
  1464. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1465. te = m.elements,
  1466. m11 = te[0], m12 = te[4], m13 = te[8],
  1467. m21 = te[1], m22 = te[5], m23 = te[9],
  1468. m31 = te[2], m32 = te[6], m33 = te[10];
  1469. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1470. && ( Math.abs( m13 - m31 ) < epsilon )
  1471. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1472. // singularity found
  1473. // first check for identity matrix which must have +1 for all terms
  1474. // in leading diagonal and zero in other terms
  1475. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1476. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1477. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1478. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1479. // this singularity is identity matrix so angle = 0
  1480. this.set( 1, 0, 0, 0 );
  1481. return this; // zero angle, arbitrary axis
  1482. }
  1483. // otherwise this singularity is angle = 180
  1484. angle = Math.PI;
  1485. var xx = ( m11 + 1 ) / 2;
  1486. var yy = ( m22 + 1 ) / 2;
  1487. var zz = ( m33 + 1 ) / 2;
  1488. var xy = ( m12 + m21 ) / 4;
  1489. var xz = ( m13 + m31 ) / 4;
  1490. var yz = ( m23 + m32 ) / 4;
  1491. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1492. if ( xx < epsilon ) {
  1493. x = 0;
  1494. y = 0.707106781;
  1495. z = 0.707106781;
  1496. } else {
  1497. x = Math.sqrt( xx );
  1498. y = xy / x;
  1499. z = xz / x;
  1500. }
  1501. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1502. if ( yy < epsilon ) {
  1503. x = 0.707106781;
  1504. y = 0;
  1505. z = 0.707106781;
  1506. } else {
  1507. y = Math.sqrt( yy );
  1508. x = xy / y;
  1509. z = yz / y;
  1510. }
  1511. } else { // m33 is the largest diagonal term so base result on this
  1512. if ( zz < epsilon ) {
  1513. x = 0.707106781;
  1514. y = 0.707106781;
  1515. z = 0;
  1516. } else {
  1517. z = Math.sqrt( zz );
  1518. x = xz / z;
  1519. y = yz / z;
  1520. }
  1521. }
  1522. this.set( x, y, z, angle );
  1523. return this; // return 180 deg rotation
  1524. }
  1525. // as we have reached here there are no singularities so we can handle normally
  1526. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1527. + ( m13 - m31 ) * ( m13 - m31 )
  1528. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1529. if ( Math.abs( s ) < 0.001 ) s = 1;
  1530. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1531. // caught by singularity test above, but I've left it in just in case
  1532. this.x = ( m32 - m23 ) / s;
  1533. this.y = ( m13 - m31 ) / s;
  1534. this.z = ( m21 - m12 ) / s;
  1535. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1536. return this;
  1537. },
  1538. min: function ( v ) {
  1539. if ( this.x > v.x ) {
  1540. this.x = v.x;
  1541. }
  1542. if ( this.y > v.y ) {
  1543. this.y = v.y;
  1544. }
  1545. if ( this.z > v.z ) {
  1546. this.z = v.z;
  1547. }
  1548. if ( this.w > v.w ) {
  1549. this.w = v.w;
  1550. }
  1551. return this;
  1552. },
  1553. max: function ( v ) {
  1554. if ( this.x < v.x ) {
  1555. this.x = v.x;
  1556. }
  1557. if ( this.y < v.y ) {
  1558. this.y = v.y;
  1559. }
  1560. if ( this.z < v.z ) {
  1561. this.z = v.z;
  1562. }
  1563. if ( this.w < v.w ) {
  1564. this.w = v.w;
  1565. }
  1566. return this;
  1567. },
  1568. clamp: function ( min, max ) {
  1569. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1570. if ( this.x < min.x ) {
  1571. this.x = min.x;
  1572. } else if ( this.x > max.x ) {
  1573. this.x = max.x;
  1574. }
  1575. if ( this.y < min.y ) {
  1576. this.y = min.y;
  1577. } else if ( this.y > max.y ) {
  1578. this.y = max.y;
  1579. }
  1580. if ( this.z < min.z ) {
  1581. this.z = min.z;
  1582. } else if ( this.z > max.z ) {
  1583. this.z = max.z;
  1584. }
  1585. if ( this.w < min.w ) {
  1586. this.w = min.w;
  1587. } else if ( this.w > max.w ) {
  1588. this.w = max.w;
  1589. }
  1590. return this;
  1591. },
  1592. clampScalar: ( function () {
  1593. var min, max;
  1594. return function ( minVal, maxVal ) {
  1595. if ( min === undefined ) {
  1596. min = new THREE.Vector4();
  1597. max = new THREE.Vector4();
  1598. }
  1599. min.set( minVal, minVal, minVal, minVal );
  1600. max.set( maxVal, maxVal, maxVal, maxVal );
  1601. return this.clamp( min, max );
  1602. };
  1603. } )(),
  1604. floor: function () {
  1605. this.x = Math.floor( this.x );
  1606. this.y = Math.floor( this.y );
  1607. this.z = Math.floor( this.z );
  1608. this.w = Math.floor( this.w );
  1609. return this;
  1610. },
  1611. ceil: function () {
  1612. this.x = Math.ceil( this.x );
  1613. this.y = Math.ceil( this.y );
  1614. this.z = Math.ceil( this.z );
  1615. this.w = Math.ceil( this.w );
  1616. return this;
  1617. },
  1618. round: function () {
  1619. this.x = Math.round( this.x );
  1620. this.y = Math.round( this.y );
  1621. this.z = Math.round( this.z );
  1622. this.w = Math.round( this.w );
  1623. return this;
  1624. },
  1625. roundToZero: function () {
  1626. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1627. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1628. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1629. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1630. return this;
  1631. },
  1632. negate: function () {
  1633. return this.multiplyScalar( -1 );
  1634. },
  1635. dot: function ( v ) {
  1636. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1637. },
  1638. lengthSq: function () {
  1639. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1640. },
  1641. length: function () {
  1642. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1643. },
  1644. lengthManhattan: function () {
  1645. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1646. },
  1647. normalize: function () {
  1648. return this.divideScalar( this.length() );
  1649. },
  1650. setLength: function ( l ) {
  1651. var oldLength = this.length();
  1652. if ( oldLength !== 0 && l !== oldLength ) {
  1653. this.multiplyScalar( l / oldLength );
  1654. }
  1655. return this;
  1656. },
  1657. lerp: function ( v, alpha ) {
  1658. this.x += ( v.x - this.x ) * alpha;
  1659. this.y += ( v.y - this.y ) * alpha;
  1660. this.z += ( v.z - this.z ) * alpha;
  1661. this.w += ( v.w - this.w ) * alpha;
  1662. return this;
  1663. },
  1664. equals: function ( v ) {
  1665. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1666. },
  1667. fromArray: function ( array ) {
  1668. this.x = array[ 0 ];
  1669. this.y = array[ 1 ];
  1670. this.z = array[ 2 ];
  1671. this.w = array[ 3 ];
  1672. return this;
  1673. },
  1674. toArray: function () {
  1675. return [ this.x, this.y, this.z, this.w ];
  1676. },
  1677. clone: function () {
  1678. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1679. }
  1680. };
  1681. /**
  1682. * @author mrdoob / http://mrdoob.com/
  1683. * @author WestLangley / http://github.com/WestLangley
  1684. * @author bhouston / http://exocortex.com
  1685. */
  1686. THREE.Euler = function ( x, y, z, order ) {
  1687. this._x = x || 0;
  1688. this._y = y || 0;
  1689. this._z = z || 0;
  1690. this._order = order || THREE.Euler.DefaultOrder;
  1691. };
  1692. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1693. THREE.Euler.DefaultOrder = 'XYZ';
  1694. THREE.Euler.prototype = {
  1695. constructor: THREE.Euler,
  1696. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1697. _quaternion: undefined,
  1698. _updateQuaternion: function () {
  1699. if ( this._quaternion !== undefined ) {
  1700. this._quaternion.setFromEuler( this, false );
  1701. }
  1702. },
  1703. get x () {
  1704. return this._x;
  1705. },
  1706. set x ( value ) {
  1707. this._x = value;
  1708. this._updateQuaternion();
  1709. },
  1710. get y () {
  1711. return this._y;
  1712. },
  1713. set y ( value ) {
  1714. this._y = value;
  1715. this._updateQuaternion();
  1716. },
  1717. get z () {
  1718. return this._z;
  1719. },
  1720. set z ( value ) {
  1721. this._z = value;
  1722. this._updateQuaternion();
  1723. },
  1724. get order () {
  1725. return this._order;
  1726. },
  1727. set order ( value ) {
  1728. this._order = value;
  1729. this._updateQuaternion();
  1730. },
  1731. set: function ( x, y, z, order ) {
  1732. this._x = x;
  1733. this._y = y;
  1734. this._z = z;
  1735. this._order = order || this._order;
  1736. this._updateQuaternion();
  1737. return this;
  1738. },
  1739. copy: function ( euler ) {
  1740. this._x = euler._x;
  1741. this._y = euler._y;
  1742. this._z = euler._z;
  1743. this._order = euler._order;
  1744. this._updateQuaternion();
  1745. return this;
  1746. },
  1747. setFromRotationMatrix: function ( m, order ) {
  1748. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1749. // clamp, to handle numerical problems
  1750. function clamp( x ) {
  1751. return Math.min( Math.max( x, -1 ), 1 );
  1752. }
  1753. var te = m.elements;
  1754. var m11 = te[0], m12 = te[4], m13 = te[8];
  1755. var m21 = te[1], m22 = te[5], m23 = te[9];
  1756. var m31 = te[2], m32 = te[6], m33 = te[10];
  1757. order = order || this._order;
  1758. if ( order === 'XYZ' ) {
  1759. this._y = Math.asin( clamp( m13 ) );
  1760. if ( Math.abs( m13 ) < 0.99999 ) {
  1761. this._x = Math.atan2( - m23, m33 );
  1762. this._z = Math.atan2( - m12, m11 );
  1763. } else {
  1764. this._x = Math.atan2( m32, m22 );
  1765. this._z = 0;
  1766. }
  1767. } else if ( order === 'YXZ' ) {
  1768. this._x = Math.asin( - clamp( m23 ) );
  1769. if ( Math.abs( m23 ) < 0.99999 ) {
  1770. this._y = Math.atan2( m13, m33 );
  1771. this._z = Math.atan2( m21, m22 );
  1772. } else {
  1773. this._y = Math.atan2( - m31, m11 );
  1774. this._z = 0;
  1775. }
  1776. } else if ( order === 'ZXY' ) {
  1777. this._x = Math.asin( clamp( m32 ) );
  1778. if ( Math.abs( m32 ) < 0.99999 ) {
  1779. this._y = Math.atan2( - m31, m33 );
  1780. this._z = Math.atan2( - m12, m22 );
  1781. } else {
  1782. this._y = 0;
  1783. this._z = Math.atan2( m21, m11 );
  1784. }
  1785. } else if ( order === 'ZYX' ) {
  1786. this._y = Math.asin( - clamp( m31 ) );
  1787. if ( Math.abs( m31 ) < 0.99999 ) {
  1788. this._x = Math.atan2( m32, m33 );
  1789. this._z = Math.atan2( m21, m11 );
  1790. } else {
  1791. this._x = 0;
  1792. this._z = Math.atan2( - m12, m22 );
  1793. }
  1794. } else if ( order === 'YZX' ) {
  1795. this._z = Math.asin( clamp( m21 ) );
  1796. if ( Math.abs( m21 ) < 0.99999 ) {
  1797. this._x = Math.atan2( - m23, m22 );
  1798. this._y = Math.atan2( - m31, m11 );
  1799. } else {
  1800. this._x = 0;
  1801. this._y = Math.atan2( m13, m33 );
  1802. }
  1803. } else if ( order === 'XZY' ) {
  1804. this._z = Math.asin( - clamp( m12 ) );
  1805. if ( Math.abs( m12 ) < 0.99999 ) {
  1806. this._x = Math.atan2( m32, m22 );
  1807. this._y = Math.atan2( m13, m11 );
  1808. } else {
  1809. this._x = Math.atan2( - m23, m33 );
  1810. this._y = 0;
  1811. }
  1812. } else {
  1813. console.warn( 'WARNING: Euler.setFromRotationMatrix() given unsupported order: ' + order )
  1814. }
  1815. this._order = order;
  1816. this._updateQuaternion();
  1817. return this;
  1818. },
  1819. setFromQuaternion: function ( q, order, update ) {
  1820. // q is assumed to be normalized
  1821. // clamp, to handle numerical problems
  1822. function clamp( x ) {
  1823. return Math.min( Math.max( x, -1 ), 1 );
  1824. }
  1825. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1826. var sqx = q.x * q.x;
  1827. var sqy = q.y * q.y;
  1828. var sqz = q.z * q.z;
  1829. var sqw = q.w * q.w;
  1830. order = order || this._order;
  1831. if ( order === 'XYZ' ) {
  1832. this._x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1833. this._y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  1834. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1835. } else if ( order === 'YXZ' ) {
  1836. this._x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  1837. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1838. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1839. } else if ( order === 'ZXY' ) {
  1840. this._x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  1841. this._y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1842. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1843. } else if ( order === 'ZYX' ) {
  1844. this._x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1845. this._y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  1846. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1847. } else if ( order === 'YZX' ) {
  1848. this._x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1849. this._y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1850. this._z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  1851. } else if ( order === 'XZY' ) {
  1852. this._x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1853. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1854. this._z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  1855. } else {
  1856. console.warn( 'WARNING: Euler.setFromQuaternion() given unsupported order: ' + order )
  1857. }
  1858. this._order = order;
  1859. if ( update !== false ) this._updateQuaternion();
  1860. return this;
  1861. },
  1862. reorder: function () {
  1863. // WARNING: this discards revolution information -bhouston
  1864. var q = new THREE.Quaternion();
  1865. return function ( newOrder ) {
  1866. q.setFromEuler( this );
  1867. this.setFromQuaternion( q, newOrder );
  1868. };
  1869. }(),
  1870. fromArray: function ( array ) {
  1871. this._x = array[ 0 ];
  1872. this._y = array[ 1 ];
  1873. this._z = array[ 2 ];
  1874. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  1875. this._updateQuaternion();
  1876. return this;
  1877. },
  1878. toArray: function () {
  1879. return [ this._x, this._y, this._z, this._order ];
  1880. },
  1881. equals: function ( euler ) {
  1882. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  1883. },
  1884. clone: function () {
  1885. return new THREE.Euler( this._x, this._y, this._z, this._order );
  1886. }
  1887. };
  1888. /**
  1889. * @author bhouston / http://exocortex.com
  1890. */
  1891. THREE.Line3 = function ( start, end ) {
  1892. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1893. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1894. };
  1895. THREE.Line3.prototype = {
  1896. constructor: THREE.Line3,
  1897. set: function ( start, end ) {
  1898. this.start.copy( start );
  1899. this.end.copy( end );
  1900. return this;
  1901. },
  1902. copy: function ( line ) {
  1903. this.start.copy( line.start );
  1904. this.end.copy( line.end );
  1905. return this;
  1906. },
  1907. center: function ( optionalTarget ) {
  1908. var result = optionalTarget || new THREE.Vector3();
  1909. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1910. },
  1911. delta: function ( optionalTarget ) {
  1912. var result = optionalTarget || new THREE.Vector3();
  1913. return result.subVectors( this.end, this.start );
  1914. },
  1915. distanceSq: function () {
  1916. return this.start.distanceToSquared( this.end );
  1917. },
  1918. distance: function () {
  1919. return this.start.distanceTo( this.end );
  1920. },
  1921. at: function ( t, optionalTarget ) {
  1922. var result = optionalTarget || new THREE.Vector3();
  1923. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1924. },
  1925. closestPointToPointParameter: function() {
  1926. var startP = new THREE.Vector3();
  1927. var startEnd = new THREE.Vector3();
  1928. return function ( point, clampToLine ) {
  1929. startP.subVectors( point, this.start );
  1930. startEnd.subVectors( this.end, this.start );
  1931. var startEnd2 = startEnd.dot( startEnd );
  1932. var startEnd_startP = startEnd.dot( startP );
  1933. var t = startEnd_startP / startEnd2;
  1934. if ( clampToLine ) {
  1935. t = THREE.Math.clamp( t, 0, 1 );
  1936. }
  1937. return t;
  1938. };
  1939. }(),
  1940. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1941. var t = this.closestPointToPointParameter( point, clampToLine );
  1942. var result = optionalTarget || new THREE.Vector3();
  1943. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1944. },
  1945. applyMatrix4: function ( matrix ) {
  1946. this.start.applyMatrix4( matrix );
  1947. this.end.applyMatrix4( matrix );
  1948. return this;
  1949. },
  1950. equals: function ( line ) {
  1951. return line.start.equals( this.start ) && line.end.equals( this.end );
  1952. },
  1953. clone: function () {
  1954. return new THREE.Line3().copy( this );
  1955. }
  1956. };
  1957. /**
  1958. * @author bhouston / http://exocortex.com
  1959. */
  1960. THREE.Box2 = function ( min, max ) {
  1961. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1962. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1963. };
  1964. THREE.Box2.prototype = {
  1965. constructor: THREE.Box2,
  1966. set: function ( min, max ) {
  1967. this.min.copy( min );
  1968. this.max.copy( max );
  1969. return this;
  1970. },
  1971. setFromPoints: function ( points ) {
  1972. if ( points.length > 0 ) {
  1973. var point = points[ 0 ];
  1974. this.min.copy( point );
  1975. this.max.copy( point );
  1976. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1977. point = points[ i ];
  1978. if ( point.x < this.min.x ) {
  1979. this.min.x = point.x;
  1980. } else if ( point.x > this.max.x ) {
  1981. this.max.x = point.x;
  1982. }
  1983. if ( point.y < this.min.y ) {
  1984. this.min.y = point.y;
  1985. } else if ( point.y > this.max.y ) {
  1986. this.max.y = point.y;
  1987. }
  1988. }
  1989. } else {
  1990. this.makeEmpty();
  1991. }
  1992. return this;
  1993. },
  1994. setFromCenterAndSize: function () {
  1995. var v1 = new THREE.Vector2();
  1996. return function ( center, size ) {
  1997. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1998. this.min.copy( center ).sub( halfSize );
  1999. this.max.copy( center ).add( halfSize );
  2000. return this;
  2001. };
  2002. }(),
  2003. copy: function ( box ) {
  2004. this.min.copy( box.min );
  2005. this.max.copy( box.max );
  2006. return this;
  2007. },
  2008. makeEmpty: function () {
  2009. this.min.x = this.min.y = Infinity;
  2010. this.max.x = this.max.y = -Infinity;
  2011. return this;
  2012. },
  2013. empty: function () {
  2014. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2015. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  2016. },
  2017. center: function ( optionalTarget ) {
  2018. var result = optionalTarget || new THREE.Vector2();
  2019. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2020. },
  2021. size: function ( optionalTarget ) {
  2022. var result = optionalTarget || new THREE.Vector2();
  2023. return result.subVectors( this.max, this.min );
  2024. },
  2025. expandByPoint: function ( point ) {
  2026. this.min.min( point );
  2027. this.max.max( point );
  2028. return this;
  2029. },
  2030. expandByVector: function ( vector ) {
  2031. this.min.sub( vector );
  2032. this.max.add( vector );
  2033. return this;
  2034. },
  2035. expandByScalar: function ( scalar ) {
  2036. this.min.addScalar( -scalar );
  2037. this.max.addScalar( scalar );
  2038. return this;
  2039. },
  2040. containsPoint: function ( point ) {
  2041. if ( point.x < this.min.x || point.x > this.max.x ||
  2042. point.y < this.min.y || point.y > this.max.y ) {
  2043. return false;
  2044. }
  2045. return true;
  2046. },
  2047. containsBox: function ( box ) {
  2048. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2049. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  2050. return true;
  2051. }
  2052. return false;
  2053. },
  2054. getParameter: function ( point, optionalTarget ) {
  2055. // This can potentially have a divide by zero if the box
  2056. // has a size dimension of 0.
  2057. var result = optionalTarget || new THREE.Vector2();
  2058. return result.set(
  2059. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2060. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  2061. );
  2062. },
  2063. isIntersectionBox: function ( box ) {
  2064. // using 6 splitting planes to rule out intersections.
  2065. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2066. box.max.y < this.min.y || box.min.y > this.max.y ) {
  2067. return false;
  2068. }
  2069. return true;
  2070. },
  2071. clampPoint: function ( point, optionalTarget ) {
  2072. var result = optionalTarget || new THREE.Vector2();
  2073. return result.copy( point ).clamp( this.min, this.max );
  2074. },
  2075. distanceToPoint: function () {
  2076. var v1 = new THREE.Vector2();
  2077. return function ( point ) {
  2078. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2079. return clampedPoint.sub( point ).length();
  2080. };
  2081. }(),
  2082. intersect: function ( box ) {
  2083. this.min.max( box.min );
  2084. this.max.min( box.max );
  2085. return this;
  2086. },
  2087. union: function ( box ) {
  2088. this.min.min( box.min );
  2089. this.max.max( box.max );
  2090. return this;
  2091. },
  2092. translate: function ( offset ) {
  2093. this.min.add( offset );
  2094. this.max.add( offset );
  2095. return this;
  2096. },
  2097. equals: function ( box ) {
  2098. return box.min.equals( this.min ) && box.max.equals( this.max );
  2099. },
  2100. clone: function () {
  2101. return new THREE.Box2().copy( this );
  2102. }
  2103. };
  2104. /**
  2105. * @author bhouston / http://exocortex.com
  2106. * @author WestLangley / http://github.com/WestLangley
  2107. */
  2108. THREE.Box3 = function ( min, max ) {
  2109. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2110. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  2111. };
  2112. THREE.Box3.prototype = {
  2113. constructor: THREE.Box3,
  2114. set: function ( min, max ) {
  2115. this.min.copy( min );
  2116. this.max.copy( max );
  2117. return this;
  2118. },
  2119. addPoint: function ( point ) {
  2120. if ( point.x < this.min.x ) {
  2121. this.min.x = point.x;
  2122. } else if ( point.x > this.max.x ) {
  2123. this.max.x = point.x;
  2124. }
  2125. if ( point.y < this.min.y ) {
  2126. this.min.y = point.y;
  2127. } else if ( point.y > this.max.y ) {
  2128. this.max.y = point.y;
  2129. }
  2130. if ( point.z < this.min.z ) {
  2131. this.min.z = point.z;
  2132. } else if ( point.z > this.max.z ) {
  2133. this.max.z = point.z;
  2134. }
  2135. },
  2136. setFromPoints: function ( points ) {
  2137. if ( points.length > 0 ) {
  2138. var point = points[ 0 ];
  2139. this.min.copy( point );
  2140. this.max.copy( point );
  2141. for ( var i = 1, il = points.length; i < il; i ++ ) {
  2142. this.addPoint( points[ i ] )
  2143. }
  2144. } else {
  2145. this.makeEmpty();
  2146. }
  2147. return this;
  2148. },
  2149. setFromCenterAndSize: function() {
  2150. var v1 = new THREE.Vector3();
  2151. return function ( center, size ) {
  2152. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2153. this.min.copy( center ).sub( halfSize );
  2154. this.max.copy( center ).add( halfSize );
  2155. return this;
  2156. };
  2157. }(),
  2158. setFromObject: function() {
  2159. // Computes the world-axis-aligned bounding box of an object (including its children),
  2160. // accounting for both the object's, and childrens', world transforms
  2161. var v1 = new THREE.Vector3();
  2162. return function( object ) {
  2163. var scope = this;
  2164. object.updateMatrixWorld( true );
  2165. this.makeEmpty();
  2166. object.traverse( function ( node ) {
  2167. if ( node.geometry !== undefined && node.geometry.vertices !== undefined ) {
  2168. var vertices = node.geometry.vertices;
  2169. for ( var i = 0, il = vertices.length; i < il; i++ ) {
  2170. v1.copy( vertices[ i ] );
  2171. v1.applyMatrix4( node.matrixWorld );
  2172. scope.expandByPoint( v1 );
  2173. }
  2174. }
  2175. } );
  2176. return this;
  2177. };
  2178. }(),
  2179. copy: function ( box ) {
  2180. this.min.copy( box.min );
  2181. this.max.copy( box.max );
  2182. return this;
  2183. },
  2184. makeEmpty: function () {
  2185. this.min.x = this.min.y = this.min.z = Infinity;
  2186. this.max.x = this.max.y = this.max.z = -Infinity;
  2187. return this;
  2188. },
  2189. empty: function () {
  2190. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2191. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2192. },
  2193. center: function ( optionalTarget ) {
  2194. var result = optionalTarget || new THREE.Vector3();
  2195. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2196. },
  2197. size: function ( optionalTarget ) {
  2198. var result = optionalTarget || new THREE.Vector3();
  2199. return result.subVectors( this.max, this.min );
  2200. },
  2201. expandByPoint: function ( point ) {
  2202. this.min.min( point );
  2203. this.max.max( point );
  2204. return this;
  2205. },
  2206. expandByVector: function ( vector ) {
  2207. this.min.sub( vector );
  2208. this.max.add( vector );
  2209. return this;
  2210. },
  2211. expandByScalar: function ( scalar ) {
  2212. this.min.addScalar( -scalar );
  2213. this.max.addScalar( scalar );
  2214. return this;
  2215. },
  2216. containsPoint: function ( point ) {
  2217. if ( point.x < this.min.x || point.x > this.max.x ||
  2218. point.y < this.min.y || point.y > this.max.y ||
  2219. point.z < this.min.z || point.z > this.max.z ) {
  2220. return false;
  2221. }
  2222. return true;
  2223. },
  2224. containsBox: function ( box ) {
  2225. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2226. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2227. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2228. return true;
  2229. }
  2230. return false;
  2231. },
  2232. getParameter: function ( point, optionalTarget ) {
  2233. // This can potentially have a divide by zero if the box
  2234. // has a size dimension of 0.
  2235. var result = optionalTarget || new THREE.Vector3();
  2236. return result.set(
  2237. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2238. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2239. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2240. );
  2241. },
  2242. isIntersectionBox: function ( box ) {
  2243. // using 6 splitting planes to rule out intersections.
  2244. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2245. box.max.y < this.min.y || box.min.y > this.max.y ||
  2246. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2247. return false;
  2248. }
  2249. return true;
  2250. },
  2251. clampPoint: function ( point, optionalTarget ) {
  2252. var result = optionalTarget || new THREE.Vector3();
  2253. return result.copy( point ).clamp( this.min, this.max );
  2254. },
  2255. distanceToPoint: function() {
  2256. var v1 = new THREE.Vector3();
  2257. return function ( point ) {
  2258. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2259. return clampedPoint.sub( point ).length();
  2260. };
  2261. }(),
  2262. getBoundingSphere: function() {
  2263. var v1 = new THREE.Vector3();
  2264. return function ( optionalTarget ) {
  2265. var result = optionalTarget || new THREE.Sphere();
  2266. result.center = this.center();
  2267. result.radius = this.size( v1 ).length() * 0.5;
  2268. return result;
  2269. };
  2270. }(),
  2271. intersect: function ( box ) {
  2272. this.min.max( box.min );
  2273. this.max.min( box.max );
  2274. return this;
  2275. },
  2276. union: function ( box ) {
  2277. this.min.min( box.min );
  2278. this.max.max( box.max );
  2279. return this;
  2280. },
  2281. applyMatrix4: function() {
  2282. var points = [
  2283. new THREE.Vector3(),
  2284. new THREE.Vector3(),
  2285. new THREE.Vector3(),
  2286. new THREE.Vector3(),
  2287. new THREE.Vector3(),
  2288. new THREE.Vector3(),
  2289. new THREE.Vector3(),
  2290. new THREE.Vector3()
  2291. ];
  2292. return function ( matrix ) {
  2293. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2294. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2295. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2296. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2297. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2298. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2299. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2300. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2301. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2302. this.makeEmpty();
  2303. this.setFromPoints( points );
  2304. return this;
  2305. };
  2306. }(),
  2307. translate: function ( offset ) {
  2308. this.min.add( offset );
  2309. this.max.add( offset );
  2310. return this;
  2311. },
  2312. equals: function ( box ) {
  2313. return box.min.equals( this.min ) && box.max.equals( this.max );
  2314. },
  2315. clone: function () {
  2316. return new THREE.Box3().copy( this );
  2317. }
  2318. };
  2319. /**
  2320. * @author alteredq / http://alteredqualia.com/
  2321. * @author WestLangley / http://github.com/WestLangley
  2322. * @author bhouston / http://exocortex.com
  2323. */
  2324. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2325. this.elements = new Float32Array(9);
  2326. this.set(
  2327. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  2328. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  2329. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  2330. );
  2331. };
  2332. THREE.Matrix3.prototype = {
  2333. constructor: THREE.Matrix3,
  2334. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2335. var te = this.elements;
  2336. te[0] = n11; te[3] = n12; te[6] = n13;
  2337. te[1] = n21; te[4] = n22; te[7] = n23;
  2338. te[2] = n31; te[5] = n32; te[8] = n33;
  2339. return this;
  2340. },
  2341. identity: function () {
  2342. this.set(
  2343. 1, 0, 0,
  2344. 0, 1, 0,
  2345. 0, 0, 1
  2346. );
  2347. return this;
  2348. },
  2349. copy: function ( m ) {
  2350. var me = m.elements;
  2351. this.set(
  2352. me[0], me[3], me[6],
  2353. me[1], me[4], me[7],
  2354. me[2], me[5], me[8]
  2355. );
  2356. return this;
  2357. },
  2358. multiplyVector3: function ( vector ) {
  2359. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2360. return vector.applyMatrix3( this );
  2361. },
  2362. multiplyVector3Array: function() {
  2363. var v1 = new THREE.Vector3();
  2364. return function ( a ) {
  2365. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2366. v1.x = a[ i ];
  2367. v1.y = a[ i + 1 ];
  2368. v1.z = a[ i + 2 ];
  2369. v1.applyMatrix3(this);
  2370. a[ i ] = v1.x;
  2371. a[ i + 1 ] = v1.y;
  2372. a[ i + 2 ] = v1.z;
  2373. }
  2374. return a;
  2375. };
  2376. }(),
  2377. multiplyScalar: function ( s ) {
  2378. var te = this.elements;
  2379. te[0] *= s; te[3] *= s; te[6] *= s;
  2380. te[1] *= s; te[4] *= s; te[7] *= s;
  2381. te[2] *= s; te[5] *= s; te[8] *= s;
  2382. return this;
  2383. },
  2384. determinant: function () {
  2385. var te = this.elements;
  2386. var a = te[0], b = te[1], c = te[2],
  2387. d = te[3], e = te[4], f = te[5],
  2388. g = te[6], h = te[7], i = te[8];
  2389. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2390. },
  2391. getInverse: function ( matrix, throwOnInvertible ) {
  2392. // input: THREE.Matrix4
  2393. // ( based on http://code.google.com/p/webgl-mjs/ )
  2394. var me = matrix.elements;
  2395. var te = this.elements;
  2396. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2397. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2398. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2399. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2400. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2401. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2402. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2403. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2404. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2405. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2406. // no inverse
  2407. if ( det === 0 ) {
  2408. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2409. if ( throwOnInvertible || false ) {
  2410. throw new Error( msg );
  2411. } else {
  2412. console.warn( msg );
  2413. }
  2414. this.identity();
  2415. return this;
  2416. }
  2417. this.multiplyScalar( 1.0 / det );
  2418. return this;
  2419. },
  2420. transpose: function () {
  2421. var tmp, m = this.elements;
  2422. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2423. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2424. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2425. return this;
  2426. },
  2427. getNormalMatrix: function ( m ) {
  2428. // input: THREE.Matrix4
  2429. this.getInverse( m ).transpose();
  2430. return this;
  2431. },
  2432. transposeIntoArray: function ( r ) {
  2433. var m = this.elements;
  2434. r[ 0 ] = m[ 0 ];
  2435. r[ 1 ] = m[ 3 ];
  2436. r[ 2 ] = m[ 6 ];
  2437. r[ 3 ] = m[ 1 ];
  2438. r[ 4 ] = m[ 4 ];
  2439. r[ 5 ] = m[ 7 ];
  2440. r[ 6 ] = m[ 2 ];
  2441. r[ 7 ] = m[ 5 ];
  2442. r[ 8 ] = m[ 8 ];
  2443. return this;
  2444. },
  2445. fromArray: function ( array ) {
  2446. this.elements.set( array );
  2447. return this;
  2448. },
  2449. toArray: function () {
  2450. var te = this.elements;
  2451. return [
  2452. te[ 0 ], te[ 1 ], te[ 2 ],
  2453. te[ 3 ], te[ 4 ], te[ 5 ],
  2454. te[ 6 ], te[ 7 ], te[ 8 ]
  2455. ];
  2456. },
  2457. clone: function () {
  2458. var te = this.elements;
  2459. return new THREE.Matrix3(
  2460. te[0], te[3], te[6],
  2461. te[1], te[4], te[7],
  2462. te[2], te[5], te[8]
  2463. );
  2464. }
  2465. };
  2466. /**
  2467. * @author mrdoob / http://mrdoob.com/
  2468. * @author supereggbert / http://www.paulbrunt.co.uk/
  2469. * @author philogb / http://blog.thejit.org/
  2470. * @author jordi_ros / http://plattsoft.com
  2471. * @author D1plo1d / http://github.com/D1plo1d
  2472. * @author alteredq / http://alteredqualia.com/
  2473. * @author mikael emtinger / http://gomo.se/
  2474. * @author timknip / http://www.floorplanner.com/
  2475. * @author bhouston / http://exocortex.com
  2476. * @author WestLangley / http://github.com/WestLangley
  2477. */
  2478. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2479. this.elements = new Float32Array( 16 );
  2480. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2481. // we should not support semi specification of Matrix4, it is just weird.
  2482. var te = this.elements;
  2483. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2484. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2485. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2486. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2487. };
  2488. THREE.Matrix4.prototype = {
  2489. constructor: THREE.Matrix4,
  2490. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2491. var te = this.elements;
  2492. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2493. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2494. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2495. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2496. return this;
  2497. },
  2498. identity: function () {
  2499. this.set(
  2500. 1, 0, 0, 0,
  2501. 0, 1, 0, 0,
  2502. 0, 0, 1, 0,
  2503. 0, 0, 0, 1
  2504. );
  2505. return this;
  2506. },
  2507. copy: function ( m ) {
  2508. this.elements.set( m.elements );
  2509. return this;
  2510. },
  2511. extractPosition: function ( m ) {
  2512. console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' );
  2513. return this.copyPosition( m );
  2514. },
  2515. copyPosition: function ( m ) {
  2516. var te = this.elements;
  2517. var me = m.elements;
  2518. te[12] = me[12];
  2519. te[13] = me[13];
  2520. te[14] = me[14];
  2521. return this;
  2522. },
  2523. extractRotation: function () {
  2524. var v1 = new THREE.Vector3();
  2525. return function ( m ) {
  2526. var te = this.elements;
  2527. var me = m.elements;
  2528. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2529. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2530. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2531. te[0] = me[0] * scaleX;
  2532. te[1] = me[1] * scaleX;
  2533. te[2] = me[2] * scaleX;
  2534. te[4] = me[4] * scaleY;
  2535. te[5] = me[5] * scaleY;
  2536. te[6] = me[6] * scaleY;
  2537. te[8] = me[8] * scaleZ;
  2538. te[9] = me[9] * scaleZ;
  2539. te[10] = me[10] * scaleZ;
  2540. return this;
  2541. };
  2542. }(),
  2543. makeRotationFromEuler: function ( euler ) {
  2544. if ( euler instanceof THREE.Euler === false ) {
  2545. console.error( 'ERROR: Matrix\'s .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  2546. }
  2547. var te = this.elements;
  2548. var x = euler.x, y = euler.y, z = euler.z;
  2549. var a = Math.cos( x ), b = Math.sin( x );
  2550. var c = Math.cos( y ), d = Math.sin( y );
  2551. var e = Math.cos( z ), f = Math.sin( z );
  2552. if ( euler.order === 'XYZ' ) {
  2553. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2554. te[0] = c * e;
  2555. te[4] = - c * f;
  2556. te[8] = d;
  2557. te[1] = af + be * d;
  2558. te[5] = ae - bf * d;
  2559. te[9] = - b * c;
  2560. te[2] = bf - ae * d;
  2561. te[6] = be + af * d;
  2562. te[10] = a * c;
  2563. } else if ( euler.order === 'YXZ' ) {
  2564. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2565. te[0] = ce + df * b;
  2566. te[4] = de * b - cf;
  2567. te[8] = a * d;
  2568. te[1] = a * f;
  2569. te[5] = a * e;
  2570. te[9] = - b;
  2571. te[2] = cf * b - de;
  2572. te[6] = df + ce * b;
  2573. te[10] = a * c;
  2574. } else if ( euler.order === 'ZXY' ) {
  2575. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2576. te[0] = ce - df * b;
  2577. te[4] = - a * f;
  2578. te[8] = de + cf * b;
  2579. te[1] = cf + de * b;
  2580. te[5] = a * e;
  2581. te[9] = df - ce * b;
  2582. te[2] = - a * d;
  2583. te[6] = b;
  2584. te[10] = a * c;
  2585. } else if ( euler.order === 'ZYX' ) {
  2586. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2587. te[0] = c * e;
  2588. te[4] = be * d - af;
  2589. te[8] = ae * d + bf;
  2590. te[1] = c * f;
  2591. te[5] = bf * d + ae;
  2592. te[9] = af * d - be;
  2593. te[2] = - d;
  2594. te[6] = b * c;
  2595. te[10] = a * c;
  2596. } else if ( euler.order === 'YZX' ) {
  2597. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2598. te[0] = c * e;
  2599. te[4] = bd - ac * f;
  2600. te[8] = bc * f + ad;
  2601. te[1] = f;
  2602. te[5] = a * e;
  2603. te[9] = - b * e;
  2604. te[2] = - d * e;
  2605. te[6] = ad * f + bc;
  2606. te[10] = ac - bd * f;
  2607. } else if ( euler.order === 'XZY' ) {
  2608. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2609. te[0] = c * e;
  2610. te[4] = - f;
  2611. te[8] = d * e;
  2612. te[1] = ac * f + bd;
  2613. te[5] = a * e;
  2614. te[9] = ad * f - bc;
  2615. te[2] = bc * f - ad;
  2616. te[6] = b * e;
  2617. te[10] = bd * f + ac;
  2618. }
  2619. // last column
  2620. te[3] = 0;
  2621. te[7] = 0;
  2622. te[11] = 0;
  2623. // bottom row
  2624. te[12] = 0;
  2625. te[13] = 0;
  2626. te[14] = 0;
  2627. te[15] = 1;
  2628. return this;
  2629. },
  2630. setRotationFromQuaternion: function ( q ) {
  2631. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' );
  2632. return this.makeRotationFromQuaternion( q );
  2633. },
  2634. makeRotationFromQuaternion: function ( q ) {
  2635. var te = this.elements;
  2636. var x = q.x, y = q.y, z = q.z, w = q.w;
  2637. var x2 = x + x, y2 = y + y, z2 = z + z;
  2638. var xx = x * x2, xy = x * y2, xz = x * z2;
  2639. var yy = y * y2, yz = y * z2, zz = z * z2;
  2640. var wx = w * x2, wy = w * y2, wz = w * z2;
  2641. te[0] = 1 - ( yy + zz );
  2642. te[4] = xy - wz;
  2643. te[8] = xz + wy;
  2644. te[1] = xy + wz;
  2645. te[5] = 1 - ( xx + zz );
  2646. te[9] = yz - wx;
  2647. te[2] = xz - wy;
  2648. te[6] = yz + wx;
  2649. te[10] = 1 - ( xx + yy );
  2650. // last column
  2651. te[3] = 0;
  2652. te[7] = 0;
  2653. te[11] = 0;
  2654. // bottom row
  2655. te[12] = 0;
  2656. te[13] = 0;
  2657. te[14] = 0;
  2658. te[15] = 1;
  2659. return this;
  2660. },
  2661. lookAt: function() {
  2662. var x = new THREE.Vector3();
  2663. var y = new THREE.Vector3();
  2664. var z = new THREE.Vector3();
  2665. return function ( eye, target, up ) {
  2666. var te = this.elements;
  2667. z.subVectors( eye, target ).normalize();
  2668. if ( z.length() === 0 ) {
  2669. z.z = 1;
  2670. }
  2671. x.crossVectors( up, z ).normalize();
  2672. if ( x.length() === 0 ) {
  2673. z.x += 0.0001;
  2674. x.crossVectors( up, z ).normalize();
  2675. }
  2676. y.crossVectors( z, x );
  2677. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2678. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2679. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2680. return this;
  2681. };
  2682. }(),
  2683. multiply: function ( m, n ) {
  2684. if ( n !== undefined ) {
  2685. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2686. return this.multiplyMatrices( m, n );
  2687. }
  2688. return this.multiplyMatrices( this, m );
  2689. },
  2690. multiplyMatrices: function ( a, b ) {
  2691. var ae = a.elements;
  2692. var be = b.elements;
  2693. var te = this.elements;
  2694. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2695. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2696. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2697. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2698. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2699. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2700. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2701. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2702. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2703. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2704. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2705. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2706. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2707. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2708. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2709. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2710. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2711. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2712. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2713. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2714. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2715. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2716. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2717. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2718. return this;
  2719. },
  2720. multiplyToArray: function ( a, b, r ) {
  2721. var te = this.elements;
  2722. this.multiplyMatrices( a, b );
  2723. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2724. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2725. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2726. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2727. return this;
  2728. },
  2729. multiplyScalar: function ( s ) {
  2730. var te = this.elements;
  2731. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2732. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2733. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2734. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2735. return this;
  2736. },
  2737. multiplyVector3: function ( vector ) {
  2738. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2739. return vector.applyProjection( this );
  2740. },
  2741. multiplyVector4: function ( vector ) {
  2742. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2743. return vector.applyMatrix4( this );
  2744. },
  2745. multiplyVector3Array: function() {
  2746. var v1 = new THREE.Vector3();
  2747. return function ( a ) {
  2748. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2749. v1.x = a[ i ];
  2750. v1.y = a[ i + 1 ];
  2751. v1.z = a[ i + 2 ];
  2752. v1.applyProjection( this );
  2753. a[ i ] = v1.x;
  2754. a[ i + 1 ] = v1.y;
  2755. a[ i + 2 ] = v1.z;
  2756. }
  2757. return a;
  2758. };
  2759. }(),
  2760. rotateAxis: function ( v ) {
  2761. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2762. v.transformDirection( this );
  2763. },
  2764. crossVector: function ( vector ) {
  2765. console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2766. return vector.applyMatrix4( this );
  2767. },
  2768. determinant: function () {
  2769. var te = this.elements;
  2770. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2771. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2772. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2773. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2774. //TODO: make this more efficient
  2775. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2776. return (
  2777. n41 * (
  2778. +n14 * n23 * n32
  2779. -n13 * n24 * n32
  2780. -n14 * n22 * n33
  2781. +n12 * n24 * n33
  2782. +n13 * n22 * n34
  2783. -n12 * n23 * n34
  2784. ) +
  2785. n42 * (
  2786. +n11 * n23 * n34
  2787. -n11 * n24 * n33
  2788. +n14 * n21 * n33
  2789. -n13 * n21 * n34
  2790. +n13 * n24 * n31
  2791. -n14 * n23 * n31
  2792. ) +
  2793. n43 * (
  2794. +n11 * n24 * n32
  2795. -n11 * n22 * n34
  2796. -n14 * n21 * n32
  2797. +n12 * n21 * n34
  2798. +n14 * n22 * n31
  2799. -n12 * n24 * n31
  2800. ) +
  2801. n44 * (
  2802. -n13 * n22 * n31
  2803. -n11 * n23 * n32
  2804. +n11 * n22 * n33
  2805. +n13 * n21 * n32
  2806. -n12 * n21 * n33
  2807. +n12 * n23 * n31
  2808. )
  2809. );
  2810. },
  2811. transpose: function () {
  2812. var te = this.elements;
  2813. var tmp;
  2814. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2815. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2816. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2817. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2818. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2819. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2820. return this;
  2821. },
  2822. flattenToArray: function ( flat ) {
  2823. var te = this.elements;
  2824. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2825. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2826. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2827. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2828. return flat;
  2829. },
  2830. flattenToArrayOffset: function( flat, offset ) {
  2831. var te = this.elements;
  2832. flat[ offset ] = te[0];
  2833. flat[ offset + 1 ] = te[1];
  2834. flat[ offset + 2 ] = te[2];
  2835. flat[ offset + 3 ] = te[3];
  2836. flat[ offset + 4 ] = te[4];
  2837. flat[ offset + 5 ] = te[5];
  2838. flat[ offset + 6 ] = te[6];
  2839. flat[ offset + 7 ] = te[7];
  2840. flat[ offset + 8 ] = te[8];
  2841. flat[ offset + 9 ] = te[9];
  2842. flat[ offset + 10 ] = te[10];
  2843. flat[ offset + 11 ] = te[11];
  2844. flat[ offset + 12 ] = te[12];
  2845. flat[ offset + 13 ] = te[13];
  2846. flat[ offset + 14 ] = te[14];
  2847. flat[ offset + 15 ] = te[15];
  2848. return flat;
  2849. },
  2850. getPosition: function() {
  2851. var v1 = new THREE.Vector3();
  2852. return function () {
  2853. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  2854. var te = this.elements;
  2855. return v1.set( te[12], te[13], te[14] );
  2856. };
  2857. }(),
  2858. setPosition: function ( v ) {
  2859. var te = this.elements;
  2860. te[12] = v.x;
  2861. te[13] = v.y;
  2862. te[14] = v.z;
  2863. return this;
  2864. },
  2865. getInverse: function ( m, throwOnInvertible ) {
  2866. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2867. var te = this.elements;
  2868. var me = m.elements;
  2869. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2870. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2871. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2872. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2873. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2874. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2875. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2876. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2877. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2878. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2879. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2880. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2881. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2882. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2883. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2884. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2885. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2886. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2887. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2888. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2889. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  2890. if ( det == 0 ) {
  2891. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2892. if ( throwOnInvertible || false ) {
  2893. throw new Error( msg );
  2894. } else {
  2895. console.warn( msg );
  2896. }
  2897. this.identity();
  2898. return this;
  2899. }
  2900. this.multiplyScalar( 1 / det );
  2901. return this;
  2902. },
  2903. translate: function ( v ) {
  2904. console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.');
  2905. },
  2906. rotateX: function ( angle ) {
  2907. console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.');
  2908. },
  2909. rotateY: function ( angle ) {
  2910. console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.');
  2911. },
  2912. rotateZ: function ( angle ) {
  2913. console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.');
  2914. },
  2915. rotateByAxis: function ( axis, angle ) {
  2916. console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.');
  2917. },
  2918. scale: function ( v ) {
  2919. var te = this.elements;
  2920. var x = v.x, y = v.y, z = v.z;
  2921. te[0] *= x; te[4] *= y; te[8] *= z;
  2922. te[1] *= x; te[5] *= y; te[9] *= z;
  2923. te[2] *= x; te[6] *= y; te[10] *= z;
  2924. te[3] *= x; te[7] *= y; te[11] *= z;
  2925. return this;
  2926. },
  2927. getMaxScaleOnAxis: function () {
  2928. var te = this.elements;
  2929. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2930. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2931. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2932. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2933. },
  2934. makeTranslation: function ( x, y, z ) {
  2935. this.set(
  2936. 1, 0, 0, x,
  2937. 0, 1, 0, y,
  2938. 0, 0, 1, z,
  2939. 0, 0, 0, 1
  2940. );
  2941. return this;
  2942. },
  2943. makeRotationX: function ( theta ) {
  2944. var c = Math.cos( theta ), s = Math.sin( theta );
  2945. this.set(
  2946. 1, 0, 0, 0,
  2947. 0, c, -s, 0,
  2948. 0, s, c, 0,
  2949. 0, 0, 0, 1
  2950. );
  2951. return this;
  2952. },
  2953. makeRotationY: function ( theta ) {
  2954. var c = Math.cos( theta ), s = Math.sin( theta );
  2955. this.set(
  2956. c, 0, s, 0,
  2957. 0, 1, 0, 0,
  2958. -s, 0, c, 0,
  2959. 0, 0, 0, 1
  2960. );
  2961. return this;
  2962. },
  2963. makeRotationZ: function ( theta ) {
  2964. var c = Math.cos( theta ), s = Math.sin( theta );
  2965. this.set(
  2966. c, -s, 0, 0,
  2967. s, c, 0, 0,
  2968. 0, 0, 1, 0,
  2969. 0, 0, 0, 1
  2970. );
  2971. return this;
  2972. },
  2973. makeRotationAxis: function ( axis, angle ) {
  2974. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2975. var c = Math.cos( angle );
  2976. var s = Math.sin( angle );
  2977. var t = 1 - c;
  2978. var x = axis.x, y = axis.y, z = axis.z;
  2979. var tx = t * x, ty = t * y;
  2980. this.set(
  2981. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2982. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2983. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2984. 0, 0, 0, 1
  2985. );
  2986. return this;
  2987. },
  2988. makeScale: function ( x, y, z ) {
  2989. this.set(
  2990. x, 0, 0, 0,
  2991. 0, y, 0, 0,
  2992. 0, 0, z, 0,
  2993. 0, 0, 0, 1
  2994. );
  2995. return this;
  2996. },
  2997. compose: function ( position, quaternion, scale ) {
  2998. this.makeRotationFromQuaternion( quaternion );
  2999. this.scale( scale );
  3000. this.setPosition( position );
  3001. return this;
  3002. },
  3003. decompose: function () {
  3004. var vector = new THREE.Vector3();
  3005. var matrix = new THREE.Matrix4();
  3006. return function ( position, quaternion, scale ) {
  3007. var te = this.elements;
  3008. var sx = vector.set( te[0], te[1], te[2] ).length();
  3009. var sy = vector.set( te[4], te[5], te[6] ).length();
  3010. var sz = vector.set( te[8], te[9], te[10] ).length();
  3011. // if determine is negative, we need to invert one scale
  3012. var det = this.determinant();
  3013. if( det < 0 ) {
  3014. sx = -sx;
  3015. }
  3016. position.x = te[12];
  3017. position.y = te[13];
  3018. position.z = te[14];
  3019. // scale the rotation part
  3020. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  3021. var invSX = 1 / sx;
  3022. var invSY = 1 / sy;
  3023. var invSZ = 1 / sz;
  3024. matrix.elements[0] *= invSX;
  3025. matrix.elements[1] *= invSX;
  3026. matrix.elements[2] *= invSX;
  3027. matrix.elements[4] *= invSY;
  3028. matrix.elements[5] *= invSY;
  3029. matrix.elements[6] *= invSY;
  3030. matrix.elements[8] *= invSZ;
  3031. matrix.elements[9] *= invSZ;
  3032. matrix.elements[10] *= invSZ;
  3033. quaternion.setFromRotationMatrix( matrix );
  3034. scale.x = sx;
  3035. scale.y = sy;
  3036. scale.z = sz;
  3037. return this;
  3038. };
  3039. }(),
  3040. makeFrustum: function ( left, right, bottom, top, near, far ) {
  3041. var te = this.elements;
  3042. var x = 2 * near / ( right - left );
  3043. var y = 2 * near / ( top - bottom );
  3044. var a = ( right + left ) / ( right - left );
  3045. var b = ( top + bottom ) / ( top - bottom );
  3046. var c = - ( far + near ) / ( far - near );
  3047. var d = - 2 * far * near / ( far - near );
  3048. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  3049. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  3050. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  3051. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  3052. return this;
  3053. },
  3054. makePerspective: function ( fov, aspect, near, far ) {
  3055. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  3056. var ymin = - ymax;
  3057. var xmin = ymin * aspect;
  3058. var xmax = ymax * aspect;
  3059. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  3060. },
  3061. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  3062. var te = this.elements;
  3063. var w = right - left;
  3064. var h = top - bottom;
  3065. var p = far - near;
  3066. var x = ( right + left ) / w;
  3067. var y = ( top + bottom ) / h;
  3068. var z = ( far + near ) / p;
  3069. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  3070. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  3071. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  3072. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  3073. return this;
  3074. },
  3075. fromArray: function ( array ) {
  3076. this.elements.set( array );
  3077. return this;
  3078. },
  3079. toArray: function () {
  3080. var te = this.elements;
  3081. return [
  3082. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  3083. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  3084. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  3085. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  3086. ];
  3087. },
  3088. clone: function () {
  3089. var te = this.elements;
  3090. return new THREE.Matrix4(
  3091. te[0], te[4], te[8], te[12],
  3092. te[1], te[5], te[9], te[13],
  3093. te[2], te[6], te[10], te[14],
  3094. te[3], te[7], te[11], te[15]
  3095. );
  3096. }
  3097. };
  3098. /**
  3099. * @author bhouston / http://exocortex.com
  3100. */
  3101. THREE.Ray = function ( origin, direction ) {
  3102. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  3103. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  3104. };
  3105. THREE.Ray.prototype = {
  3106. constructor: THREE.Ray,
  3107. set: function ( origin, direction ) {
  3108. this.origin.copy( origin );
  3109. this.direction.copy( direction );
  3110. return this;
  3111. },
  3112. copy: function ( ray ) {
  3113. this.origin.copy( ray.origin );
  3114. this.direction.copy( ray.direction );
  3115. return this;
  3116. },
  3117. at: function ( t, optionalTarget ) {
  3118. var result = optionalTarget || new THREE.Vector3();
  3119. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3120. },
  3121. recast: function () {
  3122. var v1 = new THREE.Vector3();
  3123. return function ( t ) {
  3124. this.origin.copy( this.at( t, v1 ) );
  3125. return this;
  3126. };
  3127. }(),
  3128. closestPointToPoint: function ( point, optionalTarget ) {
  3129. var result = optionalTarget || new THREE.Vector3();
  3130. result.subVectors( point, this.origin );
  3131. var directionDistance = result.dot( this.direction );
  3132. if ( directionDistance < 0 ) {
  3133. return result.copy( this.origin );
  3134. }
  3135. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3136. },
  3137. distanceToPoint: function () {
  3138. var v1 = new THREE.Vector3();
  3139. return function ( point ) {
  3140. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3141. // point behind the ray
  3142. if ( directionDistance < 0 ) {
  3143. return this.origin.distanceTo( point );
  3144. }
  3145. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3146. return v1.distanceTo( point );
  3147. };
  3148. }(),
  3149. distanceSqToSegment: function( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3150. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3151. // It returns the min distance between the ray and the segment
  3152. // defined by v0 and v1
  3153. // It can also set two optional targets :
  3154. // - The closest point on the ray
  3155. // - The closest point on the segment
  3156. var segCenter = v0.clone().add( v1 ).multiplyScalar( 0.5 );
  3157. var segDir = v1.clone().sub( v0 ).normalize();
  3158. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3159. var diff = this.origin.clone().sub( segCenter );
  3160. var a01 = - this.direction.dot( segDir );
  3161. var b0 = diff.dot( this.direction );
  3162. var b1 = - diff.dot( segDir );
  3163. var c = diff.lengthSq();
  3164. var det = Math.abs( 1 - a01 * a01 );
  3165. var s0, s1, sqrDist, extDet;
  3166. if ( det >= 0 ) {
  3167. // The ray and segment are not parallel.
  3168. s0 = a01 * b1 - b0;
  3169. s1 = a01 * b0 - b1;
  3170. extDet = segExtent * det;
  3171. if ( s0 >= 0 ) {
  3172. if ( s1 >= - extDet ) {
  3173. if ( s1 <= extDet ) {
  3174. // region 0
  3175. // Minimum at interior points of ray and segment.
  3176. var invDet = 1 / det;
  3177. s0 *= invDet;
  3178. s1 *= invDet;
  3179. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3180. } else {
  3181. // region 1
  3182. s1 = segExtent;
  3183. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3184. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3185. }
  3186. } else {
  3187. // region 5
  3188. s1 = - segExtent;
  3189. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3190. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3191. }
  3192. } else {
  3193. if ( s1 <= - extDet) {
  3194. // region 4
  3195. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3196. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3197. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3198. } else if ( s1 <= extDet ) {
  3199. // region 3
  3200. s0 = 0;
  3201. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3202. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3203. } else {
  3204. // region 2
  3205. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3206. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3207. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3208. }
  3209. }
  3210. } else {
  3211. // Ray and segment are parallel.
  3212. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3213. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3214. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3215. }
  3216. if ( optionalPointOnRay ) {
  3217. optionalPointOnRay.copy( this.direction.clone().multiplyScalar( s0 ).add( this.origin ) );
  3218. }
  3219. if ( optionalPointOnSegment ) {
  3220. optionalPointOnSegment.copy( segDir.clone().multiplyScalar( s1 ).add( segCenter ) );
  3221. }
  3222. return sqrDist;
  3223. },
  3224. isIntersectionSphere: function ( sphere ) {
  3225. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3226. },
  3227. isIntersectionPlane: function ( plane ) {
  3228. // check if the ray lies on the plane first
  3229. var distToPoint = plane.distanceToPoint( this.origin );
  3230. if ( distToPoint === 0 ) {
  3231. return true;
  3232. }
  3233. var denominator = plane.normal.dot( this.direction );
  3234. if ( denominator * distToPoint < 0 ) {
  3235. return true
  3236. }
  3237. // ray origin is behind the plane (and is pointing behind it)
  3238. return false;
  3239. },
  3240. distanceToPlane: function ( plane ) {
  3241. var denominator = plane.normal.dot( this.direction );
  3242. if ( denominator == 0 ) {
  3243. // line is coplanar, return origin
  3244. if( plane.distanceToPoint( this.origin ) == 0 ) {
  3245. return 0;
  3246. }
  3247. // Null is preferable to undefined since undefined means.... it is undefined
  3248. return null;
  3249. }
  3250. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3251. // Return if the ray never intersects the plane
  3252. return t >= 0 ? t : null;
  3253. },
  3254. intersectPlane: function ( plane, optionalTarget ) {
  3255. var t = this.distanceToPlane( plane );
  3256. if ( t === null ) {
  3257. return null;
  3258. }
  3259. return this.at( t, optionalTarget );
  3260. },
  3261. isIntersectionBox: function () {
  3262. var v = new THREE.Vector3();
  3263. return function ( box ) {
  3264. return this.intersectBox( box, v ) !== null;
  3265. }
  3266. }(),
  3267. intersectBox: function ( box , optionalTarget ) {
  3268. // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
  3269. var tmin,tmax,tymin,tymax,tzmin,tzmax;
  3270. var invdirx = 1/this.direction.x,
  3271. invdiry = 1/this.direction.y,
  3272. invdirz = 1/this.direction.z;
  3273. var origin = this.origin;
  3274. if (invdirx >= 0) {
  3275. tmin = (box.min.x - origin.x) * invdirx;
  3276. tmax = (box.max.x - origin.x) * invdirx;
  3277. } else {
  3278. tmin = (box.max.x - origin.x) * invdirx;
  3279. tmax = (box.min.x - origin.x) * invdirx;
  3280. }
  3281. if (invdiry >= 0) {
  3282. tymin = (box.min.y - origin.y) * invdiry;
  3283. tymax = (box.max.y - origin.y) * invdiry;
  3284. } else {
  3285. tymin = (box.max.y - origin.y) * invdiry;
  3286. tymax = (box.min.y - origin.y) * invdiry;
  3287. }
  3288. if ((tmin > tymax) || (tymin > tmax)) return null;
  3289. // These lines also handle the case where tmin or tmax is NaN
  3290. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3291. if (tymin > tmin || tmin !== tmin ) tmin = tymin;
  3292. if (tymax < tmax || tmax !== tmax ) tmax = tymax;
  3293. if (invdirz >= 0) {
  3294. tzmin = (box.min.z - origin.z) * invdirz;
  3295. tzmax = (box.max.z - origin.z) * invdirz;
  3296. } else {
  3297. tzmin = (box.max.z - origin.z) * invdirz;
  3298. tzmax = (box.min.z - origin.z) * invdirz;
  3299. }
  3300. if ((tmin > tzmax) || (tzmin > tmax)) return null;
  3301. if (tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3302. if (tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3303. //return point closest to the ray (positive side)
  3304. if ( tmax < 0 ) return null;
  3305. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3306. },
  3307. intersectTriangle: function() {
  3308. // Compute the offset origin, edges, and normal.
  3309. var diff = new THREE.Vector3();
  3310. var edge1 = new THREE.Vector3();
  3311. var edge2 = new THREE.Vector3();
  3312. var normal = new THREE.Vector3();
  3313. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3314. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3315. edge1.subVectors( b, a );
  3316. edge2.subVectors( c, a );
  3317. normal.crossVectors( edge1, edge2 );
  3318. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3319. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3320. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3321. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3322. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3323. var DdN = this.direction.dot( normal );
  3324. var sign;
  3325. if ( DdN > 0 ) {
  3326. if ( backfaceCulling ) return null;
  3327. sign = 1;
  3328. } else if ( DdN < 0 ) {
  3329. sign = - 1;
  3330. DdN = - DdN;
  3331. } else {
  3332. return null;
  3333. }
  3334. diff.subVectors( this.origin, a );
  3335. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3336. // b1 < 0, no intersection
  3337. if ( DdQxE2 < 0 ) {
  3338. return null;
  3339. }
  3340. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3341. // b2 < 0, no intersection
  3342. if ( DdE1xQ < 0 ) {
  3343. return null;
  3344. }
  3345. // b1+b2 > 1, no intersection
  3346. if ( DdQxE2 + DdE1xQ > DdN ) {
  3347. return null;
  3348. }
  3349. // Line intersects triangle, check if ray does.
  3350. var QdN = - sign * diff.dot( normal );
  3351. // t < 0, no intersection
  3352. if ( QdN < 0 ) {
  3353. return null;
  3354. }
  3355. // Ray intersects triangle.
  3356. return this.at( QdN / DdN, optionalTarget );
  3357. }
  3358. }(),
  3359. applyMatrix4: function ( matrix4 ) {
  3360. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3361. this.origin.applyMatrix4( matrix4 );
  3362. this.direction.sub( this.origin );
  3363. this.direction.normalize();
  3364. return this;
  3365. },
  3366. equals: function ( ray ) {
  3367. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3368. },
  3369. clone: function () {
  3370. return new THREE.Ray().copy( this );
  3371. }
  3372. };
  3373. /**
  3374. * @author bhouston / http://exocortex.com
  3375. * @author mrdoob / http://mrdoob.com/
  3376. */
  3377. THREE.Sphere = function ( center, radius ) {
  3378. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3379. this.radius = ( radius !== undefined ) ? radius : 0;
  3380. };
  3381. THREE.Sphere.prototype = {
  3382. constructor: THREE.Sphere,
  3383. set: function ( center, radius ) {
  3384. this.center.copy( center );
  3385. this.radius = radius;
  3386. return this;
  3387. },
  3388. setFromPoints: function () {
  3389. var box = new THREE.Box3();
  3390. return function ( points, optionalCenter ) {
  3391. var center = this.center;
  3392. if ( optionalCenter !== undefined ) {
  3393. center.copy( optionalCenter );
  3394. } else {
  3395. box.setFromPoints( points ).center( center );
  3396. }
  3397. var maxRadiusSq = 0;
  3398. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3399. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3400. }
  3401. this.radius = Math.sqrt( maxRadiusSq );
  3402. return this;
  3403. };
  3404. }(),
  3405. copy: function ( sphere ) {
  3406. this.center.copy( sphere.center );
  3407. this.radius = sphere.radius;
  3408. return this;
  3409. },
  3410. empty: function () {
  3411. return ( this.radius <= 0 );
  3412. },
  3413. containsPoint: function ( point ) {
  3414. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3415. },
  3416. distanceToPoint: function ( point ) {
  3417. return ( point.distanceTo( this.center ) - this.radius );
  3418. },
  3419. intersectsSphere: function ( sphere ) {
  3420. var radiusSum = this.radius + sphere.radius;
  3421. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3422. },
  3423. clampPoint: function ( point, optionalTarget ) {
  3424. var deltaLengthSq = this.center.distanceToSquared( point );
  3425. var result = optionalTarget || new THREE.Vector3();
  3426. result.copy( point );
  3427. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3428. result.sub( this.center ).normalize();
  3429. result.multiplyScalar( this.radius ).add( this.center );
  3430. }
  3431. return result;
  3432. },
  3433. getBoundingBox: function ( optionalTarget ) {
  3434. var box = optionalTarget || new THREE.Box3();
  3435. box.set( this.center, this.center );
  3436. box.expandByScalar( this.radius );
  3437. return box;
  3438. },
  3439. applyMatrix4: function ( matrix ) {
  3440. this.center.applyMatrix4( matrix );
  3441. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3442. return this;
  3443. },
  3444. translate: function ( offset ) {
  3445. this.center.add( offset );
  3446. return this;
  3447. },
  3448. equals: function ( sphere ) {
  3449. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3450. },
  3451. clone: function () {
  3452. return new THREE.Sphere().copy( this );
  3453. }
  3454. };
  3455. /**
  3456. * @author mrdoob / http://mrdoob.com/
  3457. * @author alteredq / http://alteredqualia.com/
  3458. * @author bhouston / http://exocortex.com
  3459. */
  3460. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3461. this.planes = [
  3462. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3463. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3464. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3465. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3466. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3467. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3468. ];
  3469. };
  3470. THREE.Frustum.prototype = {
  3471. constructor: THREE.Frustum,
  3472. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3473. var planes = this.planes;
  3474. planes[0].copy( p0 );
  3475. planes[1].copy( p1 );
  3476. planes[2].copy( p2 );
  3477. planes[3].copy( p3 );
  3478. planes[4].copy( p4 );
  3479. planes[5].copy( p5 );
  3480. return this;
  3481. },
  3482. copy: function ( frustum ) {
  3483. var planes = this.planes;
  3484. for( var i = 0; i < 6; i ++ ) {
  3485. planes[i].copy( frustum.planes[i] );
  3486. }
  3487. return this;
  3488. },
  3489. setFromMatrix: function ( m ) {
  3490. var planes = this.planes;
  3491. var me = m.elements;
  3492. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  3493. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  3494. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  3495. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  3496. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3497. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3498. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3499. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3500. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3501. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3502. return this;
  3503. },
  3504. intersectsObject: function () {
  3505. var sphere = new THREE.Sphere();
  3506. return function ( object ) {
  3507. var geometry = object.geometry;
  3508. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3509. sphere.copy( geometry.boundingSphere );
  3510. sphere.applyMatrix4( object.matrixWorld );
  3511. return this.intersectsSphere( sphere );
  3512. };
  3513. }(),
  3514. intersectsSphere: function ( sphere ) {
  3515. var planes = this.planes;
  3516. var center = sphere.center;
  3517. var negRadius = -sphere.radius;
  3518. for ( var i = 0; i < 6; i ++ ) {
  3519. var distance = planes[ i ].distanceToPoint( center );
  3520. if ( distance < negRadius ) {
  3521. return false;
  3522. }
  3523. }
  3524. return true;
  3525. },
  3526. intersectsBox : function() {
  3527. var p1 = new THREE.Vector3(),
  3528. p2 = new THREE.Vector3();
  3529. return function( box ) {
  3530. var planes = this.planes;
  3531. for ( var i = 0; i < 6 ; i ++ ) {
  3532. var plane = planes[i];
  3533. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3534. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3535. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3536. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3537. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3538. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3539. var d1 = plane.distanceToPoint( p1 );
  3540. var d2 = plane.distanceToPoint( p2 );
  3541. // if both outside plane, no intersection
  3542. if ( d1 < 0 && d2 < 0 ) {
  3543. return false;
  3544. }
  3545. }
  3546. return true;
  3547. };
  3548. }(),
  3549. containsPoint: function ( point ) {
  3550. var planes = this.planes;
  3551. for ( var i = 0; i < 6; i ++ ) {
  3552. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3553. return false;
  3554. }
  3555. }
  3556. return true;
  3557. },
  3558. clone: function () {
  3559. return new THREE.Frustum().copy( this );
  3560. }
  3561. };
  3562. /**
  3563. * @author bhouston / http://exocortex.com
  3564. */
  3565. THREE.Plane = function ( normal, constant ) {
  3566. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3567. this.constant = ( constant !== undefined ) ? constant : 0;
  3568. };
  3569. THREE.Plane.prototype = {
  3570. constructor: THREE.Plane,
  3571. set: function ( normal, constant ) {
  3572. this.normal.copy( normal );
  3573. this.constant = constant;
  3574. return this;
  3575. },
  3576. setComponents: function ( x, y, z, w ) {
  3577. this.normal.set( x, y, z );
  3578. this.constant = w;
  3579. return this;
  3580. },
  3581. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3582. this.normal.copy( normal );
  3583. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3584. return this;
  3585. },
  3586. setFromCoplanarPoints: function() {
  3587. var v1 = new THREE.Vector3();
  3588. var v2 = new THREE.Vector3();
  3589. return function ( a, b, c ) {
  3590. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3591. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3592. this.setFromNormalAndCoplanarPoint( normal, a );
  3593. return this;
  3594. };
  3595. }(),
  3596. copy: function ( plane ) {
  3597. this.normal.copy( plane.normal );
  3598. this.constant = plane.constant;
  3599. return this;
  3600. },
  3601. normalize: function () {
  3602. // Note: will lead to a divide by zero if the plane is invalid.
  3603. var inverseNormalLength = 1.0 / this.normal.length();
  3604. this.normal.multiplyScalar( inverseNormalLength );
  3605. this.constant *= inverseNormalLength;
  3606. return this;
  3607. },
  3608. negate: function () {
  3609. this.constant *= -1;
  3610. this.normal.negate();
  3611. return this;
  3612. },
  3613. distanceToPoint: function ( point ) {
  3614. return this.normal.dot( point ) + this.constant;
  3615. },
  3616. distanceToSphere: function ( sphere ) {
  3617. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3618. },
  3619. projectPoint: function ( point, optionalTarget ) {
  3620. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3621. },
  3622. orthoPoint: function ( point, optionalTarget ) {
  3623. var perpendicularMagnitude = this.distanceToPoint( point );
  3624. var result = optionalTarget || new THREE.Vector3();
  3625. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3626. },
  3627. isIntersectionLine: function ( line ) {
  3628. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3629. var startSign = this.distanceToPoint( line.start );
  3630. var endSign = this.distanceToPoint( line.end );
  3631. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3632. },
  3633. intersectLine: function() {
  3634. var v1 = new THREE.Vector3();
  3635. return function ( line, optionalTarget ) {
  3636. var result = optionalTarget || new THREE.Vector3();
  3637. var direction = line.delta( v1 );
  3638. var denominator = this.normal.dot( direction );
  3639. if ( denominator == 0 ) {
  3640. // line is coplanar, return origin
  3641. if( this.distanceToPoint( line.start ) == 0 ) {
  3642. return result.copy( line.start );
  3643. }
  3644. // Unsure if this is the correct method to handle this case.
  3645. return undefined;
  3646. }
  3647. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3648. if( t < 0 || t > 1 ) {
  3649. return undefined;
  3650. }
  3651. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3652. };
  3653. }(),
  3654. coplanarPoint: function ( optionalTarget ) {
  3655. var result = optionalTarget || new THREE.Vector3();
  3656. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3657. },
  3658. applyMatrix4: function() {
  3659. var v1 = new THREE.Vector3();
  3660. var v2 = new THREE.Vector3();
  3661. var m1 = new THREE.Matrix3();
  3662. return function ( matrix, optionalNormalMatrix ) {
  3663. // compute new normal based on theory here:
  3664. // http://www.songho.ca/opengl/gl_normaltransform.html
  3665. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  3666. var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix );
  3667. var newCoplanarPoint = this.coplanarPoint( v2 );
  3668. newCoplanarPoint.applyMatrix4( matrix );
  3669. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3670. return this;
  3671. };
  3672. }(),
  3673. translate: function ( offset ) {
  3674. this.constant = this.constant - offset.dot( this.normal );
  3675. return this;
  3676. },
  3677. equals: function ( plane ) {
  3678. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3679. },
  3680. clone: function () {
  3681. return new THREE.Plane().copy( this );
  3682. }
  3683. };
  3684. /**
  3685. * @author alteredq / http://alteredqualia.com/
  3686. * @author mrdoob / http://mrdoob.com/
  3687. */
  3688. THREE.Math = {
  3689. PI2: Math.PI * 2,
  3690. generateUUID: function () {
  3691. // http://www.broofa.com/Tools/Math.uuid.htm
  3692. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  3693. var uuid = new Array(36);
  3694. var rnd = 0, r;
  3695. return function () {
  3696. for ( var i = 0; i < 36; i ++ ) {
  3697. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3698. uuid[ i ] = '-';
  3699. } else if ( i == 14 ) {
  3700. uuid[ i ] = '4';
  3701. } else {
  3702. if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
  3703. r = rnd & 0xf;
  3704. rnd = rnd >> 4;
  3705. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  3706. }
  3707. }
  3708. return uuid.join('');
  3709. };
  3710. }(),
  3711. // Clamp value to range <a, b>
  3712. clamp: function ( x, a, b ) {
  3713. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3714. },
  3715. // Clamp value to range <a, inf)
  3716. clampBottom: function ( x, a ) {
  3717. return x < a ? a : x;
  3718. },
  3719. // Linear mapping from range <a1, a2> to range <b1, b2>
  3720. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3721. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3722. },
  3723. // http://en.wikipedia.org/wiki/Smoothstep
  3724. smoothstep: function ( x, min, max ) {
  3725. if ( x <= min ) return 0;
  3726. if ( x >= max ) return 1;
  3727. x = ( x - min )/( max - min );
  3728. return x*x*(3 - 2*x);
  3729. },
  3730. smootherstep: function ( x, min, max ) {
  3731. if ( x <= min ) return 0;
  3732. if ( x >= max ) return 1;
  3733. x = ( x - min )/( max - min );
  3734. return x*x*x*(x*(x*6 - 15) + 10);
  3735. },
  3736. // Random float from <0, 1> with 16 bits of randomness
  3737. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3738. random16: function () {
  3739. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3740. },
  3741. // Random integer from <low, high> interval
  3742. randInt: function ( low, high ) {
  3743. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3744. },
  3745. // Random float from <low, high> interval
  3746. randFloat: function ( low, high ) {
  3747. return low + Math.random() * ( high - low );
  3748. },
  3749. // Random float from <-range/2, range/2> interval
  3750. randFloatSpread: function ( range ) {
  3751. return range * ( 0.5 - Math.random() );
  3752. },
  3753. sign: function ( x ) {
  3754. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : 0;
  3755. },
  3756. degToRad: function() {
  3757. var degreeToRadiansFactor = Math.PI / 180;
  3758. return function ( degrees ) {
  3759. return degrees * degreeToRadiansFactor;
  3760. };
  3761. }(),
  3762. radToDeg: function() {
  3763. var radianToDegreesFactor = 180 / Math.PI;
  3764. return function ( radians ) {
  3765. return radians * radianToDegreesFactor;
  3766. };
  3767. }(),
  3768. isPowerOfTwo: function ( value ) {
  3769. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  3770. }
  3771. };
  3772. /**
  3773. * Spline from Tween.js, slightly optimized (and trashed)
  3774. * http://sole.github.com/tween.js/examples/05_spline.html
  3775. *
  3776. * @author mrdoob / http://mrdoob.com/
  3777. * @author alteredq / http://alteredqualia.com/
  3778. */
  3779. THREE.Spline = function ( points ) {
  3780. this.points = points;
  3781. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3782. point, intPoint, weight, w2, w3,
  3783. pa, pb, pc, pd;
  3784. this.initFromArray = function( a ) {
  3785. this.points = [];
  3786. for ( var i = 0; i < a.length; i++ ) {
  3787. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3788. }
  3789. };
  3790. this.getPoint = function ( k ) {
  3791. point = ( this.points.length - 1 ) * k;
  3792. intPoint = Math.floor( point );
  3793. weight = point - intPoint;
  3794. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3795. c[ 1 ] = intPoint;
  3796. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3797. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3798. pa = this.points[ c[ 0 ] ];
  3799. pb = this.points[ c[ 1 ] ];
  3800. pc = this.points[ c[ 2 ] ];
  3801. pd = this.points[ c[ 3 ] ];
  3802. w2 = weight * weight;
  3803. w3 = weight * w2;
  3804. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3805. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3806. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3807. return v3;
  3808. };
  3809. this.getControlPointsArray = function () {
  3810. var i, p, l = this.points.length,
  3811. coords = [];
  3812. for ( i = 0; i < l; i ++ ) {
  3813. p = this.points[ i ];
  3814. coords[ i ] = [ p.x, p.y, p.z ];
  3815. }
  3816. return coords;
  3817. };
  3818. // approximate length by summing linear segments
  3819. this.getLength = function ( nSubDivisions ) {
  3820. var i, index, nSamples, position,
  3821. point = 0, intPoint = 0, oldIntPoint = 0,
  3822. oldPosition = new THREE.Vector3(),
  3823. tmpVec = new THREE.Vector3(),
  3824. chunkLengths = [],
  3825. totalLength = 0;
  3826. // first point has 0 length
  3827. chunkLengths[ 0 ] = 0;
  3828. if ( !nSubDivisions ) nSubDivisions = 100;
  3829. nSamples = this.points.length * nSubDivisions;
  3830. oldPosition.copy( this.points[ 0 ] );
  3831. for ( i = 1; i < nSamples; i ++ ) {
  3832. index = i / nSamples;
  3833. position = this.getPoint( index );
  3834. tmpVec.copy( position );
  3835. totalLength += tmpVec.distanceTo( oldPosition );
  3836. oldPosition.copy( position );
  3837. point = ( this.points.length - 1 ) * index;
  3838. intPoint = Math.floor( point );
  3839. if ( intPoint != oldIntPoint ) {
  3840. chunkLengths[ intPoint ] = totalLength;
  3841. oldIntPoint = intPoint;
  3842. }
  3843. }
  3844. // last point ends with total length
  3845. chunkLengths[ chunkLengths.length ] = totalLength;
  3846. return { chunks: chunkLengths, total: totalLength };
  3847. };
  3848. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3849. var i, j,
  3850. index, indexCurrent, indexNext,
  3851. linearDistance, realDistance,
  3852. sampling, position,
  3853. newpoints = [],
  3854. tmpVec = new THREE.Vector3(),
  3855. sl = this.getLength();
  3856. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3857. for ( i = 1; i < this.points.length; i++ ) {
  3858. //tmpVec.copy( this.points[ i - 1 ] );
  3859. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3860. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3861. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3862. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3863. indexNext = i / ( this.points.length - 1 );
  3864. for ( j = 1; j < sampling - 1; j++ ) {
  3865. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3866. position = this.getPoint( index );
  3867. newpoints.push( tmpVec.copy( position ).clone() );
  3868. }
  3869. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3870. }
  3871. this.points = newpoints;
  3872. };
  3873. // Catmull-Rom
  3874. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3875. var v0 = ( p2 - p0 ) * 0.5,
  3876. v1 = ( p3 - p1 ) * 0.5;
  3877. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3878. };
  3879. };
  3880. /**
  3881. * @author bhouston / http://exocortex.com
  3882. * @author mrdoob / http://mrdoob.com/
  3883. */
  3884. THREE.Triangle = function ( a, b, c ) {
  3885. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3886. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3887. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3888. };
  3889. THREE.Triangle.normal = function() {
  3890. var v0 = new THREE.Vector3();
  3891. return function ( a, b, c, optionalTarget ) {
  3892. var result = optionalTarget || new THREE.Vector3();
  3893. result.subVectors( c, b );
  3894. v0.subVectors( a, b );
  3895. result.cross( v0 );
  3896. var resultLengthSq = result.lengthSq();
  3897. if( resultLengthSq > 0 ) {
  3898. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3899. }
  3900. return result.set( 0, 0, 0 );
  3901. };
  3902. }();
  3903. // static/instance method to calculate barycoordinates
  3904. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3905. THREE.Triangle.barycoordFromPoint = function() {
  3906. var v0 = new THREE.Vector3();
  3907. var v1 = new THREE.Vector3();
  3908. var v2 = new THREE.Vector3();
  3909. return function ( point, a, b, c, optionalTarget ) {
  3910. v0.subVectors( c, a );
  3911. v1.subVectors( b, a );
  3912. v2.subVectors( point, a );
  3913. var dot00 = v0.dot( v0 );
  3914. var dot01 = v0.dot( v1 );
  3915. var dot02 = v0.dot( v2 );
  3916. var dot11 = v1.dot( v1 );
  3917. var dot12 = v1.dot( v2 );
  3918. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3919. var result = optionalTarget || new THREE.Vector3();
  3920. // colinear or singular triangle
  3921. if( denom == 0 ) {
  3922. // arbitrary location outside of triangle?
  3923. // not sure if this is the best idea, maybe should be returning undefined
  3924. return result.set( -2, -1, -1 );
  3925. }
  3926. var invDenom = 1 / denom;
  3927. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3928. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3929. // barycoordinates must always sum to 1
  3930. return result.set( 1 - u - v, v, u );
  3931. };
  3932. }();
  3933. THREE.Triangle.containsPoint = function() {
  3934. var v1 = new THREE.Vector3();
  3935. return function ( point, a, b, c ) {
  3936. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3937. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3938. };
  3939. }();
  3940. THREE.Triangle.prototype = {
  3941. constructor: THREE.Triangle,
  3942. set: function ( a, b, c ) {
  3943. this.a.copy( a );
  3944. this.b.copy( b );
  3945. this.c.copy( c );
  3946. return this;
  3947. },
  3948. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3949. this.a.copy( points[i0] );
  3950. this.b.copy( points[i1] );
  3951. this.c.copy( points[i2] );
  3952. return this;
  3953. },
  3954. copy: function ( triangle ) {
  3955. this.a.copy( triangle.a );
  3956. this.b.copy( triangle.b );
  3957. this.c.copy( triangle.c );
  3958. return this;
  3959. },
  3960. area: function() {
  3961. var v0 = new THREE.Vector3();
  3962. var v1 = new THREE.Vector3();
  3963. return function () {
  3964. v0.subVectors( this.c, this.b );
  3965. v1.subVectors( this.a, this.b );
  3966. return v0.cross( v1 ).length() * 0.5;
  3967. };
  3968. }(),
  3969. midpoint: function ( optionalTarget ) {
  3970. var result = optionalTarget || new THREE.Vector3();
  3971. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3972. },
  3973. normal: function ( optionalTarget ) {
  3974. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3975. },
  3976. plane: function ( optionalTarget ) {
  3977. var result = optionalTarget || new THREE.Plane();
  3978. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3979. },
  3980. barycoordFromPoint: function ( point, optionalTarget ) {
  3981. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3982. },
  3983. containsPoint: function ( point ) {
  3984. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3985. },
  3986. equals: function ( triangle ) {
  3987. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3988. },
  3989. clone: function () {
  3990. return new THREE.Triangle().copy( this );
  3991. }
  3992. };
  3993. /**
  3994. * @author mrdoob / http://mrdoob.com/
  3995. */
  3996. THREE.Vertex = function ( v ) {
  3997. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3998. return v;
  3999. };
  4000. /**
  4001. * @author mrdoob / http://mrdoob.com/
  4002. */
  4003. THREE.UV = function ( u, v ) {
  4004. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  4005. return new THREE.Vector2( u, v );
  4006. };
  4007. /**
  4008. * @author alteredq / http://alteredqualia.com/
  4009. */
  4010. THREE.Clock = function ( autoStart ) {
  4011. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  4012. this.startTime = 0;
  4013. this.oldTime = 0;
  4014. this.elapsedTime = 0;
  4015. this.running = false;
  4016. };
  4017. THREE.Clock.prototype = {
  4018. constructor: THREE.Clock,
  4019. start: function () {
  4020. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  4021. ? self.performance.now()
  4022. : Date.now();
  4023. this.oldTime = this.startTime;
  4024. this.running = true;
  4025. },
  4026. stop: function () {
  4027. this.getElapsedTime();
  4028. this.running = false;
  4029. },
  4030. getElapsedTime: function () {
  4031. this.getDelta();
  4032. return this.elapsedTime;
  4033. },
  4034. getDelta: function () {
  4035. var diff = 0;
  4036. if ( this.autoStart && ! this.running ) {
  4037. this.start();
  4038. }
  4039. if ( this.running ) {
  4040. var newTime = self.performance !== undefined && self.performance.now !== undefined
  4041. ? self.performance.now()
  4042. : Date.now();
  4043. diff = 0.001 * ( newTime - this.oldTime );
  4044. this.oldTime = newTime;
  4045. this.elapsedTime += diff;
  4046. }
  4047. return diff;
  4048. }
  4049. };
  4050. /**
  4051. * https://github.com/mrdoob/eventdispatcher.js/
  4052. */
  4053. THREE.EventDispatcher = function () {}
  4054. THREE.EventDispatcher.prototype = {
  4055. constructor: THREE.EventDispatcher,
  4056. apply: function ( object ) {
  4057. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  4058. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  4059. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  4060. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  4061. },
  4062. addEventListener: function ( type, listener ) {
  4063. if ( this._listeners === undefined ) this._listeners = {};
  4064. var listeners = this._listeners;
  4065. if ( listeners[ type ] === undefined ) {
  4066. listeners[ type ] = [];
  4067. }
  4068. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4069. listeners[ type ].push( listener );
  4070. }
  4071. },
  4072. hasEventListener: function ( type, listener ) {
  4073. if ( this._listeners === undefined ) return false;
  4074. var listeners = this._listeners;
  4075. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  4076. return true;
  4077. }
  4078. return false;
  4079. },
  4080. removeEventListener: function ( type, listener ) {
  4081. if ( this._listeners === undefined ) return;
  4082. var listeners = this._listeners;
  4083. var listenerArray = listeners[ type ];
  4084. if ( listenerArray !== undefined ) {
  4085. var index = listenerArray.indexOf( listener );
  4086. if ( index !== - 1 ) {
  4087. listenerArray.splice( index, 1 );
  4088. }
  4089. }
  4090. },
  4091. dispatchEvent: function () {
  4092. var array = [];
  4093. return function ( event ) {
  4094. if ( this._listeners === undefined ) return;
  4095. var listeners = this._listeners;
  4096. var listenerArray = listeners[ event.type ];
  4097. if ( listenerArray !== undefined ) {
  4098. event.target = this;
  4099. var length = listenerArray.length;
  4100. for ( var i = 0; i < length; i ++ ) {
  4101. array[ i ] = listenerArray[ i ];
  4102. }
  4103. for ( var i = 0; i < length; i ++ ) {
  4104. array[ i ].call( this, event );
  4105. }
  4106. }
  4107. };
  4108. }()
  4109. };
  4110. /**
  4111. * @author mrdoob / http://mrdoob.com/
  4112. * @author bhouston / http://exocortex.com/
  4113. * @author stephomi / http://stephaneginier.com/
  4114. */
  4115. ( function ( THREE ) {
  4116. THREE.Raycaster = function ( origin, direction, near, far ) {
  4117. this.ray = new THREE.Ray( origin, direction );
  4118. // direction is assumed to be normalized (for accurate distance calculations)
  4119. this.near = near || 0;
  4120. this.far = far || Infinity;
  4121. };
  4122. var sphere = new THREE.Sphere();
  4123. var localRay = new THREE.Ray();
  4124. var facePlane = new THREE.Plane();
  4125. var intersectPoint = new THREE.Vector3();
  4126. var matrixPosition = new THREE.Vector3();
  4127. var inverseMatrix = new THREE.Matrix4();
  4128. var descSort = function ( a, b ) {
  4129. return a.distance - b.distance;
  4130. };
  4131. var vA = new THREE.Vector3();
  4132. var vB = new THREE.Vector3();
  4133. var vC = new THREE.Vector3();
  4134. var intersectObject = function ( object, raycaster, intersects ) {
  4135. if ( object instanceof THREE.Sprite ) {
  4136. matrixPosition.setFromMatrixPosition( object.matrixWorld );
  4137. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  4138. if ( distance > object.scale.x ) {
  4139. return intersects;
  4140. }
  4141. intersects.push( {
  4142. distance: distance,
  4143. point: object.position,
  4144. face: null,
  4145. object: object
  4146. } );
  4147. } else if ( object instanceof THREE.LOD ) {
  4148. matrixPosition.setFromMatrixPosition( object.matrixWorld );
  4149. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  4150. intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );
  4151. } else if ( object instanceof THREE.Mesh ) {
  4152. var geometry = object.geometry;
  4153. // Checking boundingSphere distance to ray
  4154. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4155. sphere.copy( geometry.boundingSphere );
  4156. sphere.applyMatrix4( object.matrixWorld );
  4157. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4158. return intersects;
  4159. }
  4160. // Check boundingBox before continuing
  4161. inverseMatrix.getInverse( object.matrixWorld );
  4162. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4163. if ( geometry.boundingBox !== null ) {
  4164. if ( localRay.isIntersectionBox( geometry.boundingBox ) === false ) {
  4165. return intersects;
  4166. }
  4167. }
  4168. if ( geometry instanceof THREE.BufferGeometry ) {
  4169. var material = object.material;
  4170. if ( material === undefined ) return intersects;
  4171. var attributes = geometry.attributes;
  4172. var a, b, c;
  4173. var precision = raycaster.precision;
  4174. if ( attributes.index !== undefined ) {
  4175. var offsets = geometry.offsets;
  4176. var indices = attributes.index.array;
  4177. var positions = attributes.position.array;
  4178. for ( var oi = 0, ol = offsets.length; oi < ol; ++oi ) {
  4179. var start = offsets[ oi ].start;
  4180. var count = offsets[ oi ].count;
  4181. var index = offsets[ oi ].index;
  4182. for ( var i = start, il = start + count; i < il; i += 3 ) {
  4183. a = index + indices[ i ];
  4184. b = index + indices[ i + 1 ];
  4185. c = index + indices[ i + 2 ];
  4186. vA.set(
  4187. positions[ a * 3 ],
  4188. positions[ a * 3 + 1 ],
  4189. positions[ a * 3 + 2 ]
  4190. );
  4191. vB.set(
  4192. positions[ b * 3 ],
  4193. positions[ b * 3 + 1 ],
  4194. positions[ b * 3 + 2 ]
  4195. );
  4196. vC.set(
  4197. positions[ c * 3 ],
  4198. positions[ c * 3 + 1 ],
  4199. positions[ c * 3 + 2 ]
  4200. );
  4201. if ( material.side === THREE.BackSide ) {
  4202. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4203. } else {
  4204. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4205. }
  4206. if ( intersectionPoint === null ) continue;
  4207. intersectionPoint.applyMatrix4( object.matrixWorld );
  4208. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4209. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4210. intersects.push( {
  4211. distance: distance,
  4212. point: intersectionPoint,
  4213. indices: [a, b, c],
  4214. face: null,
  4215. faceIndex: null,
  4216. object: object
  4217. } );
  4218. }
  4219. }
  4220. } else {
  4221. var offsets = geometry.offsets;
  4222. var positions = attributes.position.array;
  4223. for ( var i = 0, il = attributes.position.array.length; i < il; i += 3 ) {
  4224. a = i;
  4225. b = i + 1;
  4226. c = i + 2;
  4227. vA.set(
  4228. positions[ a * 3 ],
  4229. positions[ a * 3 + 1 ],
  4230. positions[ a * 3 + 2 ]
  4231. );
  4232. vB.set(
  4233. positions[ b * 3 ],
  4234. positions[ b * 3 + 1 ],
  4235. positions[ b * 3 + 2 ]
  4236. );
  4237. vC.set(
  4238. positions[ c * 3 ],
  4239. positions[ c * 3 + 1 ],
  4240. positions[ c * 3 + 2 ]
  4241. );
  4242. if ( material.side === THREE.BackSide ) {
  4243. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4244. } else {
  4245. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4246. }
  4247. if ( intersectionPoint === null ) continue;
  4248. intersectionPoint.applyMatrix4( object.matrixWorld );
  4249. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4250. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4251. intersects.push( {
  4252. distance: distance,
  4253. point: intersectionPoint,
  4254. indices: [a, b, c],
  4255. face: null,
  4256. faceIndex: null,
  4257. object: object
  4258. } );
  4259. }
  4260. }
  4261. } else if ( geometry instanceof THREE.Geometry ) {
  4262. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4263. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  4264. var a, b, c, d;
  4265. var precision = raycaster.precision;
  4266. var vertices = geometry.vertices;
  4267. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  4268. var face = geometry.faces[ f ];
  4269. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  4270. if ( material === undefined ) continue;
  4271. a = vertices[ face.a ];
  4272. b = vertices[ face.b ];
  4273. c = vertices[ face.c ];
  4274. if ( material.morphTargets === true ) {
  4275. var morphTargets = geometry.morphTargets;
  4276. var morphInfluences = object.morphTargetInfluences;
  4277. vA.set( 0, 0, 0 );
  4278. vB.set( 0, 0, 0 );
  4279. vC.set( 0, 0, 0 );
  4280. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  4281. var influence = morphInfluences[ t ];
  4282. if ( influence === 0 ) continue;
  4283. var targets = morphTargets[ t ].vertices;
  4284. vA.x += ( targets[ face.a ].x - a.x ) * influence;
  4285. vA.y += ( targets[ face.a ].y - a.y ) * influence;
  4286. vA.z += ( targets[ face.a ].z - a.z ) * influence;
  4287. vB.x += ( targets[ face.b ].x - b.x ) * influence;
  4288. vB.y += ( targets[ face.b ].y - b.y ) * influence;
  4289. vB.z += ( targets[ face.b ].z - b.z ) * influence;
  4290. vC.x += ( targets[ face.c ].x - c.x ) * influence;
  4291. vC.y += ( targets[ face.c ].y - c.y ) * influence;
  4292. vC.z += ( targets[ face.c ].z - c.z ) * influence;
  4293. }
  4294. vA.add( a );
  4295. vB.add( b );
  4296. vC.add( c );
  4297. a = vA;
  4298. b = vB;
  4299. c = vC;
  4300. }
  4301. if ( material.side === THREE.BackSide ) {
  4302. var intersectionPoint = localRay.intersectTriangle( c, b, a, true );
  4303. } else {
  4304. var intersectionPoint = localRay.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide );
  4305. }
  4306. if ( intersectionPoint === null ) continue;
  4307. intersectionPoint.applyMatrix4( object.matrixWorld );
  4308. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4309. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4310. intersects.push( {
  4311. distance: distance,
  4312. point: intersectionPoint,
  4313. face: face,
  4314. faceIndex: f,
  4315. object: object
  4316. } );
  4317. }
  4318. }
  4319. } else if ( object instanceof THREE.Line ) {
  4320. var precision = raycaster.linePrecision;
  4321. var precisionSq = precision * precision;
  4322. var geometry = object.geometry;
  4323. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4324. // Checking boundingSphere distance to ray
  4325. sphere.copy( geometry.boundingSphere );
  4326. sphere.applyMatrix4( object.matrixWorld );
  4327. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4328. return intersects;
  4329. }
  4330. inverseMatrix.getInverse( object.matrixWorld );
  4331. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4332. /* if ( geometry instanceof THREE.BufferGeometry ) {
  4333. } else */ if ( geometry instanceof THREE.Geometry ) {
  4334. var vertices = geometry.vertices;
  4335. var nbVertices = vertices.length;
  4336. var interSegment = new THREE.Vector3();
  4337. var interRay = new THREE.Vector3();
  4338. var step = object.type === THREE.LineStrip ? 1 : 2;
  4339. for ( var i = 0; i < nbVertices - 1; i = i + step ) {
  4340. var distSq = localRay.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  4341. if ( distSq > precisionSq ) continue;
  4342. var distance = localRay.origin.distanceTo( interRay );
  4343. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  4344. intersects.push( {
  4345. distance: distance,
  4346. // What do we want? intersection point on the ray or on the segment??
  4347. // point: raycaster.ray.at( distance ),
  4348. point: interSegment.clone().applyMatrix4( object.matrixWorld ),
  4349. face: null,
  4350. faceIndex: null,
  4351. object: object
  4352. } );
  4353. }
  4354. }
  4355. }
  4356. };
  4357. var intersectDescendants = function ( object, raycaster, intersects ) {
  4358. var descendants = object.getDescendants();
  4359. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  4360. intersectObject( descendants[ i ], raycaster, intersects );
  4361. }
  4362. };
  4363. //
  4364. THREE.Raycaster.prototype.precision = 0.0001;
  4365. THREE.Raycaster.prototype.linePrecision = 1;
  4366. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  4367. this.ray.set( origin, direction );
  4368. // direction is assumed to be normalized (for accurate distance calculations)
  4369. };
  4370. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  4371. var intersects = [];
  4372. if ( recursive === true ) {
  4373. intersectDescendants( object, this, intersects );
  4374. }
  4375. intersectObject( object, this, intersects );
  4376. intersects.sort( descSort );
  4377. return intersects;
  4378. };
  4379. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  4380. var intersects = [];
  4381. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4382. intersectObject( objects[ i ], this, intersects );
  4383. if ( recursive === true ) {
  4384. intersectDescendants( objects[ i ], this, intersects );
  4385. }
  4386. }
  4387. intersects.sort( descSort );
  4388. return intersects;
  4389. };
  4390. }( THREE ) );
  4391. /**
  4392. * @author mrdoob / http://mrdoob.com/
  4393. * @author mikael emtinger / http://gomo.se/
  4394. * @author alteredq / http://alteredqualia.com/
  4395. * @author WestLangley / http://github.com/WestLangley
  4396. */
  4397. THREE.Object3D = function () {
  4398. this.id = THREE.Object3DIdCount ++;
  4399. this.uuid = THREE.Math.generateUUID();
  4400. this.name = '';
  4401. this.parent = undefined;
  4402. this.children = [];
  4403. this.up = new THREE.Vector3( 0, 1, 0 );
  4404. this.position = new THREE.Vector3();
  4405. this._rotation = new THREE.Euler();
  4406. this._quaternion = new THREE.Quaternion();
  4407. this.scale = new THREE.Vector3( 1, 1, 1 );
  4408. // keep rotation and quaternion in sync
  4409. this._rotation._quaternion = this.quaternion;
  4410. this._quaternion._euler = this.rotation;
  4411. this.renderDepth = null;
  4412. this.rotationAutoUpdate = true;
  4413. this.matrix = new THREE.Matrix4();
  4414. this.matrixWorld = new THREE.Matrix4();
  4415. this.matrixAutoUpdate = true;
  4416. this.matrixWorldNeedsUpdate = true;
  4417. this.visible = true;
  4418. this.castShadow = false;
  4419. this.receiveShadow = false;
  4420. this.frustumCulled = true;
  4421. this.userData = {};
  4422. };
  4423. THREE.Object3D.prototype = {
  4424. constructor: THREE.Object3D,
  4425. get rotation () {
  4426. return this._rotation;
  4427. },
  4428. set rotation ( value ) {
  4429. this._rotation = value;
  4430. this._rotation._quaternion = this._quaternion;
  4431. this._quaternion._euler = this._rotation;
  4432. this._rotation._updateQuaternion();
  4433. },
  4434. get quaternion () {
  4435. return this._quaternion;
  4436. },
  4437. set quaternion ( value ) {
  4438. this._quaternion = value;
  4439. this._quaternion._euler = this._rotation;
  4440. this._rotation._quaternion = this._quaternion;
  4441. this._quaternion._updateEuler();
  4442. },
  4443. get eulerOrder () {
  4444. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4445. return this.rotation.order;
  4446. },
  4447. set eulerOrder ( value ) {
  4448. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4449. this.rotation.order = value;
  4450. },
  4451. get useQuaternion () {
  4452. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4453. },
  4454. set useQuaternion ( value ) {
  4455. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4456. },
  4457. applyMatrix: function ( matrix ) {
  4458. this.matrix.multiplyMatrices( matrix, this.matrix );
  4459. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4460. },
  4461. setRotationFromAxisAngle: function ( axis, angle ) {
  4462. // assumes axis is normalized
  4463. this.quaternion.setFromAxisAngle( axis, angle );
  4464. },
  4465. setRotationFromEuler: function ( euler ) {
  4466. this.quaternion.setFromEuler( euler, true );
  4467. },
  4468. setRotationFromMatrix: function ( m ) {
  4469. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4470. this.quaternion.setFromRotationMatrix( m );
  4471. },
  4472. setRotationFromQuaternion: function ( q ) {
  4473. // assumes q is normalized
  4474. this.quaternion.copy( q );
  4475. },
  4476. rotateOnAxis: function() {
  4477. // rotate object on axis in object space
  4478. // axis is assumed to be normalized
  4479. var q1 = new THREE.Quaternion();
  4480. return function ( axis, angle ) {
  4481. q1.setFromAxisAngle( axis, angle );
  4482. this.quaternion.multiply( q1 );
  4483. return this;
  4484. }
  4485. }(),
  4486. rotateX: function () {
  4487. var v1 = new THREE.Vector3( 1, 0, 0 );
  4488. return function ( angle ) {
  4489. return this.rotateOnAxis( v1, angle );
  4490. };
  4491. }(),
  4492. rotateY: function () {
  4493. var v1 = new THREE.Vector3( 0, 1, 0 );
  4494. return function ( angle ) {
  4495. return this.rotateOnAxis( v1, angle );
  4496. };
  4497. }(),
  4498. rotateZ: function () {
  4499. var v1 = new THREE.Vector3( 0, 0, 1 );
  4500. return function ( angle ) {
  4501. return this.rotateOnAxis( v1, angle );
  4502. };
  4503. }(),
  4504. translateOnAxis: function () {
  4505. // translate object by distance along axis in object space
  4506. // axis is assumed to be normalized
  4507. var v1 = new THREE.Vector3();
  4508. return function ( axis, distance ) {
  4509. v1.copy( axis );
  4510. v1.applyQuaternion( this.quaternion );
  4511. this.position.add( v1.multiplyScalar( distance ) );
  4512. return this;
  4513. }
  4514. }(),
  4515. translate: function ( distance, axis ) {
  4516. console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
  4517. return this.translateOnAxis( axis, distance );
  4518. },
  4519. translateX: function () {
  4520. var v1 = new THREE.Vector3( 1, 0, 0 );
  4521. return function ( distance ) {
  4522. return this.translateOnAxis( v1, distance );
  4523. };
  4524. }(),
  4525. translateY: function () {
  4526. var v1 = new THREE.Vector3( 0, 1, 0 );
  4527. return function ( distance ) {
  4528. return this.translateOnAxis( v1, distance );
  4529. };
  4530. }(),
  4531. translateZ: function () {
  4532. var v1 = new THREE.Vector3( 0, 0, 1 );
  4533. return function ( distance ) {
  4534. return this.translateOnAxis( v1, distance );
  4535. };
  4536. }(),
  4537. localToWorld: function ( vector ) {
  4538. return vector.applyMatrix4( this.matrixWorld );
  4539. },
  4540. worldToLocal: function () {
  4541. var m1 = new THREE.Matrix4();
  4542. return function ( vector ) {
  4543. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4544. };
  4545. }(),
  4546. lookAt: function () {
  4547. // This routine does not support objects with rotated and/or translated parent(s)
  4548. var m1 = new THREE.Matrix4();
  4549. return function ( vector ) {
  4550. m1.lookAt( vector, this.position, this.up );
  4551. this.quaternion.setFromRotationMatrix( m1 );
  4552. };
  4553. }(),
  4554. add: function ( object ) {
  4555. if ( object === this ) {
  4556. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  4557. return;
  4558. }
  4559. if ( object instanceof THREE.Object3D ) {
  4560. if ( object.parent !== undefined ) {
  4561. object.parent.remove( object );
  4562. }
  4563. object.parent = this;
  4564. object.dispatchEvent( { type: 'added' } );
  4565. this.children.push( object );
  4566. // add to scene
  4567. var scene = this;
  4568. while ( scene.parent !== undefined ) {
  4569. scene = scene.parent;
  4570. }
  4571. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4572. scene.__addObject( object );
  4573. }
  4574. }
  4575. },
  4576. remove: function ( object ) {
  4577. var index = this.children.indexOf( object );
  4578. if ( index !== - 1 ) {
  4579. object.parent = undefined;
  4580. object.dispatchEvent( { type: 'removed' } );
  4581. this.children.splice( index, 1 );
  4582. // remove from scene
  4583. var scene = this;
  4584. while ( scene.parent !== undefined ) {
  4585. scene = scene.parent;
  4586. }
  4587. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4588. scene.__removeObject( object );
  4589. }
  4590. }
  4591. },
  4592. traverse: function ( callback ) {
  4593. callback( this );
  4594. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4595. this.children[ i ].traverse( callback );
  4596. }
  4597. },
  4598. getObjectById: function ( id, recursive ) {
  4599. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4600. var child = this.children[ i ];
  4601. if ( child.id === id ) {
  4602. return child;
  4603. }
  4604. if ( recursive === true ) {
  4605. child = child.getObjectById( id, recursive );
  4606. if ( child !== undefined ) {
  4607. return child;
  4608. }
  4609. }
  4610. }
  4611. return undefined;
  4612. },
  4613. getObjectByName: function ( name, recursive ) {
  4614. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4615. var child = this.children[ i ];
  4616. if ( child.name === name ) {
  4617. return child;
  4618. }
  4619. if ( recursive === true ) {
  4620. child = child.getObjectByName( name, recursive );
  4621. if ( child !== undefined ) {
  4622. return child;
  4623. }
  4624. }
  4625. }
  4626. return undefined;
  4627. },
  4628. getChildByName: function ( name, recursive ) {
  4629. console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
  4630. return this.getObjectByName( name, recursive );
  4631. },
  4632. getDescendants: function ( array ) {
  4633. if ( array === undefined ) array = [];
  4634. Array.prototype.push.apply( array, this.children );
  4635. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4636. this.children[ i ].getDescendants( array );
  4637. }
  4638. return array;
  4639. },
  4640. updateMatrix: function () {
  4641. this.matrix.compose( this.position, this.quaternion, this.scale );
  4642. this.matrixWorldNeedsUpdate = true;
  4643. },
  4644. updateMatrixWorld: function ( force ) {
  4645. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4646. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4647. if ( this.parent === undefined ) {
  4648. this.matrixWorld.copy( this.matrix );
  4649. } else {
  4650. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4651. }
  4652. this.matrixWorldNeedsUpdate = false;
  4653. force = true;
  4654. }
  4655. // update children
  4656. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4657. this.children[ i ].updateMatrixWorld( force );
  4658. }
  4659. },
  4660. clone: function ( object, recursive ) {
  4661. if ( object === undefined ) object = new THREE.Object3D();
  4662. if ( recursive === undefined ) recursive = true;
  4663. object.name = this.name;
  4664. object.up.copy( this.up );
  4665. object.position.copy( this.position );
  4666. object.quaternion.copy( this.quaternion );
  4667. object.scale.copy( this.scale );
  4668. object.renderDepth = this.renderDepth;
  4669. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4670. object.matrix.copy( this.matrix );
  4671. object.matrixWorld.copy( this.matrixWorld );
  4672. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4673. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4674. object.visible = this.visible;
  4675. object.castShadow = this.castShadow;
  4676. object.receiveShadow = this.receiveShadow;
  4677. object.frustumCulled = this.frustumCulled;
  4678. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4679. if ( recursive === true ) {
  4680. for ( var i = 0; i < this.children.length; i ++ ) {
  4681. var child = this.children[ i ];
  4682. object.add( child.clone() );
  4683. }
  4684. }
  4685. return object;
  4686. }
  4687. };
  4688. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  4689. THREE.Object3DIdCount = 0;
  4690. /**
  4691. * @author mrdoob / http://mrdoob.com/
  4692. * @author supereggbert / http://www.paulbrunt.co.uk/
  4693. * @author julianwa / https://github.com/julianwa
  4694. */
  4695. THREE.Projector = function () {
  4696. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  4697. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  4698. _face, _faceCount, _facePool = [], _facePoolLength = 0,
  4699. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  4700. _sprite, _spriteCount, _spritePool = [], _spritePoolLength = 0,
  4701. _renderData = { objects: [], lights: [], elements: [] },
  4702. _vA = new THREE.Vector3(),
  4703. _vB = new THREE.Vector3(),
  4704. _vC = new THREE.Vector3(),
  4705. _vector3 = new THREE.Vector3(),
  4706. _vector4 = new THREE.Vector4(),
  4707. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  4708. _boundingBox = new THREE.Box3(),
  4709. _points3 = new Array( 3 ),
  4710. _points4 = new Array( 4 ),
  4711. _viewMatrix = new THREE.Matrix4(),
  4712. _viewProjectionMatrix = new THREE.Matrix4(),
  4713. _modelMatrix,
  4714. _modelViewProjectionMatrix = new THREE.Matrix4(),
  4715. _normalMatrix = new THREE.Matrix3(),
  4716. _frustum = new THREE.Frustum(),
  4717. _clippedVertex1PositionScreen = new THREE.Vector4(),
  4718. _clippedVertex2PositionScreen = new THREE.Vector4();
  4719. this.projectVector = function ( vector, camera ) {
  4720. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4721. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  4722. return vector.applyProjection( _viewProjectionMatrix );
  4723. };
  4724. this.unprojectVector = function () {
  4725. var projectionMatrixInverse = new THREE.Matrix4();
  4726. return function ( vector, camera ) {
  4727. projectionMatrixInverse.getInverse( camera.projectionMatrix );
  4728. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, projectionMatrixInverse );
  4729. return vector.applyProjection( _viewProjectionMatrix );
  4730. };
  4731. }();
  4732. this.pickingRay = function ( vector, camera ) {
  4733. // set two vectors with opposing z values
  4734. vector.z = -1.0;
  4735. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4736. this.unprojectVector( vector, camera );
  4737. this.unprojectVector( end, camera );
  4738. // find direction from vector to end
  4739. end.sub( vector ).normalize();
  4740. return new THREE.Raycaster( vector, end );
  4741. };
  4742. var projectObject = function ( object ) {
  4743. if ( object.visible === false ) return;
  4744. if ( object instanceof THREE.Light ) {
  4745. _renderData.lights.push( object );
  4746. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Sprite ) {
  4747. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4748. _object = getNextObjectInPool();
  4749. _object.id = object.id;
  4750. _object.object = object;
  4751. if ( object.renderDepth !== null ) {
  4752. _object.z = object.renderDepth;
  4753. } else {
  4754. _vector3.setFromMatrixPosition( object.matrixWorld );
  4755. _vector3.applyProjection( _viewProjectionMatrix );
  4756. _object.z = _vector3.z;
  4757. }
  4758. _renderData.objects.push( _object );
  4759. }
  4760. }
  4761. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  4762. projectObject( object.children[ i ] );
  4763. }
  4764. };
  4765. var projectGraph = function ( root, sortObjects ) {
  4766. _objectCount = 0;
  4767. _renderData.objects.length = 0;
  4768. _renderData.lights.length = 0;
  4769. projectObject( root );
  4770. if ( sortObjects === true ) {
  4771. _renderData.objects.sort( painterSort );
  4772. }
  4773. };
  4774. var RenderList = function () {
  4775. var normals = [];
  4776. var object = null;
  4777. var normalMatrix = new THREE.Matrix3();
  4778. var setObject = function ( value ) {
  4779. object = value;
  4780. normalMatrix.getNormalMatrix( object.matrixWorld );
  4781. normals.length = 0;
  4782. };
  4783. var projectVertex = function ( vertex ) {
  4784. var position = vertex.position;
  4785. var positionWorld = vertex.positionWorld;
  4786. var positionScreen = vertex.positionScreen;
  4787. positionWorld.copy( position ).applyMatrix4( _modelMatrix );
  4788. positionScreen.copy( positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4789. var invW = 1 / positionScreen.w;
  4790. positionScreen.x *= invW;
  4791. positionScreen.y *= invW;
  4792. positionScreen.z *= invW;
  4793. vertex.visible = positionScreen.x >= -1 && positionScreen.x <= 1 &&
  4794. positionScreen.y >= -1 && positionScreen.y <= 1 &&
  4795. positionScreen.z >= -1 && positionScreen.z <= 1;
  4796. };
  4797. var pushVertex = function ( x, y, z ) {
  4798. _vertex = getNextVertexInPool();
  4799. _vertex.position.set( x, y, z );
  4800. projectVertex( _vertex );
  4801. };
  4802. var pushNormal = function ( x, y, z ) {
  4803. normals.push( x, y, z );
  4804. };
  4805. var checkTriangleVisibility = function ( v1, v2, v3 ) {
  4806. _points3[ 0 ] = v1.positionScreen;
  4807. _points3[ 1 ] = v2.positionScreen;
  4808. _points3[ 2 ] = v3.positionScreen;
  4809. if ( v1.visible === true || v2.visible === true || v3.visible === true ||
  4810. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
  4811. return ( ( v3.positionScreen.x - v1.positionScreen.x ) *
  4812. ( v2.positionScreen.y - v1.positionScreen.y ) -
  4813. ( v3.positionScreen.y - v1.positionScreen.y ) *
  4814. ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4815. }
  4816. return false;
  4817. };
  4818. var pushLine = function ( a, b ) {
  4819. var v1 = _vertexPool[ a ];
  4820. var v2 = _vertexPool[ b ];
  4821. _line = getNextLineInPool();
  4822. _line.id = object.id;
  4823. _line.v1.copy( v1 );
  4824. _line.v2.copy( v2 );
  4825. _line.z = ( v1.positionScreen.z + v2.positionScreen.z ) / 2;
  4826. _line.material = object.material;
  4827. _renderData.elements.push( _line );
  4828. };
  4829. var pushTriangle = function ( a, b, c ) {
  4830. var v1 = _vertexPool[ a ];
  4831. var v2 = _vertexPool[ b ];
  4832. var v3 = _vertexPool[ c ];
  4833. if ( checkTriangleVisibility( v1, v2, v3 ) === true ) {
  4834. _face = getNextFaceInPool();
  4835. _face.id = object.id;
  4836. _face.v1.copy( v1 );
  4837. _face.v2.copy( v2 );
  4838. _face.v3.copy( v3 );
  4839. _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
  4840. for ( var i = 0; i < 3; i ++ ) {
  4841. var offset = arguments[ i ] * 3;
  4842. var normal = _face.vertexNormalsModel[ i ];
  4843. normal.set( normals[ offset + 0 ], normals[ offset + 1 ], normals[ offset + 2 ] );
  4844. normal.applyMatrix3( normalMatrix ).normalize();
  4845. }
  4846. _face.vertexNormalsLength = 3;
  4847. _face.material = object.material;
  4848. _renderData.elements.push( _face );
  4849. }
  4850. };
  4851. return {
  4852. setObject: setObject,
  4853. projectVertex: projectVertex,
  4854. checkTriangleVisibility: checkTriangleVisibility,
  4855. pushVertex: pushVertex,
  4856. pushNormal: pushNormal,
  4857. pushLine: pushLine,
  4858. pushTriangle: pushTriangle
  4859. }
  4860. };
  4861. var renderList = new RenderList();
  4862. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4863. var object, geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, uvs,
  4864. isFaceMaterial, objectMaterials;
  4865. _faceCount = 0;
  4866. _lineCount = 0;
  4867. _spriteCount = 0;
  4868. _renderData.elements.length = 0;
  4869. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4870. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4871. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4872. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4873. _frustum.setFromMatrix( _viewProjectionMatrix );
  4874. projectGraph( scene, sortObjects );
  4875. for ( var o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4876. object = _renderData.objects[ o ].object;
  4877. geometry = object.geometry;
  4878. renderList.setObject( object );
  4879. _modelMatrix = object.matrixWorld;
  4880. _vertexCount = 0;
  4881. if ( object instanceof THREE.Mesh ) {
  4882. if ( geometry instanceof THREE.BufferGeometry ) {
  4883. var attributes = geometry.attributes;
  4884. var offsets = geometry.offsets;
  4885. if ( attributes.position === undefined ) continue;
  4886. var positions = attributes.position.array;
  4887. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  4888. renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  4889. }
  4890. var normals = attributes.normal.array;
  4891. for ( var i = 0, l = normals.length; i < l; i += 3 ) {
  4892. renderList.pushNormal( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] );
  4893. }
  4894. if ( attributes.index !== undefined ) {
  4895. var indices = attributes.index.array;
  4896. if ( offsets.length > 0 ) {
  4897. for ( var o = 0; o < offsets.length; o ++ ) {
  4898. var offset = offsets[ o ];
  4899. var index = offset.index;
  4900. for ( var i = offset.start, l = offset.start + offset.count; i < l; i += 3 ) {
  4901. renderList.pushTriangle( indices[ i ] + index, indices[ i + 1 ] + index, indices[ i + 2 ] + index );
  4902. }
  4903. }
  4904. } else {
  4905. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  4906. renderList.pushTriangle( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  4907. }
  4908. }
  4909. } else {
  4910. for ( var i = 0, l = positions.length / 3; i < l; i += 3 ) {
  4911. renderList.pushTriangle( i, i + 1, i + 2 );
  4912. }
  4913. }
  4914. } else if ( geometry instanceof THREE.Geometry2 ) {
  4915. vertices = geometry.vertices;
  4916. for ( var i = 0, j = 0, l = vertices.length; i < l; i += 9, j += 3 ) {
  4917. renderList.pushVertex( vertices[ i + 0 ], vertices[ i + 1 ], vertices[ i + 2 ] );
  4918. renderList.pushVertex( vertices[ i + 3 ], vertices[ i + 4 ], vertices[ i + 5 ] );
  4919. renderList.pushVertex( vertices[ i + 6 ], vertices[ i + 7 ], vertices[ i + 8 ] );
  4920. renderList.pushTriangle( j + 0, j + 1, j + 2 );
  4921. }
  4922. } else if ( geometry instanceof THREE.Geometry ) {
  4923. vertices = geometry.vertices;
  4924. faces = geometry.faces;
  4925. faceVertexUvs = geometry.faceVertexUvs;
  4926. _normalMatrix.getNormalMatrix( _modelMatrix );
  4927. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4928. objectMaterials = isFaceMaterial === true ? object.material : null;
  4929. for ( var v = 0, vl = vertices.length; v < vl; v ++ ) {
  4930. var vertex = vertices[ v ];
  4931. renderList.pushVertex( vertex.x, vertex.y, vertex.z );
  4932. }
  4933. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  4934. face = faces[ f ];
  4935. var material = isFaceMaterial === true
  4936. ? objectMaterials.materials[ face.materialIndex ]
  4937. : object.material;
  4938. if ( material === undefined ) continue;
  4939. var side = material.side;
  4940. var v1 = _vertexPool[ face.a ];
  4941. var v2 = _vertexPool[ face.b ];
  4942. var v3 = _vertexPool[ face.c ];
  4943. if ( material.morphTargets === true ) {
  4944. var morphTargets = geometry.morphTargets;
  4945. var morphInfluences = object.morphTargetInfluences;
  4946. var v1p = v1.position;
  4947. var v2p = v2.position;
  4948. var v3p = v3.position;
  4949. _vA.set( 0, 0, 0 );
  4950. _vB.set( 0, 0, 0 );
  4951. _vC.set( 0, 0, 0 );
  4952. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  4953. var influence = morphInfluences[ t ];
  4954. if ( influence === 0 ) continue;
  4955. var targets = morphTargets[ t ].vertices;
  4956. _vA.x += ( targets[ face.a ].x - v1p.x ) * influence;
  4957. _vA.y += ( targets[ face.a ].y - v1p.y ) * influence;
  4958. _vA.z += ( targets[ face.a ].z - v1p.z ) * influence;
  4959. _vB.x += ( targets[ face.b ].x - v2p.x ) * influence;
  4960. _vB.y += ( targets[ face.b ].y - v2p.y ) * influence;
  4961. _vB.z += ( targets[ face.b ].z - v2p.z ) * influence;
  4962. _vC.x += ( targets[ face.c ].x - v3p.x ) * influence;
  4963. _vC.y += ( targets[ face.c ].y - v3p.y ) * influence;
  4964. _vC.z += ( targets[ face.c ].z - v3p.z ) * influence;
  4965. }
  4966. v1.position.add( _vA );
  4967. v2.position.add( _vB );
  4968. v3.position.add( _vC );
  4969. renderList.projectVertex( v1 );
  4970. renderList.projectVertex( v2 );
  4971. renderList.projectVertex( v3 );
  4972. }
  4973. var visible = renderList.checkTriangleVisibility( v1, v2, v3 );
  4974. if ( ( visible === false && side === THREE.FrontSide ) ||
  4975. ( visible === true && side === THREE.BackSide ) ) continue;
  4976. _face = getNextFaceInPool();
  4977. _face.id = object.id;
  4978. _face.v1.copy( v1 );
  4979. _face.v2.copy( v2 );
  4980. _face.v3.copy( v3 );
  4981. _face.normalModel.copy( face.normal );
  4982. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4983. _face.normalModel.negate();
  4984. }
  4985. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4986. _face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix );
  4987. faceVertexNormals = face.vertexNormals;
  4988. for ( var n = 0, nl = Math.min( faceVertexNormals.length, 3 ); n < nl; n ++ ) {
  4989. var normalModel = _face.vertexNormalsModel[ n ];
  4990. normalModel.copy( faceVertexNormals[ n ] );
  4991. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4992. normalModel.negate();
  4993. }
  4994. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4995. }
  4996. _face.vertexNormalsLength = faceVertexNormals.length;
  4997. for ( var c = 0, cl = Math.min( faceVertexUvs.length, 3 ); c < cl; c ++ ) {
  4998. uvs = faceVertexUvs[ c ][ f ];
  4999. if ( uvs === undefined ) continue;
  5000. for ( var u = 0, ul = uvs.length; u < ul; u ++ ) {
  5001. _face.uvs[ c ][ u ] = uvs[ u ];
  5002. }
  5003. }
  5004. _face.color = face.color;
  5005. _face.material = material;
  5006. _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
  5007. _renderData.elements.push( _face );
  5008. }
  5009. }
  5010. } else if ( object instanceof THREE.Line ) {
  5011. if ( geometry instanceof THREE.BufferGeometry ) {
  5012. var attributes = geometry.attributes;
  5013. if ( attributes.position !== undefined ) {
  5014. var positions = attributes.position.array;
  5015. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  5016. renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5017. }
  5018. if ( attributes.index !== undefined ) {
  5019. var indices = attributes.index.array;
  5020. for ( var i = 0, l = indices.length; i < l; i += 2 ) {
  5021. renderList.pushLine( indices[ i ], indices[ i + 1 ] );
  5022. }
  5023. } else {
  5024. for ( var i = 0, l = ( positions.length / 3 ) - 1; i < l; i ++ ) {
  5025. renderList.pushLine( i, i + 1 );
  5026. }
  5027. }
  5028. }
  5029. } else if ( geometry instanceof THREE.Geometry ) {
  5030. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  5031. vertices = object.geometry.vertices;
  5032. if ( vertices.length === 0 ) continue;
  5033. v1 = getNextVertexInPool();
  5034. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  5035. // Handle LineStrip and LinePieces
  5036. var step = object.type === THREE.LinePieces ? 2 : 1;
  5037. for ( var v = 1, vl = vertices.length; v < vl; v ++ ) {
  5038. v1 = getNextVertexInPool();
  5039. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  5040. if ( ( v + 1 ) % step > 0 ) continue;
  5041. v2 = _vertexPool[ _vertexCount - 2 ];
  5042. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  5043. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  5044. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  5045. // Perform the perspective divide
  5046. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  5047. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  5048. _line = getNextLineInPool();
  5049. _line.id = object.id;
  5050. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  5051. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  5052. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  5053. _line.material = object.material;
  5054. if ( object.material.vertexColors === THREE.VertexColors ) {
  5055. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  5056. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  5057. }
  5058. _renderData.elements.push( _line );
  5059. }
  5060. }
  5061. }
  5062. } else if ( object instanceof THREE.Sprite ) {
  5063. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  5064. _vector4.applyMatrix4( _viewProjectionMatrix );
  5065. var invW = 1 / _vector4.w;
  5066. _vector4.z *= invW;
  5067. if ( _vector4.z >= -1 && _vector4.z <= 1 ) {
  5068. _sprite = getNextSpriteInPool();
  5069. _sprite.id = object.id;
  5070. _sprite.x = _vector4.x * invW;
  5071. _sprite.y = _vector4.y * invW;
  5072. _sprite.z = _vector4.z;
  5073. _sprite.object = object;
  5074. _sprite.rotation = object.rotation;
  5075. _sprite.scale.x = object.scale.x * Math.abs( _sprite.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  5076. _sprite.scale.y = object.scale.y * Math.abs( _sprite.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  5077. _sprite.material = object.material;
  5078. _renderData.elements.push( _sprite );
  5079. }
  5080. }
  5081. }
  5082. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  5083. return _renderData;
  5084. };
  5085. // Pools
  5086. function getNextObjectInPool() {
  5087. if ( _objectCount === _objectPoolLength ) {
  5088. var object = new THREE.RenderableObject();
  5089. _objectPool.push( object );
  5090. _objectPoolLength ++;
  5091. _objectCount ++;
  5092. return object;
  5093. }
  5094. return _objectPool[ _objectCount ++ ];
  5095. }
  5096. function getNextVertexInPool() {
  5097. if ( _vertexCount === _vertexPoolLength ) {
  5098. var vertex = new THREE.RenderableVertex();
  5099. _vertexPool.push( vertex );
  5100. _vertexPoolLength ++;
  5101. _vertexCount ++;
  5102. return vertex;
  5103. }
  5104. return _vertexPool[ _vertexCount ++ ];
  5105. }
  5106. function getNextFaceInPool() {
  5107. if ( _faceCount === _facePoolLength ) {
  5108. var face = new THREE.RenderableFace();
  5109. _facePool.push( face );
  5110. _facePoolLength ++;
  5111. _faceCount ++;
  5112. return face;
  5113. }
  5114. return _facePool[ _faceCount ++ ];
  5115. }
  5116. function getNextLineInPool() {
  5117. if ( _lineCount === _linePoolLength ) {
  5118. var line = new THREE.RenderableLine();
  5119. _linePool.push( line );
  5120. _linePoolLength ++;
  5121. _lineCount ++
  5122. return line;
  5123. }
  5124. return _linePool[ _lineCount ++ ];
  5125. }
  5126. function getNextSpriteInPool() {
  5127. if ( _spriteCount === _spritePoolLength ) {
  5128. var sprite = new THREE.RenderableSprite();
  5129. _spritePool.push( sprite );
  5130. _spritePoolLength ++;
  5131. _spriteCount ++
  5132. return sprite;
  5133. }
  5134. return _spritePool[ _spriteCount ++ ];
  5135. }
  5136. //
  5137. function painterSort( a, b ) {
  5138. if ( a.z !== b.z ) {
  5139. return b.z - a.z;
  5140. } else if ( a.id !== b.id ) {
  5141. return a.id - b.id;
  5142. } else {
  5143. return 0;
  5144. }
  5145. }
  5146. function clipLine( s1, s2 ) {
  5147. var alpha1 = 0, alpha2 = 1,
  5148. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  5149. // Z = -1 and Z = +1, respectively.
  5150. bc1near = s1.z + s1.w,
  5151. bc2near = s2.z + s2.w,
  5152. bc1far = - s1.z + s1.w,
  5153. bc2far = - s2.z + s2.w;
  5154. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  5155. // Both vertices lie entirely within all clip planes.
  5156. return true;
  5157. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  5158. // Both vertices lie entirely outside one of the clip planes.
  5159. return false;
  5160. } else {
  5161. // The line segment spans at least one clip plane.
  5162. if ( bc1near < 0 ) {
  5163. // v1 lies outside the near plane, v2 inside
  5164. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  5165. } else if ( bc2near < 0 ) {
  5166. // v2 lies outside the near plane, v1 inside
  5167. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  5168. }
  5169. if ( bc1far < 0 ) {
  5170. // v1 lies outside the far plane, v2 inside
  5171. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  5172. } else if ( bc2far < 0 ) {
  5173. // v2 lies outside the far plane, v2 inside
  5174. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  5175. }
  5176. if ( alpha2 < alpha1 ) {
  5177. // The line segment spans two boundaries, but is outside both of them.
  5178. // (This can't happen when we're only clipping against just near/far but good
  5179. // to leave the check here for future usage if other clip planes are added.)
  5180. return false;
  5181. } else {
  5182. // Update the s1 and s2 vertices to match the clipped line segment.
  5183. s1.lerp( s2, alpha1 );
  5184. s2.lerp( s1, 1 - alpha2 );
  5185. return true;
  5186. }
  5187. }
  5188. }
  5189. };
  5190. /**
  5191. * @author mrdoob / http://mrdoob.com/
  5192. * @author alteredq / http://alteredqualia.com/
  5193. */
  5194. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  5195. this.a = a;
  5196. this.b = b;
  5197. this.c = c;
  5198. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  5199. this.vertexNormals = normal instanceof Array ? normal : [ ];
  5200. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  5201. this.vertexColors = color instanceof Array ? color : [];
  5202. this.vertexTangents = [];
  5203. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  5204. this.centroid = new THREE.Vector3();
  5205. };
  5206. THREE.Face3.prototype = {
  5207. constructor: THREE.Face3,
  5208. clone: function () {
  5209. var face = new THREE.Face3( this.a, this.b, this.c );
  5210. face.normal.copy( this.normal );
  5211. face.color.copy( this.color );
  5212. face.centroid.copy( this.centroid );
  5213. face.materialIndex = this.materialIndex;
  5214. var i, il;
  5215. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  5216. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  5217. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  5218. return face;
  5219. }
  5220. };
  5221. /**
  5222. * @author mrdoob / http://mrdoob.com/
  5223. */
  5224. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  5225. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.')
  5226. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  5227. };
  5228. /**
  5229. * @author mrdoob / http://mrdoob.com/
  5230. * @author kile / http://kile.stravaganza.org/
  5231. * @author alteredq / http://alteredqualia.com/
  5232. * @author mikael emtinger / http://gomo.se/
  5233. * @author zz85 / http://www.lab4games.net/zz85/blog
  5234. * @author bhouston / http://exocortex.com
  5235. */
  5236. THREE.Geometry = function () {
  5237. this.id = THREE.GeometryIdCount ++;
  5238. this.uuid = THREE.Math.generateUUID();
  5239. this.name = '';
  5240. this.vertices = [];
  5241. this.colors = []; // one-to-one vertex colors, used in ParticleSystem and Line
  5242. this.faces = [];
  5243. this.faceVertexUvs = [[]];
  5244. this.morphTargets = [];
  5245. this.morphColors = [];
  5246. this.morphNormals = [];
  5247. this.skinWeights = [];
  5248. this.skinIndices = [];
  5249. this.lineDistances = [];
  5250. this.boundingBox = null;
  5251. this.boundingSphere = null;
  5252. this.hasTangents = false;
  5253. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  5254. // update flags
  5255. this.verticesNeedUpdate = false;
  5256. this.elementsNeedUpdate = false;
  5257. this.uvsNeedUpdate = false;
  5258. this.normalsNeedUpdate = false;
  5259. this.tangentsNeedUpdate = false;
  5260. this.colorsNeedUpdate = false;
  5261. this.lineDistancesNeedUpdate = false;
  5262. this.buffersNeedUpdate = false;
  5263. };
  5264. THREE.Geometry.prototype = {
  5265. constructor: THREE.Geometry,
  5266. applyMatrix: function ( matrix ) {
  5267. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5268. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  5269. var vertex = this.vertices[ i ];
  5270. vertex.applyMatrix4( matrix );
  5271. }
  5272. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  5273. var face = this.faces[ i ];
  5274. face.normal.applyMatrix3( normalMatrix ).normalize();
  5275. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  5276. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  5277. }
  5278. face.centroid.applyMatrix4( matrix );
  5279. }
  5280. if ( this.boundingBox instanceof THREE.Box3 ) {
  5281. this.computeBoundingBox();
  5282. }
  5283. if ( this.boundingSphere instanceof THREE.Sphere ) {
  5284. this.computeBoundingSphere();
  5285. }
  5286. },
  5287. computeCentroids: function () {
  5288. var f, fl, face;
  5289. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5290. face = this.faces[ f ];
  5291. face.centroid.set( 0, 0, 0 );
  5292. face.centroid.add( this.vertices[ face.a ] );
  5293. face.centroid.add( this.vertices[ face.b ] );
  5294. face.centroid.add( this.vertices[ face.c ] );
  5295. face.centroid.divideScalar( 3 );
  5296. }
  5297. },
  5298. computeFaceNormals: function () {
  5299. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5300. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5301. var face = this.faces[ f ];
  5302. var vA = this.vertices[ face.a ];
  5303. var vB = this.vertices[ face.b ];
  5304. var vC = this.vertices[ face.c ];
  5305. cb.subVectors( vC, vB );
  5306. ab.subVectors( vA, vB );
  5307. cb.cross( ab );
  5308. cb.normalize();
  5309. face.normal.copy( cb );
  5310. }
  5311. },
  5312. computeVertexNormals: function ( areaWeighted ) {
  5313. var v, vl, f, fl, face, vertices;
  5314. vertices = new Array( this.vertices.length );
  5315. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5316. vertices[ v ] = new THREE.Vector3();
  5317. }
  5318. if ( areaWeighted ) {
  5319. // vertex normals weighted by triangle areas
  5320. // http://www.iquilezles.org/www/articles/normals/normals.htm
  5321. var vA, vB, vC, vD;
  5322. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  5323. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  5324. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5325. face = this.faces[ f ];
  5326. vA = this.vertices[ face.a ];
  5327. vB = this.vertices[ face.b ];
  5328. vC = this.vertices[ face.c ];
  5329. cb.subVectors( vC, vB );
  5330. ab.subVectors( vA, vB );
  5331. cb.cross( ab );
  5332. vertices[ face.a ].add( cb );
  5333. vertices[ face.b ].add( cb );
  5334. vertices[ face.c ].add( cb );
  5335. }
  5336. } else {
  5337. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5338. face = this.faces[ f ];
  5339. vertices[ face.a ].add( face.normal );
  5340. vertices[ face.b ].add( face.normal );
  5341. vertices[ face.c ].add( face.normal );
  5342. }
  5343. }
  5344. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5345. vertices[ v ].normalize();
  5346. }
  5347. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5348. face = this.faces[ f ];
  5349. face.vertexNormals[ 0 ] = vertices[ face.a ].clone();
  5350. face.vertexNormals[ 1 ] = vertices[ face.b ].clone();
  5351. face.vertexNormals[ 2 ] = vertices[ face.c ].clone();
  5352. }
  5353. },
  5354. computeMorphNormals: function () {
  5355. var i, il, f, fl, face;
  5356. // save original normals
  5357. // - create temp variables on first access
  5358. // otherwise just copy (for faster repeated calls)
  5359. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5360. face = this.faces[ f ];
  5361. if ( ! face.__originalFaceNormal ) {
  5362. face.__originalFaceNormal = face.normal.clone();
  5363. } else {
  5364. face.__originalFaceNormal.copy( face.normal );
  5365. }
  5366. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  5367. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  5368. if ( ! face.__originalVertexNormals[ i ] ) {
  5369. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  5370. } else {
  5371. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  5372. }
  5373. }
  5374. }
  5375. // use temp geometry to compute face and vertex normals for each morph
  5376. var tmpGeo = new THREE.Geometry();
  5377. tmpGeo.faces = this.faces;
  5378. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  5379. // create on first access
  5380. if ( ! this.morphNormals[ i ] ) {
  5381. this.morphNormals[ i ] = {};
  5382. this.morphNormals[ i ].faceNormals = [];
  5383. this.morphNormals[ i ].vertexNormals = [];
  5384. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  5385. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  5386. var faceNormal, vertexNormals;
  5387. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5388. face = this.faces[ f ];
  5389. faceNormal = new THREE.Vector3();
  5390. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  5391. dstNormalsFace.push( faceNormal );
  5392. dstNormalsVertex.push( vertexNormals );
  5393. }
  5394. }
  5395. var morphNormals = this.morphNormals[ i ];
  5396. // set vertices to morph target
  5397. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  5398. // compute morph normals
  5399. tmpGeo.computeFaceNormals();
  5400. tmpGeo.computeVertexNormals();
  5401. // store morph normals
  5402. var faceNormal, vertexNormals;
  5403. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5404. face = this.faces[ f ];
  5405. faceNormal = morphNormals.faceNormals[ f ];
  5406. vertexNormals = morphNormals.vertexNormals[ f ];
  5407. faceNormal.copy( face.normal );
  5408. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  5409. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  5410. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  5411. }
  5412. }
  5413. // restore original normals
  5414. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5415. face = this.faces[ f ];
  5416. face.normal = face.__originalFaceNormal;
  5417. face.vertexNormals = face.__originalVertexNormals;
  5418. }
  5419. },
  5420. computeTangents: function () {
  5421. // based on http://www.terathon.com/code/tangent.html
  5422. // tangents go to vertices
  5423. var f, fl, v, vl, i, il, vertexIndex,
  5424. face, uv, vA, vB, vC, uvA, uvB, uvC,
  5425. x1, x2, y1, y2, z1, z2,
  5426. s1, s2, t1, t2, r, t, test,
  5427. tan1 = [], tan2 = [],
  5428. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  5429. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  5430. n = new THREE.Vector3(), w;
  5431. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5432. tan1[ v ] = new THREE.Vector3();
  5433. tan2[ v ] = new THREE.Vector3();
  5434. }
  5435. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  5436. vA = context.vertices[ a ];
  5437. vB = context.vertices[ b ];
  5438. vC = context.vertices[ c ];
  5439. uvA = uv[ ua ];
  5440. uvB = uv[ ub ];
  5441. uvC = uv[ uc ];
  5442. x1 = vB.x - vA.x;
  5443. x2 = vC.x - vA.x;
  5444. y1 = vB.y - vA.y;
  5445. y2 = vC.y - vA.y;
  5446. z1 = vB.z - vA.z;
  5447. z2 = vC.z - vA.z;
  5448. s1 = uvB.x - uvA.x;
  5449. s2 = uvC.x - uvA.x;
  5450. t1 = uvB.y - uvA.y;
  5451. t2 = uvC.y - uvA.y;
  5452. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5453. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  5454. ( t2 * y1 - t1 * y2 ) * r,
  5455. ( t2 * z1 - t1 * z2 ) * r );
  5456. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  5457. ( s1 * y2 - s2 * y1 ) * r,
  5458. ( s1 * z2 - s2 * z1 ) * r );
  5459. tan1[ a ].add( sdir );
  5460. tan1[ b ].add( sdir );
  5461. tan1[ c ].add( sdir );
  5462. tan2[ a ].add( tdir );
  5463. tan2[ b ].add( tdir );
  5464. tan2[ c ].add( tdir );
  5465. }
  5466. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5467. face = this.faces[ f ];
  5468. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  5469. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  5470. }
  5471. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  5472. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5473. face = this.faces[ f ];
  5474. for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i++ ) {
  5475. n.copy( face.vertexNormals[ i ] );
  5476. vertexIndex = face[ faceIndex[ i ] ];
  5477. t = tan1[ vertexIndex ];
  5478. // Gram-Schmidt orthogonalize
  5479. tmp.copy( t );
  5480. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5481. // Calculate handedness
  5482. tmp2.crossVectors( face.vertexNormals[ i ], t );
  5483. test = tmp2.dot( tan2[ vertexIndex ] );
  5484. w = (test < 0.0) ? -1.0 : 1.0;
  5485. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  5486. }
  5487. }
  5488. this.hasTangents = true;
  5489. },
  5490. computeLineDistances: function ( ) {
  5491. var d = 0;
  5492. var vertices = this.vertices;
  5493. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5494. if ( i > 0 ) {
  5495. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  5496. }
  5497. this.lineDistances[ i ] = d;
  5498. }
  5499. },
  5500. computeBoundingBox: function () {
  5501. if ( this.boundingBox === null ) {
  5502. this.boundingBox = new THREE.Box3();
  5503. }
  5504. this.boundingBox.setFromPoints( this.vertices );
  5505. },
  5506. computeBoundingSphere: function () {
  5507. if ( this.boundingSphere === null ) {
  5508. this.boundingSphere = new THREE.Sphere();
  5509. }
  5510. this.boundingSphere.setFromPoints( this.vertices );
  5511. },
  5512. /*
  5513. * Checks for duplicate vertices with hashmap.
  5514. * Duplicated vertices are removed
  5515. * and faces' vertices are updated.
  5516. */
  5517. mergeVertices: function () {
  5518. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  5519. var unique = [], changes = [];
  5520. var v, key;
  5521. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  5522. var precision = Math.pow( 10, precisionPoints );
  5523. var i,il, face;
  5524. var indices, k, j, jl, u;
  5525. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  5526. v = this.vertices[ i ];
  5527. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  5528. if ( verticesMap[ key ] === undefined ) {
  5529. verticesMap[ key ] = i;
  5530. unique.push( this.vertices[ i ] );
  5531. changes[ i ] = unique.length - 1;
  5532. } else {
  5533. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  5534. changes[ i ] = changes[ verticesMap[ key ] ];
  5535. }
  5536. };
  5537. // if faces are completely degenerate after merging vertices, we
  5538. // have to remove them from the geometry.
  5539. var faceIndicesToRemove = [];
  5540. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  5541. face = this.faces[ i ];
  5542. face.a = changes[ face.a ];
  5543. face.b = changes[ face.b ];
  5544. face.c = changes[ face.c ];
  5545. indices = [ face.a, face.b, face.c ];
  5546. var dupIndex = -1;
  5547. // if any duplicate vertices are found in a Face3
  5548. // we have to remove the face as nothing can be saved
  5549. for ( var n = 0; n < 3; n ++ ) {
  5550. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  5551. dupIndex = n;
  5552. faceIndicesToRemove.push( i );
  5553. break;
  5554. }
  5555. }
  5556. }
  5557. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  5558. var idx = faceIndicesToRemove[ i ];
  5559. this.faces.splice( idx, 1 );
  5560. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  5561. this.faceVertexUvs[ j ].splice( idx, 1 );
  5562. }
  5563. }
  5564. // Use unique set of vertices
  5565. var diff = this.vertices.length - unique.length;
  5566. this.vertices = unique;
  5567. return diff;
  5568. },
  5569. // Geometry splitting
  5570. makeGroups: ( function () {
  5571. var geometryGroupCounter = 0;
  5572. return function ( usesFaceMaterial ) {
  5573. var f, fl, face, materialIndex,
  5574. groupHash, hash_map = {};
  5575. var numMorphTargets = this.morphTargets.length;
  5576. var numMorphNormals = this.morphNormals.length;
  5577. this.geometryGroups = {};
  5578. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5579. face = this.faces[ f ];
  5580. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  5581. if ( ! ( materialIndex in hash_map ) ) {
  5582. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  5583. }
  5584. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  5585. if ( ! ( groupHash in this.geometryGroups ) ) {
  5586. this.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  5587. }
  5588. if ( this.geometryGroups[ groupHash ].vertices + 3 > 65535 ) {
  5589. hash_map[ materialIndex ].counter += 1;
  5590. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  5591. if ( ! ( groupHash in this.geometryGroups ) ) {
  5592. this.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  5593. }
  5594. }
  5595. this.geometryGroups[ groupHash ].faces3.push( f );
  5596. this.geometryGroups[ groupHash ].vertices += 3;
  5597. }
  5598. this.geometryGroupsList = [];
  5599. for ( var g in this.geometryGroups ) {
  5600. this.geometryGroups[ g ].id = geometryGroupCounter ++;
  5601. this.geometryGroupsList.push( this.geometryGroups[ g ] );
  5602. }
  5603. };
  5604. } )(),
  5605. clone: function () {
  5606. var geometry = new THREE.Geometry();
  5607. var vertices = this.vertices;
  5608. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5609. geometry.vertices.push( vertices[ i ].clone() );
  5610. }
  5611. var faces = this.faces;
  5612. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  5613. geometry.faces.push( faces[ i ].clone() );
  5614. }
  5615. var uvs = this.faceVertexUvs[ 0 ];
  5616. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  5617. var uv = uvs[ i ], uvCopy = [];
  5618. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  5619. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  5620. }
  5621. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  5622. }
  5623. return geometry;
  5624. },
  5625. dispose: function () {
  5626. this.dispatchEvent( { type: 'dispose' } );
  5627. }
  5628. };
  5629. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  5630. THREE.GeometryIdCount = 0;
  5631. /**
  5632. * @author mrdoob / http://mrdoob.com/
  5633. */
  5634. THREE.Geometry2 = function ( size ) {
  5635. this.id = THREE.GeometryIdCount ++;
  5636. this.uuid = THREE.Math.generateUUID();
  5637. this.name = '';
  5638. this.vertices = size !== undefined ? new Float32Array( size * 3 ) : [];
  5639. this.normals = size !== undefined ? new Float32Array( size * 3 ) : [];
  5640. this.uvs = size !== undefined ? new Float32Array( size * 2 ) : [];
  5641. this.boundingBox = null;
  5642. this.boundingSphere = null;
  5643. };
  5644. THREE.Geometry2.prototype = {
  5645. constructor: THREE.Geometry2,
  5646. applyMatrix: function ( matrix ) {
  5647. matrix.multiplyVector3Array( this.vertices );
  5648. },
  5649. computeBoundingBox: function () {
  5650. if ( this.boundingBox === null ) {
  5651. this.boundingBox = new THREE.Box3();
  5652. }
  5653. var vertices = this.vertices;
  5654. var bb = this.boundingBox;
  5655. if ( vertices.length >= 3 ) {
  5656. bb.min.x = bb.max.x = vertices[ 0 ];
  5657. bb.min.y = bb.max.y = vertices[ 1 ];
  5658. bb.min.z = bb.max.z = vertices[ 2 ];
  5659. }
  5660. for ( var i = 3, il = vertices.length; i < il; i += 3 ) {
  5661. var x = vertices[ i ];
  5662. var y = vertices[ i + 1 ];
  5663. var z = vertices[ i + 2 ];
  5664. // bounding box
  5665. if ( x < bb.min.x ) {
  5666. bb.min.x = x;
  5667. } else if ( x > bb.max.x ) {
  5668. bb.max.x = x;
  5669. }
  5670. if ( y < bb.min.y ) {
  5671. bb.min.y = y;
  5672. } else if ( y > bb.max.y ) {
  5673. bb.max.y = y;
  5674. }
  5675. if ( z < bb.min.z ) {
  5676. bb.min.z = z;
  5677. } else if ( z > bb.max.z ) {
  5678. bb.max.z = z;
  5679. }
  5680. }
  5681. },
  5682. computeBoundingSphere: function () {
  5683. var box = new THREE.Box3();
  5684. var vector = new THREE.Vector3();
  5685. return function () {
  5686. if ( this.boundingSphere === null ) {
  5687. this.boundingSphere = new THREE.Sphere();
  5688. }
  5689. box.makeEmpty();
  5690. var vertices = this.vertices;
  5691. var center = this.boundingSphere.center;
  5692. for ( var i = 0, il = vertices.length; i < il; i += 3 ) {
  5693. vector.set( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] );
  5694. box.addPoint( vector );
  5695. }
  5696. box.center( center );
  5697. var maxRadiusSq = 0;
  5698. for ( var i = 0, il = vertices.length; i < il; i += 3 ) {
  5699. vector.set( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] );
  5700. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  5701. }
  5702. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5703. }
  5704. }(),
  5705. dispose: function () {
  5706. this.dispatchEvent( { type: 'dispose' } );
  5707. }
  5708. };
  5709. THREE.EventDispatcher.prototype.apply( THREE.Geometry2.prototype );
  5710. /**
  5711. * @author alteredq / http://alteredqualia.com/
  5712. */
  5713. THREE.BufferGeometry = function () {
  5714. this.id = THREE.GeometryIdCount ++;
  5715. this.uuid = THREE.Math.generateUUID();
  5716. this.name = '';
  5717. // attributes
  5718. this.attributes = {};
  5719. // offsets for chunks when using indexed elements
  5720. this.offsets = [];
  5721. // boundings
  5722. this.boundingBox = null;
  5723. this.boundingSphere = null;
  5724. };
  5725. THREE.BufferGeometry.prototype = {
  5726. constructor: THREE.BufferGeometry,
  5727. addAttribute: function ( name, type, numItems, itemSize ) {
  5728. this.attributes[ name ] = {
  5729. itemSize: itemSize,
  5730. array: new type( numItems * itemSize )
  5731. };
  5732. },
  5733. applyMatrix: function ( matrix ) {
  5734. var position = this.attributes.position;
  5735. if ( position !== undefined ) {
  5736. matrix.multiplyVector3Array( position.array );
  5737. position.needsUpdate = true;
  5738. }
  5739. var normal = this.attributes.normal;
  5740. if ( normal !== undefined ) {
  5741. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5742. normalMatrix.multiplyVector3Array( normal.array );
  5743. normal.needsUpdate = true;
  5744. }
  5745. },
  5746. computeBoundingBox: function () {
  5747. if ( this.boundingBox === null ) {
  5748. this.boundingBox = new THREE.Box3();
  5749. }
  5750. var positions = this.attributes[ "position" ].array;
  5751. if ( positions ) {
  5752. var bb = this.boundingBox;
  5753. if( positions.length >= 3 ) {
  5754. bb.min.x = bb.max.x = positions[ 0 ];
  5755. bb.min.y = bb.max.y = positions[ 1 ];
  5756. bb.min.z = bb.max.z = positions[ 2 ];
  5757. }
  5758. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  5759. var x = positions[ i ];
  5760. var y = positions[ i + 1 ];
  5761. var z = positions[ i + 2 ];
  5762. // bounding box
  5763. if ( x < bb.min.x ) {
  5764. bb.min.x = x;
  5765. } else if ( x > bb.max.x ) {
  5766. bb.max.x = x;
  5767. }
  5768. if ( y < bb.min.y ) {
  5769. bb.min.y = y;
  5770. } else if ( y > bb.max.y ) {
  5771. bb.max.y = y;
  5772. }
  5773. if ( z < bb.min.z ) {
  5774. bb.min.z = z;
  5775. } else if ( z > bb.max.z ) {
  5776. bb.max.z = z;
  5777. }
  5778. }
  5779. }
  5780. if ( positions === undefined || positions.length === 0 ) {
  5781. this.boundingBox.min.set( 0, 0, 0 );
  5782. this.boundingBox.max.set( 0, 0, 0 );
  5783. }
  5784. },
  5785. computeBoundingSphere: function () {
  5786. var box = new THREE.Box3();
  5787. var vector = new THREE.Vector3();
  5788. return function () {
  5789. if ( this.boundingSphere === null ) {
  5790. this.boundingSphere = new THREE.Sphere();
  5791. }
  5792. var positions = this.attributes[ "position" ].array;
  5793. if ( positions ) {
  5794. box.makeEmpty();
  5795. var center = this.boundingSphere.center;
  5796. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5797. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5798. box.addPoint( vector );
  5799. }
  5800. box.center( center );
  5801. var maxRadiusSq = 0;
  5802. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5803. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5804. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  5805. }
  5806. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5807. }
  5808. }
  5809. }(),
  5810. computeVertexNormals: function () {
  5811. if ( this.attributes[ "position" ] ) {
  5812. var i, il;
  5813. var j, jl;
  5814. var nVertexElements = this.attributes[ "position" ].array.length;
  5815. if ( this.attributes[ "normal" ] === undefined ) {
  5816. this.attributes[ "normal" ] = {
  5817. itemSize: 3,
  5818. array: new Float32Array( nVertexElements )
  5819. };
  5820. } else {
  5821. // reset existing normals to zero
  5822. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  5823. this.attributes[ "normal" ].array[ i ] = 0;
  5824. }
  5825. }
  5826. var positions = this.attributes[ "position" ].array;
  5827. var normals = this.attributes[ "normal" ].array;
  5828. var vA, vB, vC, x, y, z,
  5829. pA = new THREE.Vector3(),
  5830. pB = new THREE.Vector3(),
  5831. pC = new THREE.Vector3(),
  5832. cb = new THREE.Vector3(),
  5833. ab = new THREE.Vector3();
  5834. // indexed elements
  5835. if ( this.attributes[ "index" ] ) {
  5836. var indices = this.attributes[ "index" ].array;
  5837. var offsets = this.offsets;
  5838. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5839. var start = offsets[ j ].start;
  5840. var count = offsets[ j ].count;
  5841. var index = offsets[ j ].index;
  5842. for ( i = start, il = start + count; i < il; i += 3 ) {
  5843. vA = index + indices[ i ];
  5844. vB = index + indices[ i + 1 ];
  5845. vC = index + indices[ i + 2 ];
  5846. x = positions[ vA * 3 ];
  5847. y = positions[ vA * 3 + 1 ];
  5848. z = positions[ vA * 3 + 2 ];
  5849. pA.set( x, y, z );
  5850. x = positions[ vB * 3 ];
  5851. y = positions[ vB * 3 + 1 ];
  5852. z = positions[ vB * 3 + 2 ];
  5853. pB.set( x, y, z );
  5854. x = positions[ vC * 3 ];
  5855. y = positions[ vC * 3 + 1 ];
  5856. z = positions[ vC * 3 + 2 ];
  5857. pC.set( x, y, z );
  5858. cb.subVectors( pC, pB );
  5859. ab.subVectors( pA, pB );
  5860. cb.cross( ab );
  5861. normals[ vA * 3 ] += cb.x;
  5862. normals[ vA * 3 + 1 ] += cb.y;
  5863. normals[ vA * 3 + 2 ] += cb.z;
  5864. normals[ vB * 3 ] += cb.x;
  5865. normals[ vB * 3 + 1 ] += cb.y;
  5866. normals[ vB * 3 + 2 ] += cb.z;
  5867. normals[ vC * 3 ] += cb.x;
  5868. normals[ vC * 3 + 1 ] += cb.y;
  5869. normals[ vC * 3 + 2 ] += cb.z;
  5870. }
  5871. }
  5872. // non-indexed elements (unconnected triangle soup)
  5873. } else {
  5874. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5875. x = positions[ i ];
  5876. y = positions[ i + 1 ];
  5877. z = positions[ i + 2 ];
  5878. pA.set( x, y, z );
  5879. x = positions[ i + 3 ];
  5880. y = positions[ i + 4 ];
  5881. z = positions[ i + 5 ];
  5882. pB.set( x, y, z );
  5883. x = positions[ i + 6 ];
  5884. y = positions[ i + 7 ];
  5885. z = positions[ i + 8 ];
  5886. pC.set( x, y, z );
  5887. cb.subVectors( pC, pB );
  5888. ab.subVectors( pA, pB );
  5889. cb.cross( ab );
  5890. normals[ i ] = cb.x;
  5891. normals[ i + 1 ] = cb.y;
  5892. normals[ i + 2 ] = cb.z;
  5893. normals[ i + 3 ] = cb.x;
  5894. normals[ i + 4 ] = cb.y;
  5895. normals[ i + 5 ] = cb.z;
  5896. normals[ i + 6 ] = cb.x;
  5897. normals[ i + 7 ] = cb.y;
  5898. normals[ i + 8 ] = cb.z;
  5899. }
  5900. }
  5901. this.normalizeNormals();
  5902. this.normalsNeedUpdate = true;
  5903. }
  5904. },
  5905. normalizeNormals: function () {
  5906. var normals = this.attributes[ "normal" ].array;
  5907. var x, y, z, n;
  5908. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5909. x = normals[ i ];
  5910. y = normals[ i + 1 ];
  5911. z = normals[ i + 2 ];
  5912. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5913. normals[ i ] *= n;
  5914. normals[ i + 1 ] *= n;
  5915. normals[ i + 2 ] *= n;
  5916. }
  5917. },
  5918. computeTangents: function () {
  5919. // based on http://www.terathon.com/code/tangent.html
  5920. // (per vertex tangents)
  5921. if ( this.attributes[ "index" ] === undefined ||
  5922. this.attributes[ "position" ] === undefined ||
  5923. this.attributes[ "normal" ] === undefined ||
  5924. this.attributes[ "uv" ] === undefined ) {
  5925. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5926. return;
  5927. }
  5928. var indices = this.attributes[ "index" ].array;
  5929. var positions = this.attributes[ "position" ].array;
  5930. var normals = this.attributes[ "normal" ].array;
  5931. var uvs = this.attributes[ "uv" ].array;
  5932. var nVertices = positions.length / 3;
  5933. if ( this.attributes[ "tangent" ] === undefined ) {
  5934. var nTangentElements = 4 * nVertices;
  5935. this.attributes[ "tangent" ] = {
  5936. itemSize: 4,
  5937. array: new Float32Array( nTangentElements )
  5938. };
  5939. }
  5940. var tangents = this.attributes[ "tangent" ].array;
  5941. var tan1 = [], tan2 = [];
  5942. for ( var k = 0; k < nVertices; k ++ ) {
  5943. tan1[ k ] = new THREE.Vector3();
  5944. tan2[ k ] = new THREE.Vector3();
  5945. }
  5946. var xA, yA, zA,
  5947. xB, yB, zB,
  5948. xC, yC, zC,
  5949. uA, vA,
  5950. uB, vB,
  5951. uC, vC,
  5952. x1, x2, y1, y2, z1, z2,
  5953. s1, s2, t1, t2, r;
  5954. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5955. function handleTriangle( a, b, c ) {
  5956. xA = positions[ a * 3 ];
  5957. yA = positions[ a * 3 + 1 ];
  5958. zA = positions[ a * 3 + 2 ];
  5959. xB = positions[ b * 3 ];
  5960. yB = positions[ b * 3 + 1 ];
  5961. zB = positions[ b * 3 + 2 ];
  5962. xC = positions[ c * 3 ];
  5963. yC = positions[ c * 3 + 1 ];
  5964. zC = positions[ c * 3 + 2 ];
  5965. uA = uvs[ a * 2 ];
  5966. vA = uvs[ a * 2 + 1 ];
  5967. uB = uvs[ b * 2 ];
  5968. vB = uvs[ b * 2 + 1 ];
  5969. uC = uvs[ c * 2 ];
  5970. vC = uvs[ c * 2 + 1 ];
  5971. x1 = xB - xA;
  5972. x2 = xC - xA;
  5973. y1 = yB - yA;
  5974. y2 = yC - yA;
  5975. z1 = zB - zA;
  5976. z2 = zC - zA;
  5977. s1 = uB - uA;
  5978. s2 = uC - uA;
  5979. t1 = vB - vA;
  5980. t2 = vC - vA;
  5981. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5982. sdir.set(
  5983. ( t2 * x1 - t1 * x2 ) * r,
  5984. ( t2 * y1 - t1 * y2 ) * r,
  5985. ( t2 * z1 - t1 * z2 ) * r
  5986. );
  5987. tdir.set(
  5988. ( s1 * x2 - s2 * x1 ) * r,
  5989. ( s1 * y2 - s2 * y1 ) * r,
  5990. ( s1 * z2 - s2 * z1 ) * r
  5991. );
  5992. tan1[ a ].add( sdir );
  5993. tan1[ b ].add( sdir );
  5994. tan1[ c ].add( sdir );
  5995. tan2[ a ].add( tdir );
  5996. tan2[ b ].add( tdir );
  5997. tan2[ c ].add( tdir );
  5998. }
  5999. var i, il;
  6000. var j, jl;
  6001. var iA, iB, iC;
  6002. var offsets = this.offsets;
  6003. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  6004. var start = offsets[ j ].start;
  6005. var count = offsets[ j ].count;
  6006. var index = offsets[ j ].index;
  6007. for ( i = start, il = start + count; i < il; i += 3 ) {
  6008. iA = index + indices[ i ];
  6009. iB = index + indices[ i + 1 ];
  6010. iC = index + indices[ i + 2 ];
  6011. handleTriangle( iA, iB, iC );
  6012. }
  6013. }
  6014. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  6015. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  6016. var w, t, test;
  6017. function handleVertex( v ) {
  6018. n.x = normals[ v * 3 ];
  6019. n.y = normals[ v * 3 + 1 ];
  6020. n.z = normals[ v * 3 + 2 ];
  6021. n2.copy( n );
  6022. t = tan1[ v ];
  6023. // Gram-Schmidt orthogonalize
  6024. tmp.copy( t );
  6025. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6026. // Calculate handedness
  6027. tmp2.crossVectors( n2, t );
  6028. test = tmp2.dot( tan2[ v ] );
  6029. w = ( test < 0.0 ) ? -1.0 : 1.0;
  6030. tangents[ v * 4 ] = tmp.x;
  6031. tangents[ v * 4 + 1 ] = tmp.y;
  6032. tangents[ v * 4 + 2 ] = tmp.z;
  6033. tangents[ v * 4 + 3 ] = w;
  6034. }
  6035. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  6036. var start = offsets[ j ].start;
  6037. var count = offsets[ j ].count;
  6038. var index = offsets[ j ].index;
  6039. for ( i = start, il = start + count; i < il; i += 3 ) {
  6040. iA = index + indices[ i ];
  6041. iB = index + indices[ i + 1 ];
  6042. iC = index + indices[ i + 2 ];
  6043. handleVertex( iA );
  6044. handleVertex( iB );
  6045. handleVertex( iC );
  6046. }
  6047. }
  6048. },
  6049. /*
  6050. computeOffsets
  6051. Compute the draw offset for large models by chunking the index buffer into chunks of 65k addressable vertices.
  6052. This method will effectively rewrite the index buffer and remap all attributes to match the new indices.
  6053. WARNING: This method will also expand the vertex count to prevent sprawled triangles across draw offsets.
  6054. indexBufferSize - Defaults to 65535, but allows for larger or smaller chunks.
  6055. */
  6056. computeOffsets: function(indexBufferSize) {
  6057. var size = indexBufferSize;
  6058. if(indexBufferSize === undefined)
  6059. size = 65535; //WebGL limits type of index buffer values to 16-bit.
  6060. var s = Date.now();
  6061. var indices = this.attributes['index'].array;
  6062. var vertices = this.attributes['position'].array;
  6063. var verticesCount = (vertices.length/3);
  6064. var facesCount = (indices.length/3);
  6065. /*
  6066. console.log("Computing buffers in offsets of "+size+" -> indices:"+indices.length+" vertices:"+vertices.length);
  6067. console.log("Faces to process: "+(indices.length/3));
  6068. console.log("Reordering "+verticesCount+" vertices.");
  6069. */
  6070. var sortedIndices = new Uint16Array( indices.length ); //16-bit buffers
  6071. var indexPtr = 0;
  6072. var vertexPtr = 0;
  6073. var offsets = [ { start:0, count:0, index:0 } ];
  6074. var offset = offsets[0];
  6075. var duplicatedVertices = 0;
  6076. var newVerticeMaps = 0;
  6077. var faceVertices = new Int32Array(6);
  6078. var vertexMap = new Int32Array( vertices.length );
  6079. var revVertexMap = new Int32Array( vertices.length );
  6080. for(var j = 0; j < vertices.length; j++) { vertexMap[j] = -1; revVertexMap[j] = -1; }
  6081. /*
  6082. Traverse every face and reorder vertices in the proper offsets of 65k.
  6083. We can have more than 65k entries in the index buffer per offset, but only reference 65k values.
  6084. */
  6085. for(var findex = 0; findex < facesCount; findex++) {
  6086. newVerticeMaps = 0;
  6087. for(var vo = 0; vo < 3; vo++) {
  6088. var vid = indices[ findex*3 + vo ];
  6089. if(vertexMap[vid] == -1) {
  6090. //Unmapped vertice
  6091. faceVertices[vo*2] = vid;
  6092. faceVertices[vo*2+1] = -1;
  6093. newVerticeMaps++;
  6094. } else if(vertexMap[vid] < offset.index) {
  6095. //Reused vertices from previous block (duplicate)
  6096. faceVertices[vo*2] = vid;
  6097. faceVertices[vo*2+1] = -1;
  6098. duplicatedVertices++;
  6099. } else {
  6100. //Reused vertice in the current block
  6101. faceVertices[vo*2] = vid;
  6102. faceVertices[vo*2+1] = vertexMap[vid];
  6103. }
  6104. }
  6105. var faceMax = vertexPtr + newVerticeMaps;
  6106. if(faceMax > (offset.index + size)) {
  6107. var new_offset = { start:indexPtr, count:0, index:vertexPtr };
  6108. offsets.push(new_offset);
  6109. offset = new_offset;
  6110. //Re-evaluate reused vertices in light of new offset.
  6111. for(var v = 0; v < 6; v+=2) {
  6112. var new_vid = faceVertices[v+1];
  6113. if(new_vid > -1 && new_vid < offset.index)
  6114. faceVertices[v+1] = -1;
  6115. }
  6116. }
  6117. //Reindex the face.
  6118. for(var v = 0; v < 6; v+=2) {
  6119. var vid = faceVertices[v];
  6120. var new_vid = faceVertices[v+1];
  6121. if(new_vid === -1)
  6122. new_vid = vertexPtr++;
  6123. vertexMap[vid] = new_vid;
  6124. revVertexMap[new_vid] = vid;
  6125. sortedIndices[indexPtr++] = new_vid - offset.index; //XXX overflows at 16bit
  6126. offset.count++;
  6127. }
  6128. }
  6129. /* Move all attribute values to map to the new computed indices , also expand the vertice stack to match our new vertexPtr. */
  6130. this.reorderBuffers(sortedIndices, revVertexMap, vertexPtr);
  6131. this.offsets = offsets;
  6132. /*
  6133. var orderTime = Date.now();
  6134. console.log("Reorder time: "+(orderTime-s)+"ms");
  6135. console.log("Duplicated "+duplicatedVertices+" vertices.");
  6136. console.log("Compute Buffers time: "+(Date.now()-s)+"ms");
  6137. console.log("Draw offsets: "+offsets.length);
  6138. */
  6139. return offsets;
  6140. },
  6141. /*
  6142. reoderBuffers:
  6143. Reorder attributes based on a new indexBuffer and indexMap.
  6144. indexBuffer - Uint16Array of the new ordered indices.
  6145. indexMap - Int32Array where the position is the new vertex ID and the value the old vertex ID for each vertex.
  6146. vertexCount - Amount of total vertices considered in this reordering (in case you want to grow the vertice stack).
  6147. */
  6148. reorderBuffers: function(indexBuffer, indexMap, vertexCount) {
  6149. /* Create a copy of all attributes for reordering. */
  6150. var sortedAttributes = {};
  6151. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  6152. for( var attr in this.attributes ) {
  6153. if(attr == 'index')
  6154. continue;
  6155. var sourceArray = this.attributes[attr].array;
  6156. for ( var i = 0, il = types.length; i < il; i++ ) {
  6157. var type = types[i];
  6158. if (sourceArray instanceof type) {
  6159. sortedAttributes[attr] = new type( this.attributes[attr].itemSize * vertexCount );
  6160. break;
  6161. }
  6162. }
  6163. }
  6164. /* Move attribute positions based on the new index map */
  6165. for(var new_vid = 0; new_vid < vertexCount; new_vid++) {
  6166. var vid = indexMap[new_vid];
  6167. for ( var attr in this.attributes ) {
  6168. if(attr == 'index')
  6169. continue;
  6170. var attrArray = this.attributes[attr].array;
  6171. var attrSize = this.attributes[attr].itemSize;
  6172. var sortedAttr = sortedAttributes[attr];
  6173. for(var k = 0; k < attrSize; k++)
  6174. sortedAttr[ new_vid * attrSize + k ] = attrArray[ vid * attrSize + k ];
  6175. }
  6176. }
  6177. /* Carry the new sorted buffers locally */
  6178. this.attributes['index'].array = indexBuffer;
  6179. for ( var attr in this.attributes ) {
  6180. if(attr == 'index')
  6181. continue;
  6182. this.attributes[attr].array = sortedAttributes[attr];
  6183. this.attributes[attr].numItems = this.attributes[attr].itemSize * vertexCount;
  6184. }
  6185. },
  6186. clone: function () {
  6187. var geometry = new THREE.BufferGeometry();
  6188. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  6189. for ( var attr in this.attributes ) {
  6190. var sourceAttr = this.attributes[ attr ];
  6191. var sourceArray = sourceAttr.array;
  6192. var attribute = {
  6193. itemSize: sourceAttr.itemSize,
  6194. array: null
  6195. };
  6196. for ( var i = 0, il = types.length; i < il; i ++ ) {
  6197. var type = types[ i ];
  6198. if ( sourceArray instanceof type ) {
  6199. attribute.array = new type( sourceArray );
  6200. break;
  6201. }
  6202. }
  6203. geometry.attributes[ attr ] = attribute;
  6204. }
  6205. for ( var i = 0, il = this.offsets.length; i < il; i ++ ) {
  6206. var offset = this.offsets[ i ];
  6207. geometry.offsets.push( {
  6208. start: offset.start,
  6209. index: offset.index,
  6210. count: offset.count
  6211. } );
  6212. }
  6213. return geometry;
  6214. },
  6215. dispose: function () {
  6216. this.dispatchEvent( { type: 'dispose' } );
  6217. }
  6218. };
  6219. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  6220. /**
  6221. * @author mrdoob / http://mrdoob.com/
  6222. * @author mikael emtinger / http://gomo.se/
  6223. * @author WestLangley / http://github.com/WestLangley
  6224. */
  6225. THREE.Camera = function () {
  6226. THREE.Object3D.call( this );
  6227. this.matrixWorldInverse = new THREE.Matrix4();
  6228. this.projectionMatrix = new THREE.Matrix4();
  6229. };
  6230. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  6231. THREE.Camera.prototype.lookAt = function () {
  6232. // This routine does not support cameras with rotated and/or translated parent(s)
  6233. var m1 = new THREE.Matrix4();
  6234. return function ( vector ) {
  6235. m1.lookAt( this.position, vector, this.up );
  6236. this.quaternion.setFromRotationMatrix( m1 );
  6237. };
  6238. }();
  6239. THREE.Camera.prototype.clone = function (camera) {
  6240. if ( camera === undefined ) camera = new THREE.Camera();
  6241. THREE.Object3D.prototype.clone.call( this, camera );
  6242. camera.matrixWorldInverse.copy( this.matrixWorldInverse );
  6243. camera.projectionMatrix.copy( this.projectionMatrix );
  6244. return camera;
  6245. };
  6246. /**
  6247. * @author alteredq / http://alteredqualia.com/
  6248. */
  6249. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  6250. THREE.Camera.call( this );
  6251. this.left = left;
  6252. this.right = right;
  6253. this.top = top;
  6254. this.bottom = bottom;
  6255. this.near = ( near !== undefined ) ? near : 0.1;
  6256. this.far = ( far !== undefined ) ? far : 2000;
  6257. this.updateProjectionMatrix();
  6258. };
  6259. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  6260. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  6261. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  6262. };
  6263. THREE.OrthographicCamera.prototype.clone = function () {
  6264. var camera = new THREE.OrthographicCamera();
  6265. THREE.Camera.prototype.clone.call( this, camera );
  6266. camera.left = this.left;
  6267. camera.right = this.right;
  6268. camera.top = this.top;
  6269. camera.bottom = this.bottom;
  6270. camera.near = this.near;
  6271. camera.far = this.far;
  6272. return camera;
  6273. };
  6274. /**
  6275. * @author mrdoob / http://mrdoob.com/
  6276. * @author greggman / http://games.greggman.com/
  6277. * @author zz85 / http://www.lab4games.net/zz85/blog
  6278. */
  6279. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  6280. THREE.Camera.call( this );
  6281. this.fov = fov !== undefined ? fov : 50;
  6282. this.aspect = aspect !== undefined ? aspect : 1;
  6283. this.near = near !== undefined ? near : 0.1;
  6284. this.far = far !== undefined ? far : 2000;
  6285. this.updateProjectionMatrix();
  6286. };
  6287. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  6288. /**
  6289. * Uses Focal Length (in mm) to estimate and set FOV
  6290. * 35mm (fullframe) camera is used if frame size is not specified;
  6291. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  6292. */
  6293. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  6294. if ( frameHeight === undefined ) frameHeight = 24;
  6295. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  6296. this.updateProjectionMatrix();
  6297. }
  6298. /**
  6299. * Sets an offset in a larger frustum. This is useful for multi-window or
  6300. * multi-monitor/multi-machine setups.
  6301. *
  6302. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6303. * the monitors are in grid like this
  6304. *
  6305. * +---+---+---+
  6306. * | A | B | C |
  6307. * +---+---+---+
  6308. * | D | E | F |
  6309. * +---+---+---+
  6310. *
  6311. * then for each monitor you would call it like this
  6312. *
  6313. * var w = 1920;
  6314. * var h = 1080;
  6315. * var fullWidth = w * 3;
  6316. * var fullHeight = h * 2;
  6317. *
  6318. * --A--
  6319. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6320. * --B--
  6321. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6322. * --C--
  6323. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6324. * --D--
  6325. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6326. * --E--
  6327. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  6328. * --F--
  6329. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  6330. *
  6331. * Note there is no reason monitors have to be the same size or in a grid.
  6332. */
  6333. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  6334. this.fullWidth = fullWidth;
  6335. this.fullHeight = fullHeight;
  6336. this.x = x;
  6337. this.y = y;
  6338. this.width = width;
  6339. this.height = height;
  6340. this.updateProjectionMatrix();
  6341. };
  6342. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  6343. if ( this.fullWidth ) {
  6344. var aspect = this.fullWidth / this.fullHeight;
  6345. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  6346. var bottom = -top;
  6347. var left = aspect * bottom;
  6348. var right = aspect * top;
  6349. var width = Math.abs( right - left );
  6350. var height = Math.abs( top - bottom );
  6351. this.projectionMatrix.makeFrustum(
  6352. left + this.x * width / this.fullWidth,
  6353. left + ( this.x + this.width ) * width / this.fullWidth,
  6354. top - ( this.y + this.height ) * height / this.fullHeight,
  6355. top - this.y * height / this.fullHeight,
  6356. this.near,
  6357. this.far
  6358. );
  6359. } else {
  6360. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  6361. }
  6362. };
  6363. THREE.PerspectiveCamera.prototype.clone = function () {
  6364. var camera = new THREE.PerspectiveCamera();
  6365. THREE.Camera.prototype.clone.call( this, camera );
  6366. camera.fov = this.fov;
  6367. camera.aspect = this.aspect;
  6368. camera.near = this.near;
  6369. camera.far = this.far;
  6370. return camera;
  6371. };
  6372. /**
  6373. * @author mrdoob / http://mrdoob.com/
  6374. * @author alteredq / http://alteredqualia.com/
  6375. */
  6376. THREE.Light = function ( color ) {
  6377. THREE.Object3D.call( this );
  6378. this.color = new THREE.Color( color );
  6379. };
  6380. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  6381. THREE.Light.prototype.clone = function ( light ) {
  6382. if ( light === undefined ) light = new THREE.Light();
  6383. THREE.Object3D.prototype.clone.call( this, light );
  6384. light.color.copy( this.color );
  6385. return light;
  6386. };
  6387. /**
  6388. * @author mrdoob / http://mrdoob.com/
  6389. */
  6390. THREE.AmbientLight = function ( color ) {
  6391. THREE.Light.call( this, color );
  6392. };
  6393. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  6394. THREE.AmbientLight.prototype.clone = function () {
  6395. var light = new THREE.AmbientLight();
  6396. THREE.Light.prototype.clone.call( this, light );
  6397. return light;
  6398. };
  6399. /**
  6400. * @author MPanknin / http://www.redplant.de/
  6401. * @author alteredq / http://alteredqualia.com/
  6402. */
  6403. THREE.AreaLight = function ( color, intensity ) {
  6404. THREE.Light.call( this, color );
  6405. this.normal = new THREE.Vector3( 0, -1, 0 );
  6406. this.right = new THREE.Vector3( 1, 0, 0 );
  6407. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6408. this.width = 1.0;
  6409. this.height = 1.0;
  6410. this.constantAttenuation = 1.5;
  6411. this.linearAttenuation = 0.5;
  6412. this.quadraticAttenuation = 0.1;
  6413. };
  6414. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  6415. /**
  6416. * @author mrdoob / http://mrdoob.com/
  6417. * @author alteredq / http://alteredqualia.com/
  6418. */
  6419. THREE.DirectionalLight = function ( color, intensity ) {
  6420. THREE.Light.call( this, color );
  6421. this.position.set( 0, 1, 0 );
  6422. this.target = new THREE.Object3D();
  6423. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6424. this.castShadow = false;
  6425. this.onlyShadow = false;
  6426. //
  6427. this.shadowCameraNear = 50;
  6428. this.shadowCameraFar = 5000;
  6429. this.shadowCameraLeft = -500;
  6430. this.shadowCameraRight = 500;
  6431. this.shadowCameraTop = 500;
  6432. this.shadowCameraBottom = -500;
  6433. this.shadowCameraVisible = false;
  6434. this.shadowBias = 0;
  6435. this.shadowDarkness = 0.5;
  6436. this.shadowMapWidth = 512;
  6437. this.shadowMapHeight = 512;
  6438. //
  6439. this.shadowCascade = false;
  6440. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  6441. this.shadowCascadeCount = 2;
  6442. this.shadowCascadeBias = [ 0, 0, 0 ];
  6443. this.shadowCascadeWidth = [ 512, 512, 512 ];
  6444. this.shadowCascadeHeight = [ 512, 512, 512 ];
  6445. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  6446. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  6447. this.shadowCascadeArray = [];
  6448. //
  6449. this.shadowMap = null;
  6450. this.shadowMapSize = null;
  6451. this.shadowCamera = null;
  6452. this.shadowMatrix = null;
  6453. };
  6454. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  6455. THREE.DirectionalLight.prototype.clone = function () {
  6456. var light = new THREE.DirectionalLight();
  6457. THREE.Light.prototype.clone.call( this, light );
  6458. light.target = this.target.clone();
  6459. light.intensity = this.intensity;
  6460. light.castShadow = this.castShadow;
  6461. light.onlyShadow = this.onlyShadow;
  6462. return light;
  6463. };
  6464. /**
  6465. * @author alteredq / http://alteredqualia.com/
  6466. */
  6467. THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
  6468. THREE.Light.call( this, skyColor );
  6469. this.position.set( 0, 100, 0 );
  6470. this.groundColor = new THREE.Color( groundColor );
  6471. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6472. };
  6473. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  6474. THREE.HemisphereLight.prototype.clone = function () {
  6475. var light = new THREE.HemisphereLight();
  6476. THREE.Light.prototype.clone.call( this, light );
  6477. light.groundColor.copy( this.groundColor );
  6478. light.intensity = this.intensity;
  6479. return light;
  6480. };
  6481. /**
  6482. * @author mrdoob / http://mrdoob.com/
  6483. */
  6484. THREE.PointLight = function ( color, intensity, distance ) {
  6485. THREE.Light.call( this, color );
  6486. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6487. this.distance = ( distance !== undefined ) ? distance : 0;
  6488. };
  6489. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  6490. THREE.PointLight.prototype.clone = function () {
  6491. var light = new THREE.PointLight();
  6492. THREE.Light.prototype.clone.call( this, light );
  6493. light.intensity = this.intensity;
  6494. light.distance = this.distance;
  6495. return light;
  6496. };
  6497. /**
  6498. * @author alteredq / http://alteredqualia.com/
  6499. */
  6500. THREE.SpotLight = function ( color, intensity, distance, angle, exponent ) {
  6501. THREE.Light.call( this, color );
  6502. this.position.set( 0, 1, 0 );
  6503. this.target = new THREE.Object3D();
  6504. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6505. this.distance = ( distance !== undefined ) ? distance : 0;
  6506. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  6507. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  6508. this.castShadow = false;
  6509. this.onlyShadow = false;
  6510. //
  6511. this.shadowCameraNear = 50;
  6512. this.shadowCameraFar = 5000;
  6513. this.shadowCameraFov = 50;
  6514. this.shadowCameraVisible = false;
  6515. this.shadowBias = 0;
  6516. this.shadowDarkness = 0.5;
  6517. this.shadowMapWidth = 512;
  6518. this.shadowMapHeight = 512;
  6519. //
  6520. this.shadowMap = null;
  6521. this.shadowMapSize = null;
  6522. this.shadowCamera = null;
  6523. this.shadowMatrix = null;
  6524. };
  6525. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  6526. THREE.SpotLight.prototype.clone = function () {
  6527. var light = new THREE.SpotLight();
  6528. THREE.Light.prototype.clone.call( this, light );
  6529. light.target = this.target.clone();
  6530. light.intensity = this.intensity;
  6531. light.distance = this.distance;
  6532. light.angle = this.angle;
  6533. light.exponent = this.exponent;
  6534. light.castShadow = this.castShadow;
  6535. light.onlyShadow = this.onlyShadow;
  6536. return light;
  6537. };
  6538. /**
  6539. * @author alteredq / http://alteredqualia.com/
  6540. */
  6541. THREE.Loader = function ( showStatus ) {
  6542. this.showStatus = showStatus;
  6543. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  6544. this.onLoadStart = function () {};
  6545. this.onLoadProgress = function () {};
  6546. this.onLoadComplete = function () {};
  6547. };
  6548. THREE.Loader.prototype = {
  6549. constructor: THREE.Loader,
  6550. crossOrigin: undefined,
  6551. addStatusElement: function () {
  6552. var e = document.createElement( "div" );
  6553. e.style.position = "absolute";
  6554. e.style.right = "0px";
  6555. e.style.top = "0px";
  6556. e.style.fontSize = "0.8em";
  6557. e.style.textAlign = "left";
  6558. e.style.background = "rgba(0,0,0,0.25)";
  6559. e.style.color = "#fff";
  6560. e.style.width = "120px";
  6561. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  6562. e.style.zIndex = 1000;
  6563. e.innerHTML = "Loading ...";
  6564. return e;
  6565. },
  6566. updateProgress: function ( progress ) {
  6567. var message = "Loaded ";
  6568. if ( progress.total ) {
  6569. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  6570. } else {
  6571. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  6572. }
  6573. this.statusDomElement.innerHTML = message;
  6574. },
  6575. extractUrlBase: function ( url ) {
  6576. var parts = url.split( '/' );
  6577. if ( parts.length === 1 ) return './';
  6578. parts.pop();
  6579. return parts.join( '/' ) + '/';
  6580. },
  6581. initMaterials: function ( materials, texturePath ) {
  6582. var array = [];
  6583. for ( var i = 0; i < materials.length; ++ i ) {
  6584. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  6585. }
  6586. return array;
  6587. },
  6588. needsTangents: function ( materials ) {
  6589. for( var i = 0, il = materials.length; i < il; i ++ ) {
  6590. var m = materials[ i ];
  6591. if ( m instanceof THREE.ShaderMaterial ) return true;
  6592. }
  6593. return false;
  6594. },
  6595. createMaterial: function ( m, texturePath ) {
  6596. var _this = this;
  6597. function is_pow2( n ) {
  6598. var l = Math.log( n ) / Math.LN2;
  6599. return Math.floor( l ) == l;
  6600. }
  6601. function nearest_pow2( n ) {
  6602. var l = Math.log( n ) / Math.LN2;
  6603. return Math.pow( 2, Math.round( l ) );
  6604. }
  6605. function load_image( where, url ) {
  6606. var image = new Image();
  6607. image.onload = function () {
  6608. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  6609. var width = nearest_pow2( this.width );
  6610. var height = nearest_pow2( this.height );
  6611. where.image.width = width;
  6612. where.image.height = height;
  6613. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  6614. } else {
  6615. where.image = this;
  6616. }
  6617. where.needsUpdate = true;
  6618. };
  6619. if ( _this.crossOrigin !== undefined ) image.crossOrigin = _this.crossOrigin;
  6620. image.src = url;
  6621. }
  6622. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  6623. var isCompressed = /\.dds$/i.test( sourceFile );
  6624. var fullPath = texturePath + sourceFile;
  6625. if ( isCompressed ) {
  6626. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  6627. where[ name ] = texture;
  6628. } else {
  6629. var texture = document.createElement( 'canvas' );
  6630. where[ name ] = new THREE.Texture( texture );
  6631. }
  6632. where[ name ].sourceFile = sourceFile;
  6633. if( repeat ) {
  6634. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  6635. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  6636. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  6637. }
  6638. if ( offset ) {
  6639. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  6640. }
  6641. if ( wrap ) {
  6642. var wrapMap = {
  6643. "repeat": THREE.RepeatWrapping,
  6644. "mirror": THREE.MirroredRepeatWrapping
  6645. }
  6646. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  6647. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  6648. }
  6649. if ( anisotropy ) {
  6650. where[ name ].anisotropy = anisotropy;
  6651. }
  6652. if ( ! isCompressed ) {
  6653. load_image( where[ name ], fullPath );
  6654. }
  6655. }
  6656. function rgb2hex( rgb ) {
  6657. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  6658. }
  6659. // defaults
  6660. var mtype = "MeshLambertMaterial";
  6661. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  6662. // parameters from model file
  6663. if ( m.shading ) {
  6664. var shading = m.shading.toLowerCase();
  6665. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  6666. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  6667. }
  6668. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  6669. mpars.blending = THREE[ m.blending ];
  6670. }
  6671. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  6672. mpars.transparent = m.transparent;
  6673. }
  6674. if ( m.depthTest !== undefined ) {
  6675. mpars.depthTest = m.depthTest;
  6676. }
  6677. if ( m.depthWrite !== undefined ) {
  6678. mpars.depthWrite = m.depthWrite;
  6679. }
  6680. if ( m.visible !== undefined ) {
  6681. mpars.visible = m.visible;
  6682. }
  6683. if ( m.flipSided !== undefined ) {
  6684. mpars.side = THREE.BackSide;
  6685. }
  6686. if ( m.doubleSided !== undefined ) {
  6687. mpars.side = THREE.DoubleSide;
  6688. }
  6689. if ( m.wireframe !== undefined ) {
  6690. mpars.wireframe = m.wireframe;
  6691. }
  6692. if ( m.vertexColors !== undefined ) {
  6693. if ( m.vertexColors === "face" ) {
  6694. mpars.vertexColors = THREE.FaceColors;
  6695. } else if ( m.vertexColors ) {
  6696. mpars.vertexColors = THREE.VertexColors;
  6697. }
  6698. }
  6699. // colors
  6700. if ( m.colorDiffuse ) {
  6701. mpars.color = rgb2hex( m.colorDiffuse );
  6702. } else if ( m.DbgColor ) {
  6703. mpars.color = m.DbgColor;
  6704. }
  6705. if ( m.colorSpecular ) {
  6706. mpars.specular = rgb2hex( m.colorSpecular );
  6707. }
  6708. if ( m.colorAmbient ) {
  6709. mpars.ambient = rgb2hex( m.colorAmbient );
  6710. }
  6711. // modifiers
  6712. if ( m.transparency ) {
  6713. mpars.opacity = m.transparency;
  6714. }
  6715. if ( m.specularCoef ) {
  6716. mpars.shininess = m.specularCoef;
  6717. }
  6718. // textures
  6719. if ( m.mapDiffuse && texturePath ) {
  6720. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  6721. }
  6722. if ( m.mapLight && texturePath ) {
  6723. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  6724. }
  6725. if ( m.mapBump && texturePath ) {
  6726. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  6727. }
  6728. if ( m.mapNormal && texturePath ) {
  6729. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  6730. }
  6731. if ( m.mapSpecular && texturePath ) {
  6732. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  6733. }
  6734. //
  6735. if ( m.mapBumpScale ) {
  6736. mpars.bumpScale = m.mapBumpScale;
  6737. }
  6738. // special case for normal mapped material
  6739. if ( m.mapNormal ) {
  6740. var shader = THREE.ShaderLib[ "normalmap" ];
  6741. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6742. uniforms[ "tNormal" ].value = mpars.normalMap;
  6743. if ( m.mapNormalFactor ) {
  6744. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  6745. }
  6746. if ( mpars.map ) {
  6747. uniforms[ "tDiffuse" ].value = mpars.map;
  6748. uniforms[ "enableDiffuse" ].value = true;
  6749. }
  6750. if ( mpars.specularMap ) {
  6751. uniforms[ "tSpecular" ].value = mpars.specularMap;
  6752. uniforms[ "enableSpecular" ].value = true;
  6753. }
  6754. if ( mpars.lightMap ) {
  6755. uniforms[ "tAO" ].value = mpars.lightMap;
  6756. uniforms[ "enableAO" ].value = true;
  6757. }
  6758. // for the moment don't handle displacement texture
  6759. uniforms[ "diffuse" ].value.setHex( mpars.color );
  6760. uniforms[ "specular" ].value.setHex( mpars.specular );
  6761. uniforms[ "ambient" ].value.setHex( mpars.ambient );
  6762. uniforms[ "shininess" ].value = mpars.shininess;
  6763. if ( mpars.opacity !== undefined ) {
  6764. uniforms[ "opacity" ].value = mpars.opacity;
  6765. }
  6766. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6767. var material = new THREE.ShaderMaterial( parameters );
  6768. if ( mpars.transparent ) {
  6769. material.transparent = true;
  6770. }
  6771. } else {
  6772. var material = new THREE[ mtype ]( mpars );
  6773. }
  6774. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6775. return material;
  6776. }
  6777. };
  6778. /**
  6779. * @author mrdoob / http://mrdoob.com/
  6780. */
  6781. THREE.XHRLoader = function ( manager ) {
  6782. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6783. };
  6784. THREE.XHRLoader.prototype = {
  6785. constructor: THREE.XHRLoader,
  6786. load: function ( url, onLoad, onProgress, onError ) {
  6787. var scope = this;
  6788. var request = new XMLHttpRequest();
  6789. if ( onLoad !== undefined ) {
  6790. request.addEventListener( 'load', function ( event ) {
  6791. onLoad( event.target.responseText );
  6792. scope.manager.itemEnd( url );
  6793. }, false );
  6794. }
  6795. if ( onProgress !== undefined ) {
  6796. request.addEventListener( 'progress', function ( event ) {
  6797. onProgress( event );
  6798. }, false );
  6799. }
  6800. if ( onError !== undefined ) {
  6801. request.addEventListener( 'error', function ( event ) {
  6802. onError( event );
  6803. }, false );
  6804. }
  6805. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  6806. request.open( 'GET', url, true );
  6807. request.send( null );
  6808. scope.manager.itemStart( url );
  6809. },
  6810. setCrossOrigin: function ( value ) {
  6811. this.crossOrigin = value;
  6812. }
  6813. };
  6814. /**
  6815. * @author mrdoob / http://mrdoob.com/
  6816. */
  6817. THREE.ImageLoader = function ( manager ) {
  6818. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6819. };
  6820. THREE.ImageLoader.prototype = {
  6821. constructor: THREE.ImageLoader,
  6822. load: function ( url, onLoad, onProgress, onError ) {
  6823. var scope = this;
  6824. var image = document.createElement( 'img' );
  6825. if ( onLoad !== undefined ) {
  6826. image.addEventListener( 'load', function ( event ) {
  6827. scope.manager.itemEnd( url );
  6828. onLoad( this );
  6829. }, false );
  6830. }
  6831. if ( onProgress !== undefined ) {
  6832. image.addEventListener( 'progress', function ( event ) {
  6833. onProgress( event );
  6834. }, false );
  6835. }
  6836. if ( onError !== undefined ) {
  6837. image.addEventListener( 'error', function ( event ) {
  6838. onError( event );
  6839. }, false );
  6840. }
  6841. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  6842. image.src = url;
  6843. scope.manager.itemStart( url );
  6844. return image;
  6845. },
  6846. setCrossOrigin: function ( value ) {
  6847. this.crossOrigin = value;
  6848. }
  6849. }
  6850. /**
  6851. * @author mrdoob / http://mrdoob.com/
  6852. * @author alteredq / http://alteredqualia.com/
  6853. */
  6854. THREE.JSONLoader = function ( showStatus ) {
  6855. THREE.Loader.call( this, showStatus );
  6856. this.withCredentials = false;
  6857. };
  6858. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  6859. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  6860. var scope = this;
  6861. // todo: unify load API to for easier SceneLoader use
  6862. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  6863. this.onLoadStart();
  6864. this.loadAjaxJSON( this, url, callback, texturePath );
  6865. };
  6866. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  6867. var xhr = new XMLHttpRequest();
  6868. var length = 0;
  6869. xhr.onreadystatechange = function () {
  6870. if ( xhr.readyState === xhr.DONE ) {
  6871. if ( xhr.status === 200 || xhr.status === 0 ) {
  6872. if ( xhr.responseText ) {
  6873. var json = JSON.parse( xhr.responseText );
  6874. if ( json.metadata.type === 'scene' ) {
  6875. console.error( 'THREE.JSONLoader: "' + url + '" seems to be a Scene. Use THREE.SceneLoader instead.' );
  6876. return;
  6877. }
  6878. var result = context.parse( json, texturePath );
  6879. callback( result.geometry, result.materials );
  6880. } else {
  6881. console.error( 'THREE.JSONLoader: "' + url + '" seems to be unreachable or the file is empty.' );
  6882. }
  6883. // in context of more complex asset initialization
  6884. // do not block on single failed file
  6885. // maybe should go even one more level up
  6886. context.onLoadComplete();
  6887. } else {
  6888. console.error( 'THREE.JSONLoader: Couldn\'t load "' + url + '" (' + xhr.status + ')' );
  6889. }
  6890. } else if ( xhr.readyState === xhr.LOADING ) {
  6891. if ( callbackProgress ) {
  6892. if ( length === 0 ) {
  6893. length = xhr.getResponseHeader( 'Content-Length' );
  6894. }
  6895. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  6896. }
  6897. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  6898. if ( callbackProgress !== undefined ) {
  6899. length = xhr.getResponseHeader( "Content-Length" );
  6900. }
  6901. }
  6902. };
  6903. xhr.open( "GET", url, true );
  6904. xhr.withCredentials = this.withCredentials;
  6905. xhr.send( null );
  6906. };
  6907. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  6908. var scope = this,
  6909. geometry = new THREE.Geometry(),
  6910. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  6911. parseModel( scale );
  6912. parseSkin();
  6913. parseMorphing( scale );
  6914. geometry.computeCentroids();
  6915. geometry.computeFaceNormals();
  6916. geometry.computeBoundingSphere();
  6917. function parseModel( scale ) {
  6918. function isBitSet( value, position ) {
  6919. return value & ( 1 << position );
  6920. }
  6921. var i, j, fi,
  6922. offset, zLength,
  6923. colorIndex, normalIndex, uvIndex, materialIndex,
  6924. type,
  6925. isQuad,
  6926. hasMaterial,
  6927. hasFaceVertexUv,
  6928. hasFaceNormal, hasFaceVertexNormal,
  6929. hasFaceColor, hasFaceVertexColor,
  6930. vertex, face, faceA, faceB, color, hex, normal,
  6931. uvLayer, uv, u, v,
  6932. faces = json.faces,
  6933. vertices = json.vertices,
  6934. normals = json.normals,
  6935. colors = json.colors,
  6936. nUvLayers = 0;
  6937. if ( json.uvs !== undefined ) {
  6938. // disregard empty arrays
  6939. for ( i = 0; i < json.uvs.length; i++ ) {
  6940. if ( json.uvs[ i ].length ) nUvLayers ++;
  6941. }
  6942. for ( i = 0; i < nUvLayers; i++ ) {
  6943. geometry.faceVertexUvs[ i ] = [];
  6944. }
  6945. }
  6946. offset = 0;
  6947. zLength = vertices.length;
  6948. while ( offset < zLength ) {
  6949. vertex = new THREE.Vector3();
  6950. vertex.x = vertices[ offset ++ ] * scale;
  6951. vertex.y = vertices[ offset ++ ] * scale;
  6952. vertex.z = vertices[ offset ++ ] * scale;
  6953. geometry.vertices.push( vertex );
  6954. }
  6955. offset = 0;
  6956. zLength = faces.length;
  6957. while ( offset < zLength ) {
  6958. type = faces[ offset ++ ];
  6959. isQuad = isBitSet( type, 0 );
  6960. hasMaterial = isBitSet( type, 1 );
  6961. hasFaceVertexUv = isBitSet( type, 3 );
  6962. hasFaceNormal = isBitSet( type, 4 );
  6963. hasFaceVertexNormal = isBitSet( type, 5 );
  6964. hasFaceColor = isBitSet( type, 6 );
  6965. hasFaceVertexColor = isBitSet( type, 7 );
  6966. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  6967. if ( isQuad ) {
  6968. faceA = new THREE.Face3();
  6969. faceA.a = faces[ offset ];
  6970. faceA.b = faces[ offset + 1 ];
  6971. faceA.c = faces[ offset + 3 ];
  6972. faceB = new THREE.Face3();
  6973. faceB.a = faces[ offset + 1 ];
  6974. faceB.b = faces[ offset + 2 ];
  6975. faceB.c = faces[ offset + 3 ];
  6976. offset += 4;
  6977. if ( hasMaterial ) {
  6978. materialIndex = faces[ offset ++ ];
  6979. faceA.materialIndex = materialIndex;
  6980. faceB.materialIndex = materialIndex;
  6981. }
  6982. // to get face <=> uv index correspondence
  6983. fi = geometry.faces.length;
  6984. if ( hasFaceVertexUv ) {
  6985. for ( i = 0; i < nUvLayers; i++ ) {
  6986. uvLayer = json.uvs[ i ];
  6987. geometry.faceVertexUvs[ i ][ fi ] = [];
  6988. geometry.faceVertexUvs[ i ][ fi + 1 ] = []
  6989. for ( j = 0; j < 4; j ++ ) {
  6990. uvIndex = faces[ offset ++ ];
  6991. u = uvLayer[ uvIndex * 2 ];
  6992. v = uvLayer[ uvIndex * 2 + 1 ];
  6993. uv = new THREE.Vector2( u, v );
  6994. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  6995. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  6996. }
  6997. }
  6998. }
  6999. if ( hasFaceNormal ) {
  7000. normalIndex = faces[ offset ++ ] * 3;
  7001. faceA.normal.set(
  7002. normals[ normalIndex ++ ],
  7003. normals[ normalIndex ++ ],
  7004. normals[ normalIndex ]
  7005. );
  7006. faceB.normal.copy( faceA.normal );
  7007. }
  7008. if ( hasFaceVertexNormal ) {
  7009. for ( i = 0; i < 4; i++ ) {
  7010. normalIndex = faces[ offset ++ ] * 3;
  7011. normal = new THREE.Vector3(
  7012. normals[ normalIndex ++ ],
  7013. normals[ normalIndex ++ ],
  7014. normals[ normalIndex ]
  7015. );
  7016. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  7017. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  7018. }
  7019. }
  7020. if ( hasFaceColor ) {
  7021. colorIndex = faces[ offset ++ ];
  7022. hex = colors[ colorIndex ];
  7023. faceA.color.setHex( hex );
  7024. faceB.color.setHex( hex );
  7025. }
  7026. if ( hasFaceVertexColor ) {
  7027. for ( i = 0; i < 4; i++ ) {
  7028. colorIndex = faces[ offset ++ ];
  7029. hex = colors[ colorIndex ];
  7030. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  7031. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  7032. }
  7033. }
  7034. geometry.faces.push( faceA );
  7035. geometry.faces.push( faceB );
  7036. } else {
  7037. face = new THREE.Face3();
  7038. face.a = faces[ offset ++ ];
  7039. face.b = faces[ offset ++ ];
  7040. face.c = faces[ offset ++ ];
  7041. if ( hasMaterial ) {
  7042. materialIndex = faces[ offset ++ ];
  7043. face.materialIndex = materialIndex;
  7044. }
  7045. // to get face <=> uv index correspondence
  7046. fi = geometry.faces.length;
  7047. if ( hasFaceVertexUv ) {
  7048. for ( i = 0; i < nUvLayers; i++ ) {
  7049. uvLayer = json.uvs[ i ];
  7050. geometry.faceVertexUvs[ i ][ fi ] = [];
  7051. for ( j = 0; j < 3; j ++ ) {
  7052. uvIndex = faces[ offset ++ ];
  7053. u = uvLayer[ uvIndex * 2 ];
  7054. v = uvLayer[ uvIndex * 2 + 1 ];
  7055. uv = new THREE.Vector2( u, v );
  7056. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7057. }
  7058. }
  7059. }
  7060. if ( hasFaceNormal ) {
  7061. normalIndex = faces[ offset ++ ] * 3;
  7062. face.normal.set(
  7063. normals[ normalIndex ++ ],
  7064. normals[ normalIndex ++ ],
  7065. normals[ normalIndex ]
  7066. );
  7067. }
  7068. if ( hasFaceVertexNormal ) {
  7069. for ( i = 0; i < 3; i++ ) {
  7070. normalIndex = faces[ offset ++ ] * 3;
  7071. normal = new THREE.Vector3(
  7072. normals[ normalIndex ++ ],
  7073. normals[ normalIndex ++ ],
  7074. normals[ normalIndex ]
  7075. );
  7076. face.vertexNormals.push( normal );
  7077. }
  7078. }
  7079. if ( hasFaceColor ) {
  7080. colorIndex = faces[ offset ++ ];
  7081. face.color.setHex( colors[ colorIndex ] );
  7082. }
  7083. if ( hasFaceVertexColor ) {
  7084. for ( i = 0; i < 3; i++ ) {
  7085. colorIndex = faces[ offset ++ ];
  7086. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  7087. }
  7088. }
  7089. geometry.faces.push( face );
  7090. }
  7091. }
  7092. };
  7093. function parseSkin() {
  7094. if ( json.skinWeights ) {
  7095. for ( var i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  7096. var x = json.skinWeights[ i ];
  7097. var y = json.skinWeights[ i + 1 ];
  7098. var z = 0;
  7099. var w = 0;
  7100. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  7101. }
  7102. }
  7103. if ( json.skinIndices ) {
  7104. for ( var i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  7105. var a = json.skinIndices[ i ];
  7106. var b = json.skinIndices[ i + 1 ];
  7107. var c = 0;
  7108. var d = 0;
  7109. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  7110. }
  7111. }
  7112. geometry.bones = json.bones;
  7113. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  7114. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  7115. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  7116. }
  7117. // could change this to json.animations[0] or remove completely
  7118. geometry.animation = json.animation;
  7119. geometry.animations = json.animations;
  7120. };
  7121. function parseMorphing( scale ) {
  7122. if ( json.morphTargets !== undefined ) {
  7123. var i, l, v, vl, dstVertices, srcVertices;
  7124. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  7125. geometry.morphTargets[ i ] = {};
  7126. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  7127. geometry.morphTargets[ i ].vertices = [];
  7128. dstVertices = geometry.morphTargets[ i ].vertices;
  7129. srcVertices = json.morphTargets [ i ].vertices;
  7130. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  7131. var vertex = new THREE.Vector3();
  7132. vertex.x = srcVertices[ v ] * scale;
  7133. vertex.y = srcVertices[ v + 1 ] * scale;
  7134. vertex.z = srcVertices[ v + 2 ] * scale;
  7135. dstVertices.push( vertex );
  7136. }
  7137. }
  7138. }
  7139. if ( json.morphColors !== undefined ) {
  7140. var i, l, c, cl, dstColors, srcColors, color;
  7141. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  7142. geometry.morphColors[ i ] = {};
  7143. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  7144. geometry.morphColors[ i ].colors = [];
  7145. dstColors = geometry.morphColors[ i ].colors;
  7146. srcColors = json.morphColors [ i ].colors;
  7147. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  7148. color = new THREE.Color( 0xffaa00 );
  7149. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  7150. dstColors.push( color );
  7151. }
  7152. }
  7153. }
  7154. };
  7155. if ( json.materials === undefined ) {
  7156. return { geometry: geometry };
  7157. } else {
  7158. var materials = this.initMaterials( json.materials, texturePath );
  7159. if ( this.needsTangents( materials ) ) {
  7160. geometry.computeTangents();
  7161. }
  7162. return { geometry: geometry, materials: materials };
  7163. }
  7164. };
  7165. /**
  7166. * @author mrdoob / http://mrdoob.com/
  7167. */
  7168. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  7169. var scope = this;
  7170. var loaded = 0, total = 0;
  7171. this.onLoad = onLoad;
  7172. this.onProgress = onProgress;
  7173. this.onError = onError;
  7174. this.itemStart = function ( url ) {
  7175. total ++;
  7176. };
  7177. this.itemEnd = function ( url ) {
  7178. loaded ++;
  7179. if ( scope.onProgress !== undefined ) {
  7180. scope.onProgress( url, loaded, total );
  7181. }
  7182. if ( loaded === total && scope.onLoad !== undefined ) {
  7183. scope.onLoad();
  7184. }
  7185. };
  7186. };
  7187. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  7188. /**
  7189. * @author mrdoob / http://mrdoob.com/
  7190. */
  7191. THREE.BufferGeometryLoader = function ( manager ) {
  7192. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7193. };
  7194. THREE.BufferGeometryLoader.prototype = {
  7195. constructor: THREE.BufferGeometryLoader,
  7196. load: function ( url, onLoad, onProgress, onError ) {
  7197. var scope = this;
  7198. var loader = new THREE.XHRLoader();
  7199. loader.setCrossOrigin( this.crossOrigin );
  7200. loader.load( url, function ( text ) {
  7201. onLoad( scope.parse( JSON.parse( text ) ) );
  7202. } );
  7203. },
  7204. setCrossOrigin: function ( value ) {
  7205. this.crossOrigin = value;
  7206. },
  7207. parse: function ( json ) {
  7208. var geometry = new THREE.BufferGeometry();
  7209. var attributes = json.attributes;
  7210. var offsets = json.offsets;
  7211. var boundingSphere = json.boundingSphere;
  7212. for ( var key in attributes ) {
  7213. var attribute = attributes[ key ];
  7214. geometry.attributes[ key ] = {
  7215. itemSize: attribute.itemSize,
  7216. array: new self[ attribute.type ]( attribute.array )
  7217. }
  7218. }
  7219. if ( offsets !== undefined ) {
  7220. geometry.offsets = JSON.parse( JSON.stringify( offsets ) );
  7221. }
  7222. if ( boundingSphere !== undefined ) {
  7223. geometry.boundingSphere = new THREE.Sphere(
  7224. new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ),
  7225. boundingSphere.radius
  7226. );
  7227. }
  7228. return geometry;
  7229. }
  7230. };
  7231. /**
  7232. * @author mrdoob / http://mrdoob.com/
  7233. */
  7234. THREE.Geometry2Loader = function ( manager ) {
  7235. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7236. };
  7237. THREE.Geometry2Loader.prototype = {
  7238. constructor: THREE.Geometry2Loader,
  7239. load: function ( url, onLoad, onProgress, onError ) {
  7240. var scope = this;
  7241. var loader = new THREE.XHRLoader();
  7242. loader.setCrossOrigin( this.crossOrigin );
  7243. loader.load( url, function ( text ) {
  7244. onLoad( scope.parse( JSON.parse( text ) ) );
  7245. } );
  7246. },
  7247. setCrossOrigin: function ( value ) {
  7248. this.crossOrigin = value;
  7249. },
  7250. parse: function ( json ) {
  7251. var geometry = new THREE.Geometry2( json.vertices.length / 3 );
  7252. var attributes = [ 'vertices', 'normals', 'uvs' ];
  7253. var boundingSphere = json.boundingSphere;
  7254. for ( var key in attributes ) {
  7255. var attribute = attributes[ key ];
  7256. geometry[ attribute ].set( json[ attribute ] );
  7257. }
  7258. if ( boundingSphere !== undefined ) {
  7259. geometry.boundingSphere = new THREE.Sphere(
  7260. new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ),
  7261. boundingSphere.radius
  7262. );
  7263. }
  7264. return geometry;
  7265. }
  7266. };
  7267. /**
  7268. * @author mrdoob / http://mrdoob.com/
  7269. */
  7270. THREE.MaterialLoader = function ( manager ) {
  7271. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7272. };
  7273. THREE.MaterialLoader.prototype = {
  7274. constructor: THREE.MaterialLoader,
  7275. load: function ( url, onLoad, onProgress, onError ) {
  7276. var scope = this;
  7277. var loader = new THREE.XHRLoader();
  7278. loader.setCrossOrigin( this.crossOrigin );
  7279. loader.load( url, function ( text ) {
  7280. onLoad( scope.parse( JSON.parse( text ) ) );
  7281. } );
  7282. },
  7283. setCrossOrigin: function ( value ) {
  7284. this.crossOrigin = value;
  7285. },
  7286. parse: function ( json ) {
  7287. var material = new THREE[ json.type ];
  7288. if ( json.color !== undefined ) material.color.setHex( json.color );
  7289. if ( json.ambient !== undefined ) material.ambient.setHex( json.ambient );
  7290. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  7291. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  7292. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  7293. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  7294. if ( json.blending !== undefined ) material.blending = json.blending;
  7295. if ( json.side !== undefined ) material.side = json.side;
  7296. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  7297. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  7298. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  7299. if ( json.materials !== undefined ) {
  7300. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  7301. material.materials.push( this.parse( json.materials[ i ] ) );
  7302. }
  7303. }
  7304. return material;
  7305. }
  7306. };
  7307. /**
  7308. * @author mrdoob / http://mrdoob.com/
  7309. */
  7310. THREE.ObjectLoader = function ( manager ) {
  7311. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7312. };
  7313. THREE.ObjectLoader.prototype = {
  7314. constructor: THREE.ObjectLoader,
  7315. load: function ( url, onLoad, onProgress, onError ) {
  7316. var scope = this;
  7317. var loader = new THREE.XHRLoader( scope.manager );
  7318. loader.setCrossOrigin( this.crossOrigin );
  7319. loader.load( url, function ( text ) {
  7320. onLoad( scope.parse( JSON.parse( text ) ) );
  7321. } );
  7322. },
  7323. setCrossOrigin: function ( value ) {
  7324. this.crossOrigin = value;
  7325. },
  7326. parse: function ( json ) {
  7327. var geometries = this.parseGeometries( json.geometries );
  7328. var materials = this.parseMaterials( json.materials );
  7329. var object = this.parseObject( json.object, geometries, materials );
  7330. return object;
  7331. },
  7332. parseGeometries: function ( json ) {
  7333. var geometries = {};
  7334. if ( json !== undefined ) {
  7335. var geometryLoader = new THREE.JSONLoader();
  7336. var geometry2Loader = new THREE.Geometry2Loader();
  7337. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  7338. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7339. var geometry;
  7340. var data = json[ i ];
  7341. switch ( data.type ) {
  7342. case 'PlaneGeometry':
  7343. geometry = new THREE.PlaneGeometry(
  7344. data.width,
  7345. data.height,
  7346. data.widthSegments,
  7347. data.heightSegments
  7348. );
  7349. break;
  7350. case 'BoxGeometry':
  7351. case 'CubeGeometry': // DEPRECATED
  7352. geometry = new THREE.BoxGeometry(
  7353. data.width,
  7354. data.height,
  7355. data.depth,
  7356. data.widthSegments,
  7357. data.heightSegments,
  7358. data.depthSegments
  7359. );
  7360. break;
  7361. case 'CircleGeometry':
  7362. geometry = new THREE.CircleGeometry(
  7363. data.radius,
  7364. data.segments
  7365. );
  7366. break;
  7367. case 'CylinderGeometry':
  7368. geometry = new THREE.CylinderGeometry(
  7369. data.radiusTop,
  7370. data.radiusBottom,
  7371. data.height,
  7372. data.radialSegments,
  7373. data.heightSegments,
  7374. data.openEnded
  7375. );
  7376. break;
  7377. case 'SphereGeometry':
  7378. geometry = new THREE.SphereGeometry(
  7379. data.radius,
  7380. data.widthSegments,
  7381. data.heightSegments,
  7382. data.phiStart,
  7383. data.phiLength,
  7384. data.thetaStart,
  7385. data.thetaLength
  7386. );
  7387. break;
  7388. case 'IcosahedronGeometry':
  7389. geometry = new THREE.IcosahedronGeometry(
  7390. data.radius,
  7391. data.detail
  7392. );
  7393. break;
  7394. case 'TorusGeometry':
  7395. geometry = new THREE.TorusGeometry(
  7396. data.radius,
  7397. data.tube,
  7398. data.radialSegments,
  7399. data.tubularSegments,
  7400. data.arc
  7401. );
  7402. break;
  7403. case 'TorusKnotGeometry':
  7404. geometry = new THREE.TorusKnotGeometry(
  7405. data.radius,
  7406. data.tube,
  7407. data.radialSegments,
  7408. data.tubularSegments,
  7409. data.p,
  7410. data.q,
  7411. data.heightScale
  7412. );
  7413. break;
  7414. case 'BufferGeometry':
  7415. geometry = bufferGeometryLoader.parse( data.data );
  7416. break;
  7417. case 'Geometry2':
  7418. geometry = geometry2Loader.parse( data.data );
  7419. break;
  7420. case 'Geometry':
  7421. geometry = geometryLoader.parse( data.data ).geometry;
  7422. break;
  7423. }
  7424. geometry.uuid = data.uuid;
  7425. if ( data.name !== undefined ) geometry.name = data.name;
  7426. geometries[ data.uuid ] = geometry;
  7427. }
  7428. }
  7429. return geometries;
  7430. },
  7431. parseMaterials: function ( json ) {
  7432. var materials = {};
  7433. if ( json !== undefined ) {
  7434. var loader = new THREE.MaterialLoader();
  7435. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7436. var data = json[ i ];
  7437. var material = loader.parse( data );
  7438. material.uuid = data.uuid;
  7439. if ( data.name !== undefined ) material.name = data.name;
  7440. materials[ data.uuid ] = material;
  7441. }
  7442. }
  7443. return materials;
  7444. },
  7445. parseObject: function () {
  7446. var matrix = new THREE.Matrix4();
  7447. return function ( data, geometries, materials ) {
  7448. var object;
  7449. switch ( data.type ) {
  7450. case 'Scene':
  7451. object = new THREE.Scene();
  7452. break;
  7453. case 'PerspectiveCamera':
  7454. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  7455. break;
  7456. case 'OrthographicCamera':
  7457. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  7458. break;
  7459. case 'AmbientLight':
  7460. object = new THREE.AmbientLight( data.color );
  7461. break;
  7462. case 'DirectionalLight':
  7463. object = new THREE.DirectionalLight( data.color, data.intensity );
  7464. break;
  7465. case 'PointLight':
  7466. object = new THREE.PointLight( data.color, data.intensity, data.distance );
  7467. break;
  7468. case 'SpotLight':
  7469. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent );
  7470. break;
  7471. case 'HemisphereLight':
  7472. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  7473. break;
  7474. case 'Mesh':
  7475. var geometry = geometries[ data.geometry ];
  7476. var material = materials[ data.material ];
  7477. if ( geometry === undefined ) {
  7478. console.error( 'THREE.ObjectLoader: Undefined geometry ' + data.geometry );
  7479. }
  7480. if ( material === undefined ) {
  7481. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  7482. }
  7483. object = new THREE.Mesh( geometry, material );
  7484. break;
  7485. case 'Sprite':
  7486. var material = materials[ data.material ];
  7487. if ( material === undefined ) {
  7488. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  7489. }
  7490. object = new THREE.Sprite( material );
  7491. break;
  7492. default:
  7493. object = new THREE.Object3D();
  7494. }
  7495. object.uuid = data.uuid;
  7496. if ( data.name !== undefined ) object.name = data.name;
  7497. if ( data.matrix !== undefined ) {
  7498. matrix.fromArray( data.matrix );
  7499. matrix.decompose( object.position, object.quaternion, object.scale );
  7500. } else {
  7501. if ( data.position !== undefined ) object.position.fromArray( data.position );
  7502. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  7503. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  7504. }
  7505. if ( data.visible !== undefined ) object.visible = data.visible;
  7506. if ( data.userData !== undefined ) object.userData = data.userData;
  7507. if ( data.children !== undefined ) {
  7508. for ( var child in data.children ) {
  7509. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  7510. }
  7511. }
  7512. return object;
  7513. }
  7514. }()
  7515. };
  7516. /**
  7517. * @author alteredq / http://alteredqualia.com/
  7518. */
  7519. THREE.SceneLoader = function () {
  7520. this.onLoadStart = function () {};
  7521. this.onLoadProgress = function() {};
  7522. this.onLoadComplete = function () {};
  7523. this.callbackSync = function () {};
  7524. this.callbackProgress = function () {};
  7525. this.geometryHandlers = {};
  7526. this.hierarchyHandlers = {};
  7527. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  7528. };
  7529. THREE.SceneLoader.prototype = {
  7530. constructor: THREE.SceneLoader,
  7531. load: function ( url, onLoad, onProgress, onError ) {
  7532. var scope = this;
  7533. var loader = new THREE.XHRLoader( scope.manager );
  7534. loader.setCrossOrigin( this.crossOrigin );
  7535. loader.load( url, function ( text ) {
  7536. scope.parse( JSON.parse( text ), onLoad, url );
  7537. } );
  7538. },
  7539. setCrossOrigin: function ( value ) {
  7540. this.crossOrigin = value;
  7541. },
  7542. addGeometryHandler: function ( typeID, loaderClass ) {
  7543. this.geometryHandlers[ typeID ] = { "loaderClass": loaderClass };
  7544. },
  7545. addHierarchyHandler: function ( typeID, loaderClass ) {
  7546. this.hierarchyHandlers[ typeID ] = { "loaderClass": loaderClass };
  7547. },
  7548. parse: function ( json, callbackFinished, url ) {
  7549. var scope = this;
  7550. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  7551. var geometry, material, camera, fog,
  7552. texture, images, color,
  7553. light, hex, intensity,
  7554. counter_models, counter_textures,
  7555. total_models, total_textures,
  7556. result;
  7557. var target_array = [];
  7558. var data = json;
  7559. // async geometry loaders
  7560. for ( var typeID in this.geometryHandlers ) {
  7561. var loaderClass = this.geometryHandlers[ typeID ][ "loaderClass" ];
  7562. this.geometryHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  7563. }
  7564. // async hierachy loaders
  7565. for ( var typeID in this.hierarchyHandlers ) {
  7566. var loaderClass = this.hierarchyHandlers[ typeID ][ "loaderClass" ];
  7567. this.hierarchyHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  7568. }
  7569. counter_models = 0;
  7570. counter_textures = 0;
  7571. result = {
  7572. scene: new THREE.Scene(),
  7573. geometries: {},
  7574. face_materials: {},
  7575. materials: {},
  7576. textures: {},
  7577. objects: {},
  7578. cameras: {},
  7579. lights: {},
  7580. fogs: {},
  7581. empties: {},
  7582. groups: {}
  7583. };
  7584. if ( data.transform ) {
  7585. var position = data.transform.position,
  7586. rotation = data.transform.rotation,
  7587. scale = data.transform.scale;
  7588. if ( position ) {
  7589. result.scene.position.fromArray( position );
  7590. }
  7591. if ( rotation ) {
  7592. result.scene.rotation.fromArray( rotation );
  7593. }
  7594. if ( scale ) {
  7595. result.scene.scale.fromArray( scale );
  7596. }
  7597. if ( position || rotation || scale ) {
  7598. result.scene.updateMatrix();
  7599. result.scene.updateMatrixWorld();
  7600. }
  7601. }
  7602. function get_url( source_url, url_type ) {
  7603. if ( url_type == "relativeToHTML" ) {
  7604. return source_url;
  7605. } else {
  7606. return urlBase + source_url;
  7607. }
  7608. };
  7609. // toplevel loader function, delegates to handle_children
  7610. function handle_objects() {
  7611. handle_children( result.scene, data.objects );
  7612. }
  7613. // handle all the children from the loaded json and attach them to given parent
  7614. function handle_children( parent, children ) {
  7615. var mat, dst, pos, rot, scl, quat;
  7616. for ( var objID in children ) {
  7617. // check by id if child has already been handled,
  7618. // if not, create new object
  7619. var object = result.objects[ objID ];
  7620. var objJSON = children[ objID ];
  7621. if ( object === undefined ) {
  7622. // meshes
  7623. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7624. if ( objJSON.loading === undefined ) {
  7625. var reservedTypes = {
  7626. "type": 1, "url": 1, "material": 1,
  7627. "position": 1, "rotation": 1, "scale" : 1,
  7628. "visible": 1, "children": 1, "userData": 1,
  7629. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1
  7630. };
  7631. var loaderParameters = {};
  7632. for ( var parType in objJSON ) {
  7633. if ( ! ( parType in reservedTypes ) ) {
  7634. loaderParameters[ parType ] = objJSON[ parType ];
  7635. }
  7636. }
  7637. material = result.materials[ objJSON.material ];
  7638. objJSON.loading = true;
  7639. var loader = scope.hierarchyHandlers[ objJSON.type ][ "loaderObject" ];
  7640. // ColladaLoader
  7641. if ( loader.options ) {
  7642. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  7643. // UTF8Loader
  7644. // OBJLoader
  7645. } else {
  7646. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  7647. }
  7648. }
  7649. } else if ( objJSON.geometry !== undefined ) {
  7650. geometry = result.geometries[ objJSON.geometry ];
  7651. // geometry already loaded
  7652. if ( geometry ) {
  7653. var needsTangents = false;
  7654. material = result.materials[ objJSON.material ];
  7655. needsTangents = material instanceof THREE.ShaderMaterial;
  7656. pos = objJSON.position;
  7657. rot = objJSON.rotation;
  7658. scl = objJSON.scale;
  7659. mat = objJSON.matrix;
  7660. quat = objJSON.quaternion;
  7661. // use materials from the model file
  7662. // if there is no material specified in the object
  7663. if ( ! objJSON.material ) {
  7664. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7665. }
  7666. // use materials from the model file
  7667. // if there is just empty face material
  7668. // (must create new material as each model has its own face material)
  7669. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  7670. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7671. }
  7672. if ( material instanceof THREE.MeshFaceMaterial ) {
  7673. for ( var i = 0; i < material.materials.length; i ++ ) {
  7674. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  7675. }
  7676. }
  7677. if ( needsTangents ) {
  7678. geometry.computeTangents();
  7679. }
  7680. if ( objJSON.skin ) {
  7681. object = new THREE.SkinnedMesh( geometry, material );
  7682. } else if ( objJSON.morph ) {
  7683. object = new THREE.MorphAnimMesh( geometry, material );
  7684. if ( objJSON.duration !== undefined ) {
  7685. object.duration = objJSON.duration;
  7686. }
  7687. if ( objJSON.time !== undefined ) {
  7688. object.time = objJSON.time;
  7689. }
  7690. if ( objJSON.mirroredLoop !== undefined ) {
  7691. object.mirroredLoop = objJSON.mirroredLoop;
  7692. }
  7693. if ( material.morphNormals ) {
  7694. geometry.computeMorphNormals();
  7695. }
  7696. } else {
  7697. object = new THREE.Mesh( geometry, material );
  7698. }
  7699. object.name = objID;
  7700. if ( mat ) {
  7701. object.matrixAutoUpdate = false;
  7702. object.matrix.set(
  7703. mat[0], mat[1], mat[2], mat[3],
  7704. mat[4], mat[5], mat[6], mat[7],
  7705. mat[8], mat[9], mat[10], mat[11],
  7706. mat[12], mat[13], mat[14], mat[15]
  7707. );
  7708. } else {
  7709. object.position.fromArray( pos );
  7710. if ( quat ) {
  7711. object.quaternion.fromArray( quat );
  7712. } else {
  7713. object.rotation.fromArray( rot );
  7714. }
  7715. object.scale.fromArray( scl );
  7716. }
  7717. object.visible = objJSON.visible;
  7718. object.castShadow = objJSON.castShadow;
  7719. object.receiveShadow = objJSON.receiveShadow;
  7720. parent.add( object );
  7721. result.objects[ objID ] = object;
  7722. }
  7723. // lights
  7724. } else if ( objJSON.type === "AmbientLight" || objJSON.type === "PointLight" ||
  7725. objJSON.type === "DirectionalLight" || objJSON.type === "SpotLight" ||
  7726. objJSON.type === "HemisphereLight" || objJSON.type === "AreaLight" ) {
  7727. var color = objJSON.color;
  7728. var intensity = objJSON.intensity;
  7729. var distance = objJSON.distance;
  7730. var position = objJSON.position;
  7731. var rotation = objJSON.rotation;
  7732. switch ( objJSON.type ) {
  7733. case 'AmbientLight':
  7734. light = new THREE.AmbientLight( color );
  7735. break;
  7736. case 'PointLight':
  7737. light = new THREE.PointLight( color, intensity, distance );
  7738. light.position.fromArray( position );
  7739. break;
  7740. case 'DirectionalLight':
  7741. light = new THREE.DirectionalLight( color, intensity );
  7742. light.position.fromArray( objJSON.direction );
  7743. break;
  7744. case 'SpotLight':
  7745. light = new THREE.SpotLight( color, intensity, distance, 1 );
  7746. light.angle = objJSON.angle;
  7747. light.position.fromArray( position );
  7748. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  7749. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  7750. break;
  7751. case 'HemisphereLight':
  7752. light = new THREE.DirectionalLight( color, intensity, distance );
  7753. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  7754. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  7755. break;
  7756. case 'AreaLight':
  7757. light = new THREE.AreaLight(color, intensity);
  7758. light.position.fromArray( position );
  7759. light.width = objJSON.size;
  7760. light.height = objJSON.size_y;
  7761. break;
  7762. }
  7763. parent.add( light );
  7764. light.name = objID;
  7765. result.lights[ objID ] = light;
  7766. result.objects[ objID ] = light;
  7767. // cameras
  7768. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  7769. pos = objJSON.position;
  7770. rot = objJSON.rotation;
  7771. quat = objJSON.quaternion;
  7772. if ( objJSON.type === "PerspectiveCamera" ) {
  7773. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  7774. } else if ( objJSON.type === "OrthographicCamera" ) {
  7775. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  7776. }
  7777. camera.name = objID;
  7778. camera.position.fromArray( pos );
  7779. if ( quat !== undefined ) {
  7780. camera.quaternion.fromArray( quat );
  7781. } else if ( rot !== undefined ) {
  7782. camera.rotation.fromArray( rot );
  7783. }
  7784. parent.add( camera );
  7785. result.cameras[ objID ] = camera;
  7786. result.objects[ objID ] = camera;
  7787. // pure Object3D
  7788. } else {
  7789. pos = objJSON.position;
  7790. rot = objJSON.rotation;
  7791. scl = objJSON.scale;
  7792. quat = objJSON.quaternion;
  7793. object = new THREE.Object3D();
  7794. object.name = objID;
  7795. object.position.fromArray( pos );
  7796. if ( quat ) {
  7797. object.quaternion.fromArray( quat );
  7798. } else {
  7799. object.rotation.fromArray( rot );
  7800. }
  7801. object.scale.fromArray( scl );
  7802. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  7803. parent.add( object );
  7804. result.objects[ objID ] = object;
  7805. result.empties[ objID ] = object;
  7806. }
  7807. if ( object ) {
  7808. if ( objJSON.userData !== undefined ) {
  7809. for ( var key in objJSON.userData ) {
  7810. var value = objJSON.userData[ key ];
  7811. object.userData[ key ] = value;
  7812. }
  7813. }
  7814. if ( objJSON.groups !== undefined ) {
  7815. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  7816. var groupID = objJSON.groups[ i ];
  7817. if ( result.groups[ groupID ] === undefined ) {
  7818. result.groups[ groupID ] = [];
  7819. }
  7820. result.groups[ groupID ].push( objID );
  7821. }
  7822. }
  7823. }
  7824. }
  7825. if ( object !== undefined && objJSON.children !== undefined ) {
  7826. handle_children( object, objJSON.children );
  7827. }
  7828. }
  7829. };
  7830. function handle_mesh( geo, mat, id ) {
  7831. result.geometries[ id ] = geo;
  7832. result.face_materials[ id ] = mat;
  7833. handle_objects();
  7834. };
  7835. function handle_hierarchy( node, id, parent, material, obj ) {
  7836. var p = obj.position;
  7837. var r = obj.rotation;
  7838. var q = obj.quaternion;
  7839. var s = obj.scale;
  7840. node.position.fromArray( p );
  7841. if ( q ) {
  7842. node.quaternion.fromArray( q );
  7843. } else {
  7844. node.rotation.fromArray( r );
  7845. }
  7846. node.scale.fromArray( s );
  7847. // override children materials
  7848. // if object material was specified in JSON explicitly
  7849. if ( material ) {
  7850. node.traverse( function ( child ) {
  7851. child.material = material;
  7852. } );
  7853. }
  7854. // override children visibility
  7855. // with root node visibility as specified in JSON
  7856. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  7857. node.traverse( function ( child ) {
  7858. child.visible = visible;
  7859. } );
  7860. parent.add( node );
  7861. node.name = id;
  7862. result.objects[ id ] = node;
  7863. handle_objects();
  7864. };
  7865. function create_callback_geometry( id ) {
  7866. return function ( geo, mat ) {
  7867. geo.name = id;
  7868. handle_mesh( geo, mat, id );
  7869. counter_models -= 1;
  7870. scope.onLoadComplete();
  7871. async_callback_gate();
  7872. }
  7873. };
  7874. function create_callback_hierachy( id, parent, material, obj ) {
  7875. return function ( event ) {
  7876. var result;
  7877. // loaders which use EventDispatcher
  7878. if ( event.content ) {
  7879. result = event.content;
  7880. // ColladaLoader
  7881. } else if ( event.dae ) {
  7882. result = event.scene;
  7883. // UTF8Loader
  7884. } else {
  7885. result = event;
  7886. }
  7887. handle_hierarchy( result, id, parent, material, obj );
  7888. counter_models -= 1;
  7889. scope.onLoadComplete();
  7890. async_callback_gate();
  7891. }
  7892. };
  7893. function create_callback_embed( id ) {
  7894. return function ( geo, mat ) {
  7895. geo.name = id;
  7896. result.geometries[ id ] = geo;
  7897. result.face_materials[ id ] = mat;
  7898. }
  7899. };
  7900. function async_callback_gate() {
  7901. var progress = {
  7902. totalModels : total_models,
  7903. totalTextures : total_textures,
  7904. loadedModels : total_models - counter_models,
  7905. loadedTextures : total_textures - counter_textures
  7906. };
  7907. scope.callbackProgress( progress, result );
  7908. scope.onLoadProgress();
  7909. if ( counter_models === 0 && counter_textures === 0 ) {
  7910. finalize();
  7911. callbackFinished( result );
  7912. }
  7913. };
  7914. function finalize() {
  7915. // take care of targets which could be asynchronously loaded objects
  7916. for ( var i = 0; i < target_array.length; i ++ ) {
  7917. var ta = target_array[ i ];
  7918. var target = result.objects[ ta.targetName ];
  7919. if ( target ) {
  7920. ta.object.target = target;
  7921. } else {
  7922. // if there was error and target of specified name doesn't exist in the scene file
  7923. // create instead dummy target
  7924. // (target must be added to scene explicitly as parent is already added)
  7925. ta.object.target = new THREE.Object3D();
  7926. result.scene.add( ta.object.target );
  7927. }
  7928. ta.object.target.userData.targetInverse = ta.object;
  7929. }
  7930. };
  7931. var callbackTexture = function ( count ) {
  7932. counter_textures -= count;
  7933. async_callback_gate();
  7934. scope.onLoadComplete();
  7935. };
  7936. // must use this instead of just directly calling callbackTexture
  7937. // because of closure in the calling context loop
  7938. var generateTextureCallback = function ( count ) {
  7939. return function () {
  7940. callbackTexture( count );
  7941. };
  7942. };
  7943. function traverse_json_hierarchy( objJSON, callback ) {
  7944. callback( objJSON );
  7945. if ( objJSON.children !== undefined ) {
  7946. for ( var objChildID in objJSON.children ) {
  7947. traverse_json_hierarchy( objJSON.children[ objChildID ], callback );
  7948. }
  7949. }
  7950. };
  7951. // first go synchronous elements
  7952. // fogs
  7953. var fogID, fogJSON;
  7954. for ( fogID in data.fogs ) {
  7955. fogJSON = data.fogs[ fogID ];
  7956. if ( fogJSON.type === "linear" ) {
  7957. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  7958. } else if ( fogJSON.type === "exp2" ) {
  7959. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  7960. }
  7961. color = fogJSON.color;
  7962. fog.color.setRGB( color[0], color[1], color[2] );
  7963. result.fogs[ fogID ] = fog;
  7964. }
  7965. // now come potentially asynchronous elements
  7966. // geometries
  7967. // count how many geometries will be loaded asynchronously
  7968. var geoID, geoJSON;
  7969. for ( geoID in data.geometries ) {
  7970. geoJSON = data.geometries[ geoID ];
  7971. if ( geoJSON.type in this.geometryHandlers ) {
  7972. counter_models += 1;
  7973. scope.onLoadStart();
  7974. }
  7975. }
  7976. // count how many hierarchies will be loaded asynchronously
  7977. for ( var objID in data.objects ) {
  7978. traverse_json_hierarchy( data.objects[ objID ], function ( objJSON ) {
  7979. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7980. counter_models += 1;
  7981. scope.onLoadStart();
  7982. }
  7983. });
  7984. }
  7985. total_models = counter_models;
  7986. for ( geoID in data.geometries ) {
  7987. geoJSON = data.geometries[ geoID ];
  7988. if ( geoJSON.type === "cube" ) {
  7989. geometry = new THREE.BoxGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  7990. geometry.name = geoID;
  7991. result.geometries[ geoID ] = geometry;
  7992. } else if ( geoJSON.type === "plane" ) {
  7993. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  7994. geometry.name = geoID;
  7995. result.geometries[ geoID ] = geometry;
  7996. } else if ( geoJSON.type === "sphere" ) {
  7997. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  7998. geometry.name = geoID;
  7999. result.geometries[ geoID ] = geometry;
  8000. } else if ( geoJSON.type === "cylinder" ) {
  8001. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  8002. geometry.name = geoID;
  8003. result.geometries[ geoID ] = geometry;
  8004. } else if ( geoJSON.type === "torus" ) {
  8005. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  8006. geometry.name = geoID;
  8007. result.geometries[ geoID ] = geometry;
  8008. } else if ( geoJSON.type === "icosahedron" ) {
  8009. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  8010. geometry.name = geoID;
  8011. result.geometries[ geoID ] = geometry;
  8012. } else if ( geoJSON.type in this.geometryHandlers ) {
  8013. var loaderParameters = {};
  8014. for ( var parType in geoJSON ) {
  8015. if ( parType !== "type" && parType !== "url" ) {
  8016. loaderParameters[ parType ] = geoJSON[ parType ];
  8017. }
  8018. }
  8019. var loader = this.geometryHandlers[ geoJSON.type ][ "loaderObject" ];
  8020. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  8021. } else if ( geoJSON.type === "embedded" ) {
  8022. var modelJson = data.embeds[ geoJSON.id ],
  8023. texture_path = "";
  8024. // pass metadata along to jsonLoader so it knows the format version
  8025. modelJson.metadata = data.metadata;
  8026. if ( modelJson ) {
  8027. var jsonLoader = this.geometryHandlers[ "ascii" ][ "loaderObject" ];
  8028. var model = jsonLoader.parse( modelJson, texture_path );
  8029. create_callback_embed( geoID )( model.geometry, model.materials );
  8030. }
  8031. }
  8032. }
  8033. // textures
  8034. // count how many textures will be loaded asynchronously
  8035. var textureID, textureJSON;
  8036. for ( textureID in data.textures ) {
  8037. textureJSON = data.textures[ textureID ];
  8038. if ( textureJSON.url instanceof Array ) {
  8039. counter_textures += textureJSON.url.length;
  8040. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  8041. scope.onLoadStart();
  8042. }
  8043. } else {
  8044. counter_textures += 1;
  8045. scope.onLoadStart();
  8046. }
  8047. }
  8048. total_textures = counter_textures;
  8049. for ( textureID in data.textures ) {
  8050. textureJSON = data.textures[ textureID ];
  8051. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  8052. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  8053. }
  8054. if ( textureJSON.url instanceof Array ) {
  8055. var count = textureJSON.url.length;
  8056. var url_array = [];
  8057. for( var i = 0; i < count; i ++ ) {
  8058. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  8059. }
  8060. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  8061. if ( isCompressed ) {
  8062. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  8063. } else {
  8064. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  8065. }
  8066. } else {
  8067. var isCompressed = /\.dds$/i.test( textureJSON.url );
  8068. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  8069. var textureCallback = generateTextureCallback( 1 );
  8070. if ( isCompressed ) {
  8071. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  8072. } else {
  8073. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  8074. }
  8075. if ( THREE[ textureJSON.minFilter ] !== undefined )
  8076. texture.minFilter = THREE[ textureJSON.minFilter ];
  8077. if ( THREE[ textureJSON.magFilter ] !== undefined )
  8078. texture.magFilter = THREE[ textureJSON.magFilter ];
  8079. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  8080. if ( textureJSON.repeat ) {
  8081. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  8082. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  8083. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  8084. }
  8085. if ( textureJSON.offset ) {
  8086. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  8087. }
  8088. // handle wrap after repeat so that default repeat can be overriden
  8089. if ( textureJSON.wrap ) {
  8090. var wrapMap = {
  8091. "repeat": THREE.RepeatWrapping,
  8092. "mirror": THREE.MirroredRepeatWrapping
  8093. }
  8094. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  8095. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  8096. }
  8097. }
  8098. result.textures[ textureID ] = texture;
  8099. }
  8100. // materials
  8101. var matID, matJSON;
  8102. var parID;
  8103. for ( matID in data.materials ) {
  8104. matJSON = data.materials[ matID ];
  8105. for ( parID in matJSON.parameters ) {
  8106. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  8107. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  8108. } else if ( parID === "shading" ) {
  8109. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  8110. } else if ( parID === "side" ) {
  8111. if ( matJSON.parameters[ parID ] == "double" ) {
  8112. matJSON.parameters[ parID ] = THREE.DoubleSide;
  8113. } else if ( matJSON.parameters[ parID ] == "back" ) {
  8114. matJSON.parameters[ parID ] = THREE.BackSide;
  8115. } else {
  8116. matJSON.parameters[ parID ] = THREE.FrontSide;
  8117. }
  8118. } else if ( parID === "blending" ) {
  8119. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  8120. } else if ( parID === "combine" ) {
  8121. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  8122. } else if ( parID === "vertexColors" ) {
  8123. if ( matJSON.parameters[ parID ] == "face" ) {
  8124. matJSON.parameters[ parID ] = THREE.FaceColors;
  8125. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  8126. } else if ( matJSON.parameters[ parID ] ) {
  8127. matJSON.parameters[ parID ] = THREE.VertexColors;
  8128. }
  8129. } else if ( parID === "wrapRGB" ) {
  8130. var v3 = matJSON.parameters[ parID ];
  8131. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  8132. }
  8133. }
  8134. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  8135. matJSON.parameters.transparent = true;
  8136. }
  8137. if ( matJSON.parameters.normalMap ) {
  8138. var shader = THREE.ShaderLib[ "normalmap" ];
  8139. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  8140. var diffuse = matJSON.parameters.color;
  8141. var specular = matJSON.parameters.specular;
  8142. var ambient = matJSON.parameters.ambient;
  8143. var shininess = matJSON.parameters.shininess;
  8144. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  8145. if ( matJSON.parameters.normalScale ) {
  8146. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  8147. }
  8148. if ( matJSON.parameters.map ) {
  8149. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  8150. uniforms[ "enableDiffuse" ].value = true;
  8151. }
  8152. if ( matJSON.parameters.envMap ) {
  8153. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  8154. uniforms[ "enableReflection" ].value = true;
  8155. uniforms[ "reflectivity" ].value = matJSON.parameters.reflectivity;
  8156. }
  8157. if ( matJSON.parameters.lightMap ) {
  8158. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  8159. uniforms[ "enableAO" ].value = true;
  8160. }
  8161. if ( matJSON.parameters.specularMap ) {
  8162. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  8163. uniforms[ "enableSpecular" ].value = true;
  8164. }
  8165. if ( matJSON.parameters.displacementMap ) {
  8166. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  8167. uniforms[ "enableDisplacement" ].value = true;
  8168. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  8169. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  8170. }
  8171. uniforms[ "diffuse" ].value.setHex( diffuse );
  8172. uniforms[ "specular" ].value.setHex( specular );
  8173. uniforms[ "ambient" ].value.setHex( ambient );
  8174. uniforms[ "shininess" ].value = shininess;
  8175. if ( matJSON.parameters.opacity ) {
  8176. uniforms[ "opacity" ].value = matJSON.parameters.opacity;
  8177. }
  8178. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  8179. material = new THREE.ShaderMaterial( parameters );
  8180. } else {
  8181. material = new THREE[ matJSON.type ]( matJSON.parameters );
  8182. }
  8183. material.name = matID;
  8184. result.materials[ matID ] = material;
  8185. }
  8186. // second pass through all materials to initialize MeshFaceMaterials
  8187. // that could be referring to other materials out of order
  8188. for ( matID in data.materials ) {
  8189. matJSON = data.materials[ matID ];
  8190. if ( matJSON.parameters.materials ) {
  8191. var materialArray = [];
  8192. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  8193. var label = matJSON.parameters.materials[ i ];
  8194. materialArray.push( result.materials[ label ] );
  8195. }
  8196. result.materials[ matID ].materials = materialArray;
  8197. }
  8198. }
  8199. // objects ( synchronous init of procedural primitives )
  8200. handle_objects();
  8201. // defaults
  8202. if ( result.cameras && data.defaults.camera ) {
  8203. result.currentCamera = result.cameras[ data.defaults.camera ];
  8204. }
  8205. if ( result.fogs && data.defaults.fog ) {
  8206. result.scene.fog = result.fogs[ data.defaults.fog ];
  8207. }
  8208. // synchronous callback
  8209. scope.callbackSync( result );
  8210. // just in case there are no async elements
  8211. async_callback_gate();
  8212. }
  8213. }
  8214. /**
  8215. * @author mrdoob / http://mrdoob.com/
  8216. */
  8217. THREE.TextureLoader = function ( manager ) {
  8218. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  8219. };
  8220. THREE.TextureLoader.prototype = {
  8221. constructor: THREE.TextureLoader,
  8222. load: function ( url, onLoad, onProgress, onError ) {
  8223. var scope = this;
  8224. var loader = new THREE.ImageLoader( scope.manager );
  8225. loader.setCrossOrigin( this.crossOrigin );
  8226. loader.load( url, function ( image ) {
  8227. var texture = new THREE.Texture( image );
  8228. texture.needsUpdate = true;
  8229. if ( onLoad !== undefined ) {
  8230. onLoad( texture );
  8231. }
  8232. } );
  8233. },
  8234. setCrossOrigin: function ( value ) {
  8235. this.crossOrigin = value;
  8236. }
  8237. };
  8238. /**
  8239. * @author mrdoob / http://mrdoob.com/
  8240. * @author alteredq / http://alteredqualia.com/
  8241. */
  8242. THREE.Material = function () {
  8243. this.id = THREE.MaterialIdCount ++;
  8244. this.uuid = THREE.Math.generateUUID();
  8245. this.name = '';
  8246. this.side = THREE.FrontSide;
  8247. this.opacity = 1;
  8248. this.transparent = false;
  8249. this.blending = THREE.NormalBlending;
  8250. this.blendSrc = THREE.SrcAlphaFactor;
  8251. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  8252. this.blendEquation = THREE.AddEquation;
  8253. this.depthTest = true;
  8254. this.depthWrite = true;
  8255. this.polygonOffset = false;
  8256. this.polygonOffsetFactor = 0;
  8257. this.polygonOffsetUnits = 0;
  8258. this.alphaTest = 0;
  8259. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  8260. this.visible = true;
  8261. this.needsUpdate = true;
  8262. };
  8263. THREE.Material.prototype = {
  8264. constructor: THREE.Material,
  8265. setValues: function ( values ) {
  8266. if ( values === undefined ) return;
  8267. for ( var key in values ) {
  8268. var newValue = values[ key ];
  8269. if ( newValue === undefined ) {
  8270. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  8271. continue;
  8272. }
  8273. if ( key in this ) {
  8274. var currentValue = this[ key ];
  8275. if ( currentValue instanceof THREE.Color ) {
  8276. currentValue.set( newValue );
  8277. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  8278. currentValue.copy( newValue );
  8279. } else if ( key == 'overdraw') {
  8280. // ensure overdraw is backwards-compatable with legacy boolean type
  8281. this[ key ] = Number(newValue);
  8282. } else {
  8283. this[ key ] = newValue;
  8284. }
  8285. }
  8286. }
  8287. },
  8288. clone: function ( material ) {
  8289. if ( material === undefined ) material = new THREE.Material();
  8290. material.name = this.name;
  8291. material.side = this.side;
  8292. material.opacity = this.opacity;
  8293. material.transparent = this.transparent;
  8294. material.blending = this.blending;
  8295. material.blendSrc = this.blendSrc;
  8296. material.blendDst = this.blendDst;
  8297. material.blendEquation = this.blendEquation;
  8298. material.depthTest = this.depthTest;
  8299. material.depthWrite = this.depthWrite;
  8300. material.polygonOffset = this.polygonOffset;
  8301. material.polygonOffsetFactor = this.polygonOffsetFactor;
  8302. material.polygonOffsetUnits = this.polygonOffsetUnits;
  8303. material.alphaTest = this.alphaTest;
  8304. material.overdraw = this.overdraw;
  8305. material.visible = this.visible;
  8306. return material;
  8307. },
  8308. dispose: function () {
  8309. this.dispatchEvent( { type: 'dispose' } );
  8310. }
  8311. };
  8312. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  8313. THREE.MaterialIdCount = 0;
  8314. /**
  8315. * @author mrdoob / http://mrdoob.com/
  8316. * @author alteredq / http://alteredqualia.com/
  8317. *
  8318. * parameters = {
  8319. * color: <hex>,
  8320. * opacity: <float>,
  8321. *
  8322. * blending: THREE.NormalBlending,
  8323. * depthTest: <bool>,
  8324. * depthWrite: <bool>,
  8325. *
  8326. * linewidth: <float>,
  8327. * linecap: "round",
  8328. * linejoin: "round",
  8329. *
  8330. * vertexColors: <bool>
  8331. *
  8332. * fog: <bool>
  8333. * }
  8334. */
  8335. THREE.LineBasicMaterial = function ( parameters ) {
  8336. THREE.Material.call( this );
  8337. this.color = new THREE.Color( 0xffffff );
  8338. this.linewidth = 1;
  8339. this.linecap = 'round';
  8340. this.linejoin = 'round';
  8341. this.vertexColors = false;
  8342. this.fog = true;
  8343. this.setValues( parameters );
  8344. };
  8345. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8346. THREE.LineBasicMaterial.prototype.clone = function () {
  8347. var material = new THREE.LineBasicMaterial();
  8348. THREE.Material.prototype.clone.call( this, material );
  8349. material.color.copy( this.color );
  8350. material.linewidth = this.linewidth;
  8351. material.linecap = this.linecap;
  8352. material.linejoin = this.linejoin;
  8353. material.vertexColors = this.vertexColors;
  8354. material.fog = this.fog;
  8355. return material;
  8356. };
  8357. /**
  8358. * @author alteredq / http://alteredqualia.com/
  8359. *
  8360. * parameters = {
  8361. * color: <hex>,
  8362. * opacity: <float>,
  8363. *
  8364. * blending: THREE.NormalBlending,
  8365. * depthTest: <bool>,
  8366. * depthWrite: <bool>,
  8367. *
  8368. * linewidth: <float>,
  8369. *
  8370. * scale: <float>,
  8371. * dashSize: <float>,
  8372. * gapSize: <float>,
  8373. *
  8374. * vertexColors: <bool>
  8375. *
  8376. * fog: <bool>
  8377. * }
  8378. */
  8379. THREE.LineDashedMaterial = function ( parameters ) {
  8380. THREE.Material.call( this );
  8381. this.color = new THREE.Color( 0xffffff );
  8382. this.linewidth = 1;
  8383. this.scale = 1;
  8384. this.dashSize = 3;
  8385. this.gapSize = 1;
  8386. this.vertexColors = false;
  8387. this.fog = true;
  8388. this.setValues( parameters );
  8389. };
  8390. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  8391. THREE.LineDashedMaterial.prototype.clone = function () {
  8392. var material = new THREE.LineDashedMaterial();
  8393. THREE.Material.prototype.clone.call( this, material );
  8394. material.color.copy( this.color );
  8395. material.linewidth = this.linewidth;
  8396. material.scale = this.scale;
  8397. material.dashSize = this.dashSize;
  8398. material.gapSize = this.gapSize;
  8399. material.vertexColors = this.vertexColors;
  8400. material.fog = this.fog;
  8401. return material;
  8402. };
  8403. /**
  8404. * @author mrdoob / http://mrdoob.com/
  8405. * @author alteredq / http://alteredqualia.com/
  8406. *
  8407. * parameters = {
  8408. * color: <hex>,
  8409. * opacity: <float>,
  8410. * map: new THREE.Texture( <Image> ),
  8411. *
  8412. * lightMap: new THREE.Texture( <Image> ),
  8413. *
  8414. * specularMap: new THREE.Texture( <Image> ),
  8415. *
  8416. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8417. * combine: THREE.Multiply,
  8418. * reflectivity: <float>,
  8419. * refractionRatio: <float>,
  8420. *
  8421. * shading: THREE.SmoothShading,
  8422. * blending: THREE.NormalBlending,
  8423. * depthTest: <bool>,
  8424. * depthWrite: <bool>,
  8425. *
  8426. * wireframe: <boolean>,
  8427. * wireframeLinewidth: <float>,
  8428. *
  8429. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8430. *
  8431. * skinning: <bool>,
  8432. * morphTargets: <bool>,
  8433. *
  8434. * fog: <bool>
  8435. * }
  8436. */
  8437. THREE.MeshBasicMaterial = function ( parameters ) {
  8438. THREE.Material.call( this );
  8439. this.color = new THREE.Color( 0xffffff ); // emissive
  8440. this.map = null;
  8441. this.lightMap = null;
  8442. this.specularMap = null;
  8443. this.envMap = null;
  8444. this.combine = THREE.MultiplyOperation;
  8445. this.reflectivity = 1;
  8446. this.refractionRatio = 0.98;
  8447. this.fog = true;
  8448. this.shading = THREE.SmoothShading;
  8449. this.wireframe = false;
  8450. this.wireframeLinewidth = 1;
  8451. this.wireframeLinecap = 'round';
  8452. this.wireframeLinejoin = 'round';
  8453. this.vertexColors = THREE.NoColors;
  8454. this.skinning = false;
  8455. this.morphTargets = false;
  8456. this.setValues( parameters );
  8457. };
  8458. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8459. THREE.MeshBasicMaterial.prototype.clone = function () {
  8460. var material = new THREE.MeshBasicMaterial();
  8461. THREE.Material.prototype.clone.call( this, material );
  8462. material.color.copy( this.color );
  8463. material.map = this.map;
  8464. material.lightMap = this.lightMap;
  8465. material.specularMap = this.specularMap;
  8466. material.envMap = this.envMap;
  8467. material.combine = this.combine;
  8468. material.reflectivity = this.reflectivity;
  8469. material.refractionRatio = this.refractionRatio;
  8470. material.fog = this.fog;
  8471. material.shading = this.shading;
  8472. material.wireframe = this.wireframe;
  8473. material.wireframeLinewidth = this.wireframeLinewidth;
  8474. material.wireframeLinecap = this.wireframeLinecap;
  8475. material.wireframeLinejoin = this.wireframeLinejoin;
  8476. material.vertexColors = this.vertexColors;
  8477. material.skinning = this.skinning;
  8478. material.morphTargets = this.morphTargets;
  8479. return material;
  8480. };
  8481. /**
  8482. * @author mrdoob / http://mrdoob.com/
  8483. * @author alteredq / http://alteredqualia.com/
  8484. *
  8485. * parameters = {
  8486. * color: <hex>,
  8487. * ambient: <hex>,
  8488. * emissive: <hex>,
  8489. * opacity: <float>,
  8490. *
  8491. * map: new THREE.Texture( <Image> ),
  8492. *
  8493. * lightMap: new THREE.Texture( <Image> ),
  8494. *
  8495. * specularMap: new THREE.Texture( <Image> ),
  8496. *
  8497. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8498. * combine: THREE.Multiply,
  8499. * reflectivity: <float>,
  8500. * refractionRatio: <float>,
  8501. *
  8502. * shading: THREE.SmoothShading,
  8503. * blending: THREE.NormalBlending,
  8504. * depthTest: <bool>,
  8505. * depthWrite: <bool>,
  8506. *
  8507. * wireframe: <boolean>,
  8508. * wireframeLinewidth: <float>,
  8509. *
  8510. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8511. *
  8512. * skinning: <bool>,
  8513. * morphTargets: <bool>,
  8514. * morphNormals: <bool>,
  8515. *
  8516. * fog: <bool>
  8517. * }
  8518. */
  8519. THREE.MeshLambertMaterial = function ( parameters ) {
  8520. THREE.Material.call( this );
  8521. this.color = new THREE.Color( 0xffffff ); // diffuse
  8522. this.ambient = new THREE.Color( 0xffffff );
  8523. this.emissive = new THREE.Color( 0x000000 );
  8524. this.wrapAround = false;
  8525. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8526. this.map = null;
  8527. this.lightMap = null;
  8528. this.specularMap = null;
  8529. this.envMap = null;
  8530. this.combine = THREE.MultiplyOperation;
  8531. this.reflectivity = 1;
  8532. this.refractionRatio = 0.98;
  8533. this.fog = true;
  8534. this.shading = THREE.SmoothShading;
  8535. this.wireframe = false;
  8536. this.wireframeLinewidth = 1;
  8537. this.wireframeLinecap = 'round';
  8538. this.wireframeLinejoin = 'round';
  8539. this.vertexColors = THREE.NoColors;
  8540. this.skinning = false;
  8541. this.morphTargets = false;
  8542. this.morphNormals = false;
  8543. this.setValues( parameters );
  8544. };
  8545. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  8546. THREE.MeshLambertMaterial.prototype.clone = function () {
  8547. var material = new THREE.MeshLambertMaterial();
  8548. THREE.Material.prototype.clone.call( this, material );
  8549. material.color.copy( this.color );
  8550. material.ambient.copy( this.ambient );
  8551. material.emissive.copy( this.emissive );
  8552. material.wrapAround = this.wrapAround;
  8553. material.wrapRGB.copy( this.wrapRGB );
  8554. material.map = this.map;
  8555. material.lightMap = this.lightMap;
  8556. material.specularMap = this.specularMap;
  8557. material.envMap = this.envMap;
  8558. material.combine = this.combine;
  8559. material.reflectivity = this.reflectivity;
  8560. material.refractionRatio = this.refractionRatio;
  8561. material.fog = this.fog;
  8562. material.shading = this.shading;
  8563. material.wireframe = this.wireframe;
  8564. material.wireframeLinewidth = this.wireframeLinewidth;
  8565. material.wireframeLinecap = this.wireframeLinecap;
  8566. material.wireframeLinejoin = this.wireframeLinejoin;
  8567. material.vertexColors = this.vertexColors;
  8568. material.skinning = this.skinning;
  8569. material.morphTargets = this.morphTargets;
  8570. material.morphNormals = this.morphNormals;
  8571. return material;
  8572. };
  8573. /**
  8574. * @author mrdoob / http://mrdoob.com/
  8575. * @author alteredq / http://alteredqualia.com/
  8576. *
  8577. * parameters = {
  8578. * color: <hex>,
  8579. * ambient: <hex>,
  8580. * emissive: <hex>,
  8581. * specular: <hex>,
  8582. * shininess: <float>,
  8583. * opacity: <float>,
  8584. *
  8585. * map: new THREE.Texture( <Image> ),
  8586. *
  8587. * lightMap: new THREE.Texture( <Image> ),
  8588. *
  8589. * bumpMap: new THREE.Texture( <Image> ),
  8590. * bumpScale: <float>,
  8591. *
  8592. * normalMap: new THREE.Texture( <Image> ),
  8593. * normalScale: <Vector2>,
  8594. *
  8595. * specularMap: new THREE.Texture( <Image> ),
  8596. *
  8597. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8598. * combine: THREE.Multiply,
  8599. * reflectivity: <float>,
  8600. * refractionRatio: <float>,
  8601. *
  8602. * shading: THREE.SmoothShading,
  8603. * blending: THREE.NormalBlending,
  8604. * depthTest: <bool>,
  8605. * depthWrite: <bool>,
  8606. *
  8607. * wireframe: <boolean>,
  8608. * wireframeLinewidth: <float>,
  8609. *
  8610. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8611. *
  8612. * skinning: <bool>,
  8613. * morphTargets: <bool>,
  8614. * morphNormals: <bool>,
  8615. *
  8616. * fog: <bool>
  8617. * }
  8618. */
  8619. THREE.MeshPhongMaterial = function ( parameters ) {
  8620. THREE.Material.call( this );
  8621. this.color = new THREE.Color( 0xffffff ); // diffuse
  8622. this.ambient = new THREE.Color( 0xffffff );
  8623. this.emissive = new THREE.Color( 0x000000 );
  8624. this.specular = new THREE.Color( 0x111111 );
  8625. this.shininess = 30;
  8626. this.metal = false;
  8627. this.wrapAround = false;
  8628. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8629. this.map = null;
  8630. this.lightMap = null;
  8631. this.bumpMap = null;
  8632. this.bumpScale = 1;
  8633. this.normalMap = null;
  8634. this.normalScale = new THREE.Vector2( 1, 1 );
  8635. this.specularMap = null;
  8636. this.envMap = null;
  8637. this.combine = THREE.MultiplyOperation;
  8638. this.reflectivity = 1;
  8639. this.refractionRatio = 0.98;
  8640. this.fog = true;
  8641. this.shading = THREE.SmoothShading;
  8642. this.wireframe = false;
  8643. this.wireframeLinewidth = 1;
  8644. this.wireframeLinecap = 'round';
  8645. this.wireframeLinejoin = 'round';
  8646. this.vertexColors = THREE.NoColors;
  8647. this.skinning = false;
  8648. this.morphTargets = false;
  8649. this.morphNormals = false;
  8650. this.setValues( parameters );
  8651. };
  8652. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  8653. THREE.MeshPhongMaterial.prototype.clone = function () {
  8654. var material = new THREE.MeshPhongMaterial();
  8655. THREE.Material.prototype.clone.call( this, material );
  8656. material.color.copy( this.color );
  8657. material.ambient.copy( this.ambient );
  8658. material.emissive.copy( this.emissive );
  8659. material.specular.copy( this.specular );
  8660. material.shininess = this.shininess;
  8661. material.metal = this.metal;
  8662. material.wrapAround = this.wrapAround;
  8663. material.wrapRGB.copy( this.wrapRGB );
  8664. material.map = this.map;
  8665. material.lightMap = this.lightMap;
  8666. material.bumpMap = this.bumpMap;
  8667. material.bumpScale = this.bumpScale;
  8668. material.normalMap = this.normalMap;
  8669. material.normalScale.copy( this.normalScale );
  8670. material.specularMap = this.specularMap;
  8671. material.envMap = this.envMap;
  8672. material.combine = this.combine;
  8673. material.reflectivity = this.reflectivity;
  8674. material.refractionRatio = this.refractionRatio;
  8675. material.fog = this.fog;
  8676. material.shading = this.shading;
  8677. material.wireframe = this.wireframe;
  8678. material.wireframeLinewidth = this.wireframeLinewidth;
  8679. material.wireframeLinecap = this.wireframeLinecap;
  8680. material.wireframeLinejoin = this.wireframeLinejoin;
  8681. material.vertexColors = this.vertexColors;
  8682. material.skinning = this.skinning;
  8683. material.morphTargets = this.morphTargets;
  8684. material.morphNormals = this.morphNormals;
  8685. return material;
  8686. };
  8687. /**
  8688. * @author mrdoob / http://mrdoob.com/
  8689. * @author alteredq / http://alteredqualia.com/
  8690. *
  8691. * parameters = {
  8692. * opacity: <float>,
  8693. *
  8694. * blending: THREE.NormalBlending,
  8695. * depthTest: <bool>,
  8696. * depthWrite: <bool>,
  8697. *
  8698. * wireframe: <boolean>,
  8699. * wireframeLinewidth: <float>
  8700. * }
  8701. */
  8702. THREE.MeshDepthMaterial = function ( parameters ) {
  8703. THREE.Material.call( this );
  8704. this.wireframe = false;
  8705. this.wireframeLinewidth = 1;
  8706. this.setValues( parameters );
  8707. };
  8708. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  8709. THREE.MeshDepthMaterial.prototype.clone = function () {
  8710. var material = new THREE.MeshDepthMaterial();
  8711. THREE.Material.prototype.clone.call( this, material );
  8712. material.wireframe = this.wireframe;
  8713. material.wireframeLinewidth = this.wireframeLinewidth;
  8714. return material;
  8715. };
  8716. /**
  8717. * @author mrdoob / http://mrdoob.com/
  8718. *
  8719. * parameters = {
  8720. * opacity: <float>,
  8721. *
  8722. * shading: THREE.FlatShading,
  8723. * blending: THREE.NormalBlending,
  8724. * depthTest: <bool>,
  8725. * depthWrite: <bool>,
  8726. *
  8727. * wireframe: <boolean>,
  8728. * wireframeLinewidth: <float>
  8729. * }
  8730. */
  8731. THREE.MeshNormalMaterial = function ( parameters ) {
  8732. THREE.Material.call( this, parameters );
  8733. this.shading = THREE.FlatShading;
  8734. this.wireframe = false;
  8735. this.wireframeLinewidth = 1;
  8736. this.morphTargets = false;
  8737. this.setValues( parameters );
  8738. };
  8739. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  8740. THREE.MeshNormalMaterial.prototype.clone = function () {
  8741. var material = new THREE.MeshNormalMaterial();
  8742. THREE.Material.prototype.clone.call( this, material );
  8743. material.shading = this.shading;
  8744. material.wireframe = this.wireframe;
  8745. material.wireframeLinewidth = this.wireframeLinewidth;
  8746. return material;
  8747. };
  8748. /**
  8749. * @author mrdoob / http://mrdoob.com/
  8750. */
  8751. THREE.MeshFaceMaterial = function ( materials ) {
  8752. this.materials = materials instanceof Array ? materials : [];
  8753. };
  8754. THREE.MeshFaceMaterial.prototype.clone = function () {
  8755. var material = new THREE.MeshFaceMaterial();
  8756. for ( var i = 0; i < this.materials.length; i ++ ) {
  8757. material.materials.push( this.materials[ i ].clone() );
  8758. }
  8759. return material;
  8760. };
  8761. /**
  8762. * @author mrdoob / http://mrdoob.com/
  8763. * @author alteredq / http://alteredqualia.com/
  8764. *
  8765. * parameters = {
  8766. * color: <hex>,
  8767. * opacity: <float>,
  8768. * map: new THREE.Texture( <Image> ),
  8769. *
  8770. * size: <float>,
  8771. *
  8772. * blending: THREE.NormalBlending,
  8773. * depthTest: <bool>,
  8774. * depthWrite: <bool>,
  8775. *
  8776. * vertexColors: <bool>,
  8777. *
  8778. * fog: <bool>
  8779. * }
  8780. */
  8781. THREE.ParticleSystemMaterial = function ( parameters ) {
  8782. THREE.Material.call( this );
  8783. this.color = new THREE.Color( 0xffffff );
  8784. this.map = null;
  8785. this.size = 1;
  8786. this.sizeAttenuation = true;
  8787. this.vertexColors = false;
  8788. this.fog = true;
  8789. this.setValues( parameters );
  8790. };
  8791. THREE.ParticleSystemMaterial.prototype = Object.create( THREE.Material.prototype );
  8792. THREE.ParticleSystemMaterial.prototype.clone = function () {
  8793. var material = new THREE.ParticleSystemMaterial();
  8794. THREE.Material.prototype.clone.call( this, material );
  8795. material.color.copy( this.color );
  8796. material.map = this.map;
  8797. material.size = this.size;
  8798. material.sizeAttenuation = this.sizeAttenuation;
  8799. material.vertexColors = this.vertexColors;
  8800. material.fog = this.fog;
  8801. return material;
  8802. };
  8803. // backwards compatibility
  8804. THREE.ParticleBasicMaterial = THREE.ParticleSystemMaterial;
  8805. /**
  8806. * @author alteredq / http://alteredqualia.com/
  8807. *
  8808. * parameters = {
  8809. * fragmentShader: <string>,
  8810. * vertexShader: <string>,
  8811. *
  8812. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  8813. *
  8814. * defines: { "label" : "value" },
  8815. *
  8816. * shading: THREE.SmoothShading,
  8817. * blending: THREE.NormalBlending,
  8818. * depthTest: <bool>,
  8819. * depthWrite: <bool>,
  8820. *
  8821. * wireframe: <boolean>,
  8822. * wireframeLinewidth: <float>,
  8823. *
  8824. * lights: <bool>,
  8825. *
  8826. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8827. *
  8828. * skinning: <bool>,
  8829. * morphTargets: <bool>,
  8830. * morphNormals: <bool>,
  8831. *
  8832. * fog: <bool>
  8833. * }
  8834. */
  8835. THREE.ShaderMaterial = function ( parameters ) {
  8836. THREE.Material.call( this );
  8837. this.fragmentShader = "void main() {}";
  8838. this.vertexShader = "void main() {}";
  8839. this.uniforms = {};
  8840. this.defines = {};
  8841. this.attributes = null;
  8842. this.shading = THREE.SmoothShading;
  8843. this.linewidth = 1;
  8844. this.wireframe = false;
  8845. this.wireframeLinewidth = 1;
  8846. this.fog = false; // set to use scene fog
  8847. this.lights = false; // set to use scene lights
  8848. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  8849. this.skinning = false; // set to use skinning attribute streams
  8850. this.morphTargets = false; // set to use morph targets
  8851. this.morphNormals = false; // set to use morph normals
  8852. // When rendered geometry doesn't include these attributes but the material does,
  8853. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8854. this.defaultAttributeValues = {
  8855. "color" : [ 1, 1, 1],
  8856. "uv" : [ 0, 0 ],
  8857. "uv2" : [ 0, 0 ]
  8858. };
  8859. // By default, bind position to attribute index 0. In WebGL, attribute 0
  8860. // should always be used to avoid potentially expensive emulation.
  8861. this.index0AttributeName = "position";
  8862. this.setValues( parameters );
  8863. };
  8864. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  8865. THREE.ShaderMaterial.prototype.clone = function () {
  8866. var material = new THREE.ShaderMaterial();
  8867. THREE.Material.prototype.clone.call( this, material );
  8868. material.fragmentShader = this.fragmentShader;
  8869. material.vertexShader = this.vertexShader;
  8870. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  8871. material.attributes = this.attributes;
  8872. material.defines = this.defines;
  8873. material.shading = this.shading;
  8874. material.wireframe = this.wireframe;
  8875. material.wireframeLinewidth = this.wireframeLinewidth;
  8876. material.fog = this.fog;
  8877. material.lights = this.lights;
  8878. material.vertexColors = this.vertexColors;
  8879. material.skinning = this.skinning;
  8880. material.morphTargets = this.morphTargets;
  8881. material.morphNormals = this.morphNormals;
  8882. return material;
  8883. };
  8884. /**
  8885. * @author alteredq / http://alteredqualia.com/
  8886. *
  8887. * parameters = {
  8888. * color: <hex>,
  8889. * opacity: <float>,
  8890. * map: new THREE.Texture( <Image> ),
  8891. *
  8892. * blending: THREE.NormalBlending,
  8893. * depthTest: <bool>,
  8894. * depthWrite: <bool>,
  8895. *
  8896. * uvOffset: new THREE.Vector2(),
  8897. * uvScale: new THREE.Vector2(),
  8898. *
  8899. * fog: <bool>
  8900. * }
  8901. */
  8902. THREE.SpriteMaterial = function ( parameters ) {
  8903. THREE.Material.call( this );
  8904. // defaults
  8905. this.color = new THREE.Color( 0xffffff );
  8906. this.map = null;
  8907. this.rotation = 0;
  8908. this.fog = false;
  8909. // set parameters
  8910. this.setValues( parameters );
  8911. };
  8912. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  8913. THREE.SpriteMaterial.prototype.clone = function () {
  8914. var material = new THREE.SpriteMaterial();
  8915. THREE.Material.prototype.clone.call( this, material );
  8916. material.color.copy( this.color );
  8917. material.map = this.map;
  8918. material.rotation = this.rotation;
  8919. material.fog = this.fog;
  8920. return material;
  8921. };
  8922. /**
  8923. * @author mrdoob / http://mrdoob.com/
  8924. *
  8925. * parameters = {
  8926. * color: <hex>,
  8927. * program: <function>,
  8928. * opacity: <float>,
  8929. * blending: THREE.NormalBlending
  8930. * }
  8931. */
  8932. THREE.SpriteCanvasMaterial = function ( parameters ) {
  8933. THREE.Material.call( this );
  8934. this.color = new THREE.Color( 0xffffff );
  8935. this.program = function ( context, color ) {};
  8936. this.setValues( parameters );
  8937. };
  8938. THREE.SpriteCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  8939. THREE.SpriteCanvasMaterial.prototype.clone = function () {
  8940. var material = new THREE.SpriteCanvasMaterial();
  8941. THREE.Material.prototype.clone.call( this, material );
  8942. material.color.copy( this.color );
  8943. material.program = this.program;
  8944. return material;
  8945. };
  8946. // backwards compatibility
  8947. THREE.ParticleCanvasMaterial = THREE.SpriteCanvasMaterial;
  8948. /**
  8949. * @author mrdoob / http://mrdoob.com/
  8950. * @author alteredq / http://alteredqualia.com/
  8951. * @author szimek / https://github.com/szimek/
  8952. */
  8953. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8954. this.id = THREE.TextureIdCount ++;
  8955. this.uuid = THREE.Math.generateUUID();
  8956. this.name = '';
  8957. this.image = image;
  8958. this.mipmaps = [];
  8959. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  8960. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  8961. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  8962. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  8963. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  8964. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  8965. this.format = format !== undefined ? format : THREE.RGBAFormat;
  8966. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  8967. this.offset = new THREE.Vector2( 0, 0 );
  8968. this.repeat = new THREE.Vector2( 1, 1 );
  8969. this.generateMipmaps = true;
  8970. this.premultiplyAlpha = false;
  8971. this.flipY = true;
  8972. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  8973. this._needsUpdate = false;
  8974. this.onUpdate = null;
  8975. };
  8976. THREE.Texture.prototype = {
  8977. constructor: THREE.Texture,
  8978. get needsUpdate () {
  8979. return this._needsUpdate;
  8980. },
  8981. set needsUpdate ( value ) {
  8982. if ( value === true ) this.update();
  8983. this._needsUpdate = value;
  8984. },
  8985. clone: function ( texture ) {
  8986. if ( texture === undefined ) texture = new THREE.Texture();
  8987. texture.image = this.image;
  8988. texture.mipmaps = this.mipmaps.slice(0);
  8989. texture.mapping = this.mapping;
  8990. texture.wrapS = this.wrapS;
  8991. texture.wrapT = this.wrapT;
  8992. texture.magFilter = this.magFilter;
  8993. texture.minFilter = this.minFilter;
  8994. texture.anisotropy = this.anisotropy;
  8995. texture.format = this.format;
  8996. texture.type = this.type;
  8997. texture.offset.copy( this.offset );
  8998. texture.repeat.copy( this.repeat );
  8999. texture.generateMipmaps = this.generateMipmaps;
  9000. texture.premultiplyAlpha = this.premultiplyAlpha;
  9001. texture.flipY = this.flipY;
  9002. texture.unpackAlignment = this.unpackAlignment;
  9003. return texture;
  9004. },
  9005. update: function () {
  9006. this.dispatchEvent( { type: 'update' } );
  9007. },
  9008. dispose: function () {
  9009. this.dispatchEvent( { type: 'dispose' } );
  9010. }
  9011. };
  9012. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  9013. THREE.TextureIdCount = 0;
  9014. /**
  9015. * @author alteredq / http://alteredqualia.com/
  9016. */
  9017. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  9018. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  9019. this.image = { width: width, height: height };
  9020. this.mipmaps = mipmaps;
  9021. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  9022. };
  9023. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  9024. THREE.CompressedTexture.prototype.clone = function () {
  9025. var texture = new THREE.CompressedTexture();
  9026. THREE.Texture.prototype.clone.call( this, texture );
  9027. return texture;
  9028. };
  9029. /**
  9030. * @author alteredq / http://alteredqualia.com/
  9031. */
  9032. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  9033. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  9034. this.image = { data: data, width: width, height: height };
  9035. };
  9036. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  9037. THREE.DataTexture.prototype.clone = function () {
  9038. var texture = new THREE.DataTexture();
  9039. THREE.Texture.prototype.clone.call( this, texture );
  9040. return texture;
  9041. };
  9042. /**
  9043. * @author alteredq / http://alteredqualia.com/
  9044. */
  9045. THREE.ParticleSystem = function ( geometry, material ) {
  9046. THREE.Object3D.call( this );
  9047. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9048. this.material = material !== undefined ? material : new THREE.ParticleSystemMaterial( { color: Math.random() * 0xffffff } );
  9049. this.sortParticles = false;
  9050. this.frustumCulled = false;
  9051. };
  9052. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  9053. THREE.ParticleSystem.prototype.clone = function ( object ) {
  9054. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  9055. object.sortParticles = this.sortParticles;
  9056. THREE.Object3D.prototype.clone.call( this, object );
  9057. return object;
  9058. };
  9059. /**
  9060. * @author mrdoob / http://mrdoob.com/
  9061. */
  9062. THREE.Line = function ( geometry, material, type ) {
  9063. THREE.Object3D.call( this );
  9064. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9065. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  9066. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  9067. };
  9068. THREE.LineStrip = 0;
  9069. THREE.LinePieces = 1;
  9070. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  9071. THREE.Line.prototype.clone = function ( object ) {
  9072. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  9073. THREE.Object3D.prototype.clone.call( this, object );
  9074. return object;
  9075. };
  9076. /**
  9077. * @author mrdoob / http://mrdoob.com/
  9078. * @author alteredq / http://alteredqualia.com/
  9079. * @author mikael emtinger / http://gomo.se/
  9080. * @author jonobr1 / http://jonobr1.com/
  9081. */
  9082. THREE.Mesh = function ( geometry, material ) {
  9083. THREE.Object3D.call( this );
  9084. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9085. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  9086. this.updateMorphTargets();
  9087. };
  9088. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  9089. THREE.Mesh.prototype.updateMorphTargets = function () {
  9090. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  9091. this.morphTargetBase = -1;
  9092. this.morphTargetForcedOrder = [];
  9093. this.morphTargetInfluences = [];
  9094. this.morphTargetDictionary = {};
  9095. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  9096. this.morphTargetInfluences.push( 0 );
  9097. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  9098. }
  9099. }
  9100. };
  9101. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  9102. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  9103. return this.morphTargetDictionary[ name ];
  9104. }
  9105. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  9106. return 0;
  9107. };
  9108. THREE.Mesh.prototype.clone = function ( object ) {
  9109. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  9110. THREE.Object3D.prototype.clone.call( this, object );
  9111. return object;
  9112. };
  9113. /**
  9114. * @author mikael emtinger / http://gomo.se/
  9115. * @author alteredq / http://alteredqualia.com/
  9116. */
  9117. THREE.Bone = function( belongsToSkin ) {
  9118. THREE.Object3D.call( this );
  9119. this.skin = belongsToSkin;
  9120. this.skinMatrix = new THREE.Matrix4();
  9121. };
  9122. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  9123. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  9124. // update local
  9125. if ( this.matrixAutoUpdate ) {
  9126. forceUpdate |= this.updateMatrix();
  9127. }
  9128. // update skin matrix
  9129. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  9130. if( parentSkinMatrix ) {
  9131. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  9132. } else {
  9133. this.skinMatrix.copy( this.matrix );
  9134. }
  9135. this.matrixWorldNeedsUpdate = false;
  9136. forceUpdate = true;
  9137. }
  9138. // update children
  9139. var child, i, l = this.children.length;
  9140. for ( i = 0; i < l; i ++ ) {
  9141. this.children[ i ].update( this.skinMatrix, forceUpdate );
  9142. }
  9143. };
  9144. /**
  9145. * @author mikael emtinger / http://gomo.se/
  9146. * @author alteredq / http://alteredqualia.com/
  9147. */
  9148. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  9149. THREE.Mesh.call( this, geometry, material );
  9150. //
  9151. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  9152. // init bones
  9153. this.identityMatrix = new THREE.Matrix4();
  9154. this.bones = [];
  9155. this.boneMatrices = [];
  9156. var b, bone, gbone, p, q, s;
  9157. if ( this.geometry && this.geometry.bones !== undefined ) {
  9158. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  9159. gbone = this.geometry.bones[ b ];
  9160. p = gbone.pos;
  9161. q = gbone.rotq;
  9162. s = gbone.scl;
  9163. bone = this.addBone();
  9164. bone.name = gbone.name;
  9165. bone.position.set( p[0], p[1], p[2] );
  9166. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  9167. if ( s !== undefined ) {
  9168. bone.scale.set( s[0], s[1], s[2] );
  9169. } else {
  9170. bone.scale.set( 1, 1, 1 );
  9171. }
  9172. }
  9173. for ( b = 0; b < this.bones.length; b ++ ) {
  9174. gbone = this.geometry.bones[ b ];
  9175. bone = this.bones[ b ];
  9176. if ( gbone.parent === -1 ) {
  9177. this.add( bone );
  9178. } else {
  9179. this.bones[ gbone.parent ].add( bone );
  9180. }
  9181. }
  9182. //
  9183. var nBones = this.bones.length;
  9184. if ( this.useVertexTexture ) {
  9185. // layout (1 matrix = 4 pixels)
  9186. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  9187. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  9188. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  9189. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  9190. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  9191. var size;
  9192. if ( nBones > 256 )
  9193. size = 64;
  9194. else if ( nBones > 64 )
  9195. size = 32;
  9196. else if ( nBones > 16 )
  9197. size = 16;
  9198. else
  9199. size = 8;
  9200. this.boneTextureWidth = size;
  9201. this.boneTextureHeight = size;
  9202. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  9203. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  9204. this.boneTexture.minFilter = THREE.NearestFilter;
  9205. this.boneTexture.magFilter = THREE.NearestFilter;
  9206. this.boneTexture.generateMipmaps = false;
  9207. this.boneTexture.flipY = false;
  9208. } else {
  9209. this.boneMatrices = new Float32Array( 16 * nBones );
  9210. }
  9211. this.pose();
  9212. }
  9213. };
  9214. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  9215. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  9216. if ( bone === undefined ) {
  9217. bone = new THREE.Bone( this );
  9218. }
  9219. this.bones.push( bone );
  9220. return bone;
  9221. };
  9222. THREE.SkinnedMesh.prototype.updateMatrixWorld = function () {
  9223. var offsetMatrix = new THREE.Matrix4();
  9224. return function ( force ) {
  9225. this.matrixAutoUpdate && this.updateMatrix();
  9226. // update matrixWorld
  9227. if ( this.matrixWorldNeedsUpdate || force ) {
  9228. if ( this.parent ) {
  9229. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9230. } else {
  9231. this.matrixWorld.copy( this.matrix );
  9232. }
  9233. this.matrixWorldNeedsUpdate = false;
  9234. force = true;
  9235. }
  9236. // update children
  9237. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  9238. var child = this.children[ i ];
  9239. if ( child instanceof THREE.Bone ) {
  9240. child.update( this.identityMatrix, false );
  9241. } else {
  9242. child.updateMatrixWorld( true );
  9243. }
  9244. }
  9245. // make a snapshot of the bones' rest position
  9246. if ( this.boneInverses == undefined ) {
  9247. this.boneInverses = [];
  9248. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9249. var inverse = new THREE.Matrix4();
  9250. inverse.getInverse( this.bones[ b ].skinMatrix );
  9251. this.boneInverses.push( inverse );
  9252. }
  9253. }
  9254. // flatten bone matrices to array
  9255. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9256. // compute the offset between the current and the original transform;
  9257. // TODO: we could get rid of this multiplication step if the skinMatrix
  9258. // was already representing the offset; however, this requires some
  9259. // major changes to the animation system
  9260. offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  9261. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  9262. }
  9263. if ( this.useVertexTexture ) {
  9264. this.boneTexture.needsUpdate = true;
  9265. }
  9266. };
  9267. }();
  9268. THREE.SkinnedMesh.prototype.pose = function () {
  9269. this.updateMatrixWorld( true );
  9270. this.normalizeSkinWeights();
  9271. };
  9272. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  9273. if ( this.geometry instanceof THREE.Geometry ) {
  9274. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  9275. var sw = this.geometry.skinWeights[ i ];
  9276. var scale = 1.0 / sw.lengthManhattan();
  9277. if ( scale !== Infinity ) {
  9278. sw.multiplyScalar( scale );
  9279. } else {
  9280. sw.set( 1 ); // this will be normalized by the shader anyway
  9281. }
  9282. }
  9283. } else {
  9284. // skinning weights assumed to be normalized for THREE.BufferGeometry
  9285. }
  9286. };
  9287. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  9288. if ( object === undefined ) {
  9289. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  9290. }
  9291. THREE.Mesh.prototype.clone.call( this, object );
  9292. return object;
  9293. };
  9294. /**
  9295. * @author alteredq / http://alteredqualia.com/
  9296. */
  9297. THREE.MorphAnimMesh = function ( geometry, material ) {
  9298. THREE.Mesh.call( this, geometry, material );
  9299. // API
  9300. this.duration = 1000; // milliseconds
  9301. this.mirroredLoop = false;
  9302. this.time = 0;
  9303. // internals
  9304. this.lastKeyframe = 0;
  9305. this.currentKeyframe = 0;
  9306. this.direction = 1;
  9307. this.directionBackwards = false;
  9308. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  9309. };
  9310. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  9311. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  9312. this.startKeyframe = start;
  9313. this.endKeyframe = end;
  9314. this.length = this.endKeyframe - this.startKeyframe + 1;
  9315. };
  9316. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  9317. this.direction = 1;
  9318. this.directionBackwards = false;
  9319. };
  9320. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  9321. this.direction = -1;
  9322. this.directionBackwards = true;
  9323. };
  9324. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  9325. var geometry = this.geometry;
  9326. if ( ! geometry.animations ) geometry.animations = {};
  9327. var firstAnimation, animations = geometry.animations;
  9328. var pattern = /([a-z]+)(\d+)/;
  9329. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  9330. var morph = geometry.morphTargets[ i ];
  9331. var parts = morph.name.match( pattern );
  9332. if ( parts && parts.length > 1 ) {
  9333. var label = parts[ 1 ];
  9334. var num = parts[ 2 ];
  9335. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  9336. var animation = animations[ label ];
  9337. if ( i < animation.start ) animation.start = i;
  9338. if ( i > animation.end ) animation.end = i;
  9339. if ( ! firstAnimation ) firstAnimation = label;
  9340. }
  9341. }
  9342. geometry.firstAnimation = firstAnimation;
  9343. };
  9344. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  9345. if ( ! this.geometry.animations ) this.geometry.animations = {};
  9346. this.geometry.animations[ label ] = { start: start, end: end };
  9347. };
  9348. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  9349. var animation = this.geometry.animations[ label ];
  9350. if ( animation ) {
  9351. this.setFrameRange( animation.start, animation.end );
  9352. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  9353. this.time = 0;
  9354. } else {
  9355. console.warn( "animation[" + label + "] undefined" );
  9356. }
  9357. };
  9358. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  9359. var frameTime = this.duration / this.length;
  9360. this.time += this.direction * delta;
  9361. if ( this.mirroredLoop ) {
  9362. if ( this.time > this.duration || this.time < 0 ) {
  9363. this.direction *= -1;
  9364. if ( this.time > this.duration ) {
  9365. this.time = this.duration;
  9366. this.directionBackwards = true;
  9367. }
  9368. if ( this.time < 0 ) {
  9369. this.time = 0;
  9370. this.directionBackwards = false;
  9371. }
  9372. }
  9373. } else {
  9374. this.time = this.time % this.duration;
  9375. if ( this.time < 0 ) this.time += this.duration;
  9376. }
  9377. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  9378. if ( keyframe !== this.currentKeyframe ) {
  9379. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  9380. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  9381. this.morphTargetInfluences[ keyframe ] = 0;
  9382. this.lastKeyframe = this.currentKeyframe;
  9383. this.currentKeyframe = keyframe;
  9384. }
  9385. var mix = ( this.time % frameTime ) / frameTime;
  9386. if ( this.directionBackwards ) {
  9387. mix = 1 - mix;
  9388. }
  9389. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  9390. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  9391. };
  9392. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  9393. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  9394. object.duration = this.duration;
  9395. object.mirroredLoop = this.mirroredLoop;
  9396. object.time = this.time;
  9397. object.lastKeyframe = this.lastKeyframe;
  9398. object.currentKeyframe = this.currentKeyframe;
  9399. object.direction = this.direction;
  9400. object.directionBackwards = this.directionBackwards;
  9401. THREE.Mesh.prototype.clone.call( this, object );
  9402. return object;
  9403. };
  9404. /**
  9405. * @author mikael emtinger / http://gomo.se/
  9406. * @author alteredq / http://alteredqualia.com/
  9407. * @author mrdoob / http://mrdoob.com/
  9408. */
  9409. THREE.LOD = function () {
  9410. THREE.Object3D.call( this );
  9411. this.objects = [];
  9412. };
  9413. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  9414. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  9415. if ( distance === undefined ) distance = 0;
  9416. distance = Math.abs( distance );
  9417. for ( var l = 0; l < this.objects.length; l ++ ) {
  9418. if ( distance < this.objects[ l ].distance ) {
  9419. break;
  9420. }
  9421. }
  9422. this.objects.splice( l, 0, { distance: distance, object: object } );
  9423. this.add( object );
  9424. };
  9425. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  9426. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9427. if ( distance < this.objects[ i ].distance ) {
  9428. break;
  9429. }
  9430. }
  9431. return this.objects[ i - 1 ].object;
  9432. };
  9433. THREE.LOD.prototype.update = function () {
  9434. var v1 = new THREE.Vector3();
  9435. var v2 = new THREE.Vector3();
  9436. return function ( camera ) {
  9437. if ( this.objects.length > 1 ) {
  9438. v1.setFromMatrixPosition( camera.matrixWorld );
  9439. v2.setFromMatrixPosition( this.matrixWorld );
  9440. var distance = v1.distanceTo( v2 );
  9441. this.objects[ 0 ].object.visible = true;
  9442. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9443. if ( distance >= this.objects[ i ].distance ) {
  9444. this.objects[ i - 1 ].object.visible = false;
  9445. this.objects[ i ].object.visible = true;
  9446. } else {
  9447. break;
  9448. }
  9449. }
  9450. for( ; i < l; i ++ ) {
  9451. this.objects[ i ].object.visible = false;
  9452. }
  9453. }
  9454. };
  9455. }();
  9456. THREE.LOD.prototype.clone = function ( object ) {
  9457. if ( object === undefined ) object = new THREE.LOD();
  9458. THREE.Object3D.prototype.clone.call( this, object );
  9459. for ( var i = 0, l = this.objects.length; i < l; i ++ ) {
  9460. var x = this.objects[i].object.clone();
  9461. x.visible = i === 0;
  9462. object.addLevel( x, this.objects[i].distance );
  9463. }
  9464. return object;
  9465. };
  9466. /**
  9467. * @author mikael emtinger / http://gomo.se/
  9468. * @author alteredq / http://alteredqualia.com/
  9469. */
  9470. THREE.Sprite = ( function () {
  9471. var geometry = new THREE.Geometry2( 3 );
  9472. geometry.vertices.set( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0 ] );
  9473. return function ( material ) {
  9474. THREE.Object3D.call( this );
  9475. this.geometry = geometry;
  9476. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  9477. };
  9478. } )();
  9479. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  9480. /*
  9481. * Custom update matrix
  9482. */
  9483. THREE.Sprite.prototype.updateMatrix = function () {
  9484. this.matrix.compose( this.position, this.quaternion, this.scale );
  9485. this.matrixWorldNeedsUpdate = true;
  9486. };
  9487. THREE.Sprite.prototype.clone = function ( object ) {
  9488. if ( object === undefined ) object = new THREE.Sprite( this.material );
  9489. THREE.Object3D.prototype.clone.call( this, object );
  9490. return object;
  9491. };
  9492. // Backwards compatibility
  9493. THREE.Particle = THREE.Sprite;
  9494. /**
  9495. * @author mrdoob / http://mrdoob.com/
  9496. */
  9497. THREE.Scene = function () {
  9498. THREE.Object3D.call( this );
  9499. this.fog = null;
  9500. this.overrideMaterial = null;
  9501. this.autoUpdate = true; // checked by the renderer
  9502. this.matrixAutoUpdate = false;
  9503. this.__lights = [];
  9504. this.__objectsAdded = [];
  9505. this.__objectsRemoved = [];
  9506. };
  9507. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  9508. THREE.Scene.prototype.__addObject = function ( object ) {
  9509. if ( object instanceof THREE.Light ) {
  9510. if ( this.__lights.indexOf( object ) === - 1 ) {
  9511. this.__lights.push( object );
  9512. }
  9513. if ( object.target && object.target.parent === undefined ) {
  9514. this.add( object.target );
  9515. }
  9516. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  9517. this.__objectsAdded.push( object );
  9518. // check if previously removed
  9519. var i = this.__objectsRemoved.indexOf( object );
  9520. if ( i !== -1 ) {
  9521. this.__objectsRemoved.splice( i, 1 );
  9522. }
  9523. }
  9524. this.dispatchEvent( { type: 'objectAdded', object: object } );
  9525. object.dispatchEvent( { type: 'addedToScene', scene: this } );
  9526. for ( var c = 0; c < object.children.length; c ++ ) {
  9527. this.__addObject( object.children[ c ] );
  9528. }
  9529. };
  9530. THREE.Scene.prototype.__removeObject = function ( object ) {
  9531. if ( object instanceof THREE.Light ) {
  9532. var i = this.__lights.indexOf( object );
  9533. if ( i !== -1 ) {
  9534. this.__lights.splice( i, 1 );
  9535. }
  9536. if ( object.shadowCascadeArray ) {
  9537. for ( var x = 0; x < object.shadowCascadeArray.length; x ++ ) {
  9538. this.__removeObject( object.shadowCascadeArray[ x ] );
  9539. }
  9540. }
  9541. } else if ( !( object instanceof THREE.Camera ) ) {
  9542. this.__objectsRemoved.push( object );
  9543. // check if previously added
  9544. var i = this.__objectsAdded.indexOf( object );
  9545. if ( i !== -1 ) {
  9546. this.__objectsAdded.splice( i, 1 );
  9547. }
  9548. }
  9549. this.dispatchEvent( { type: 'objectRemoved', object: object } );
  9550. object.dispatchEvent( { type: 'removedFromScene', scene: this } );
  9551. for ( var c = 0; c < object.children.length; c ++ ) {
  9552. this.__removeObject( object.children[ c ] );
  9553. }
  9554. };
  9555. THREE.Scene.prototype.clone = function ( object ) {
  9556. if ( object === undefined ) object = new THREE.Scene();
  9557. THREE.Object3D.prototype.clone.call(this, object);
  9558. if ( this.fog !== null ) object.fog = this.fog.clone();
  9559. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  9560. object.autoUpdate = this.autoUpdate;
  9561. object.matrixAutoUpdate = this.matrixAutoUpdate;
  9562. return object;
  9563. };
  9564. /**
  9565. * @author mrdoob / http://mrdoob.com/
  9566. * @author alteredq / http://alteredqualia.com/
  9567. */
  9568. THREE.Fog = function ( color, near, far ) {
  9569. this.name = '';
  9570. this.color = new THREE.Color( color );
  9571. this.near = ( near !== undefined ) ? near : 1;
  9572. this.far = ( far !== undefined ) ? far : 1000;
  9573. };
  9574. THREE.Fog.prototype.clone = function () {
  9575. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  9576. };
  9577. /**
  9578. * @author mrdoob / http://mrdoob.com/
  9579. * @author alteredq / http://alteredqualia.com/
  9580. */
  9581. THREE.FogExp2 = function ( color, density ) {
  9582. this.name = '';
  9583. this.color = new THREE.Color( color );
  9584. this.density = ( density !== undefined ) ? density : 0.00025;
  9585. };
  9586. THREE.FogExp2.prototype.clone = function () {
  9587. return new THREE.FogExp2( this.color.getHex(), this.density );
  9588. };
  9589. /**
  9590. * @author mrdoob / http://mrdoob.com/
  9591. */
  9592. THREE.CanvasRenderer = function ( parameters ) {
  9593. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  9594. var smoothstep = THREE.Math.smoothstep;
  9595. parameters = parameters || {};
  9596. var _this = this,
  9597. _renderData, _elements, _lights,
  9598. _projector = new THREE.Projector(),
  9599. _canvas = parameters.canvas !== undefined
  9600. ? parameters.canvas
  9601. : document.createElement( 'canvas' ),
  9602. _canvasWidth = _canvas.width,
  9603. _canvasHeight = _canvas.height,
  9604. _canvasWidthHalf = Math.floor( _canvasWidth / 2 ),
  9605. _canvasHeightHalf = Math.floor( _canvasHeight / 2 ),
  9606. _context = _canvas.getContext( '2d' ),
  9607. _clearColor = new THREE.Color( 0x000000 ),
  9608. _clearAlpha = 0,
  9609. _contextGlobalAlpha = 1,
  9610. _contextGlobalCompositeOperation = 0,
  9611. _contextStrokeStyle = null,
  9612. _contextFillStyle = null,
  9613. _contextLineWidth = null,
  9614. _contextLineCap = null,
  9615. _contextLineJoin = null,
  9616. _contextDashSize = null,
  9617. _contextGapSize = 0,
  9618. _camera,
  9619. _v1, _v2, _v3, _v4,
  9620. _v5 = new THREE.RenderableVertex(),
  9621. _v6 = new THREE.RenderableVertex(),
  9622. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  9623. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  9624. _color = new THREE.Color(),
  9625. _color1 = new THREE.Color(),
  9626. _color2 = new THREE.Color(),
  9627. _color3 = new THREE.Color(),
  9628. _color4 = new THREE.Color(),
  9629. _diffuseColor = new THREE.Color(),
  9630. _emissiveColor = new THREE.Color(),
  9631. _lightColor = new THREE.Color(),
  9632. _patterns = {},
  9633. _near, _far,
  9634. _image, _uvs,
  9635. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  9636. _clipBox = new THREE.Box2(),
  9637. _clearBox = new THREE.Box2(),
  9638. _elemBox = new THREE.Box2(),
  9639. _ambientLight = new THREE.Color(),
  9640. _directionalLights = new THREE.Color(),
  9641. _pointLights = new THREE.Color(),
  9642. _vector3 = new THREE.Vector3(), // Needed for PointLight
  9643. _normal = new THREE.Vector3(),
  9644. _normalViewMatrix = new THREE.Matrix3(),
  9645. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  9646. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  9647. _pixelMap = document.createElement( 'canvas' );
  9648. _pixelMap.width = _pixelMap.height = 2;
  9649. _pixelMapContext = _pixelMap.getContext( '2d' );
  9650. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  9651. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  9652. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  9653. _pixelMapData = _pixelMapImage.data;
  9654. _gradientMap = document.createElement( 'canvas' );
  9655. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  9656. _gradientMapContext = _gradientMap.getContext( '2d' );
  9657. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  9658. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  9659. _gradientMapQuality --; // Fix UVs
  9660. // dash+gap fallbacks for Firefox and everything else
  9661. if ( _context.setLineDash === undefined ) {
  9662. if ( _context.mozDash !== undefined ) {
  9663. _context.setLineDash = function ( values ) {
  9664. _context.mozDash = values[ 0 ] !== null ? values : null;
  9665. }
  9666. } else {
  9667. _context.setLineDash = function () {}
  9668. }
  9669. }
  9670. this.domElement = _canvas;
  9671. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  9672. ? parameters.devicePixelRatio
  9673. : self.devicePixelRatio !== undefined
  9674. ? self.devicePixelRatio
  9675. : 1;
  9676. this.autoClear = true;
  9677. this.sortObjects = true;
  9678. this.sortElements = true;
  9679. this.info = {
  9680. render: {
  9681. vertices: 0,
  9682. faces: 0
  9683. }
  9684. }
  9685. // WebGLRenderer compatibility
  9686. this.supportsVertexTextures = function () {};
  9687. this.setFaceCulling = function () {};
  9688. this.setSize = function ( width, height, updateStyle ) {
  9689. _canvasWidth = width * this.devicePixelRatio;
  9690. _canvasHeight = height * this.devicePixelRatio;
  9691. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  9692. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  9693. _canvas.width = _canvasWidth;
  9694. _canvas.height = _canvasHeight;
  9695. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  9696. _canvas.style.width = width + 'px';
  9697. _canvas.style.height = height + 'px';
  9698. }
  9699. _clipBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf ),
  9700. _clipBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9701. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  9702. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9703. _contextGlobalAlpha = 1;
  9704. _contextGlobalCompositeOperation = 0;
  9705. _contextStrokeStyle = null;
  9706. _contextFillStyle = null;
  9707. _contextLineWidth = null;
  9708. _contextLineCap = null;
  9709. _contextLineJoin = null;
  9710. };
  9711. this.setClearColor = function ( color, alpha ) {
  9712. _clearColor.set( color );
  9713. _clearAlpha = alpha !== undefined ? alpha : 1;
  9714. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  9715. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9716. };
  9717. this.setClearColorHex = function ( hex, alpha ) {
  9718. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  9719. this.setClearColor( hex, alpha );
  9720. };
  9721. this.getMaxAnisotropy = function () {
  9722. return 0;
  9723. };
  9724. this.clear = function () {
  9725. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  9726. if ( _clearBox.empty() === false ) {
  9727. _clearBox.intersect( _clipBox );
  9728. _clearBox.expandByScalar( 2 );
  9729. if ( _clearAlpha < 1 ) {
  9730. _context.clearRect(
  9731. _clearBox.min.x | 0,
  9732. _clearBox.min.y | 0,
  9733. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9734. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9735. );
  9736. }
  9737. if ( _clearAlpha > 0 ) {
  9738. setBlending( THREE.NormalBlending );
  9739. setOpacity( 1 );
  9740. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  9741. _context.fillRect(
  9742. _clearBox.min.x | 0,
  9743. _clearBox.min.y | 0,
  9744. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9745. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9746. );
  9747. }
  9748. _clearBox.makeEmpty();
  9749. }
  9750. };
  9751. // compatibility
  9752. this.clearColor = function () {};
  9753. this.clearDepth = function () {};
  9754. this.clearStencil = function () {};
  9755. this.render = function ( scene, camera ) {
  9756. if ( camera instanceof THREE.Camera === false ) {
  9757. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  9758. return;
  9759. }
  9760. if ( this.autoClear === true ) this.clear();
  9761. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  9762. _this.info.render.vertices = 0;
  9763. _this.info.render.faces = 0;
  9764. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  9765. _elements = _renderData.elements;
  9766. _lights = _renderData.lights;
  9767. _camera = camera;
  9768. _normalViewMatrix.getNormalMatrix( camera.matrixWorldInverse );
  9769. /* DEBUG
  9770. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  9771. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  9772. */
  9773. calculateLights();
  9774. for ( var e = 0, el = _elements.length; e < el; e ++ ) {
  9775. var element = _elements[ e ];
  9776. var material = element.material;
  9777. if ( material === undefined || material.visible === false ) continue;
  9778. _elemBox.makeEmpty();
  9779. if ( element instanceof THREE.RenderableSprite ) {
  9780. _v1 = element;
  9781. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  9782. renderSprite( _v1, element, material );
  9783. } else if ( element instanceof THREE.RenderableLine ) {
  9784. _v1 = element.v1; _v2 = element.v2;
  9785. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9786. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9787. _elemBox.setFromPoints( [
  9788. _v1.positionScreen,
  9789. _v2.positionScreen
  9790. ] );
  9791. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9792. renderLine( _v1, _v2, element, material );
  9793. }
  9794. } else if ( element instanceof THREE.RenderableFace ) {
  9795. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  9796. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  9797. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  9798. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  9799. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9800. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9801. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  9802. if ( material.overdraw > 0 ) {
  9803. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  9804. expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
  9805. expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
  9806. }
  9807. _elemBox.setFromPoints( [
  9808. _v1.positionScreen,
  9809. _v2.positionScreen,
  9810. _v3.positionScreen
  9811. ] );
  9812. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9813. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  9814. }
  9815. }
  9816. /* DEBUG
  9817. setLineWidth( 1 );
  9818. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  9819. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  9820. */
  9821. _clearBox.union( _elemBox );
  9822. }
  9823. /* DEBUG
  9824. setLineWidth( 1 );
  9825. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  9826. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  9827. */
  9828. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  9829. };
  9830. //
  9831. function calculateLights() {
  9832. _ambientLight.setRGB( 0, 0, 0 );
  9833. _directionalLights.setRGB( 0, 0, 0 );
  9834. _pointLights.setRGB( 0, 0, 0 );
  9835. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9836. var light = _lights[ l ];
  9837. var lightColor = light.color;
  9838. if ( light instanceof THREE.AmbientLight ) {
  9839. _ambientLight.add( lightColor );
  9840. } else if ( light instanceof THREE.DirectionalLight ) {
  9841. // for sprites
  9842. _directionalLights.add( lightColor );
  9843. } else if ( light instanceof THREE.PointLight ) {
  9844. // for sprites
  9845. _pointLights.add( lightColor );
  9846. }
  9847. }
  9848. }
  9849. function calculateLight( position, normal, color ) {
  9850. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9851. var light = _lights[ l ];
  9852. _lightColor.copy( light.color );
  9853. if ( light instanceof THREE.DirectionalLight ) {
  9854. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld ).normalize();
  9855. var amount = normal.dot( lightPosition );
  9856. if ( amount <= 0 ) continue;
  9857. amount *= light.intensity;
  9858. color.add( _lightColor.multiplyScalar( amount ) );
  9859. } else if ( light instanceof THREE.PointLight ) {
  9860. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld );
  9861. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  9862. if ( amount <= 0 ) continue;
  9863. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  9864. if ( amount == 0 ) continue;
  9865. amount *= light.intensity;
  9866. color.add( _lightColor.multiplyScalar( amount ) );
  9867. }
  9868. }
  9869. }
  9870. function renderSprite( v1, element, material ) {
  9871. setOpacity( material.opacity );
  9872. setBlending( material.blending );
  9873. var scaleX = element.scale.x * _canvasWidthHalf;
  9874. var scaleY = element.scale.y * _canvasHeightHalf;
  9875. var dist = 0.5 * Math.sqrt( scaleX * scaleX + scaleY * scaleY ); // allow for rotated sprite
  9876. _elemBox.min.set( v1.x - dist, v1.y - dist );
  9877. _elemBox.max.set( v1.x + dist, v1.y + dist );
  9878. if ( material instanceof THREE.SpriteMaterial ||
  9879. material instanceof THREE.ParticleSystemMaterial ) { // Backwards compatibility
  9880. var texture = material.map;
  9881. if ( texture !== null ) {
  9882. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  9883. if ( texture.image !== undefined && texture.image.width > 0 ) {
  9884. textureToPattern( texture );
  9885. }
  9886. texture.addEventListener( 'update', onTextureUpdate );
  9887. }
  9888. var pattern = _patterns[ texture.id ];
  9889. if ( pattern !== undefined ) {
  9890. setFillStyle( pattern );
  9891. } else {
  9892. setFillStyle( 'rgba( 0, 0, 0, 1 )' );
  9893. }
  9894. //
  9895. var bitmap = texture.image;
  9896. var ox = bitmap.width * texture.offset.x;
  9897. var oy = bitmap.height * texture.offset.y;
  9898. var sx = bitmap.width * texture.repeat.x;
  9899. var sy = bitmap.height * texture.repeat.y;
  9900. var cx = scaleX / sx;
  9901. var cy = scaleY / sy;
  9902. _context.save();
  9903. _context.translate( v1.x, v1.y );
  9904. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9905. _context.translate( - scaleX / 2, - scaleY / 2 );
  9906. _context.scale( cx, cy );
  9907. _context.translate( - ox, - oy );
  9908. _context.fillRect( ox, oy, sx, sy );
  9909. _context.restore();
  9910. } else { // no texture
  9911. setFillStyle( material.color.getStyle() );
  9912. _context.save();
  9913. _context.translate( v1.x, v1.y );
  9914. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9915. _context.scale( scaleX, - scaleY );
  9916. _context.fillRect( - 0.5, - 0.5, 1, 1 );
  9917. _context.restore();
  9918. }
  9919. } else if ( material instanceof THREE.SpriteCanvasMaterial ) {
  9920. setStrokeStyle( material.color.getStyle() );
  9921. setFillStyle( material.color.getStyle() );
  9922. _context.save();
  9923. _context.translate( v1.x, v1.y );
  9924. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9925. _context.scale( scaleX, scaleY );
  9926. material.program( _context );
  9927. _context.restore();
  9928. }
  9929. /* DEBUG
  9930. setStrokeStyle( 'rgb(255,255,0)' );
  9931. _context.beginPath();
  9932. _context.moveTo( v1.x - 10, v1.y );
  9933. _context.lineTo( v1.x + 10, v1.y );
  9934. _context.moveTo( v1.x, v1.y - 10 );
  9935. _context.lineTo( v1.x, v1.y + 10 );
  9936. _context.stroke();
  9937. */
  9938. }
  9939. function renderLine( v1, v2, element, material ) {
  9940. setOpacity( material.opacity );
  9941. setBlending( material.blending );
  9942. _context.beginPath();
  9943. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  9944. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  9945. if ( material instanceof THREE.LineBasicMaterial ) {
  9946. setLineWidth( material.linewidth );
  9947. setLineCap( material.linecap );
  9948. setLineJoin( material.linejoin );
  9949. if ( material.vertexColors !== THREE.VertexColors ) {
  9950. setStrokeStyle( material.color.getStyle() );
  9951. } else {
  9952. var colorStyle1 = element.vertexColors[0].getStyle();
  9953. var colorStyle2 = element.vertexColors[1].getStyle();
  9954. if ( colorStyle1 === colorStyle2 ) {
  9955. setStrokeStyle( colorStyle1 );
  9956. } else {
  9957. try {
  9958. var grad = _context.createLinearGradient(
  9959. v1.positionScreen.x,
  9960. v1.positionScreen.y,
  9961. v2.positionScreen.x,
  9962. v2.positionScreen.y
  9963. );
  9964. grad.addColorStop( 0, colorStyle1 );
  9965. grad.addColorStop( 1, colorStyle2 );
  9966. } catch ( exception ) {
  9967. grad = colorStyle1;
  9968. }
  9969. setStrokeStyle( grad );
  9970. }
  9971. }
  9972. _context.stroke();
  9973. _elemBox.expandByScalar( material.linewidth * 2 );
  9974. } else if ( material instanceof THREE.LineDashedMaterial ) {
  9975. setLineWidth( material.linewidth );
  9976. setLineCap( material.linecap );
  9977. setLineJoin( material.linejoin );
  9978. setStrokeStyle( material.color.getStyle() );
  9979. setDashAndGap( material.dashSize, material.gapSize );
  9980. _context.stroke();
  9981. _elemBox.expandByScalar( material.linewidth * 2 );
  9982. setDashAndGap( null, null );
  9983. }
  9984. }
  9985. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  9986. _this.info.render.vertices += 3;
  9987. _this.info.render.faces ++;
  9988. setOpacity( material.opacity );
  9989. setBlending( material.blending );
  9990. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9991. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9992. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9993. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  9994. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  9995. _diffuseColor.copy( material.color );
  9996. _emissiveColor.copy( material.emissive );
  9997. if ( material.vertexColors === THREE.FaceColors ) {
  9998. _diffuseColor.multiply( element.color );
  9999. }
  10000. if ( material.wireframe === false && material.shading === THREE.SmoothShading && element.vertexNormalsLength === 3 ) {
  10001. _color1.copy( _ambientLight );
  10002. _color2.copy( _ambientLight );
  10003. _color3.copy( _ambientLight );
  10004. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  10005. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  10006. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  10007. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  10008. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  10009. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  10010. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  10011. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  10012. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  10013. } else {
  10014. _color.copy( _ambientLight );
  10015. calculateLight( element.centroidModel, element.normalModel, _color );
  10016. _color.multiply( _diffuseColor ).add( _emissiveColor );
  10017. material.wireframe === true
  10018. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  10019. : fillPath( _color );
  10020. }
  10021. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  10022. if ( material.map !== null ) {
  10023. if ( material.map.mapping instanceof THREE.UVMapping ) {
  10024. _uvs = element.uvs[ 0 ];
  10025. 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 );
  10026. }
  10027. } else if ( material.envMap !== null ) {
  10028. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  10029. _normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix );
  10030. _uv1x = 0.5 * _normal.x + 0.5;
  10031. _uv1y = 0.5 * _normal.y + 0.5;
  10032. _normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix );
  10033. _uv2x = 0.5 * _normal.x + 0.5;
  10034. _uv2y = 0.5 * _normal.y + 0.5;
  10035. _normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix );
  10036. _uv3x = 0.5 * _normal.x + 0.5;
  10037. _uv3y = 0.5 * _normal.y + 0.5;
  10038. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  10039. }/* else if ( material.envMap.mapping === THREE.SphericalRefractionMapping ) {
  10040. }*/
  10041. } else {
  10042. _color.copy( material.color );
  10043. if ( material.vertexColors === THREE.FaceColors ) {
  10044. _color.multiply( element.color );
  10045. }
  10046. material.wireframe === true
  10047. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  10048. : fillPath( _color );
  10049. }
  10050. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  10051. _near = _camera.near;
  10052. _far = _camera.far;
  10053. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  10054. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  10055. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  10056. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  10057. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  10058. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  10059. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  10060. if ( material.shading === THREE.FlatShading ) {
  10061. _normal.copy( element.normalModel ).applyMatrix3( _normalViewMatrix );
  10062. _color.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  10063. material.wireframe === true
  10064. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  10065. : fillPath( _color );
  10066. } else if ( material.shading === THREE.SmoothShading ) {
  10067. _normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix );
  10068. _color1.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  10069. _normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix );
  10070. _color2.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  10071. _normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix );
  10072. _color3.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  10073. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  10074. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  10075. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  10076. }
  10077. }
  10078. }
  10079. //
  10080. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  10081. _context.beginPath();
  10082. _context.moveTo( x0, y0 );
  10083. _context.lineTo( x1, y1 );
  10084. _context.lineTo( x2, y2 );
  10085. _context.closePath();
  10086. }
  10087. function strokePath( color, linewidth, linecap, linejoin ) {
  10088. setLineWidth( linewidth );
  10089. setLineCap( linecap );
  10090. setLineJoin( linejoin );
  10091. setStrokeStyle( color.getStyle() );
  10092. _context.stroke();
  10093. _elemBox.expandByScalar( linewidth * 2 );
  10094. }
  10095. function fillPath( color ) {
  10096. setFillStyle( color.getStyle() );
  10097. _context.fill();
  10098. }
  10099. function onTextureUpdate ( event ) {
  10100. textureToPattern( event.target );
  10101. }
  10102. function textureToPattern( texture ) {
  10103. var repeatX = texture.wrapS === THREE.RepeatWrapping;
  10104. var repeatY = texture.wrapT === THREE.RepeatWrapping;
  10105. var image = texture.image;
  10106. var canvas = document.createElement( 'canvas' );
  10107. canvas.width = image.width;
  10108. canvas.height = image.height;
  10109. var context = canvas.getContext( '2d' );
  10110. context.setTransform( 1, 0, 0, - 1, 0, image.height );
  10111. context.drawImage( image, 0, 0 );
  10112. _patterns[ texture.id ] = _context.createPattern(
  10113. canvas, repeatX === true && repeatY === true
  10114. ? 'repeat'
  10115. : repeatX === true && repeatY === false
  10116. ? 'repeat-x'
  10117. : repeatX === false && repeatY === true
  10118. ? 'repeat-y'
  10119. : 'no-repeat'
  10120. );
  10121. }
  10122. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  10123. if ( texture instanceof THREE.DataTexture ) return;
  10124. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  10125. if ( texture.image !== undefined && texture.image.width > 0 ) {
  10126. textureToPattern( texture );
  10127. }
  10128. texture.addEventListener( 'update', onTextureUpdate );
  10129. }
  10130. var pattern = _patterns[ texture.id ];
  10131. if ( pattern !== undefined ) {
  10132. setFillStyle( pattern );
  10133. } else {
  10134. setFillStyle( 'rgba(0,0,0,1)' );
  10135. _context.fill();
  10136. return;
  10137. }
  10138. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  10139. var a, b, c, d, e, f, det, idet,
  10140. offsetX = texture.offset.x / texture.repeat.x,
  10141. offsetY = texture.offset.y / texture.repeat.y,
  10142. width = texture.image.width * texture.repeat.x,
  10143. height = texture.image.height * texture.repeat.y;
  10144. u0 = ( u0 + offsetX ) * width;
  10145. v0 = ( v0 + offsetY ) * height;
  10146. u1 = ( u1 + offsetX ) * width;
  10147. v1 = ( v1 + offsetY ) * height;
  10148. u2 = ( u2 + offsetX ) * width;
  10149. v2 = ( v2 + offsetY ) * height;
  10150. x1 -= x0; y1 -= y0;
  10151. x2 -= x0; y2 -= y0;
  10152. u1 -= u0; v1 -= v0;
  10153. u2 -= u0; v2 -= v0;
  10154. det = u1 * v2 - u2 * v1;
  10155. if ( det === 0 ) return;
  10156. idet = 1 / det;
  10157. a = ( v2 * x1 - v1 * x2 ) * idet;
  10158. b = ( v2 * y1 - v1 * y2 ) * idet;
  10159. c = ( u1 * x2 - u2 * x1 ) * idet;
  10160. d = ( u1 * y2 - u2 * y1 ) * idet;
  10161. e = x0 - a * u0 - c * v0;
  10162. f = y0 - b * u0 - d * v0;
  10163. _context.save();
  10164. _context.transform( a, b, c, d, e, f );
  10165. _context.fill();
  10166. _context.restore();
  10167. }
  10168. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  10169. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  10170. var a, b, c, d, e, f, det, idet,
  10171. width = image.width - 1,
  10172. height = image.height - 1;
  10173. u0 *= width; v0 *= height;
  10174. u1 *= width; v1 *= height;
  10175. u2 *= width; v2 *= height;
  10176. x1 -= x0; y1 -= y0;
  10177. x2 -= x0; y2 -= y0;
  10178. u1 -= u0; v1 -= v0;
  10179. u2 -= u0; v2 -= v0;
  10180. det = u1 * v2 - u2 * v1;
  10181. idet = 1 / det;
  10182. a = ( v2 * x1 - v1 * x2 ) * idet;
  10183. b = ( v2 * y1 - v1 * y2 ) * idet;
  10184. c = ( u1 * x2 - u2 * x1 ) * idet;
  10185. d = ( u1 * y2 - u2 * y1 ) * idet;
  10186. e = x0 - a * u0 - c * v0;
  10187. f = y0 - b * u0 - d * v0;
  10188. _context.save();
  10189. _context.transform( a, b, c, d, e, f );
  10190. _context.clip();
  10191. _context.drawImage( image, 0, 0 );
  10192. _context.restore();
  10193. }
  10194. function getGradientTexture( color1, color2, color3, color4 ) {
  10195. // http://mrdoob.com/blog/post/710
  10196. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  10197. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  10198. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  10199. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  10200. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  10201. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  10202. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  10203. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  10204. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  10205. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  10206. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  10207. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  10208. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  10209. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  10210. return _gradientMap;
  10211. }
  10212. // Hide anti-alias gaps
  10213. function expand( v1, v2, pixels ) {
  10214. var x = v2.x - v1.x, y = v2.y - v1.y,
  10215. det = x * x + y * y, idet;
  10216. if ( det === 0 ) return;
  10217. idet = pixels / Math.sqrt( det );
  10218. x *= idet; y *= idet;
  10219. v2.x += x; v2.y += y;
  10220. v1.x -= x; v1.y -= y;
  10221. }
  10222. // Context cached methods.
  10223. function setOpacity( value ) {
  10224. if ( _contextGlobalAlpha !== value ) {
  10225. _context.globalAlpha = value;
  10226. _contextGlobalAlpha = value;
  10227. }
  10228. }
  10229. function setBlending( value ) {
  10230. if ( _contextGlobalCompositeOperation !== value ) {
  10231. if ( value === THREE.NormalBlending ) {
  10232. _context.globalCompositeOperation = 'source-over';
  10233. } else if ( value === THREE.AdditiveBlending ) {
  10234. _context.globalCompositeOperation = 'lighter';
  10235. } else if ( value === THREE.SubtractiveBlending ) {
  10236. _context.globalCompositeOperation = 'darker';
  10237. }
  10238. _contextGlobalCompositeOperation = value;
  10239. }
  10240. }
  10241. function setLineWidth( value ) {
  10242. if ( _contextLineWidth !== value ) {
  10243. _context.lineWidth = value;
  10244. _contextLineWidth = value;
  10245. }
  10246. }
  10247. function setLineCap( value ) {
  10248. // "butt", "round", "square"
  10249. if ( _contextLineCap !== value ) {
  10250. _context.lineCap = value;
  10251. _contextLineCap = value;
  10252. }
  10253. }
  10254. function setLineJoin( value ) {
  10255. // "round", "bevel", "miter"
  10256. if ( _contextLineJoin !== value ) {
  10257. _context.lineJoin = value;
  10258. _contextLineJoin = value;
  10259. }
  10260. }
  10261. function setStrokeStyle( value ) {
  10262. if ( _contextStrokeStyle !== value ) {
  10263. _context.strokeStyle = value;
  10264. _contextStrokeStyle = value;
  10265. }
  10266. }
  10267. function setFillStyle( value ) {
  10268. if ( _contextFillStyle !== value ) {
  10269. _context.fillStyle = value;
  10270. _contextFillStyle = value;
  10271. }
  10272. }
  10273. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  10274. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  10275. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  10276. _contextDashSize = dashSizeValue;
  10277. _contextGapSize = gapSizeValue;
  10278. }
  10279. }
  10280. };
  10281. /**
  10282. * Shader chunks for WebLG Shader library
  10283. *
  10284. * @author alteredq / http://alteredqualia.com/
  10285. * @author mrdoob / http://mrdoob.com/
  10286. * @author mikael emtinger / http://gomo.se/
  10287. */
  10288. THREE.ShaderChunk = {
  10289. // FOG
  10290. fog_pars_fragment: [
  10291. "#ifdef USE_FOG",
  10292. "uniform vec3 fogColor;",
  10293. "#ifdef FOG_EXP2",
  10294. "uniform float fogDensity;",
  10295. "#else",
  10296. "uniform float fogNear;",
  10297. "uniform float fogFar;",
  10298. "#endif",
  10299. "#endif"
  10300. ].join("\n"),
  10301. fog_fragment: [
  10302. "#ifdef USE_FOG",
  10303. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10304. "#ifdef FOG_EXP2",
  10305. "const float LOG2 = 1.442695;",
  10306. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  10307. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  10308. "#else",
  10309. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  10310. "#endif",
  10311. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  10312. "#endif"
  10313. ].join("\n"),
  10314. // ENVIRONMENT MAP
  10315. envmap_pars_fragment: [
  10316. "#ifdef USE_ENVMAP",
  10317. "uniform float reflectivity;",
  10318. "uniform samplerCube envMap;",
  10319. "uniform float flipEnvMap;",
  10320. "uniform int combine;",
  10321. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  10322. "uniform bool useRefract;",
  10323. "uniform float refractionRatio;",
  10324. "#else",
  10325. "varying vec3 vReflect;",
  10326. "#endif",
  10327. "#endif"
  10328. ].join("\n"),
  10329. envmap_fragment: [
  10330. "#ifdef USE_ENVMAP",
  10331. "vec3 reflectVec;",
  10332. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  10333. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  10334. "if ( useRefract ) {",
  10335. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  10336. "} else { ",
  10337. "reflectVec = reflect( cameraToVertex, normal );",
  10338. "}",
  10339. "#else",
  10340. "reflectVec = vReflect;",
  10341. "#endif",
  10342. "#ifdef DOUBLE_SIDED",
  10343. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10344. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  10345. "#else",
  10346. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  10347. "#endif",
  10348. "#ifdef GAMMA_INPUT",
  10349. "cubeColor.xyz *= cubeColor.xyz;",
  10350. "#endif",
  10351. "if ( combine == 1 ) {",
  10352. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  10353. "} else if ( combine == 2 ) {",
  10354. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  10355. "} else {",
  10356. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  10357. "}",
  10358. "#endif"
  10359. ].join("\n"),
  10360. envmap_pars_vertex: [
  10361. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  10362. "varying vec3 vReflect;",
  10363. "uniform float refractionRatio;",
  10364. "uniform bool useRefract;",
  10365. "#endif"
  10366. ].join("\n"),
  10367. worldpos_vertex : [
  10368. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  10369. "#ifdef USE_SKINNING",
  10370. "vec4 worldPosition = modelMatrix * skinned;",
  10371. "#endif",
  10372. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  10373. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  10374. "#endif",
  10375. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  10376. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  10377. "#endif",
  10378. "#endif"
  10379. ].join("\n"),
  10380. envmap_vertex : [
  10381. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  10382. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  10383. "worldNormal = normalize( worldNormal );",
  10384. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  10385. "if ( useRefract ) {",
  10386. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  10387. "} else {",
  10388. "vReflect = reflect( cameraToVertex, worldNormal );",
  10389. "}",
  10390. "#endif"
  10391. ].join("\n"),
  10392. // COLOR MAP (particles)
  10393. map_particle_pars_fragment: [
  10394. "#ifdef USE_MAP",
  10395. "uniform sampler2D map;",
  10396. "#endif"
  10397. ].join("\n"),
  10398. map_particle_fragment: [
  10399. "#ifdef USE_MAP",
  10400. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  10401. "#endif"
  10402. ].join("\n"),
  10403. // COLOR MAP (triangles)
  10404. map_pars_vertex: [
  10405. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10406. "varying vec2 vUv;",
  10407. "uniform vec4 offsetRepeat;",
  10408. "#endif"
  10409. ].join("\n"),
  10410. map_pars_fragment: [
  10411. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10412. "varying vec2 vUv;",
  10413. "#endif",
  10414. "#ifdef USE_MAP",
  10415. "uniform sampler2D map;",
  10416. "#endif"
  10417. ].join("\n"),
  10418. map_vertex: [
  10419. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10420. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  10421. "#endif"
  10422. ].join("\n"),
  10423. map_fragment: [
  10424. "#ifdef USE_MAP",
  10425. "vec4 texelColor = texture2D( map, vUv );",
  10426. "#ifdef GAMMA_INPUT",
  10427. "texelColor.xyz *= texelColor.xyz;",
  10428. "#endif",
  10429. "gl_FragColor = gl_FragColor * texelColor;",
  10430. "#endif"
  10431. ].join("\n"),
  10432. // LIGHT MAP
  10433. lightmap_pars_fragment: [
  10434. "#ifdef USE_LIGHTMAP",
  10435. "varying vec2 vUv2;",
  10436. "uniform sampler2D lightMap;",
  10437. "#endif"
  10438. ].join("\n"),
  10439. lightmap_pars_vertex: [
  10440. "#ifdef USE_LIGHTMAP",
  10441. "varying vec2 vUv2;",
  10442. "#endif"
  10443. ].join("\n"),
  10444. lightmap_fragment: [
  10445. "#ifdef USE_LIGHTMAP",
  10446. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  10447. "#endif"
  10448. ].join("\n"),
  10449. lightmap_vertex: [
  10450. "#ifdef USE_LIGHTMAP",
  10451. "vUv2 = uv2;",
  10452. "#endif"
  10453. ].join("\n"),
  10454. // BUMP MAP
  10455. bumpmap_pars_fragment: [
  10456. "#ifdef USE_BUMPMAP",
  10457. "uniform sampler2D bumpMap;",
  10458. "uniform float bumpScale;",
  10459. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  10460. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  10461. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  10462. "vec2 dHdxy_fwd() {",
  10463. "vec2 dSTdx = dFdx( vUv );",
  10464. "vec2 dSTdy = dFdy( vUv );",
  10465. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  10466. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  10467. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  10468. "return vec2( dBx, dBy );",
  10469. "}",
  10470. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  10471. "vec3 vSigmaX = dFdx( surf_pos );",
  10472. "vec3 vSigmaY = dFdy( surf_pos );",
  10473. "vec3 vN = surf_norm;", // normalized
  10474. "vec3 R1 = cross( vSigmaY, vN );",
  10475. "vec3 R2 = cross( vN, vSigmaX );",
  10476. "float fDet = dot( vSigmaX, R1 );",
  10477. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  10478. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  10479. "}",
  10480. "#endif"
  10481. ].join("\n"),
  10482. // NORMAL MAP
  10483. normalmap_pars_fragment: [
  10484. "#ifdef USE_NORMALMAP",
  10485. "uniform sampler2D normalMap;",
  10486. "uniform vec2 normalScale;",
  10487. // Per-Pixel Tangent Space Normal Mapping
  10488. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  10489. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  10490. "vec3 q0 = dFdx( eye_pos.xyz );",
  10491. "vec3 q1 = dFdy( eye_pos.xyz );",
  10492. "vec2 st0 = dFdx( vUv.st );",
  10493. "vec2 st1 = dFdy( vUv.st );",
  10494. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  10495. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  10496. "vec3 N = normalize( surf_norm );",
  10497. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  10498. "mapN.xy = normalScale * mapN.xy;",
  10499. "mat3 tsn = mat3( S, T, N );",
  10500. "return normalize( tsn * mapN );",
  10501. "}",
  10502. "#endif"
  10503. ].join("\n"),
  10504. // SPECULAR MAP
  10505. specularmap_pars_fragment: [
  10506. "#ifdef USE_SPECULARMAP",
  10507. "uniform sampler2D specularMap;",
  10508. "#endif"
  10509. ].join("\n"),
  10510. specularmap_fragment: [
  10511. "float specularStrength;",
  10512. "#ifdef USE_SPECULARMAP",
  10513. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  10514. "specularStrength = texelSpecular.r;",
  10515. "#else",
  10516. "specularStrength = 1.0;",
  10517. "#endif"
  10518. ].join("\n"),
  10519. // LIGHTS LAMBERT
  10520. lights_lambert_pars_vertex: [
  10521. "uniform vec3 ambient;",
  10522. "uniform vec3 diffuse;",
  10523. "uniform vec3 emissive;",
  10524. "uniform vec3 ambientLightColor;",
  10525. "#if MAX_DIR_LIGHTS > 0",
  10526. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10527. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10528. "#endif",
  10529. "#if MAX_HEMI_LIGHTS > 0",
  10530. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10531. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10532. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10533. "#endif",
  10534. "#if MAX_POINT_LIGHTS > 0",
  10535. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10536. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10537. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10538. "#endif",
  10539. "#if MAX_SPOT_LIGHTS > 0",
  10540. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10541. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10542. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10543. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10544. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10545. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10546. "#endif",
  10547. "#ifdef WRAP_AROUND",
  10548. "uniform vec3 wrapRGB;",
  10549. "#endif"
  10550. ].join("\n"),
  10551. lights_lambert_vertex: [
  10552. "vLightFront = vec3( 0.0 );",
  10553. "#ifdef DOUBLE_SIDED",
  10554. "vLightBack = vec3( 0.0 );",
  10555. "#endif",
  10556. "transformedNormal = normalize( transformedNormal );",
  10557. "#if MAX_DIR_LIGHTS > 0",
  10558. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10559. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10560. "vec3 dirVector = normalize( lDirection.xyz );",
  10561. "float dotProduct = dot( transformedNormal, dirVector );",
  10562. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10563. "#ifdef DOUBLE_SIDED",
  10564. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10565. "#ifdef WRAP_AROUND",
  10566. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10567. "#endif",
  10568. "#endif",
  10569. "#ifdef WRAP_AROUND",
  10570. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10571. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  10572. "#ifdef DOUBLE_SIDED",
  10573. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  10574. "#endif",
  10575. "#endif",
  10576. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  10577. "#ifdef DOUBLE_SIDED",
  10578. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  10579. "#endif",
  10580. "}",
  10581. "#endif",
  10582. "#if MAX_POINT_LIGHTS > 0",
  10583. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10584. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10585. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10586. "float lDistance = 1.0;",
  10587. "if ( pointLightDistance[ i ] > 0.0 )",
  10588. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10589. "lVector = normalize( lVector );",
  10590. "float dotProduct = dot( transformedNormal, lVector );",
  10591. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10592. "#ifdef DOUBLE_SIDED",
  10593. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10594. "#ifdef WRAP_AROUND",
  10595. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10596. "#endif",
  10597. "#endif",
  10598. "#ifdef WRAP_AROUND",
  10599. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10600. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  10601. "#ifdef DOUBLE_SIDED",
  10602. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  10603. "#endif",
  10604. "#endif",
  10605. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  10606. "#ifdef DOUBLE_SIDED",
  10607. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  10608. "#endif",
  10609. "}",
  10610. "#endif",
  10611. "#if MAX_SPOT_LIGHTS > 0",
  10612. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10613. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10614. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10615. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  10616. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10617. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10618. "float lDistance = 1.0;",
  10619. "if ( spotLightDistance[ i ] > 0.0 )",
  10620. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10621. "lVector = normalize( lVector );",
  10622. "float dotProduct = dot( transformedNormal, lVector );",
  10623. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10624. "#ifdef DOUBLE_SIDED",
  10625. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10626. "#ifdef WRAP_AROUND",
  10627. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10628. "#endif",
  10629. "#endif",
  10630. "#ifdef WRAP_AROUND",
  10631. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10632. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  10633. "#ifdef DOUBLE_SIDED",
  10634. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  10635. "#endif",
  10636. "#endif",
  10637. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  10638. "#ifdef DOUBLE_SIDED",
  10639. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  10640. "#endif",
  10641. "}",
  10642. "}",
  10643. "#endif",
  10644. "#if MAX_HEMI_LIGHTS > 0",
  10645. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10646. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10647. "vec3 lVector = normalize( lDirection.xyz );",
  10648. "float dotProduct = dot( transformedNormal, lVector );",
  10649. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10650. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  10651. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10652. "#ifdef DOUBLE_SIDED",
  10653. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  10654. "#endif",
  10655. "}",
  10656. "#endif",
  10657. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  10658. "#ifdef DOUBLE_SIDED",
  10659. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  10660. "#endif"
  10661. ].join("\n"),
  10662. // LIGHTS PHONG
  10663. lights_phong_pars_vertex: [
  10664. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10665. "varying vec3 vWorldPosition;",
  10666. "#endif"
  10667. ].join("\n"),
  10668. lights_phong_vertex: [
  10669. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10670. "vWorldPosition = worldPosition.xyz;",
  10671. "#endif"
  10672. ].join("\n"),
  10673. lights_phong_pars_fragment: [
  10674. "uniform vec3 ambientLightColor;",
  10675. "#if MAX_DIR_LIGHTS > 0",
  10676. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10677. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10678. "#endif",
  10679. "#if MAX_HEMI_LIGHTS > 0",
  10680. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10681. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10682. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10683. "#endif",
  10684. "#if MAX_POINT_LIGHTS > 0",
  10685. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10686. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10687. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10688. "#endif",
  10689. "#if MAX_SPOT_LIGHTS > 0",
  10690. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10691. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10692. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10693. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10694. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10695. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10696. "#endif",
  10697. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10698. "varying vec3 vWorldPosition;",
  10699. "#endif",
  10700. "#ifdef WRAP_AROUND",
  10701. "uniform vec3 wrapRGB;",
  10702. "#endif",
  10703. "varying vec3 vViewPosition;",
  10704. "varying vec3 vNormal;"
  10705. ].join("\n"),
  10706. lights_phong_fragment: [
  10707. "vec3 normal = normalize( vNormal );",
  10708. "vec3 viewPosition = normalize( vViewPosition );",
  10709. "#ifdef DOUBLE_SIDED",
  10710. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10711. "#endif",
  10712. "#ifdef USE_NORMALMAP",
  10713. "normal = perturbNormal2Arb( -vViewPosition, normal );",
  10714. "#elif defined( USE_BUMPMAP )",
  10715. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  10716. "#endif",
  10717. "#if MAX_POINT_LIGHTS > 0",
  10718. "vec3 pointDiffuse = vec3( 0.0 );",
  10719. "vec3 pointSpecular = vec3( 0.0 );",
  10720. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10721. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10722. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10723. "float lDistance = 1.0;",
  10724. "if ( pointLightDistance[ i ] > 0.0 )",
  10725. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10726. "lVector = normalize( lVector );",
  10727. // diffuse
  10728. "float dotProduct = dot( normal, lVector );",
  10729. "#ifdef WRAP_AROUND",
  10730. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  10731. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10732. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10733. "#else",
  10734. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  10735. "#endif",
  10736. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  10737. // specular
  10738. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  10739. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10740. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  10741. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10742. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10743. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, pointHalfVector ), 0.0 ), 5.0 );",
  10744. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  10745. "}",
  10746. "#endif",
  10747. "#if MAX_SPOT_LIGHTS > 0",
  10748. "vec3 spotDiffuse = vec3( 0.0 );",
  10749. "vec3 spotSpecular = vec3( 0.0 );",
  10750. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10751. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10752. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10753. "float lDistance = 1.0;",
  10754. "if ( spotLightDistance[ i ] > 0.0 )",
  10755. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10756. "lVector = normalize( lVector );",
  10757. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10758. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10759. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10760. // diffuse
  10761. "float dotProduct = dot( normal, lVector );",
  10762. "#ifdef WRAP_AROUND",
  10763. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  10764. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10765. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10766. "#else",
  10767. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  10768. "#endif",
  10769. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  10770. // specular
  10771. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  10772. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10773. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  10774. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10775. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10776. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, spotHalfVector ), 0.0 ), 5.0 );",
  10777. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  10778. "}",
  10779. "}",
  10780. "#endif",
  10781. "#if MAX_DIR_LIGHTS > 0",
  10782. "vec3 dirDiffuse = vec3( 0.0 );",
  10783. "vec3 dirSpecular = vec3( 0.0 );" ,
  10784. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10785. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10786. "vec3 dirVector = normalize( lDirection.xyz );",
  10787. // diffuse
  10788. "float dotProduct = dot( normal, dirVector );",
  10789. "#ifdef WRAP_AROUND",
  10790. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  10791. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10792. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  10793. "#else",
  10794. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  10795. "#endif",
  10796. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  10797. // specular
  10798. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10799. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10800. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  10801. /*
  10802. // fresnel term from skin shader
  10803. "const float F0 = 0.128;",
  10804. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  10805. "float exponential = pow( base, 5.0 );",
  10806. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  10807. */
  10808. /*
  10809. // fresnel term from fresnel shader
  10810. "const float mFresnelBias = 0.08;",
  10811. "const float mFresnelScale = 0.3;",
  10812. "const float mFresnelPower = 5.0;",
  10813. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  10814. */
  10815. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10816. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10817. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  10818. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( dirVector, dirHalfVector ), 0.0 ), 5.0 );",
  10819. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10820. "}",
  10821. "#endif",
  10822. "#if MAX_HEMI_LIGHTS > 0",
  10823. "vec3 hemiDiffuse = vec3( 0.0 );",
  10824. "vec3 hemiSpecular = vec3( 0.0 );" ,
  10825. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10826. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10827. "vec3 lVector = normalize( lDirection.xyz );",
  10828. // diffuse
  10829. "float dotProduct = dot( normal, lVector );",
  10830. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10831. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10832. "hemiDiffuse += diffuse * hemiColor;",
  10833. // specular (sky light)
  10834. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10835. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10836. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  10837. // specular (ground light)
  10838. "vec3 lVectorGround = -lVector;",
  10839. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10840. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10841. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  10842. "float dotProductGround = dot( normal, lVectorGround );",
  10843. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10844. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10845. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, hemiHalfVectorSky ), 0.0 ), 5.0 );",
  10846. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 0.0 ), 5.0 );",
  10847. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10848. "}",
  10849. "#endif",
  10850. "vec3 totalDiffuse = vec3( 0.0 );",
  10851. "vec3 totalSpecular = vec3( 0.0 );",
  10852. "#if MAX_DIR_LIGHTS > 0",
  10853. "totalDiffuse += dirDiffuse;",
  10854. "totalSpecular += dirSpecular;",
  10855. "#endif",
  10856. "#if MAX_HEMI_LIGHTS > 0",
  10857. "totalDiffuse += hemiDiffuse;",
  10858. "totalSpecular += hemiSpecular;",
  10859. "#endif",
  10860. "#if MAX_POINT_LIGHTS > 0",
  10861. "totalDiffuse += pointDiffuse;",
  10862. "totalSpecular += pointSpecular;",
  10863. "#endif",
  10864. "#if MAX_SPOT_LIGHTS > 0",
  10865. "totalDiffuse += spotDiffuse;",
  10866. "totalSpecular += spotSpecular;",
  10867. "#endif",
  10868. "#ifdef METAL",
  10869. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  10870. "#else",
  10871. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  10872. "#endif"
  10873. ].join("\n"),
  10874. // VERTEX COLORS
  10875. color_pars_fragment: [
  10876. "#ifdef USE_COLOR",
  10877. "varying vec3 vColor;",
  10878. "#endif"
  10879. ].join("\n"),
  10880. color_fragment: [
  10881. "#ifdef USE_COLOR",
  10882. "gl_FragColor = gl_FragColor * vec4( vColor, 1.0 );",
  10883. "#endif"
  10884. ].join("\n"),
  10885. color_pars_vertex: [
  10886. "#ifdef USE_COLOR",
  10887. "varying vec3 vColor;",
  10888. "#endif"
  10889. ].join("\n"),
  10890. color_vertex: [
  10891. "#ifdef USE_COLOR",
  10892. "#ifdef GAMMA_INPUT",
  10893. "vColor = color * color;",
  10894. "#else",
  10895. "vColor = color;",
  10896. "#endif",
  10897. "#endif"
  10898. ].join("\n"),
  10899. // SKINNING
  10900. skinning_pars_vertex: [
  10901. "#ifdef USE_SKINNING",
  10902. "#ifdef BONE_TEXTURE",
  10903. "uniform sampler2D boneTexture;",
  10904. "uniform int boneTextureWidth;",
  10905. "uniform int boneTextureHeight;",
  10906. "mat4 getBoneMatrix( const in float i ) {",
  10907. "float j = i * 4.0;",
  10908. "float x = mod( j, float( boneTextureWidth ) );",
  10909. "float y = floor( j / float( boneTextureWidth ) );",
  10910. "float dx = 1.0 / float( boneTextureWidth );",
  10911. "float dy = 1.0 / float( boneTextureHeight );",
  10912. "y = dy * ( y + 0.5 );",
  10913. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  10914. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  10915. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  10916. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  10917. "mat4 bone = mat4( v1, v2, v3, v4 );",
  10918. "return bone;",
  10919. "}",
  10920. "#else",
  10921. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  10922. "mat4 getBoneMatrix( const in float i ) {",
  10923. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  10924. "return bone;",
  10925. "}",
  10926. "#endif",
  10927. "#endif"
  10928. ].join("\n"),
  10929. skinbase_vertex: [
  10930. "#ifdef USE_SKINNING",
  10931. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  10932. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  10933. "mat4 boneMatZ = getBoneMatrix( skinIndex.z );",
  10934. "mat4 boneMatW = getBoneMatrix( skinIndex.w );",
  10935. "#endif"
  10936. ].join("\n"),
  10937. skinning_vertex: [
  10938. "#ifdef USE_SKINNING",
  10939. "#ifdef USE_MORPHTARGETS",
  10940. "vec4 skinVertex = vec4( morphed, 1.0 );",
  10941. "#else",
  10942. "vec4 skinVertex = vec4( position, 1.0 );",
  10943. "#endif",
  10944. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10945. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10946. "skinned += boneMatZ * skinVertex * skinWeight.z;",
  10947. "skinned += boneMatW * skinVertex * skinWeight.w;",
  10948. "#endif"
  10949. ].join("\n"),
  10950. // MORPHING
  10951. morphtarget_pars_vertex: [
  10952. "#ifdef USE_MORPHTARGETS",
  10953. "#ifndef USE_MORPHNORMALS",
  10954. "uniform float morphTargetInfluences[ 8 ];",
  10955. "#else",
  10956. "uniform float morphTargetInfluences[ 4 ];",
  10957. "#endif",
  10958. "#endif"
  10959. ].join("\n"),
  10960. morphtarget_vertex: [
  10961. "#ifdef USE_MORPHTARGETS",
  10962. "vec3 morphed = vec3( 0.0 );",
  10963. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  10964. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  10965. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  10966. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  10967. "#ifndef USE_MORPHNORMALS",
  10968. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  10969. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  10970. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  10971. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  10972. "#endif",
  10973. "morphed += position;",
  10974. "#endif"
  10975. ].join("\n"),
  10976. default_vertex : [
  10977. "vec4 mvPosition;",
  10978. "#ifdef USE_SKINNING",
  10979. "mvPosition = modelViewMatrix * skinned;",
  10980. "#endif",
  10981. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  10982. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  10983. "#endif",
  10984. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  10985. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10986. "#endif",
  10987. "gl_Position = projectionMatrix * mvPosition;"
  10988. ].join("\n"),
  10989. morphnormal_vertex: [
  10990. "#ifdef USE_MORPHNORMALS",
  10991. "vec3 morphedNormal = vec3( 0.0 );",
  10992. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  10993. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  10994. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  10995. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  10996. "morphedNormal += normal;",
  10997. "#endif"
  10998. ].join("\n"),
  10999. skinnormal_vertex: [
  11000. "#ifdef USE_SKINNING",
  11001. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  11002. "skinMatrix += skinWeight.y * boneMatY;",
  11003. "#ifdef USE_MORPHNORMALS",
  11004. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  11005. "#else",
  11006. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  11007. "#endif",
  11008. "#endif"
  11009. ].join("\n"),
  11010. defaultnormal_vertex: [
  11011. "vec3 objectNormal;",
  11012. "#ifdef USE_SKINNING",
  11013. "objectNormal = skinnedNormal.xyz;",
  11014. "#endif",
  11015. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  11016. "objectNormal = morphedNormal;",
  11017. "#endif",
  11018. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  11019. "objectNormal = normal;",
  11020. "#endif",
  11021. "#ifdef FLIP_SIDED",
  11022. "objectNormal = -objectNormal;",
  11023. "#endif",
  11024. "vec3 transformedNormal = normalMatrix * objectNormal;"
  11025. ].join("\n"),
  11026. // SHADOW MAP
  11027. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  11028. // http://spidergl.org/example.php?id=6
  11029. // http://fabiensanglard.net/shadowmapping
  11030. shadowmap_pars_fragment: [
  11031. "#ifdef USE_SHADOWMAP",
  11032. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  11033. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  11034. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  11035. "uniform float shadowBias[ MAX_SHADOWS ];",
  11036. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  11037. "float unpackDepth( const in vec4 rgba_depth ) {",
  11038. "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 );",
  11039. "float depth = dot( rgba_depth, bit_shift );",
  11040. "return depth;",
  11041. "}",
  11042. "#endif"
  11043. ].join("\n"),
  11044. shadowmap_fragment: [
  11045. "#ifdef USE_SHADOWMAP",
  11046. "#ifdef SHADOWMAP_DEBUG",
  11047. "vec3 frustumColors[3];",
  11048. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  11049. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  11050. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  11051. "#endif",
  11052. "#ifdef SHADOWMAP_CASCADE",
  11053. "int inFrustumCount = 0;",
  11054. "#endif",
  11055. "float fDepth;",
  11056. "vec3 shadowColor = vec3( 1.0 );",
  11057. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11058. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  11059. // "if ( something && something )" breaks ATI OpenGL shader compiler
  11060. // "if ( all( something, something ) )" using this instead
  11061. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  11062. "bool inFrustum = all( inFrustumVec );",
  11063. // don't shadow pixels outside of light frustum
  11064. // use just first frustum (for cascades)
  11065. // don't shadow pixels behind far plane of light frustum
  11066. "#ifdef SHADOWMAP_CASCADE",
  11067. "inFrustumCount += int( inFrustum );",
  11068. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  11069. "#else",
  11070. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  11071. "#endif",
  11072. "bool frustumTest = all( frustumTestVec );",
  11073. "if ( frustumTest ) {",
  11074. "shadowCoord.z += shadowBias[ i ];",
  11075. "#if defined( SHADOWMAP_TYPE_PCF )",
  11076. // Percentage-close filtering
  11077. // (9 pixel kernel)
  11078. // http://fabiensanglard.net/shadowmappingPCF/
  11079. "float shadow = 0.0;",
  11080. /*
  11081. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  11082. // must enroll loop manually
  11083. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  11084. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  11085. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  11086. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  11087. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  11088. "float fDepth = unpackDepth( rgbaDepth );",
  11089. "if ( fDepth < shadowCoord.z )",
  11090. "shadow += 1.0;",
  11091. "}",
  11092. "shadow /= 9.0;",
  11093. */
  11094. "const float shadowDelta = 1.0 / 9.0;",
  11095. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  11096. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  11097. "float dx0 = -1.25 * xPixelOffset;",
  11098. "float dy0 = -1.25 * yPixelOffset;",
  11099. "float dx1 = 1.25 * xPixelOffset;",
  11100. "float dy1 = 1.25 * yPixelOffset;",
  11101. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  11102. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11103. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  11104. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11105. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  11106. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11107. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  11108. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11109. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  11110. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11111. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  11112. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11113. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  11114. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11115. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  11116. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11117. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  11118. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11119. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  11120. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  11121. // Percentage-close filtering
  11122. // (9 pixel kernel)
  11123. // http://fabiensanglard.net/shadowmappingPCF/
  11124. "float shadow = 0.0;",
  11125. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  11126. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  11127. "float dx0 = -1.0 * xPixelOffset;",
  11128. "float dy0 = -1.0 * yPixelOffset;",
  11129. "float dx1 = 1.0 * xPixelOffset;",
  11130. "float dy1 = 1.0 * yPixelOffset;",
  11131. "mat3 shadowKernel;",
  11132. "mat3 depthKernel;",
  11133. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  11134. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  11135. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  11136. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  11137. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  11138. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  11139. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  11140. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  11141. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  11142. "vec3 shadowZ = vec3( shadowCoord.z );",
  11143. "shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  11144. "shadowKernel[0] *= vec3(0.25);",
  11145. "shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  11146. "shadowKernel[1] *= vec3(0.25);",
  11147. "shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  11148. "shadowKernel[2] *= vec3(0.25);",
  11149. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  11150. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  11151. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  11152. "vec4 shadowValues;",
  11153. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  11154. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  11155. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  11156. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  11157. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  11158. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  11159. "#else",
  11160. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  11161. "float fDepth = unpackDepth( rgbaDepth );",
  11162. "if ( fDepth < shadowCoord.z )",
  11163. // spot with multiple shadows is darker
  11164. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  11165. // spot with multiple shadows has the same color as single shadow spot
  11166. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  11167. "#endif",
  11168. "}",
  11169. "#ifdef SHADOWMAP_DEBUG",
  11170. "#ifdef SHADOWMAP_CASCADE",
  11171. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  11172. "#else",
  11173. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  11174. "#endif",
  11175. "#endif",
  11176. "}",
  11177. "#ifdef GAMMA_OUTPUT",
  11178. "shadowColor *= shadowColor;",
  11179. "#endif",
  11180. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  11181. "#endif"
  11182. ].join("\n"),
  11183. shadowmap_pars_vertex: [
  11184. "#ifdef USE_SHADOWMAP",
  11185. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  11186. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  11187. "#endif"
  11188. ].join("\n"),
  11189. shadowmap_vertex: [
  11190. "#ifdef USE_SHADOWMAP",
  11191. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11192. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11193. "}",
  11194. "#endif"
  11195. ].join("\n"),
  11196. // ALPHATEST
  11197. alphatest_fragment: [
  11198. "#ifdef ALPHATEST",
  11199. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  11200. "#endif"
  11201. ].join("\n"),
  11202. // LINEAR SPACE
  11203. linear_to_gamma_fragment: [
  11204. "#ifdef GAMMA_OUTPUT",
  11205. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  11206. "#endif"
  11207. ].join("\n")
  11208. };
  11209. /**
  11210. * Uniform Utilities
  11211. */
  11212. THREE.UniformsUtils = {
  11213. merge: function ( uniforms ) {
  11214. var u, p, tmp, merged = {};
  11215. for ( u = 0; u < uniforms.length; u ++ ) {
  11216. tmp = this.clone( uniforms[ u ] );
  11217. for ( p in tmp ) {
  11218. merged[ p ] = tmp[ p ];
  11219. }
  11220. }
  11221. return merged;
  11222. },
  11223. clone: function ( uniforms_src ) {
  11224. var u, p, parameter, parameter_src, uniforms_dst = {};
  11225. for ( u in uniforms_src ) {
  11226. uniforms_dst[ u ] = {};
  11227. for ( p in uniforms_src[ u ] ) {
  11228. parameter_src = uniforms_src[ u ][ p ];
  11229. if ( parameter_src instanceof THREE.Color ||
  11230. parameter_src instanceof THREE.Vector2 ||
  11231. parameter_src instanceof THREE.Vector3 ||
  11232. parameter_src instanceof THREE.Vector4 ||
  11233. parameter_src instanceof THREE.Matrix4 ||
  11234. parameter_src instanceof THREE.Texture ) {
  11235. uniforms_dst[ u ][ p ] = parameter_src.clone();
  11236. } else if ( parameter_src instanceof Array ) {
  11237. uniforms_dst[ u ][ p ] = parameter_src.slice();
  11238. } else {
  11239. uniforms_dst[ u ][ p ] = parameter_src;
  11240. }
  11241. }
  11242. }
  11243. return uniforms_dst;
  11244. }
  11245. };
  11246. /**
  11247. * Uniforms library for shared webgl shaders
  11248. */
  11249. THREE.UniformsLib = {
  11250. common: {
  11251. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  11252. "opacity" : { type: "f", value: 1.0 },
  11253. "map" : { type: "t", value: null },
  11254. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  11255. "lightMap" : { type: "t", value: null },
  11256. "specularMap" : { type: "t", value: null },
  11257. "envMap" : { type: "t", value: null },
  11258. "flipEnvMap" : { type: "f", value: -1 },
  11259. "useRefract" : { type: "i", value: 0 },
  11260. "reflectivity" : { type: "f", value: 1.0 },
  11261. "refractionRatio" : { type: "f", value: 0.98 },
  11262. "combine" : { type: "i", value: 0 },
  11263. "morphTargetInfluences" : { type: "f", value: 0 }
  11264. },
  11265. bump: {
  11266. "bumpMap" : { type: "t", value: null },
  11267. "bumpScale" : { type: "f", value: 1 }
  11268. },
  11269. normalmap: {
  11270. "normalMap" : { type: "t", value: null },
  11271. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  11272. },
  11273. fog : {
  11274. "fogDensity" : { type: "f", value: 0.00025 },
  11275. "fogNear" : { type: "f", value: 1 },
  11276. "fogFar" : { type: "f", value: 2000 },
  11277. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  11278. },
  11279. lights: {
  11280. "ambientLightColor" : { type: "fv", value: [] },
  11281. "directionalLightDirection" : { type: "fv", value: [] },
  11282. "directionalLightColor" : { type: "fv", value: [] },
  11283. "hemisphereLightDirection" : { type: "fv", value: [] },
  11284. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  11285. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  11286. "pointLightColor" : { type: "fv", value: [] },
  11287. "pointLightPosition" : { type: "fv", value: [] },
  11288. "pointLightDistance" : { type: "fv1", value: [] },
  11289. "spotLightColor" : { type: "fv", value: [] },
  11290. "spotLightPosition" : { type: "fv", value: [] },
  11291. "spotLightDirection" : { type: "fv", value: [] },
  11292. "spotLightDistance" : { type: "fv1", value: [] },
  11293. "spotLightAngleCos" : { type: "fv1", value: [] },
  11294. "spotLightExponent" : { type: "fv1", value: [] }
  11295. },
  11296. particle: {
  11297. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  11298. "opacity" : { type: "f", value: 1.0 },
  11299. "size" : { type: "f", value: 1.0 },
  11300. "scale" : { type: "f", value: 1.0 },
  11301. "map" : { type: "t", value: null },
  11302. "fogDensity" : { type: "f", value: 0.00025 },
  11303. "fogNear" : { type: "f", value: 1 },
  11304. "fogFar" : { type: "f", value: 2000 },
  11305. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  11306. },
  11307. shadowmap: {
  11308. "shadowMap": { type: "tv", value: [] },
  11309. "shadowMapSize": { type: "v2v", value: [] },
  11310. "shadowBias" : { type: "fv1", value: [] },
  11311. "shadowDarkness": { type: "fv1", value: [] },
  11312. "shadowMatrix" : { type: "m4v", value: [] }
  11313. }
  11314. };
  11315. /**
  11316. * Webgl Shader Library for three.js
  11317. *
  11318. * @author alteredq / http://alteredqualia.com/
  11319. * @author mrdoob / http://mrdoob.com/
  11320. * @author mikael emtinger / http://gomo.se/
  11321. */
  11322. THREE.ShaderLib = {
  11323. 'basic': {
  11324. uniforms: THREE.UniformsUtils.merge( [
  11325. THREE.UniformsLib[ "common" ],
  11326. THREE.UniformsLib[ "fog" ],
  11327. THREE.UniformsLib[ "shadowmap" ]
  11328. ] ),
  11329. vertexShader: [
  11330. THREE.ShaderChunk[ "map_pars_vertex" ],
  11331. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11332. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11333. THREE.ShaderChunk[ "color_pars_vertex" ],
  11334. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11335. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11336. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11337. "void main() {",
  11338. THREE.ShaderChunk[ "map_vertex" ],
  11339. THREE.ShaderChunk[ "lightmap_vertex" ],
  11340. THREE.ShaderChunk[ "color_vertex" ],
  11341. THREE.ShaderChunk[ "skinbase_vertex" ],
  11342. "#ifdef USE_ENVMAP",
  11343. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11344. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11345. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11346. "#endif",
  11347. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11348. THREE.ShaderChunk[ "skinning_vertex" ],
  11349. THREE.ShaderChunk[ "default_vertex" ],
  11350. THREE.ShaderChunk[ "worldpos_vertex" ],
  11351. THREE.ShaderChunk[ "envmap_vertex" ],
  11352. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11353. "}"
  11354. ].join("\n"),
  11355. fragmentShader: [
  11356. "uniform vec3 diffuse;",
  11357. "uniform float opacity;",
  11358. THREE.ShaderChunk[ "color_pars_fragment" ],
  11359. THREE.ShaderChunk[ "map_pars_fragment" ],
  11360. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11361. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11362. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11363. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11364. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11365. "void main() {",
  11366. "gl_FragColor = vec4( diffuse, opacity );",
  11367. THREE.ShaderChunk[ "map_fragment" ],
  11368. THREE.ShaderChunk[ "alphatest_fragment" ],
  11369. THREE.ShaderChunk[ "specularmap_fragment" ],
  11370. THREE.ShaderChunk[ "lightmap_fragment" ],
  11371. THREE.ShaderChunk[ "color_fragment" ],
  11372. THREE.ShaderChunk[ "envmap_fragment" ],
  11373. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11374. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11375. THREE.ShaderChunk[ "fog_fragment" ],
  11376. "}"
  11377. ].join("\n")
  11378. },
  11379. 'lambert': {
  11380. uniforms: THREE.UniformsUtils.merge( [
  11381. THREE.UniformsLib[ "common" ],
  11382. THREE.UniformsLib[ "fog" ],
  11383. THREE.UniformsLib[ "lights" ],
  11384. THREE.UniformsLib[ "shadowmap" ],
  11385. {
  11386. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  11387. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  11388. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11389. }
  11390. ] ),
  11391. vertexShader: [
  11392. "#define LAMBERT",
  11393. "varying vec3 vLightFront;",
  11394. "#ifdef DOUBLE_SIDED",
  11395. "varying vec3 vLightBack;",
  11396. "#endif",
  11397. THREE.ShaderChunk[ "map_pars_vertex" ],
  11398. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11399. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11400. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  11401. THREE.ShaderChunk[ "color_pars_vertex" ],
  11402. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11403. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11404. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11405. "void main() {",
  11406. THREE.ShaderChunk[ "map_vertex" ],
  11407. THREE.ShaderChunk[ "lightmap_vertex" ],
  11408. THREE.ShaderChunk[ "color_vertex" ],
  11409. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11410. THREE.ShaderChunk[ "skinbase_vertex" ],
  11411. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11412. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11413. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11414. THREE.ShaderChunk[ "skinning_vertex" ],
  11415. THREE.ShaderChunk[ "default_vertex" ],
  11416. THREE.ShaderChunk[ "worldpos_vertex" ],
  11417. THREE.ShaderChunk[ "envmap_vertex" ],
  11418. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  11419. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11420. "}"
  11421. ].join("\n"),
  11422. fragmentShader: [
  11423. "uniform float opacity;",
  11424. "varying vec3 vLightFront;",
  11425. "#ifdef DOUBLE_SIDED",
  11426. "varying vec3 vLightBack;",
  11427. "#endif",
  11428. THREE.ShaderChunk[ "color_pars_fragment" ],
  11429. THREE.ShaderChunk[ "map_pars_fragment" ],
  11430. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11431. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11432. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11433. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11434. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11435. "void main() {",
  11436. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  11437. THREE.ShaderChunk[ "map_fragment" ],
  11438. THREE.ShaderChunk[ "alphatest_fragment" ],
  11439. THREE.ShaderChunk[ "specularmap_fragment" ],
  11440. "#ifdef DOUBLE_SIDED",
  11441. //"float isFront = float( gl_FrontFacing );",
  11442. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  11443. "if ( gl_FrontFacing )",
  11444. "gl_FragColor.xyz *= vLightFront;",
  11445. "else",
  11446. "gl_FragColor.xyz *= vLightBack;",
  11447. "#else",
  11448. "gl_FragColor.xyz *= vLightFront;",
  11449. "#endif",
  11450. THREE.ShaderChunk[ "lightmap_fragment" ],
  11451. THREE.ShaderChunk[ "color_fragment" ],
  11452. THREE.ShaderChunk[ "envmap_fragment" ],
  11453. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11454. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11455. THREE.ShaderChunk[ "fog_fragment" ],
  11456. "}"
  11457. ].join("\n")
  11458. },
  11459. 'phong': {
  11460. uniforms: THREE.UniformsUtils.merge( [
  11461. THREE.UniformsLib[ "common" ],
  11462. THREE.UniformsLib[ "bump" ],
  11463. THREE.UniformsLib[ "normalmap" ],
  11464. THREE.UniformsLib[ "fog" ],
  11465. THREE.UniformsLib[ "lights" ],
  11466. THREE.UniformsLib[ "shadowmap" ],
  11467. {
  11468. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  11469. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  11470. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  11471. "shininess": { type: "f", value: 30 },
  11472. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11473. }
  11474. ] ),
  11475. vertexShader: [
  11476. "#define PHONG",
  11477. "varying vec3 vViewPosition;",
  11478. "varying vec3 vNormal;",
  11479. THREE.ShaderChunk[ "map_pars_vertex" ],
  11480. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11481. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11482. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  11483. THREE.ShaderChunk[ "color_pars_vertex" ],
  11484. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11485. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11486. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11487. "void main() {",
  11488. THREE.ShaderChunk[ "map_vertex" ],
  11489. THREE.ShaderChunk[ "lightmap_vertex" ],
  11490. THREE.ShaderChunk[ "color_vertex" ],
  11491. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11492. THREE.ShaderChunk[ "skinbase_vertex" ],
  11493. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11494. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11495. "vNormal = normalize( transformedNormal );",
  11496. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11497. THREE.ShaderChunk[ "skinning_vertex" ],
  11498. THREE.ShaderChunk[ "default_vertex" ],
  11499. "vViewPosition = -mvPosition.xyz;",
  11500. THREE.ShaderChunk[ "worldpos_vertex" ],
  11501. THREE.ShaderChunk[ "envmap_vertex" ],
  11502. THREE.ShaderChunk[ "lights_phong_vertex" ],
  11503. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11504. "}"
  11505. ].join("\n"),
  11506. fragmentShader: [
  11507. "uniform vec3 diffuse;",
  11508. "uniform float opacity;",
  11509. "uniform vec3 ambient;",
  11510. "uniform vec3 emissive;",
  11511. "uniform vec3 specular;",
  11512. "uniform float shininess;",
  11513. THREE.ShaderChunk[ "color_pars_fragment" ],
  11514. THREE.ShaderChunk[ "map_pars_fragment" ],
  11515. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11516. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11517. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11518. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  11519. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11520. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  11521. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  11522. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11523. "void main() {",
  11524. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  11525. THREE.ShaderChunk[ "map_fragment" ],
  11526. THREE.ShaderChunk[ "alphatest_fragment" ],
  11527. THREE.ShaderChunk[ "specularmap_fragment" ],
  11528. THREE.ShaderChunk[ "lights_phong_fragment" ],
  11529. THREE.ShaderChunk[ "lightmap_fragment" ],
  11530. THREE.ShaderChunk[ "color_fragment" ],
  11531. THREE.ShaderChunk[ "envmap_fragment" ],
  11532. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11533. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11534. THREE.ShaderChunk[ "fog_fragment" ],
  11535. "}"
  11536. ].join("\n")
  11537. },
  11538. 'particle_basic': {
  11539. uniforms: THREE.UniformsUtils.merge( [
  11540. THREE.UniformsLib[ "particle" ],
  11541. THREE.UniformsLib[ "shadowmap" ]
  11542. ] ),
  11543. vertexShader: [
  11544. "uniform float size;",
  11545. "uniform float scale;",
  11546. THREE.ShaderChunk[ "color_pars_vertex" ],
  11547. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11548. "void main() {",
  11549. THREE.ShaderChunk[ "color_vertex" ],
  11550. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11551. "#ifdef USE_SIZEATTENUATION",
  11552. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  11553. "#else",
  11554. "gl_PointSize = size;",
  11555. "#endif",
  11556. "gl_Position = projectionMatrix * mvPosition;",
  11557. THREE.ShaderChunk[ "worldpos_vertex" ],
  11558. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11559. "}"
  11560. ].join("\n"),
  11561. fragmentShader: [
  11562. "uniform vec3 psColor;",
  11563. "uniform float opacity;",
  11564. THREE.ShaderChunk[ "color_pars_fragment" ],
  11565. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  11566. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11567. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11568. "void main() {",
  11569. "gl_FragColor = vec4( psColor, opacity );",
  11570. THREE.ShaderChunk[ "map_particle_fragment" ],
  11571. THREE.ShaderChunk[ "alphatest_fragment" ],
  11572. THREE.ShaderChunk[ "color_fragment" ],
  11573. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11574. THREE.ShaderChunk[ "fog_fragment" ],
  11575. "}"
  11576. ].join("\n")
  11577. },
  11578. 'dashed': {
  11579. uniforms: THREE.UniformsUtils.merge( [
  11580. THREE.UniformsLib[ "common" ],
  11581. THREE.UniformsLib[ "fog" ],
  11582. {
  11583. "scale": { type: "f", value: 1 },
  11584. "dashSize": { type: "f", value: 1 },
  11585. "totalSize": { type: "f", value: 2 }
  11586. }
  11587. ] ),
  11588. vertexShader: [
  11589. "uniform float scale;",
  11590. "attribute float lineDistance;",
  11591. "varying float vLineDistance;",
  11592. THREE.ShaderChunk[ "color_pars_vertex" ],
  11593. "void main() {",
  11594. THREE.ShaderChunk[ "color_vertex" ],
  11595. "vLineDistance = scale * lineDistance;",
  11596. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11597. "gl_Position = projectionMatrix * mvPosition;",
  11598. "}"
  11599. ].join("\n"),
  11600. fragmentShader: [
  11601. "uniform vec3 diffuse;",
  11602. "uniform float opacity;",
  11603. "uniform float dashSize;",
  11604. "uniform float totalSize;",
  11605. "varying float vLineDistance;",
  11606. THREE.ShaderChunk[ "color_pars_fragment" ],
  11607. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11608. "void main() {",
  11609. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  11610. "discard;",
  11611. "}",
  11612. "gl_FragColor = vec4( diffuse, opacity );",
  11613. THREE.ShaderChunk[ "color_fragment" ],
  11614. THREE.ShaderChunk[ "fog_fragment" ],
  11615. "}"
  11616. ].join("\n")
  11617. },
  11618. 'depth': {
  11619. uniforms: {
  11620. "mNear": { type: "f", value: 1.0 },
  11621. "mFar" : { type: "f", value: 2000.0 },
  11622. "opacity" : { type: "f", value: 1.0 }
  11623. },
  11624. vertexShader: [
  11625. "void main() {",
  11626. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11627. "}"
  11628. ].join("\n"),
  11629. fragmentShader: [
  11630. "uniform float mNear;",
  11631. "uniform float mFar;",
  11632. "uniform float opacity;",
  11633. "void main() {",
  11634. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  11635. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  11636. "gl_FragColor = vec4( vec3( color ), opacity );",
  11637. "}"
  11638. ].join("\n")
  11639. },
  11640. 'normal': {
  11641. uniforms: {
  11642. "opacity" : { type: "f", value: 1.0 }
  11643. },
  11644. vertexShader: [
  11645. "varying vec3 vNormal;",
  11646. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11647. "void main() {",
  11648. "vNormal = normalize( normalMatrix * normal );",
  11649. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11650. THREE.ShaderChunk[ "default_vertex" ],
  11651. "}"
  11652. ].join("\n"),
  11653. fragmentShader: [
  11654. "uniform float opacity;",
  11655. "varying vec3 vNormal;",
  11656. "void main() {",
  11657. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  11658. "}"
  11659. ].join("\n")
  11660. },
  11661. /* -------------------------------------------------------------------------
  11662. // Normal map shader
  11663. // - Blinn-Phong
  11664. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  11665. // - point and directional lights (use with "lights: true" material option)
  11666. ------------------------------------------------------------------------- */
  11667. 'normalmap' : {
  11668. uniforms: THREE.UniformsUtils.merge( [
  11669. THREE.UniformsLib[ "fog" ],
  11670. THREE.UniformsLib[ "lights" ],
  11671. THREE.UniformsLib[ "shadowmap" ],
  11672. {
  11673. "enableAO" : { type: "i", value: 0 },
  11674. "enableDiffuse" : { type: "i", value: 0 },
  11675. "enableSpecular" : { type: "i", value: 0 },
  11676. "enableReflection": { type: "i", value: 0 },
  11677. "enableDisplacement": { type: "i", value: 0 },
  11678. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  11679. "tDiffuse" : { type: "t", value: null },
  11680. "tCube" : { type: "t", value: null },
  11681. "tNormal" : { type: "t", value: null },
  11682. "tSpecular" : { type: "t", value: null },
  11683. "tAO" : { type: "t", value: null },
  11684. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11685. "uDisplacementBias": { type: "f", value: 0.0 },
  11686. "uDisplacementScale": { type: "f", value: 1.0 },
  11687. "diffuse": { type: "c", value: new THREE.Color( 0xffffff ) },
  11688. "specular": { type: "c", value: new THREE.Color( 0x111111 ) },
  11689. "ambient": { type: "c", value: new THREE.Color( 0xffffff ) },
  11690. "shininess": { type: "f", value: 30 },
  11691. "opacity": { type: "f", value: 1 },
  11692. "useRefract": { type: "i", value: 0 },
  11693. "refractionRatio": { type: "f", value: 0.98 },
  11694. "reflectivity": { type: "f", value: 0.5 },
  11695. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  11696. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11697. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11698. }
  11699. ] ),
  11700. fragmentShader: [
  11701. "uniform vec3 ambient;",
  11702. "uniform vec3 diffuse;",
  11703. "uniform vec3 specular;",
  11704. "uniform float shininess;",
  11705. "uniform float opacity;",
  11706. "uniform bool enableDiffuse;",
  11707. "uniform bool enableSpecular;",
  11708. "uniform bool enableAO;",
  11709. "uniform bool enableReflection;",
  11710. "uniform sampler2D tDiffuse;",
  11711. "uniform sampler2D tNormal;",
  11712. "uniform sampler2D tSpecular;",
  11713. "uniform sampler2D tAO;",
  11714. "uniform samplerCube tCube;",
  11715. "uniform vec2 uNormalScale;",
  11716. "uniform bool useRefract;",
  11717. "uniform float refractionRatio;",
  11718. "uniform float reflectivity;",
  11719. "varying vec3 vTangent;",
  11720. "varying vec3 vBinormal;",
  11721. "varying vec3 vNormal;",
  11722. "varying vec2 vUv;",
  11723. "uniform vec3 ambientLightColor;",
  11724. "#if MAX_DIR_LIGHTS > 0",
  11725. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11726. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11727. "#endif",
  11728. "#if MAX_HEMI_LIGHTS > 0",
  11729. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  11730. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  11731. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  11732. "#endif",
  11733. "#if MAX_POINT_LIGHTS > 0",
  11734. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11735. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11736. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11737. "#endif",
  11738. "#if MAX_SPOT_LIGHTS > 0",
  11739. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  11740. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  11741. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  11742. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  11743. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  11744. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  11745. "#endif",
  11746. "#ifdef WRAP_AROUND",
  11747. "uniform vec3 wrapRGB;",
  11748. "#endif",
  11749. "varying vec3 vWorldPosition;",
  11750. "varying vec3 vViewPosition;",
  11751. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11752. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11753. "void main() {",
  11754. "gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  11755. "vec3 specularTex = vec3( 1.0 );",
  11756. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  11757. "normalTex.xy *= uNormalScale;",
  11758. "normalTex = normalize( normalTex );",
  11759. "if( enableDiffuse ) {",
  11760. "#ifdef GAMMA_INPUT",
  11761. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  11762. "texelColor.xyz *= texelColor.xyz;",
  11763. "gl_FragColor = gl_FragColor * texelColor;",
  11764. "#else",
  11765. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  11766. "#endif",
  11767. "}",
  11768. "if( enableAO ) {",
  11769. "#ifdef GAMMA_INPUT",
  11770. "vec4 aoColor = texture2D( tAO, vUv );",
  11771. "aoColor.xyz *= aoColor.xyz;",
  11772. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  11773. "#else",
  11774. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  11775. "#endif",
  11776. "}",
  11777. "if( enableSpecular )",
  11778. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  11779. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  11780. "vec3 finalNormal = tsb * normalTex;",
  11781. "#ifdef FLIP_SIDED",
  11782. "finalNormal = -finalNormal;",
  11783. "#endif",
  11784. "vec3 normal = normalize( finalNormal );",
  11785. "vec3 viewPosition = normalize( vViewPosition );",
  11786. // point lights
  11787. "#if MAX_POINT_LIGHTS > 0",
  11788. "vec3 pointDiffuse = vec3( 0.0 );",
  11789. "vec3 pointSpecular = vec3( 0.0 );",
  11790. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11791. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11792. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  11793. "float pointDistance = 1.0;",
  11794. "if ( pointLightDistance[ i ] > 0.0 )",
  11795. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  11796. "pointVector = normalize( pointVector );",
  11797. // diffuse
  11798. "#ifdef WRAP_AROUND",
  11799. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  11800. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  11801. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11802. "#else",
  11803. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  11804. "#endif",
  11805. "pointDiffuse += pointDistance * pointLightColor[ i ] * diffuse * pointDiffuseWeight;",
  11806. // specular
  11807. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  11808. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11809. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  11810. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11811. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11812. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  11813. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  11814. "}",
  11815. "#endif",
  11816. // spot lights
  11817. "#if MAX_SPOT_LIGHTS > 0",
  11818. "vec3 spotDiffuse = vec3( 0.0 );",
  11819. "vec3 spotSpecular = vec3( 0.0 );",
  11820. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  11821. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  11822. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  11823. "float spotDistance = 1.0;",
  11824. "if ( spotLightDistance[ i ] > 0.0 )",
  11825. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  11826. "spotVector = normalize( spotVector );",
  11827. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  11828. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  11829. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  11830. // diffuse
  11831. "#ifdef WRAP_AROUND",
  11832. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  11833. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  11834. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  11835. "#else",
  11836. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  11837. "#endif",
  11838. "spotDiffuse += spotDistance * spotLightColor[ i ] * diffuse * spotDiffuseWeight * spotEffect;",
  11839. // specular
  11840. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  11841. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  11842. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  11843. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11844. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11845. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  11846. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  11847. "}",
  11848. "}",
  11849. "#endif",
  11850. // directional lights
  11851. "#if MAX_DIR_LIGHTS > 0",
  11852. "vec3 dirDiffuse = vec3( 0.0 );",
  11853. "vec3 dirSpecular = vec3( 0.0 );",
  11854. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  11855. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11856. "vec3 dirVector = normalize( lDirection.xyz );",
  11857. // diffuse
  11858. "#ifdef WRAP_AROUND",
  11859. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  11860. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  11861. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  11862. "#else",
  11863. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  11864. "#endif",
  11865. "dirDiffuse += directionalLightColor[ i ] * diffuse * dirDiffuseWeight;",
  11866. // specular
  11867. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11868. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11869. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  11870. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11871. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11872. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  11873. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11874. "}",
  11875. "#endif",
  11876. // hemisphere lights
  11877. "#if MAX_HEMI_LIGHTS > 0",
  11878. "vec3 hemiDiffuse = vec3( 0.0 );",
  11879. "vec3 hemiSpecular = vec3( 0.0 );" ,
  11880. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  11881. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  11882. "vec3 lVector = normalize( lDirection.xyz );",
  11883. // diffuse
  11884. "float dotProduct = dot( normal, lVector );",
  11885. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  11886. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  11887. "hemiDiffuse += diffuse * hemiColor;",
  11888. // specular (sky light)
  11889. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  11890. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  11891. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  11892. // specular (ground light)
  11893. "vec3 lVectorGround = -lVector;",
  11894. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  11895. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  11896. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  11897. "float dotProductGround = dot( normal, lVectorGround );",
  11898. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11899. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11900. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  11901. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  11902. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  11903. "}",
  11904. "#endif",
  11905. // all lights contribution summation
  11906. "vec3 totalDiffuse = vec3( 0.0 );",
  11907. "vec3 totalSpecular = vec3( 0.0 );",
  11908. "#if MAX_DIR_LIGHTS > 0",
  11909. "totalDiffuse += dirDiffuse;",
  11910. "totalSpecular += dirSpecular;",
  11911. "#endif",
  11912. "#if MAX_HEMI_LIGHTS > 0",
  11913. "totalDiffuse += hemiDiffuse;",
  11914. "totalSpecular += hemiSpecular;",
  11915. "#endif",
  11916. "#if MAX_POINT_LIGHTS > 0",
  11917. "totalDiffuse += pointDiffuse;",
  11918. "totalSpecular += pointSpecular;",
  11919. "#endif",
  11920. "#if MAX_SPOT_LIGHTS > 0",
  11921. "totalDiffuse += spotDiffuse;",
  11922. "totalSpecular += spotSpecular;",
  11923. "#endif",
  11924. "#ifdef METAL",
  11925. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  11926. "#else",
  11927. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  11928. "#endif",
  11929. "if ( enableReflection ) {",
  11930. "vec3 vReflect;",
  11931. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  11932. "if ( useRefract ) {",
  11933. "vReflect = refract( cameraToVertex, normal, refractionRatio );",
  11934. "} else {",
  11935. "vReflect = reflect( cameraToVertex, normal );",
  11936. "}",
  11937. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  11938. "#ifdef GAMMA_INPUT",
  11939. "cubeColor.xyz *= cubeColor.xyz;",
  11940. "#endif",
  11941. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * reflectivity );",
  11942. "}",
  11943. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11944. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11945. THREE.ShaderChunk[ "fog_fragment" ],
  11946. "}"
  11947. ].join("\n"),
  11948. vertexShader: [
  11949. "attribute vec4 tangent;",
  11950. "uniform vec2 uOffset;",
  11951. "uniform vec2 uRepeat;",
  11952. "uniform bool enableDisplacement;",
  11953. "#ifdef VERTEX_TEXTURES",
  11954. "uniform sampler2D tDisplacement;",
  11955. "uniform float uDisplacementScale;",
  11956. "uniform float uDisplacementBias;",
  11957. "#endif",
  11958. "varying vec3 vTangent;",
  11959. "varying vec3 vBinormal;",
  11960. "varying vec3 vNormal;",
  11961. "varying vec2 vUv;",
  11962. "varying vec3 vWorldPosition;",
  11963. "varying vec3 vViewPosition;",
  11964. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11965. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11966. "void main() {",
  11967. THREE.ShaderChunk[ "skinbase_vertex" ],
  11968. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11969. // normal, tangent and binormal vectors
  11970. "#ifdef USE_SKINNING",
  11971. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  11972. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  11973. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  11974. "#else",
  11975. "vNormal = normalize( normalMatrix * normal );",
  11976. "vTangent = normalize( normalMatrix * tangent.xyz );",
  11977. "#endif",
  11978. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  11979. "vUv = uv * uRepeat + uOffset;",
  11980. // displacement mapping
  11981. "vec3 displacedPosition;",
  11982. "#ifdef VERTEX_TEXTURES",
  11983. "if ( enableDisplacement ) {",
  11984. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  11985. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  11986. "displacedPosition = position + normalize( normal ) * df;",
  11987. "} else {",
  11988. "#ifdef USE_SKINNING",
  11989. "vec4 skinVertex = vec4( position, 1.0 );",
  11990. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11991. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11992. "displacedPosition = skinned.xyz;",
  11993. "#else",
  11994. "displacedPosition = position;",
  11995. "#endif",
  11996. "}",
  11997. "#else",
  11998. "#ifdef USE_SKINNING",
  11999. "vec4 skinVertex = vec4( position, 1.0 );",
  12000. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  12001. "skinned += boneMatY * skinVertex * skinWeight.y;",
  12002. "displacedPosition = skinned.xyz;",
  12003. "#else",
  12004. "displacedPosition = position;",
  12005. "#endif",
  12006. "#endif",
  12007. //
  12008. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  12009. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  12010. "gl_Position = projectionMatrix * mvPosition;",
  12011. //
  12012. "vWorldPosition = worldPosition.xyz;",
  12013. "vViewPosition = -mvPosition.xyz;",
  12014. // shadows
  12015. "#ifdef USE_SHADOWMAP",
  12016. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  12017. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  12018. "}",
  12019. "#endif",
  12020. "}"
  12021. ].join("\n")
  12022. },
  12023. /* -------------------------------------------------------------------------
  12024. // Cube map shader
  12025. ------------------------------------------------------------------------- */
  12026. 'cube': {
  12027. uniforms: { "tCube": { type: "t", value: null },
  12028. "tFlip": { type: "f", value: -1 } },
  12029. vertexShader: [
  12030. "varying vec3 vWorldPosition;",
  12031. "void main() {",
  12032. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  12033. "vWorldPosition = worldPosition.xyz;",
  12034. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  12035. "}"
  12036. ].join("\n"),
  12037. fragmentShader: [
  12038. "uniform samplerCube tCube;",
  12039. "uniform float tFlip;",
  12040. "varying vec3 vWorldPosition;",
  12041. "void main() {",
  12042. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  12043. "}"
  12044. ].join("\n")
  12045. },
  12046. // Depth encoding into RGBA texture
  12047. // based on SpiderGL shadow map example
  12048. // http://spidergl.org/example.php?id=6
  12049. // originally from
  12050. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  12051. // see also here:
  12052. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  12053. 'depthRGBA': {
  12054. uniforms: {},
  12055. vertexShader: [
  12056. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  12057. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  12058. "void main() {",
  12059. THREE.ShaderChunk[ "skinbase_vertex" ],
  12060. THREE.ShaderChunk[ "morphtarget_vertex" ],
  12061. THREE.ShaderChunk[ "skinning_vertex" ],
  12062. THREE.ShaderChunk[ "default_vertex" ],
  12063. "}"
  12064. ].join("\n"),
  12065. fragmentShader: [
  12066. "vec4 pack_depth( const in float depth ) {",
  12067. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  12068. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  12069. "vec4 res = fract( depth * bit_shift );",
  12070. "res -= res.xxyz * bit_mask;",
  12071. "return res;",
  12072. "}",
  12073. "void main() {",
  12074. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  12075. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  12076. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  12077. //"gl_FragData[ 0 ] = pack_depth( z );",
  12078. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  12079. "}"
  12080. ].join("\n")
  12081. }
  12082. };
  12083. /**
  12084. * @author supereggbert / http://www.paulbrunt.co.uk/
  12085. * @author mrdoob / http://mrdoob.com/
  12086. * @author alteredq / http://alteredqualia.com/
  12087. * @author szimek / https://github.com/szimek/
  12088. */
  12089. THREE.WebGLRenderer = function ( parameters ) {
  12090. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  12091. parameters = parameters || {};
  12092. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  12093. _context = parameters.context !== undefined ? parameters.context : null,
  12094. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  12095. _buffers = {},
  12096. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  12097. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  12098. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  12099. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  12100. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  12101. _clearColor = new THREE.Color( 0x000000 ),
  12102. _clearAlpha = 0;
  12103. // public properties
  12104. this.domElement = _canvas;
  12105. this.context = null;
  12106. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  12107. ? parameters.devicePixelRatio
  12108. : self.devicePixelRatio !== undefined
  12109. ? self.devicePixelRatio
  12110. : 1;
  12111. // clearing
  12112. this.autoClear = true;
  12113. this.autoClearColor = true;
  12114. this.autoClearDepth = true;
  12115. this.autoClearStencil = true;
  12116. // scene graph
  12117. this.sortObjects = true;
  12118. this.autoUpdateObjects = true;
  12119. // physically based shading
  12120. this.gammaInput = false;
  12121. this.gammaOutput = false;
  12122. // shadow map
  12123. this.shadowMapEnabled = false;
  12124. this.shadowMapAutoUpdate = true;
  12125. this.shadowMapType = THREE.PCFShadowMap;
  12126. this.shadowMapCullFace = THREE.CullFaceFront;
  12127. this.shadowMapDebug = false;
  12128. this.shadowMapCascade = false;
  12129. // morphs
  12130. this.maxMorphTargets = 8;
  12131. this.maxMorphNormals = 4;
  12132. // flags
  12133. this.autoScaleCubemaps = true;
  12134. // custom render plugins
  12135. this.renderPluginsPre = [];
  12136. this.renderPluginsPost = [];
  12137. // info
  12138. this.info = {
  12139. memory: {
  12140. programs: 0,
  12141. geometries: 0,
  12142. textures: 0
  12143. },
  12144. render: {
  12145. calls: 0,
  12146. vertices: 0,
  12147. faces: 0,
  12148. points: 0
  12149. }
  12150. };
  12151. // internal properties
  12152. var _this = this,
  12153. _programs = [],
  12154. _programs_counter = 0,
  12155. // internal state cache
  12156. _currentProgram = null,
  12157. _currentFramebuffer = null,
  12158. _currentMaterialId = -1,
  12159. _currentGeometryGroupHash = null,
  12160. _currentCamera = null,
  12161. _usedTextureUnits = 0,
  12162. // GL state cache
  12163. _oldDoubleSided = -1,
  12164. _oldFlipSided = -1,
  12165. _oldBlending = -1,
  12166. _oldBlendEquation = -1,
  12167. _oldBlendSrc = -1,
  12168. _oldBlendDst = -1,
  12169. _oldDepthTest = -1,
  12170. _oldDepthWrite = -1,
  12171. _oldPolygonOffset = null,
  12172. _oldPolygonOffsetFactor = null,
  12173. _oldPolygonOffsetUnits = null,
  12174. _oldLineWidth = null,
  12175. _viewportX = 0,
  12176. _viewportY = 0,
  12177. _viewportWidth = _canvas.width,
  12178. _viewportHeight = _canvas.height,
  12179. _currentWidth = 0,
  12180. _currentHeight = 0,
  12181. _enabledAttributes = new Uint8Array( 16 ),
  12182. // frustum
  12183. _frustum = new THREE.Frustum(),
  12184. // camera matrices cache
  12185. _projScreenMatrix = new THREE.Matrix4(),
  12186. _projScreenMatrixPS = new THREE.Matrix4(),
  12187. _vector3 = new THREE.Vector3(),
  12188. // light arrays cache
  12189. _direction = new THREE.Vector3(),
  12190. _lightsNeedUpdate = true,
  12191. _lights = {
  12192. ambient: [ 0, 0, 0 ],
  12193. directional: { length: 0, colors: new Array(), positions: new Array() },
  12194. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  12195. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  12196. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  12197. };
  12198. // initialize
  12199. var _gl;
  12200. var _glExtensionTextureFloat;
  12201. var _glExtensionTextureFloatLinear;
  12202. var _glExtensionStandardDerivatives;
  12203. var _glExtensionTextureFilterAnisotropic;
  12204. var _glExtensionCompressedTextureS3TC;
  12205. initGL();
  12206. setDefaultGLState();
  12207. this.context = _gl;
  12208. // GPU capabilities
  12209. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  12210. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  12211. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  12212. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  12213. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  12214. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  12215. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  12216. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  12217. //
  12218. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  12219. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  12220. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  12221. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  12222. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  12223. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  12224. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  12225. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  12226. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  12227. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  12228. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  12229. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  12230. // clamp precision to maximum available
  12231. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  12232. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  12233. if ( _precision === "highp" && ! highpAvailable ) {
  12234. if ( mediumpAvailable ) {
  12235. _precision = "mediump";
  12236. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  12237. } else {
  12238. _precision = "lowp";
  12239. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  12240. }
  12241. }
  12242. if ( _precision === "mediump" && ! mediumpAvailable ) {
  12243. _precision = "lowp";
  12244. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  12245. }
  12246. // API
  12247. this.getContext = function () {
  12248. return _gl;
  12249. };
  12250. this.supportsVertexTextures = function () {
  12251. return _supportsVertexTextures;
  12252. };
  12253. this.supportsFloatTextures = function () {
  12254. return _glExtensionTextureFloat;
  12255. };
  12256. this.supportsStandardDerivatives = function () {
  12257. return _glExtensionStandardDerivatives;
  12258. };
  12259. this.supportsCompressedTextureS3TC = function () {
  12260. return _glExtensionCompressedTextureS3TC;
  12261. };
  12262. this.getMaxAnisotropy = function () {
  12263. return _maxAnisotropy;
  12264. };
  12265. this.getPrecision = function () {
  12266. return _precision;
  12267. };
  12268. this.setSize = function ( width, height, updateStyle ) {
  12269. _canvas.width = width * this.devicePixelRatio;
  12270. _canvas.height = height * this.devicePixelRatio;
  12271. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  12272. _canvas.style.width = width + 'px';
  12273. _canvas.style.height = height + 'px';
  12274. }
  12275. this.setViewport( 0, 0, width, height );
  12276. };
  12277. this.setViewport = function ( x, y, width, height ) {
  12278. _viewportX = x * this.devicePixelRatio;
  12279. _viewportY = y * this.devicePixelRatio;
  12280. _viewportWidth = width * this.devicePixelRatio;
  12281. _viewportHeight = height * this.devicePixelRatio;
  12282. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  12283. };
  12284. this.setScissor = function ( x, y, width, height ) {
  12285. _gl.scissor(
  12286. x * this.devicePixelRatio,
  12287. y * this.devicePixelRatio,
  12288. width * this.devicePixelRatio,
  12289. height * this.devicePixelRatio
  12290. );
  12291. };
  12292. this.enableScissorTest = function ( enable ) {
  12293. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  12294. };
  12295. // Clearing
  12296. this.setClearColor = function ( color, alpha ) {
  12297. _clearColor.set( color );
  12298. _clearAlpha = alpha !== undefined ? alpha : 1;
  12299. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  12300. };
  12301. this.setClearColorHex = function ( hex, alpha ) {
  12302. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  12303. this.setClearColor( hex, alpha );
  12304. };
  12305. this.getClearColor = function () {
  12306. return _clearColor;
  12307. };
  12308. this.getClearAlpha = function () {
  12309. return _clearAlpha;
  12310. };
  12311. this.clear = function ( color, depth, stencil ) {
  12312. var bits = 0;
  12313. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  12314. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  12315. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  12316. _gl.clear( bits );
  12317. };
  12318. this.clearColor = function () {
  12319. _gl.clear( _gl.COLOR_BUFFER_BIT );
  12320. };
  12321. this.clearDepth = function () {
  12322. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  12323. };
  12324. this.clearStencil = function () {
  12325. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  12326. };
  12327. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  12328. this.setRenderTarget( renderTarget );
  12329. this.clear( color, depth, stencil );
  12330. };
  12331. // Plugins
  12332. this.addPostPlugin = function ( plugin ) {
  12333. plugin.init( this );
  12334. this.renderPluginsPost.push( plugin );
  12335. };
  12336. this.addPrePlugin = function ( plugin ) {
  12337. plugin.init( this );
  12338. this.renderPluginsPre.push( plugin );
  12339. };
  12340. // Rendering
  12341. this.updateShadowMap = function ( scene, camera ) {
  12342. _currentProgram = null;
  12343. _oldBlending = -1;
  12344. _oldDepthTest = -1;
  12345. _oldDepthWrite = -1;
  12346. _currentGeometryGroupHash = -1;
  12347. _currentMaterialId = -1;
  12348. _lightsNeedUpdate = true;
  12349. _oldDoubleSided = -1;
  12350. _oldFlipSided = -1;
  12351. this.shadowMapPlugin.update( scene, camera );
  12352. };
  12353. // Internal functions
  12354. // Buffer allocation
  12355. function createParticleBuffers ( geometry ) {
  12356. geometry.__webglVertexBuffer = _gl.createBuffer();
  12357. geometry.__webglColorBuffer = _gl.createBuffer();
  12358. _this.info.memory.geometries ++;
  12359. };
  12360. function createLineBuffers ( geometry ) {
  12361. geometry.__webglVertexBuffer = _gl.createBuffer();
  12362. geometry.__webglColorBuffer = _gl.createBuffer();
  12363. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  12364. _this.info.memory.geometries ++;
  12365. };
  12366. function createMeshBuffers ( geometryGroup ) {
  12367. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  12368. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  12369. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  12370. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  12371. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  12372. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  12373. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  12374. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  12375. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  12376. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  12377. var m, ml;
  12378. if ( geometryGroup.numMorphTargets ) {
  12379. geometryGroup.__webglMorphTargetsBuffers = [];
  12380. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12381. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  12382. }
  12383. }
  12384. if ( geometryGroup.numMorphNormals ) {
  12385. geometryGroup.__webglMorphNormalsBuffers = [];
  12386. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12387. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  12388. }
  12389. }
  12390. _this.info.memory.geometries ++;
  12391. };
  12392. // Events
  12393. var onGeometryDispose = function ( event ) {
  12394. var geometry = event.target;
  12395. geometry.removeEventListener( 'dispose', onGeometryDispose );
  12396. deallocateGeometry( geometry );
  12397. };
  12398. var onTextureDispose = function ( event ) {
  12399. var texture = event.target;
  12400. texture.removeEventListener( 'dispose', onTextureDispose );
  12401. deallocateTexture( texture );
  12402. _this.info.memory.textures --;
  12403. };
  12404. var onRenderTargetDispose = function ( event ) {
  12405. var renderTarget = event.target;
  12406. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  12407. deallocateRenderTarget( renderTarget );
  12408. _this.info.memory.textures --;
  12409. };
  12410. var onMaterialDispose = function ( event ) {
  12411. var material = event.target;
  12412. material.removeEventListener( 'dispose', onMaterialDispose );
  12413. deallocateMaterial( material );
  12414. };
  12415. // Buffer deallocation
  12416. var deleteBuffers = function ( geometry ) {
  12417. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  12418. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  12419. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  12420. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  12421. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  12422. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  12423. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  12424. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  12425. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  12426. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  12427. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  12428. // custom attributes
  12429. if ( geometry.__webglCustomAttributesList !== undefined ) {
  12430. for ( var id in geometry.__webglCustomAttributesList ) {
  12431. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  12432. }
  12433. }
  12434. _this.info.memory.geometries --;
  12435. };
  12436. var deallocateGeometry = function ( geometry ) {
  12437. geometry.__webglInit = undefined;
  12438. if ( geometry instanceof THREE.BufferGeometry ) {
  12439. var attributes = geometry.attributes;
  12440. for ( var key in attributes ) {
  12441. if ( attributes[ key ].buffer !== undefined ) {
  12442. _gl.deleteBuffer( attributes[ key ].buffer );
  12443. }
  12444. }
  12445. _this.info.memory.geometries --;
  12446. } if ( geometry instanceof THREE.Geometry2 ) {
  12447. delete _buffers[ geometry.id ];
  12448. _this.info.memory.geometries --;
  12449. } else {
  12450. if ( geometry.geometryGroups !== undefined ) {
  12451. for ( var g in geometry.geometryGroups ) {
  12452. var geometryGroup = geometry.geometryGroups[ g ];
  12453. if ( geometryGroup.numMorphTargets !== undefined ) {
  12454. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12455. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  12456. }
  12457. }
  12458. if ( geometryGroup.numMorphNormals !== undefined ) {
  12459. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12460. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  12461. }
  12462. }
  12463. deleteBuffers( geometryGroup );
  12464. }
  12465. } else {
  12466. deleteBuffers( geometry );
  12467. }
  12468. }
  12469. };
  12470. var deallocateTexture = function ( texture ) {
  12471. if ( texture.image && texture.image.__webglTextureCube ) {
  12472. // cube texture
  12473. _gl.deleteTexture( texture.image.__webglTextureCube );
  12474. } else {
  12475. // 2D texture
  12476. if ( ! texture.__webglInit ) return;
  12477. texture.__webglInit = false;
  12478. _gl.deleteTexture( texture.__webglTexture );
  12479. }
  12480. };
  12481. var deallocateRenderTarget = function ( renderTarget ) {
  12482. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  12483. _gl.deleteTexture( renderTarget.__webglTexture );
  12484. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  12485. for ( var i = 0; i < 6; i ++ ) {
  12486. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  12487. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  12488. }
  12489. } else {
  12490. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  12491. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  12492. }
  12493. };
  12494. var deallocateMaterial = function ( material ) {
  12495. var program = material.program;
  12496. if ( program === undefined ) return;
  12497. material.program = undefined;
  12498. // only deallocate GL program if this was the last use of shared program
  12499. // assumed there is only single copy of any program in the _programs list
  12500. // (that's how it's constructed)
  12501. var i, il, programInfo;
  12502. var deleteProgram = false;
  12503. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12504. programInfo = _programs[ i ];
  12505. if ( programInfo.program === program ) {
  12506. programInfo.usedTimes --;
  12507. if ( programInfo.usedTimes === 0 ) {
  12508. deleteProgram = true;
  12509. }
  12510. break;
  12511. }
  12512. }
  12513. if ( deleteProgram === true ) {
  12514. // avoid using array.splice, this is costlier than creating new array from scratch
  12515. var newPrograms = [];
  12516. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12517. programInfo = _programs[ i ];
  12518. if ( programInfo.program !== program ) {
  12519. newPrograms.push( programInfo );
  12520. }
  12521. }
  12522. _programs = newPrograms;
  12523. _gl.deleteProgram( program );
  12524. _this.info.memory.programs --;
  12525. }
  12526. };
  12527. // Buffer initialization
  12528. function initCustomAttributes ( geometry, object ) {
  12529. var nvertices = geometry.vertices.length;
  12530. var material = object.material;
  12531. if ( material.attributes ) {
  12532. if ( geometry.__webglCustomAttributesList === undefined ) {
  12533. geometry.__webglCustomAttributesList = [];
  12534. }
  12535. for ( var a in material.attributes ) {
  12536. var attribute = material.attributes[ a ];
  12537. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12538. attribute.__webglInitialized = true;
  12539. var size = 1; // "f" and "i"
  12540. if ( attribute.type === "v2" ) size = 2;
  12541. else if ( attribute.type === "v3" ) size = 3;
  12542. else if ( attribute.type === "v4" ) size = 4;
  12543. else if ( attribute.type === "c" ) size = 3;
  12544. attribute.size = size;
  12545. attribute.array = new Float32Array( nvertices * size );
  12546. attribute.buffer = _gl.createBuffer();
  12547. attribute.buffer.belongsToAttribute = a;
  12548. attribute.needsUpdate = true;
  12549. }
  12550. geometry.__webglCustomAttributesList.push( attribute );
  12551. }
  12552. }
  12553. };
  12554. function initParticleBuffers ( geometry, object ) {
  12555. var nvertices = geometry.vertices.length;
  12556. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12557. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12558. geometry.__sortArray = [];
  12559. geometry.__webglParticleCount = nvertices;
  12560. initCustomAttributes ( geometry, object );
  12561. };
  12562. function initLineBuffers ( geometry, object ) {
  12563. var nvertices = geometry.vertices.length;
  12564. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12565. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12566. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  12567. geometry.__webglLineCount = nvertices;
  12568. initCustomAttributes ( geometry, object );
  12569. };
  12570. function initMeshBuffers ( geometryGroup, object ) {
  12571. var geometry = object.geometry,
  12572. faces3 = geometryGroup.faces3,
  12573. nvertices = faces3.length * 3,
  12574. ntris = faces3.length * 1,
  12575. nlines = faces3.length * 3,
  12576. material = getBufferMaterial( object, geometryGroup ),
  12577. uvType = bufferGuessUVType( material ),
  12578. normalType = bufferGuessNormalType( material ),
  12579. vertexColorType = bufferGuessVertexColorType( material );
  12580. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  12581. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  12582. if ( normalType ) {
  12583. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  12584. }
  12585. if ( geometry.hasTangents ) {
  12586. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  12587. }
  12588. if ( vertexColorType ) {
  12589. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  12590. }
  12591. if ( uvType ) {
  12592. if ( geometry.faceVertexUvs.length > 0 ) {
  12593. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  12594. }
  12595. if ( geometry.faceVertexUvs.length > 1 ) {
  12596. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  12597. }
  12598. }
  12599. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  12600. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  12601. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  12602. }
  12603. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  12604. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  12605. var m, ml;
  12606. if ( geometryGroup.numMorphTargets ) {
  12607. geometryGroup.__morphTargetsArrays = [];
  12608. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12609. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  12610. }
  12611. }
  12612. if ( geometryGroup.numMorphNormals ) {
  12613. geometryGroup.__morphNormalsArrays = [];
  12614. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12615. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  12616. }
  12617. }
  12618. geometryGroup.__webglFaceCount = ntris * 3;
  12619. geometryGroup.__webglLineCount = nlines * 2;
  12620. // custom attributes
  12621. if ( material.attributes ) {
  12622. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  12623. geometryGroup.__webglCustomAttributesList = [];
  12624. }
  12625. for ( var a in material.attributes ) {
  12626. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  12627. // attribute buffers which are correctly indexed in the setMeshBuffers function
  12628. var originalAttribute = material.attributes[ a ];
  12629. var attribute = {};
  12630. for ( var property in originalAttribute ) {
  12631. attribute[ property ] = originalAttribute[ property ];
  12632. }
  12633. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12634. attribute.__webglInitialized = true;
  12635. var size = 1; // "f" and "i"
  12636. if( attribute.type === "v2" ) size = 2;
  12637. else if( attribute.type === "v3" ) size = 3;
  12638. else if( attribute.type === "v4" ) size = 4;
  12639. else if( attribute.type === "c" ) size = 3;
  12640. attribute.size = size;
  12641. attribute.array = new Float32Array( nvertices * size );
  12642. attribute.buffer = _gl.createBuffer();
  12643. attribute.buffer.belongsToAttribute = a;
  12644. originalAttribute.needsUpdate = true;
  12645. attribute.__original = originalAttribute;
  12646. }
  12647. geometryGroup.__webglCustomAttributesList.push( attribute );
  12648. }
  12649. }
  12650. geometryGroup.__inittedArrays = true;
  12651. };
  12652. function getBufferMaterial( object, geometryGroup ) {
  12653. return object.material instanceof THREE.MeshFaceMaterial
  12654. ? object.material.materials[ geometryGroup.materialIndex ]
  12655. : object.material;
  12656. };
  12657. function materialNeedsSmoothNormals ( material ) {
  12658. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  12659. };
  12660. function bufferGuessNormalType ( material ) {
  12661. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  12662. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  12663. return false;
  12664. }
  12665. if ( materialNeedsSmoothNormals( material ) ) {
  12666. return THREE.SmoothShading;
  12667. } else {
  12668. return THREE.FlatShading;
  12669. }
  12670. };
  12671. function bufferGuessVertexColorType( material ) {
  12672. if ( material.vertexColors ) {
  12673. return material.vertexColors;
  12674. }
  12675. return false;
  12676. };
  12677. function bufferGuessUVType( material ) {
  12678. // material must use some texture to require uvs
  12679. if ( material.map ||
  12680. material.lightMap ||
  12681. material.bumpMap ||
  12682. material.normalMap ||
  12683. material.specularMap ||
  12684. material instanceof THREE.ShaderMaterial ) {
  12685. return true;
  12686. }
  12687. return false;
  12688. };
  12689. //
  12690. function initDirectBuffers( geometry ) {
  12691. var a, attribute, type;
  12692. for ( a in geometry.attributes ) {
  12693. if ( a === "index" ) {
  12694. type = _gl.ELEMENT_ARRAY_BUFFER;
  12695. } else {
  12696. type = _gl.ARRAY_BUFFER;
  12697. }
  12698. attribute = geometry.attributes[ a ];
  12699. attribute.buffer = _gl.createBuffer();
  12700. _gl.bindBuffer( type, attribute.buffer );
  12701. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  12702. }
  12703. };
  12704. function initGeometry2Buffers( geometry ) {
  12705. var buffers = {};
  12706. var attributes = [ 'vertices', 'normals', 'uvs' ];
  12707. for ( var key in attributes ) {
  12708. var array = geometry[ attributes[ key ] ];
  12709. var buffer = _gl.createBuffer();
  12710. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12711. _gl.bufferData( _gl.ARRAY_BUFFER, array, _gl.STATIC_DRAW );
  12712. buffers[ attributes[ key ] ] = buffer;
  12713. }
  12714. _buffers[ geometry.id ] = buffers;
  12715. };
  12716. // Buffer setting
  12717. function setParticleBuffers ( geometry, hint, object ) {
  12718. var v, c, vertex, offset, index, color,
  12719. vertices = geometry.vertices,
  12720. vl = vertices.length,
  12721. colors = geometry.colors,
  12722. cl = colors.length,
  12723. vertexArray = geometry.__vertexArray,
  12724. colorArray = geometry.__colorArray,
  12725. sortArray = geometry.__sortArray,
  12726. dirtyVertices = geometry.verticesNeedUpdate,
  12727. dirtyElements = geometry.elementsNeedUpdate,
  12728. dirtyColors = geometry.colorsNeedUpdate,
  12729. customAttributes = geometry.__webglCustomAttributesList,
  12730. i, il,
  12731. a, ca, cal, value,
  12732. customAttribute;
  12733. if ( object.sortParticles ) {
  12734. _projScreenMatrixPS.copy( _projScreenMatrix );
  12735. _projScreenMatrixPS.multiply( object.matrixWorld );
  12736. for ( v = 0; v < vl; v ++ ) {
  12737. vertex = vertices[ v ];
  12738. _vector3.copy( vertex );
  12739. _vector3.applyProjection( _projScreenMatrixPS );
  12740. sortArray[ v ] = [ _vector3.z, v ];
  12741. }
  12742. sortArray.sort( numericalSort );
  12743. for ( v = 0; v < vl; v ++ ) {
  12744. vertex = vertices[ sortArray[v][1] ];
  12745. offset = v * 3;
  12746. vertexArray[ offset ] = vertex.x;
  12747. vertexArray[ offset + 1 ] = vertex.y;
  12748. vertexArray[ offset + 2 ] = vertex.z;
  12749. }
  12750. for ( c = 0; c < cl; c ++ ) {
  12751. offset = c * 3;
  12752. color = colors[ sortArray[c][1] ];
  12753. colorArray[ offset ] = color.r;
  12754. colorArray[ offset + 1 ] = color.g;
  12755. colorArray[ offset + 2 ] = color.b;
  12756. }
  12757. if ( customAttributes ) {
  12758. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12759. customAttribute = customAttributes[ i ];
  12760. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  12761. offset = 0;
  12762. cal = customAttribute.value.length;
  12763. if ( customAttribute.size === 1 ) {
  12764. for ( ca = 0; ca < cal; ca ++ ) {
  12765. index = sortArray[ ca ][ 1 ];
  12766. customAttribute.array[ ca ] = customAttribute.value[ index ];
  12767. }
  12768. } else if ( customAttribute.size === 2 ) {
  12769. for ( ca = 0; ca < cal; ca ++ ) {
  12770. index = sortArray[ ca ][ 1 ];
  12771. value = customAttribute.value[ index ];
  12772. customAttribute.array[ offset ] = value.x;
  12773. customAttribute.array[ offset + 1 ] = value.y;
  12774. offset += 2;
  12775. }
  12776. } else if ( customAttribute.size === 3 ) {
  12777. if ( customAttribute.type === "c" ) {
  12778. for ( ca = 0; ca < cal; ca ++ ) {
  12779. index = sortArray[ ca ][ 1 ];
  12780. value = customAttribute.value[ index ];
  12781. customAttribute.array[ offset ] = value.r;
  12782. customAttribute.array[ offset + 1 ] = value.g;
  12783. customAttribute.array[ offset + 2 ] = value.b;
  12784. offset += 3;
  12785. }
  12786. } else {
  12787. for ( ca = 0; ca < cal; ca ++ ) {
  12788. index = sortArray[ ca ][ 1 ];
  12789. value = customAttribute.value[ index ];
  12790. customAttribute.array[ offset ] = value.x;
  12791. customAttribute.array[ offset + 1 ] = value.y;
  12792. customAttribute.array[ offset + 2 ] = value.z;
  12793. offset += 3;
  12794. }
  12795. }
  12796. } else if ( customAttribute.size === 4 ) {
  12797. for ( ca = 0; ca < cal; ca ++ ) {
  12798. index = sortArray[ ca ][ 1 ];
  12799. value = customAttribute.value[ index ];
  12800. customAttribute.array[ offset ] = value.x;
  12801. customAttribute.array[ offset + 1 ] = value.y;
  12802. customAttribute.array[ offset + 2 ] = value.z;
  12803. customAttribute.array[ offset + 3 ] = value.w;
  12804. offset += 4;
  12805. }
  12806. }
  12807. }
  12808. }
  12809. } else {
  12810. if ( dirtyVertices ) {
  12811. for ( v = 0; v < vl; v ++ ) {
  12812. vertex = vertices[ v ];
  12813. offset = v * 3;
  12814. vertexArray[ offset ] = vertex.x;
  12815. vertexArray[ offset + 1 ] = vertex.y;
  12816. vertexArray[ offset + 2 ] = vertex.z;
  12817. }
  12818. }
  12819. if ( dirtyColors ) {
  12820. for ( c = 0; c < cl; c ++ ) {
  12821. color = colors[ c ];
  12822. offset = c * 3;
  12823. colorArray[ offset ] = color.r;
  12824. colorArray[ offset + 1 ] = color.g;
  12825. colorArray[ offset + 2 ] = color.b;
  12826. }
  12827. }
  12828. if ( customAttributes ) {
  12829. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12830. customAttribute = customAttributes[ i ];
  12831. if ( customAttribute.needsUpdate &&
  12832. ( customAttribute.boundTo === undefined ||
  12833. customAttribute.boundTo === "vertices") ) {
  12834. cal = customAttribute.value.length;
  12835. offset = 0;
  12836. if ( customAttribute.size === 1 ) {
  12837. for ( ca = 0; ca < cal; ca ++ ) {
  12838. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12839. }
  12840. } else if ( customAttribute.size === 2 ) {
  12841. for ( ca = 0; ca < cal; ca ++ ) {
  12842. value = customAttribute.value[ ca ];
  12843. customAttribute.array[ offset ] = value.x;
  12844. customAttribute.array[ offset + 1 ] = value.y;
  12845. offset += 2;
  12846. }
  12847. } else if ( customAttribute.size === 3 ) {
  12848. if ( customAttribute.type === "c" ) {
  12849. for ( ca = 0; ca < cal; ca ++ ) {
  12850. value = customAttribute.value[ ca ];
  12851. customAttribute.array[ offset ] = value.r;
  12852. customAttribute.array[ offset + 1 ] = value.g;
  12853. customAttribute.array[ offset + 2 ] = value.b;
  12854. offset += 3;
  12855. }
  12856. } else {
  12857. for ( ca = 0; ca < cal; ca ++ ) {
  12858. value = customAttribute.value[ ca ];
  12859. customAttribute.array[ offset ] = value.x;
  12860. customAttribute.array[ offset + 1 ] = value.y;
  12861. customAttribute.array[ offset + 2 ] = value.z;
  12862. offset += 3;
  12863. }
  12864. }
  12865. } else if ( customAttribute.size === 4 ) {
  12866. for ( ca = 0; ca < cal; ca ++ ) {
  12867. value = customAttribute.value[ ca ];
  12868. customAttribute.array[ offset ] = value.x;
  12869. customAttribute.array[ offset + 1 ] = value.y;
  12870. customAttribute.array[ offset + 2 ] = value.z;
  12871. customAttribute.array[ offset + 3 ] = value.w;
  12872. offset += 4;
  12873. }
  12874. }
  12875. }
  12876. }
  12877. }
  12878. }
  12879. if ( dirtyVertices || object.sortParticles ) {
  12880. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12881. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12882. }
  12883. if ( dirtyColors || object.sortParticles ) {
  12884. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12885. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12886. }
  12887. if ( customAttributes ) {
  12888. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12889. customAttribute = customAttributes[ i ];
  12890. if ( customAttribute.needsUpdate || object.sortParticles ) {
  12891. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12892. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12893. }
  12894. }
  12895. }
  12896. };
  12897. function setLineBuffers ( geometry, hint ) {
  12898. var v, c, d, vertex, offset, color,
  12899. vertices = geometry.vertices,
  12900. colors = geometry.colors,
  12901. lineDistances = geometry.lineDistances,
  12902. vl = vertices.length,
  12903. cl = colors.length,
  12904. dl = lineDistances.length,
  12905. vertexArray = geometry.__vertexArray,
  12906. colorArray = geometry.__colorArray,
  12907. lineDistanceArray = geometry.__lineDistanceArray,
  12908. dirtyVertices = geometry.verticesNeedUpdate,
  12909. dirtyColors = geometry.colorsNeedUpdate,
  12910. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  12911. customAttributes = geometry.__webglCustomAttributesList,
  12912. i, il,
  12913. a, ca, cal, value,
  12914. customAttribute;
  12915. if ( dirtyVertices ) {
  12916. for ( v = 0; v < vl; v ++ ) {
  12917. vertex = vertices[ v ];
  12918. offset = v * 3;
  12919. vertexArray[ offset ] = vertex.x;
  12920. vertexArray[ offset + 1 ] = vertex.y;
  12921. vertexArray[ offset + 2 ] = vertex.z;
  12922. }
  12923. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12924. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12925. }
  12926. if ( dirtyColors ) {
  12927. for ( c = 0; c < cl; c ++ ) {
  12928. color = colors[ c ];
  12929. offset = c * 3;
  12930. colorArray[ offset ] = color.r;
  12931. colorArray[ offset + 1 ] = color.g;
  12932. colorArray[ offset + 2 ] = color.b;
  12933. }
  12934. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12935. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12936. }
  12937. if ( dirtyLineDistances ) {
  12938. for ( d = 0; d < dl; d ++ ) {
  12939. lineDistanceArray[ d ] = lineDistances[ d ];
  12940. }
  12941. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  12942. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  12943. }
  12944. if ( customAttributes ) {
  12945. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12946. customAttribute = customAttributes[ i ];
  12947. if ( customAttribute.needsUpdate &&
  12948. ( customAttribute.boundTo === undefined ||
  12949. customAttribute.boundTo === "vertices" ) ) {
  12950. offset = 0;
  12951. cal = customAttribute.value.length;
  12952. if ( customAttribute.size === 1 ) {
  12953. for ( ca = 0; ca < cal; ca ++ ) {
  12954. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12955. }
  12956. } else if ( customAttribute.size === 2 ) {
  12957. for ( ca = 0; ca < cal; ca ++ ) {
  12958. value = customAttribute.value[ ca ];
  12959. customAttribute.array[ offset ] = value.x;
  12960. customAttribute.array[ offset + 1 ] = value.y;
  12961. offset += 2;
  12962. }
  12963. } else if ( customAttribute.size === 3 ) {
  12964. if ( customAttribute.type === "c" ) {
  12965. for ( ca = 0; ca < cal; ca ++ ) {
  12966. value = customAttribute.value[ ca ];
  12967. customAttribute.array[ offset ] = value.r;
  12968. customAttribute.array[ offset + 1 ] = value.g;
  12969. customAttribute.array[ offset + 2 ] = value.b;
  12970. offset += 3;
  12971. }
  12972. } else {
  12973. for ( ca = 0; ca < cal; ca ++ ) {
  12974. value = customAttribute.value[ ca ];
  12975. customAttribute.array[ offset ] = value.x;
  12976. customAttribute.array[ offset + 1 ] = value.y;
  12977. customAttribute.array[ offset + 2 ] = value.z;
  12978. offset += 3;
  12979. }
  12980. }
  12981. } else if ( customAttribute.size === 4 ) {
  12982. for ( ca = 0; ca < cal; ca ++ ) {
  12983. value = customAttribute.value[ ca ];
  12984. customAttribute.array[ offset ] = value.x;
  12985. customAttribute.array[ offset + 1 ] = value.y;
  12986. customAttribute.array[ offset + 2 ] = value.z;
  12987. customAttribute.array[ offset + 3 ] = value.w;
  12988. offset += 4;
  12989. }
  12990. }
  12991. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12992. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12993. }
  12994. }
  12995. }
  12996. };
  12997. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  12998. if ( ! geometryGroup.__inittedArrays ) {
  12999. return;
  13000. }
  13001. var normalType = bufferGuessNormalType( material ),
  13002. vertexColorType = bufferGuessVertexColorType( material ),
  13003. uvType = bufferGuessUVType( material ),
  13004. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  13005. var f, fl, fi, face,
  13006. vertexNormals, faceNormal, normal,
  13007. vertexColors, faceColor,
  13008. vertexTangents,
  13009. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  13010. c1, c2, c3, c4,
  13011. sw1, sw2, sw3, sw4,
  13012. si1, si2, si3, si4,
  13013. sa1, sa2, sa3, sa4,
  13014. sb1, sb2, sb3, sb4,
  13015. m, ml, i, il,
  13016. vn, uvi, uv2i,
  13017. vk, vkl, vka,
  13018. nka, chf, faceVertexNormals,
  13019. a,
  13020. vertexIndex = 0,
  13021. offset = 0,
  13022. offset_uv = 0,
  13023. offset_uv2 = 0,
  13024. offset_face = 0,
  13025. offset_normal = 0,
  13026. offset_tangent = 0,
  13027. offset_line = 0,
  13028. offset_color = 0,
  13029. offset_skin = 0,
  13030. offset_morphTarget = 0,
  13031. offset_custom = 0,
  13032. offset_customSrc = 0,
  13033. value,
  13034. vertexArray = geometryGroup.__vertexArray,
  13035. uvArray = geometryGroup.__uvArray,
  13036. uv2Array = geometryGroup.__uv2Array,
  13037. normalArray = geometryGroup.__normalArray,
  13038. tangentArray = geometryGroup.__tangentArray,
  13039. colorArray = geometryGroup.__colorArray,
  13040. skinIndexArray = geometryGroup.__skinIndexArray,
  13041. skinWeightArray = geometryGroup.__skinWeightArray,
  13042. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  13043. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  13044. customAttributes = geometryGroup.__webglCustomAttributesList,
  13045. customAttribute,
  13046. faceArray = geometryGroup.__faceArray,
  13047. lineArray = geometryGroup.__lineArray,
  13048. geometry = object.geometry, // this is shared for all chunks
  13049. dirtyVertices = geometry.verticesNeedUpdate,
  13050. dirtyElements = geometry.elementsNeedUpdate,
  13051. dirtyUvs = geometry.uvsNeedUpdate,
  13052. dirtyNormals = geometry.normalsNeedUpdate,
  13053. dirtyTangents = geometry.tangentsNeedUpdate,
  13054. dirtyColors = geometry.colorsNeedUpdate,
  13055. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  13056. vertices = geometry.vertices,
  13057. chunk_faces3 = geometryGroup.faces3,
  13058. obj_faces = geometry.faces,
  13059. obj_uvs = geometry.faceVertexUvs[ 0 ],
  13060. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  13061. obj_colors = geometry.colors,
  13062. obj_skinIndices = geometry.skinIndices,
  13063. obj_skinWeights = geometry.skinWeights,
  13064. morphTargets = geometry.morphTargets,
  13065. morphNormals = geometry.morphNormals;
  13066. if ( dirtyVertices ) {
  13067. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13068. face = obj_faces[ chunk_faces3[ f ] ];
  13069. v1 = vertices[ face.a ];
  13070. v2 = vertices[ face.b ];
  13071. v3 = vertices[ face.c ];
  13072. vertexArray[ offset ] = v1.x;
  13073. vertexArray[ offset + 1 ] = v1.y;
  13074. vertexArray[ offset + 2 ] = v1.z;
  13075. vertexArray[ offset + 3 ] = v2.x;
  13076. vertexArray[ offset + 4 ] = v2.y;
  13077. vertexArray[ offset + 5 ] = v2.z;
  13078. vertexArray[ offset + 6 ] = v3.x;
  13079. vertexArray[ offset + 7 ] = v3.y;
  13080. vertexArray[ offset + 8 ] = v3.z;
  13081. offset += 9;
  13082. }
  13083. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13084. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  13085. }
  13086. if ( dirtyMorphTargets ) {
  13087. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  13088. offset_morphTarget = 0;
  13089. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13090. chf = chunk_faces3[ f ];
  13091. face = obj_faces[ chf ];
  13092. // morph positions
  13093. v1 = morphTargets[ vk ].vertices[ face.a ];
  13094. v2 = morphTargets[ vk ].vertices[ face.b ];
  13095. v3 = morphTargets[ vk ].vertices[ face.c ];
  13096. vka = morphTargetsArrays[ vk ];
  13097. vka[ offset_morphTarget ] = v1.x;
  13098. vka[ offset_morphTarget + 1 ] = v1.y;
  13099. vka[ offset_morphTarget + 2 ] = v1.z;
  13100. vka[ offset_morphTarget + 3 ] = v2.x;
  13101. vka[ offset_morphTarget + 4 ] = v2.y;
  13102. vka[ offset_morphTarget + 5 ] = v2.z;
  13103. vka[ offset_morphTarget + 6 ] = v3.x;
  13104. vka[ offset_morphTarget + 7 ] = v3.y;
  13105. vka[ offset_morphTarget + 8 ] = v3.z;
  13106. // morph normals
  13107. if ( material.morphNormals ) {
  13108. if ( needsSmoothNormals ) {
  13109. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  13110. n1 = faceVertexNormals.a;
  13111. n2 = faceVertexNormals.b;
  13112. n3 = faceVertexNormals.c;
  13113. } else {
  13114. n1 = morphNormals[ vk ].faceNormals[ chf ];
  13115. n2 = n1;
  13116. n3 = n1;
  13117. }
  13118. nka = morphNormalsArrays[ vk ];
  13119. nka[ offset_morphTarget ] = n1.x;
  13120. nka[ offset_morphTarget + 1 ] = n1.y;
  13121. nka[ offset_morphTarget + 2 ] = n1.z;
  13122. nka[ offset_morphTarget + 3 ] = n2.x;
  13123. nka[ offset_morphTarget + 4 ] = n2.y;
  13124. nka[ offset_morphTarget + 5 ] = n2.z;
  13125. nka[ offset_morphTarget + 6 ] = n3.x;
  13126. nka[ offset_morphTarget + 7 ] = n3.y;
  13127. nka[ offset_morphTarget + 8 ] = n3.z;
  13128. }
  13129. //
  13130. offset_morphTarget += 9;
  13131. }
  13132. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  13133. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  13134. if ( material.morphNormals ) {
  13135. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  13136. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  13137. }
  13138. }
  13139. }
  13140. if ( obj_skinWeights.length ) {
  13141. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13142. face = obj_faces[ chunk_faces3[ f ] ];
  13143. // weights
  13144. sw1 = obj_skinWeights[ face.a ];
  13145. sw2 = obj_skinWeights[ face.b ];
  13146. sw3 = obj_skinWeights[ face.c ];
  13147. skinWeightArray[ offset_skin ] = sw1.x;
  13148. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  13149. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  13150. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  13151. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  13152. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  13153. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  13154. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  13155. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  13156. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  13157. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  13158. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  13159. // indices
  13160. si1 = obj_skinIndices[ face.a ];
  13161. si2 = obj_skinIndices[ face.b ];
  13162. si3 = obj_skinIndices[ face.c ];
  13163. skinIndexArray[ offset_skin ] = si1.x;
  13164. skinIndexArray[ offset_skin + 1 ] = si1.y;
  13165. skinIndexArray[ offset_skin + 2 ] = si1.z;
  13166. skinIndexArray[ offset_skin + 3 ] = si1.w;
  13167. skinIndexArray[ offset_skin + 4 ] = si2.x;
  13168. skinIndexArray[ offset_skin + 5 ] = si2.y;
  13169. skinIndexArray[ offset_skin + 6 ] = si2.z;
  13170. skinIndexArray[ offset_skin + 7 ] = si2.w;
  13171. skinIndexArray[ offset_skin + 8 ] = si3.x;
  13172. skinIndexArray[ offset_skin + 9 ] = si3.y;
  13173. skinIndexArray[ offset_skin + 10 ] = si3.z;
  13174. skinIndexArray[ offset_skin + 11 ] = si3.w;
  13175. offset_skin += 12;
  13176. }
  13177. if ( offset_skin > 0 ) {
  13178. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13179. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  13180. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13181. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  13182. }
  13183. }
  13184. if ( dirtyColors && vertexColorType ) {
  13185. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13186. face = obj_faces[ chunk_faces3[ f ] ];
  13187. vertexColors = face.vertexColors;
  13188. faceColor = face.color;
  13189. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  13190. c1 = vertexColors[ 0 ];
  13191. c2 = vertexColors[ 1 ];
  13192. c3 = vertexColors[ 2 ];
  13193. } else {
  13194. c1 = faceColor;
  13195. c2 = faceColor;
  13196. c3 = faceColor;
  13197. }
  13198. colorArray[ offset_color ] = c1.r;
  13199. colorArray[ offset_color + 1 ] = c1.g;
  13200. colorArray[ offset_color + 2 ] = c1.b;
  13201. colorArray[ offset_color + 3 ] = c2.r;
  13202. colorArray[ offset_color + 4 ] = c2.g;
  13203. colorArray[ offset_color + 5 ] = c2.b;
  13204. colorArray[ offset_color + 6 ] = c3.r;
  13205. colorArray[ offset_color + 7 ] = c3.g;
  13206. colorArray[ offset_color + 8 ] = c3.b;
  13207. offset_color += 9;
  13208. }
  13209. if ( offset_color > 0 ) {
  13210. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13211. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  13212. }
  13213. }
  13214. if ( dirtyTangents && geometry.hasTangents ) {
  13215. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13216. face = obj_faces[ chunk_faces3[ f ] ];
  13217. vertexTangents = face.vertexTangents;
  13218. t1 = vertexTangents[ 0 ];
  13219. t2 = vertexTangents[ 1 ];
  13220. t3 = vertexTangents[ 2 ];
  13221. tangentArray[ offset_tangent ] = t1.x;
  13222. tangentArray[ offset_tangent + 1 ] = t1.y;
  13223. tangentArray[ offset_tangent + 2 ] = t1.z;
  13224. tangentArray[ offset_tangent + 3 ] = t1.w;
  13225. tangentArray[ offset_tangent + 4 ] = t2.x;
  13226. tangentArray[ offset_tangent + 5 ] = t2.y;
  13227. tangentArray[ offset_tangent + 6 ] = t2.z;
  13228. tangentArray[ offset_tangent + 7 ] = t2.w;
  13229. tangentArray[ offset_tangent + 8 ] = t3.x;
  13230. tangentArray[ offset_tangent + 9 ] = t3.y;
  13231. tangentArray[ offset_tangent + 10 ] = t3.z;
  13232. tangentArray[ offset_tangent + 11 ] = t3.w;
  13233. offset_tangent += 12;
  13234. }
  13235. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13236. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  13237. }
  13238. if ( dirtyNormals && normalType ) {
  13239. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13240. face = obj_faces[ chunk_faces3[ f ] ];
  13241. vertexNormals = face.vertexNormals;
  13242. faceNormal = face.normal;
  13243. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  13244. for ( i = 0; i < 3; i ++ ) {
  13245. vn = vertexNormals[ i ];
  13246. normalArray[ offset_normal ] = vn.x;
  13247. normalArray[ offset_normal + 1 ] = vn.y;
  13248. normalArray[ offset_normal + 2 ] = vn.z;
  13249. offset_normal += 3;
  13250. }
  13251. } else {
  13252. for ( i = 0; i < 3; i ++ ) {
  13253. normalArray[ offset_normal ] = faceNormal.x;
  13254. normalArray[ offset_normal + 1 ] = faceNormal.y;
  13255. normalArray[ offset_normal + 2 ] = faceNormal.z;
  13256. offset_normal += 3;
  13257. }
  13258. }
  13259. }
  13260. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13261. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  13262. }
  13263. if ( dirtyUvs && obj_uvs && uvType ) {
  13264. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13265. fi = chunk_faces3[ f ];
  13266. uv = obj_uvs[ fi ];
  13267. if ( uv === undefined ) continue;
  13268. for ( i = 0; i < 3; i ++ ) {
  13269. uvi = uv[ i ];
  13270. uvArray[ offset_uv ] = uvi.x;
  13271. uvArray[ offset_uv + 1 ] = uvi.y;
  13272. offset_uv += 2;
  13273. }
  13274. }
  13275. if ( offset_uv > 0 ) {
  13276. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13277. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  13278. }
  13279. }
  13280. if ( dirtyUvs && obj_uvs2 && uvType ) {
  13281. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13282. fi = chunk_faces3[ f ];
  13283. uv2 = obj_uvs2[ fi ];
  13284. if ( uv2 === undefined ) continue;
  13285. for ( i = 0; i < 3; i ++ ) {
  13286. uv2i = uv2[ i ];
  13287. uv2Array[ offset_uv2 ] = uv2i.x;
  13288. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  13289. offset_uv2 += 2;
  13290. }
  13291. }
  13292. if ( offset_uv2 > 0 ) {
  13293. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13294. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  13295. }
  13296. }
  13297. if ( dirtyElements ) {
  13298. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13299. faceArray[ offset_face ] = vertexIndex;
  13300. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  13301. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  13302. offset_face += 3;
  13303. lineArray[ offset_line ] = vertexIndex;
  13304. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  13305. lineArray[ offset_line + 2 ] = vertexIndex;
  13306. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  13307. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  13308. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  13309. offset_line += 6;
  13310. vertexIndex += 3;
  13311. }
  13312. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13313. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  13314. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13315. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  13316. }
  13317. if ( customAttributes ) {
  13318. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13319. customAttribute = customAttributes[ i ];
  13320. if ( ! customAttribute.__original.needsUpdate ) continue;
  13321. offset_custom = 0;
  13322. offset_customSrc = 0;
  13323. if ( customAttribute.size === 1 ) {
  13324. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13325. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13326. face = obj_faces[ chunk_faces3[ f ] ];
  13327. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  13328. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  13329. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  13330. offset_custom += 3;
  13331. }
  13332. } else if ( customAttribute.boundTo === "faces" ) {
  13333. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13334. value = customAttribute.value[ chunk_faces3[ f ] ];
  13335. customAttribute.array[ offset_custom ] = value;
  13336. customAttribute.array[ offset_custom + 1 ] = value;
  13337. customAttribute.array[ offset_custom + 2 ] = value;
  13338. offset_custom += 3;
  13339. }
  13340. }
  13341. } else if ( customAttribute.size === 2 ) {
  13342. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13343. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13344. face = obj_faces[ chunk_faces3[ f ] ];
  13345. v1 = customAttribute.value[ face.a ];
  13346. v2 = customAttribute.value[ face.b ];
  13347. v3 = customAttribute.value[ face.c ];
  13348. customAttribute.array[ offset_custom ] = v1.x;
  13349. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13350. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13351. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13352. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13353. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13354. offset_custom += 6;
  13355. }
  13356. } else if ( customAttribute.boundTo === "faces" ) {
  13357. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13358. value = customAttribute.value[ chunk_faces3[ f ] ];
  13359. v1 = value;
  13360. v2 = value;
  13361. v3 = value;
  13362. customAttribute.array[ offset_custom ] = v1.x;
  13363. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13364. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13365. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13366. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13367. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13368. offset_custom += 6;
  13369. }
  13370. }
  13371. } else if ( customAttribute.size === 3 ) {
  13372. var pp;
  13373. if ( customAttribute.type === "c" ) {
  13374. pp = [ "r", "g", "b" ];
  13375. } else {
  13376. pp = [ "x", "y", "z" ];
  13377. }
  13378. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13379. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13380. face = obj_faces[ chunk_faces3[ f ] ];
  13381. v1 = customAttribute.value[ face.a ];
  13382. v2 = customAttribute.value[ face.b ];
  13383. v3 = customAttribute.value[ face.c ];
  13384. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13385. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13386. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13387. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13388. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13389. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13390. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13391. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13392. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13393. offset_custom += 9;
  13394. }
  13395. } else if ( customAttribute.boundTo === "faces" ) {
  13396. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13397. value = customAttribute.value[ chunk_faces3[ f ] ];
  13398. v1 = value;
  13399. v2 = value;
  13400. v3 = value;
  13401. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13402. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13403. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13404. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13405. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13406. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13407. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13408. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13409. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13410. offset_custom += 9;
  13411. }
  13412. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13413. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13414. value = customAttribute.value[ chunk_faces3[ f ] ];
  13415. v1 = value[ 0 ];
  13416. v2 = value[ 1 ];
  13417. v3 = value[ 2 ];
  13418. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13419. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13420. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13421. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13422. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13423. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13424. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13425. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13426. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13427. offset_custom += 9;
  13428. }
  13429. }
  13430. } else if ( customAttribute.size === 4 ) {
  13431. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13432. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13433. face = obj_faces[ chunk_faces3[ f ] ];
  13434. v1 = customAttribute.value[ face.a ];
  13435. v2 = customAttribute.value[ face.b ];
  13436. v3 = customAttribute.value[ face.c ];
  13437. customAttribute.array[ offset_custom ] = v1.x;
  13438. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13439. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13440. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13441. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13442. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13443. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13444. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13445. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13446. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13447. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13448. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13449. offset_custom += 12;
  13450. }
  13451. } else if ( customAttribute.boundTo === "faces" ) {
  13452. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13453. value = customAttribute.value[ chunk_faces3[ f ] ];
  13454. v1 = value;
  13455. v2 = value;
  13456. v3 = value;
  13457. customAttribute.array[ offset_custom ] = v1.x;
  13458. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13459. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13460. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13461. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13462. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13463. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13464. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13465. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13466. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13467. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13468. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13469. offset_custom += 12;
  13470. }
  13471. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13472. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13473. value = customAttribute.value[ chunk_faces3[ f ] ];
  13474. v1 = value[ 0 ];
  13475. v2 = value[ 1 ];
  13476. v3 = value[ 2 ];
  13477. customAttribute.array[ offset_custom ] = v1.x;
  13478. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13479. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13480. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13481. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13482. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13483. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13484. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13485. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13486. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13487. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13488. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13489. offset_custom += 12;
  13490. }
  13491. }
  13492. }
  13493. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  13494. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  13495. }
  13496. }
  13497. if ( dispose ) {
  13498. delete geometryGroup.__inittedArrays;
  13499. delete geometryGroup.__colorArray;
  13500. delete geometryGroup.__normalArray;
  13501. delete geometryGroup.__tangentArray;
  13502. delete geometryGroup.__uvArray;
  13503. delete geometryGroup.__uv2Array;
  13504. delete geometryGroup.__faceArray;
  13505. delete geometryGroup.__vertexArray;
  13506. delete geometryGroup.__lineArray;
  13507. delete geometryGroup.__skinIndexArray;
  13508. delete geometryGroup.__skinWeightArray;
  13509. }
  13510. };
  13511. // used by renderBufferDirect for THREE.Line
  13512. function setupLinesVertexAttributes( material, programAttributes, geometryAttributes, startIndex ) {
  13513. var attributeItem, attributeName, attributePointer, attributeSize;
  13514. for ( attributeName in programAttributes ) {
  13515. attributePointer = programAttributes[ attributeName ];
  13516. attributeItem = geometryAttributes[ attributeName ];
  13517. if ( attributePointer >= 0 ) {
  13518. if ( attributeItem ) {
  13519. attributeSize = attributeItem.itemSize;
  13520. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13521. enableAttribute( attributePointer );
  13522. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13523. } else if ( material.defaultAttributeValues ) {
  13524. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13525. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13526. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13527. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13528. }
  13529. }
  13530. }
  13531. }
  13532. }
  13533. function setDirectBuffers( geometry, hint ) {
  13534. var attributes = geometry.attributes;
  13535. var attributeName, attributeItem;
  13536. for ( attributeName in attributes ) {
  13537. attributeItem = attributes[ attributeName ];
  13538. if ( attributeItem.needsUpdate ) {
  13539. if ( attributeName === 'index' ) {
  13540. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  13541. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  13542. } else {
  13543. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13544. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  13545. }
  13546. attributeItem.needsUpdate = false;
  13547. }
  13548. }
  13549. }
  13550. function setGeometry2Buffers( geometry, hint ) {
  13551. if ( geometry.needsUpdate === false ) return;
  13552. var attributes = [ 'vertices', 'normals', 'uvs' ];
  13553. var buffers = _buffers[ geometry.id ];
  13554. for ( var key in attributes ) {
  13555. var array = geometry[ attributes[ key ] ];
  13556. var buffer = buffers[ attributes[ key ] ];
  13557. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  13558. _gl.bufferData( _gl.ARRAY_BUFFER, array, hint );
  13559. }
  13560. geometry.needsUpdate = false;
  13561. };
  13562. // Buffer rendering
  13563. this.renderBufferImmediate = function ( object, program, material ) {
  13564. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  13565. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  13566. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  13567. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  13568. if ( object.hasPositions ) {
  13569. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  13570. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  13571. _gl.enableVertexAttribArray( program.attributes.position );
  13572. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13573. }
  13574. if ( object.hasNormals ) {
  13575. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  13576. if ( material.shading === THREE.FlatShading ) {
  13577. var nx, ny, nz,
  13578. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  13579. normalArray,
  13580. i, il = object.count * 3;
  13581. for( i = 0; i < il; i += 9 ) {
  13582. normalArray = object.normalArray;
  13583. nax = normalArray[ i ];
  13584. nay = normalArray[ i + 1 ];
  13585. naz = normalArray[ i + 2 ];
  13586. nbx = normalArray[ i + 3 ];
  13587. nby = normalArray[ i + 4 ];
  13588. nbz = normalArray[ i + 5 ];
  13589. ncx = normalArray[ i + 6 ];
  13590. ncy = normalArray[ i + 7 ];
  13591. ncz = normalArray[ i + 8 ];
  13592. nx = ( nax + nbx + ncx ) / 3;
  13593. ny = ( nay + nby + ncy ) / 3;
  13594. nz = ( naz + nbz + ncz ) / 3;
  13595. normalArray[ i ] = nx;
  13596. normalArray[ i + 1 ] = ny;
  13597. normalArray[ i + 2 ] = nz;
  13598. normalArray[ i + 3 ] = nx;
  13599. normalArray[ i + 4 ] = ny;
  13600. normalArray[ i + 5 ] = nz;
  13601. normalArray[ i + 6 ] = nx;
  13602. normalArray[ i + 7 ] = ny;
  13603. normalArray[ i + 8 ] = nz;
  13604. }
  13605. }
  13606. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13607. _gl.enableVertexAttribArray( program.attributes.normal );
  13608. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13609. }
  13610. if ( object.hasUvs && material.map ) {
  13611. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13612. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13613. _gl.enableVertexAttribArray( program.attributes.uv );
  13614. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13615. }
  13616. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13617. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13618. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13619. _gl.enableVertexAttribArray( program.attributes.color );
  13620. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13621. }
  13622. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13623. object.count = 0;
  13624. };
  13625. this.renderBufferGeometry2 = function ( camera, lights, fog, material, geometry, object ) {
  13626. var program = setProgram( camera, lights, fog, material, object );
  13627. var programAttributes = program.attributes;
  13628. var attributes = { 'position': 'vertices', 'normal': 'normals', 'uv': 'uvs' };
  13629. var itemSizes = { 'position': 3, 'normal': 3, 'uv': 2 };
  13630. var buffers = _buffers[ geometry.id ];
  13631. disableAttributes();
  13632. for ( var name in programAttributes ) {
  13633. var attributePointer = programAttributes[ name ];
  13634. if ( attributePointer >= 0 ) {
  13635. var array = geometry[ attributes[ name ] ];
  13636. if ( array !== undefined && array.length > 0 ) {
  13637. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers[ attributes[ name ] ] );
  13638. enableAttribute( attributePointer );
  13639. _gl.vertexAttribPointer( attributePointer, itemSizes[ name ], _gl.FLOAT, false, 0, 0 );
  13640. } else {
  13641. if ( itemSizes[ name ] === 3 ) {
  13642. _gl.vertexAttrib3fv( attributePointer, [ 0, 0, 0 ] );
  13643. } else if ( itemSizes[ name ] === 2 ) {
  13644. _gl.vertexAttrib2fv( attributePointer, [ 0, 0 ] );
  13645. }
  13646. }
  13647. }
  13648. }
  13649. _gl.drawArrays( _gl.TRIANGLES, 0, geometry.vertices.length / 3 );
  13650. };
  13651. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  13652. if ( material.visible === false ) return;
  13653. var linewidth, a, attribute;
  13654. var attributeItem, attributeName, attributePointer, attributeSize;
  13655. var program = setProgram( camera, lights, fog, material, object );
  13656. var programAttributes = program.attributes;
  13657. var geometryAttributes = geometry.attributes;
  13658. var updateBuffers = false,
  13659. wireframeBit = material.wireframe ? 1 : 0,
  13660. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13661. if ( geometryHash !== _currentGeometryGroupHash ) {
  13662. _currentGeometryGroupHash = geometryHash;
  13663. updateBuffers = true;
  13664. }
  13665. if ( updateBuffers ) {
  13666. disableAttributes();
  13667. }
  13668. // render mesh
  13669. if ( object instanceof THREE.Mesh ) {
  13670. var index = geometryAttributes[ "index" ];
  13671. // indexed triangles
  13672. if ( index ) {
  13673. var offsets = geometry.offsets;
  13674. // if there is more than 1 chunk
  13675. // must set attribute pointers to use new offsets for each chunk
  13676. // even if geometry and materials didn't change
  13677. if ( offsets.length > 1 ) updateBuffers = true;
  13678. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13679. var startIndex = offsets[ i ].index;
  13680. if ( updateBuffers ) {
  13681. for ( attributeName in programAttributes ) {
  13682. attributePointer = programAttributes[ attributeName ];
  13683. attributeItem = geometryAttributes[ attributeName ];
  13684. if ( attributePointer >= 0 ) {
  13685. if ( attributeItem ) {
  13686. attributeSize = attributeItem.itemSize;
  13687. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13688. enableAttribute( attributePointer );
  13689. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13690. } else if ( material.defaultAttributeValues ) {
  13691. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13692. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13693. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13694. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13695. }
  13696. }
  13697. }
  13698. }
  13699. // indices
  13700. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13701. }
  13702. // render indexed triangles
  13703. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  13704. _this.info.render.calls ++;
  13705. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13706. _this.info.render.faces += offsets[ i ].count / 3;
  13707. }
  13708. // non-indexed triangles
  13709. } else {
  13710. if ( updateBuffers ) {
  13711. for ( attributeName in programAttributes ) {
  13712. if ( attributeName === 'index') continue;
  13713. attributePointer = programAttributes[ attributeName ];
  13714. attributeItem = geometryAttributes[ attributeName ];
  13715. if ( attributePointer >= 0 ) {
  13716. if ( attributeItem ) {
  13717. attributeSize = attributeItem.itemSize;
  13718. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13719. enableAttribute( attributePointer );
  13720. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13721. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  13722. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13723. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13724. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13725. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13726. }
  13727. }
  13728. }
  13729. }
  13730. }
  13731. var position = geometry.attributes[ "position" ];
  13732. // render non-indexed triangles
  13733. _gl.drawArrays( _gl.TRIANGLES, 0, position.array.length / 3 );
  13734. _this.info.render.calls ++;
  13735. _this.info.render.vertices += position.array.length / 3;
  13736. _this.info.render.faces += position.array.length / 3 / 3;
  13737. }
  13738. // render particles
  13739. } else if ( object instanceof THREE.ParticleSystem ) {
  13740. if ( updateBuffers ) {
  13741. for ( attributeName in programAttributes ) {
  13742. attributePointer = programAttributes[ attributeName ];
  13743. attributeItem = geometryAttributes[ attributeName ];
  13744. if ( attributePointer >= 0 ) {
  13745. if ( attributeItem ) {
  13746. attributeSize = attributeItem.itemSize;
  13747. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13748. enableAttribute( attributePointer );
  13749. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13750. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  13751. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13752. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13753. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13754. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13755. }
  13756. }
  13757. }
  13758. }
  13759. }
  13760. var position = geometryAttributes[ "position" ];
  13761. // render particles
  13762. _gl.drawArrays( _gl.POINTS, 0, position.array.length / 3 );
  13763. _this.info.render.calls ++;
  13764. _this.info.render.points += position.array.length / 3;
  13765. } else if ( object instanceof THREE.Line ) {
  13766. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13767. setLineWidth( material.linewidth );
  13768. var index = geometryAttributes[ "index" ];
  13769. // indexed lines
  13770. if ( index ) {
  13771. var offsets = geometry.offsets;
  13772. // if there is more than 1 chunk
  13773. // must set attribute pointers to use new offsets for each chunk
  13774. // even if geometry and materials didn't change
  13775. if ( offsets.length > 1 ) updateBuffers = true;
  13776. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13777. var startIndex = offsets[ i ].index;
  13778. if ( updateBuffers ) {
  13779. setupLinesVertexAttributes(material, programAttributes, geometryAttributes, startIndex);
  13780. // indices
  13781. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13782. }
  13783. // render indexed lines
  13784. _gl.drawElements( _gl.LINES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16Array
  13785. _this.info.render.calls ++;
  13786. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13787. }
  13788. }
  13789. // non-indexed lines
  13790. else {
  13791. if ( updateBuffers ) {
  13792. setupLinesVertexAttributes(material, programAttributes, geometryAttributes, 0);
  13793. }
  13794. var position = geometryAttributes[ "position" ];
  13795. _gl.drawArrays( primitives, 0, position.array.length / 3 );
  13796. _this.info.render.calls ++;
  13797. _this.info.render.points += position.array.length;
  13798. }
  13799. }
  13800. };
  13801. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  13802. if ( material.visible === false ) return;
  13803. var linewidth, a, attribute, i, il;
  13804. var program = setProgram( camera, lights, fog, material, object );
  13805. var attributes = program.attributes;
  13806. var updateBuffers = false,
  13807. wireframeBit = material.wireframe ? 1 : 0,
  13808. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13809. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  13810. _currentGeometryGroupHash = geometryGroupHash;
  13811. updateBuffers = true;
  13812. }
  13813. if ( updateBuffers ) {
  13814. disableAttributes();
  13815. }
  13816. // vertices
  13817. if ( !material.morphTargets && attributes.position >= 0 ) {
  13818. if ( updateBuffers ) {
  13819. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13820. enableAttribute( attributes.position );
  13821. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13822. }
  13823. } else {
  13824. if ( object.morphTargetBase ) {
  13825. setupMorphTargets( material, geometryGroup, object );
  13826. }
  13827. }
  13828. if ( updateBuffers ) {
  13829. // custom attributes
  13830. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  13831. if ( geometryGroup.__webglCustomAttributesList ) {
  13832. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  13833. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  13834. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  13835. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  13836. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  13837. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  13838. }
  13839. }
  13840. }
  13841. // colors
  13842. if ( attributes.color >= 0 ) {
  13843. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  13844. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13845. enableAttribute( attributes.color );
  13846. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13847. } else if ( material.defaultAttributeValues ) {
  13848. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  13849. }
  13850. }
  13851. // normals
  13852. if ( attributes.normal >= 0 ) {
  13853. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13854. enableAttribute( attributes.normal );
  13855. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13856. }
  13857. // tangents
  13858. if ( attributes.tangent >= 0 ) {
  13859. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13860. enableAttribute( attributes.tangent );
  13861. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  13862. }
  13863. // uvs
  13864. if ( attributes.uv >= 0 ) {
  13865. if ( object.geometry.faceVertexUvs[0] ) {
  13866. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13867. enableAttribute( attributes.uv );
  13868. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13869. } else if ( material.defaultAttributeValues ) {
  13870. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  13871. }
  13872. }
  13873. if ( attributes.uv2 >= 0 ) {
  13874. if ( object.geometry.faceVertexUvs[1] ) {
  13875. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13876. enableAttribute( attributes.uv2 );
  13877. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  13878. } else if ( material.defaultAttributeValues ) {
  13879. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  13880. }
  13881. }
  13882. if ( material.skinning &&
  13883. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  13884. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13885. enableAttribute( attributes.skinIndex );
  13886. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  13887. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13888. enableAttribute( attributes.skinWeight );
  13889. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  13890. }
  13891. // line distances
  13892. if ( attributes.lineDistance >= 0 ) {
  13893. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  13894. enableAttribute( attributes.lineDistance );
  13895. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  13896. }
  13897. }
  13898. // render mesh
  13899. if ( object instanceof THREE.Mesh ) {
  13900. // wireframe
  13901. if ( material.wireframe ) {
  13902. setLineWidth( material.wireframeLinewidth );
  13903. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13904. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  13905. // triangles
  13906. } else {
  13907. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13908. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  13909. }
  13910. _this.info.render.calls ++;
  13911. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  13912. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  13913. // render lines
  13914. } else if ( object instanceof THREE.Line ) {
  13915. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13916. setLineWidth( material.linewidth );
  13917. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  13918. _this.info.render.calls ++;
  13919. // render particles
  13920. } else if ( object instanceof THREE.ParticleSystem ) {
  13921. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  13922. _this.info.render.calls ++;
  13923. _this.info.render.points += geometryGroup.__webglParticleCount;
  13924. }
  13925. };
  13926. function enableAttribute( attribute ) {
  13927. if ( _enabledAttributes[ attribute ] === 0 ) {
  13928. _gl.enableVertexAttribArray( attribute );
  13929. _enabledAttributes[ attribute ] = 1;
  13930. }
  13931. };
  13932. function disableAttributes() {
  13933. for ( var attribute in _enabledAttributes ) {
  13934. if ( _enabledAttributes[ attribute ] === 1 ) {
  13935. _gl.disableVertexAttribArray( attribute );
  13936. _enabledAttributes[ attribute ] = 0;
  13937. }
  13938. }
  13939. };
  13940. function setupMorphTargets ( material, geometryGroup, object ) {
  13941. // set base
  13942. var attributes = material.program.attributes;
  13943. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  13944. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13945. enableAttribute( attributes.position );
  13946. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13947. } else if ( attributes.position >= 0 ) {
  13948. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13949. enableAttribute( attributes.position );
  13950. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13951. }
  13952. if ( object.morphTargetForcedOrder.length ) {
  13953. // set forced order
  13954. var m = 0;
  13955. var order = object.morphTargetForcedOrder;
  13956. var influences = object.morphTargetInfluences;
  13957. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13958. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13959. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13960. enableAttribute( attributes[ "morphTarget" + m ] );
  13961. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13962. }
  13963. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13964. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13965. enableAttribute( attributes[ "morphNormal" + m ] );
  13966. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13967. }
  13968. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13969. m ++;
  13970. }
  13971. } else {
  13972. // find the most influencing
  13973. var influence, activeInfluenceIndices = [];
  13974. var influences = object.morphTargetInfluences;
  13975. var i, il = influences.length;
  13976. for ( i = 0; i < il; i ++ ) {
  13977. influence = influences[ i ];
  13978. if ( influence > 0 ) {
  13979. activeInfluenceIndices.push( [ influence, i ] );
  13980. }
  13981. }
  13982. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13983. activeInfluenceIndices.sort( numericalSort );
  13984. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13985. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13986. activeInfluenceIndices.sort( numericalSort );
  13987. } else if ( activeInfluenceIndices.length === 0 ) {
  13988. activeInfluenceIndices.push( [ 0, 0 ] );
  13989. };
  13990. var influenceIndex, m = 0;
  13991. while ( m < material.numSupportedMorphTargets ) {
  13992. if ( activeInfluenceIndices[ m ] ) {
  13993. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13994. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13995. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13996. enableAttribute( attributes[ "morphTarget" + m ] );
  13997. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13998. }
  13999. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  14000. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  14001. enableAttribute( attributes[ "morphNormal" + m ] );
  14002. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  14003. }
  14004. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  14005. } else {
  14006. /*
  14007. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  14008. if ( material.morphNormals ) {
  14009. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  14010. }
  14011. */
  14012. object.__webglMorphTargetInfluences[ m ] = 0;
  14013. }
  14014. m ++;
  14015. }
  14016. }
  14017. // load updated influences uniform
  14018. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  14019. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  14020. }
  14021. };
  14022. // Sorting
  14023. function painterSortStable ( a, b ) {
  14024. if ( a.z !== b.z ) {
  14025. return b.z - a.z;
  14026. } else {
  14027. return a.id - b.id;
  14028. }
  14029. };
  14030. function numericalSort ( a, b ) {
  14031. return b[ 0 ] - a[ 0 ];
  14032. };
  14033. // Rendering
  14034. this.render = function ( scene, camera, renderTarget, forceClear ) {
  14035. if ( camera instanceof THREE.Camera === false ) {
  14036. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  14037. return;
  14038. }
  14039. var i, il,
  14040. webglObject, object,
  14041. renderList,
  14042. lights = scene.__lights,
  14043. fog = scene.fog;
  14044. // reset caching for this frame
  14045. _currentMaterialId = -1;
  14046. _lightsNeedUpdate = true;
  14047. // update scene graph
  14048. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  14049. // update camera matrices and frustum
  14050. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  14051. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  14052. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  14053. _frustum.setFromMatrix( _projScreenMatrix );
  14054. // update WebGL objects
  14055. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  14056. // custom render plugins (pre pass)
  14057. renderPlugins( this.renderPluginsPre, scene, camera );
  14058. //
  14059. _this.info.render.calls = 0;
  14060. _this.info.render.vertices = 0;
  14061. _this.info.render.faces = 0;
  14062. _this.info.render.points = 0;
  14063. this.setRenderTarget( renderTarget );
  14064. if ( this.autoClear || forceClear ) {
  14065. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  14066. }
  14067. // set matrices for regular objects (frustum culled)
  14068. renderList = scene.__webglObjects;
  14069. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  14070. webglObject = renderList[ i ];
  14071. object = webglObject.object;
  14072. webglObject.id = i;
  14073. webglObject.render = false;
  14074. if ( object.visible ) {
  14075. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  14076. setupMatrices( object, camera );
  14077. unrollBufferMaterial( webglObject );
  14078. webglObject.render = true;
  14079. if ( this.sortObjects === true ) {
  14080. if ( object.renderDepth !== null ) {
  14081. webglObject.z = object.renderDepth;
  14082. } else {
  14083. _vector3.setFromMatrixPosition( object.matrixWorld );
  14084. _vector3.applyProjection( _projScreenMatrix );
  14085. webglObject.z = _vector3.z;
  14086. }
  14087. }
  14088. }
  14089. }
  14090. }
  14091. if ( this.sortObjects ) {
  14092. renderList.sort( painterSortStable );
  14093. }
  14094. // set matrices for immediate objects
  14095. renderList = scene.__webglObjectsImmediate;
  14096. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  14097. webglObject = renderList[ i ];
  14098. object = webglObject.object;
  14099. if ( object.visible ) {
  14100. setupMatrices( object, camera );
  14101. unrollImmediateBufferMaterial( webglObject );
  14102. }
  14103. }
  14104. if ( scene.overrideMaterial ) {
  14105. var material = scene.overrideMaterial;
  14106. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  14107. this.setDepthTest( material.depthTest );
  14108. this.setDepthWrite( material.depthWrite );
  14109. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14110. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  14111. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  14112. } else {
  14113. var material = null;
  14114. // opaque pass (front-to-back order)
  14115. this.setBlending( THREE.NoBlending );
  14116. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  14117. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  14118. // transparent pass (back-to-front order)
  14119. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  14120. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  14121. }
  14122. // custom render plugins (post pass)
  14123. renderPlugins( this.renderPluginsPost, scene, camera );
  14124. // Generate mipmap if we're using any kind of mipmap filtering
  14125. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  14126. updateRenderTargetMipmap( renderTarget );
  14127. }
  14128. // Ensure depth buffer writing is enabled so it can be cleared on next render
  14129. this.setDepthTest( true );
  14130. this.setDepthWrite( true );
  14131. // _gl.finish();
  14132. };
  14133. function renderPlugins( plugins, scene, camera ) {
  14134. if ( ! plugins.length ) return;
  14135. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  14136. // reset state for plugin (to start from clean slate)
  14137. _currentProgram = null;
  14138. _currentCamera = null;
  14139. _oldBlending = -1;
  14140. _oldDepthTest = -1;
  14141. _oldDepthWrite = -1;
  14142. _oldDoubleSided = -1;
  14143. _oldFlipSided = -1;
  14144. _currentGeometryGroupHash = -1;
  14145. _currentMaterialId = -1;
  14146. _lightsNeedUpdate = true;
  14147. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  14148. // reset state after plugin (anything could have changed)
  14149. _currentProgram = null;
  14150. _currentCamera = null;
  14151. _oldBlending = -1;
  14152. _oldDepthTest = -1;
  14153. _oldDepthWrite = -1;
  14154. _oldDoubleSided = -1;
  14155. _oldFlipSided = -1;
  14156. _currentGeometryGroupHash = -1;
  14157. _currentMaterialId = -1;
  14158. _lightsNeedUpdate = true;
  14159. }
  14160. };
  14161. function renderObjects( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  14162. var webglObject, object, buffer, material, start, end, delta;
  14163. if ( reverse ) {
  14164. start = renderList.length - 1;
  14165. end = -1;
  14166. delta = -1;
  14167. } else {
  14168. start = 0;
  14169. end = renderList.length;
  14170. delta = 1;
  14171. }
  14172. for ( var i = start; i !== end; i += delta ) {
  14173. webglObject = renderList[ i ];
  14174. if ( webglObject.render ) {
  14175. object = webglObject.object;
  14176. buffer = webglObject.buffer;
  14177. if ( overrideMaterial ) {
  14178. material = overrideMaterial;
  14179. } else {
  14180. material = webglObject[ materialType ];
  14181. if ( ! material ) continue;
  14182. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  14183. _this.setDepthTest( material.depthTest );
  14184. _this.setDepthWrite( material.depthWrite );
  14185. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14186. }
  14187. _this.setMaterialFaces( material );
  14188. if ( buffer instanceof THREE.BufferGeometry ) {
  14189. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  14190. } else if ( buffer instanceof THREE.Geometry2 ) {
  14191. _this.renderBufferGeometry2( camera, lights, fog, material, buffer, object );
  14192. } else {
  14193. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  14194. }
  14195. }
  14196. }
  14197. };
  14198. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  14199. var webglObject, object, material, program;
  14200. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  14201. webglObject = renderList[ i ];
  14202. object = webglObject.object;
  14203. if ( object.visible ) {
  14204. if ( overrideMaterial ) {
  14205. material = overrideMaterial;
  14206. } else {
  14207. material = webglObject[ materialType ];
  14208. if ( ! material ) continue;
  14209. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  14210. _this.setDepthTest( material.depthTest );
  14211. _this.setDepthWrite( material.depthWrite );
  14212. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14213. }
  14214. _this.renderImmediateObject( camera, lights, fog, material, object );
  14215. }
  14216. }
  14217. };
  14218. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  14219. var program = setProgram( camera, lights, fog, material, object );
  14220. _currentGeometryGroupHash = -1;
  14221. _this.setMaterialFaces( material );
  14222. if ( object.immediateRenderCallback ) {
  14223. object.immediateRenderCallback( program, _gl, _frustum );
  14224. } else {
  14225. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  14226. }
  14227. };
  14228. function unrollImmediateBufferMaterial ( globject ) {
  14229. var object = globject.object,
  14230. material = object.material;
  14231. if ( material.transparent ) {
  14232. globject.transparent = material;
  14233. globject.opaque = null;
  14234. } else {
  14235. globject.opaque = material;
  14236. globject.transparent = null;
  14237. }
  14238. };
  14239. function unrollBufferMaterial ( globject ) {
  14240. var object = globject.object;
  14241. var buffer = globject.buffer;
  14242. var geometry = object.geometry;
  14243. var material = object.material;
  14244. if ( material instanceof THREE.MeshFaceMaterial ) {
  14245. var materialIndex = geometry instanceof THREE.BufferGeometry ? 0 : buffer.materialIndex;
  14246. material = material.materials[ materialIndex ];
  14247. if ( material.transparent ) {
  14248. globject.transparent = material;
  14249. globject.opaque = null;
  14250. } else {
  14251. globject.opaque = material;
  14252. globject.transparent = null;
  14253. }
  14254. } else {
  14255. if ( material ) {
  14256. if ( material.transparent ) {
  14257. globject.transparent = material;
  14258. globject.opaque = null;
  14259. } else {
  14260. globject.opaque = material;
  14261. globject.transparent = null;
  14262. }
  14263. }
  14264. }
  14265. };
  14266. // Objects refresh
  14267. this.initWebGLObjects = function ( scene ) {
  14268. if ( !scene.__webglObjects ) {
  14269. scene.__webglObjects = [];
  14270. scene.__webglObjectsImmediate = [];
  14271. scene.__webglSprites = [];
  14272. scene.__webglFlares = [];
  14273. }
  14274. while ( scene.__objectsAdded.length ) {
  14275. addObject( scene.__objectsAdded[ 0 ], scene );
  14276. scene.__objectsAdded.splice( 0, 1 );
  14277. }
  14278. while ( scene.__objectsRemoved.length ) {
  14279. removeObject( scene.__objectsRemoved[ 0 ], scene );
  14280. scene.__objectsRemoved.splice( 0, 1 );
  14281. }
  14282. // update must be called after objects adding / removal
  14283. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  14284. var object = scene.__webglObjects[ o ].object;
  14285. // TODO: Remove this hack (WebGLRenderer refactoring)
  14286. if ( object.__webglInit === undefined ) {
  14287. if ( object.__webglActive !== undefined ) {
  14288. removeObject( object, scene );
  14289. }
  14290. addObject( object, scene );
  14291. }
  14292. updateObject( object );
  14293. }
  14294. };
  14295. // Objects adding
  14296. function addObject( object, scene ) {
  14297. var g, geometry, material, geometryGroup;
  14298. if ( object.__webglInit === undefined ) {
  14299. object.__webglInit = true;
  14300. object._modelViewMatrix = new THREE.Matrix4();
  14301. object._normalMatrix = new THREE.Matrix3();
  14302. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  14303. object.geometry.__webglInit = true;
  14304. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  14305. }
  14306. geometry = object.geometry;
  14307. if ( geometry === undefined ) {
  14308. // fail silently for now
  14309. } else if ( geometry instanceof THREE.BufferGeometry ) {
  14310. initDirectBuffers( geometry );
  14311. } else if ( geometry instanceof THREE.Geometry2 ) {
  14312. initGeometry2Buffers( geometry );
  14313. } else if ( object instanceof THREE.Mesh ) {
  14314. material = object.material;
  14315. if ( geometry.geometryGroups === undefined ) {
  14316. geometry.makeGroups( material instanceof THREE.MeshFaceMaterial );
  14317. }
  14318. // create separate VBOs per geometry chunk
  14319. for ( g in geometry.geometryGroups ) {
  14320. geometryGroup = geometry.geometryGroups[ g ];
  14321. // initialise VBO on the first access
  14322. if ( ! geometryGroup.__webglVertexBuffer ) {
  14323. createMeshBuffers( geometryGroup );
  14324. initMeshBuffers( geometryGroup, object );
  14325. geometry.verticesNeedUpdate = true;
  14326. geometry.morphTargetsNeedUpdate = true;
  14327. geometry.elementsNeedUpdate = true;
  14328. geometry.uvsNeedUpdate = true;
  14329. geometry.normalsNeedUpdate = true;
  14330. geometry.tangentsNeedUpdate = true;
  14331. geometry.colorsNeedUpdate = true;
  14332. }
  14333. }
  14334. } else if ( object instanceof THREE.Line ) {
  14335. if ( ! geometry.__webglVertexBuffer ) {
  14336. createLineBuffers( geometry );
  14337. initLineBuffers( geometry, object );
  14338. geometry.verticesNeedUpdate = true;
  14339. geometry.colorsNeedUpdate = true;
  14340. geometry.lineDistancesNeedUpdate = true;
  14341. }
  14342. } else if ( object instanceof THREE.ParticleSystem ) {
  14343. if ( ! geometry.__webglVertexBuffer ) {
  14344. createParticleBuffers( geometry );
  14345. initParticleBuffers( geometry, object );
  14346. geometry.verticesNeedUpdate = true;
  14347. geometry.colorsNeedUpdate = true;
  14348. }
  14349. }
  14350. }
  14351. if ( object.__webglActive === undefined ) {
  14352. if ( object instanceof THREE.Mesh ) {
  14353. geometry = object.geometry;
  14354. if ( geometry instanceof THREE.BufferGeometry ) {
  14355. addBuffer( scene.__webglObjects, geometry, object );
  14356. } else if ( geometry instanceof THREE.Geometry2 ) {
  14357. addBuffer( scene.__webglObjects, geometry, object );
  14358. } else if ( geometry instanceof THREE.Geometry ) {
  14359. for ( g in geometry.geometryGroups ) {
  14360. geometryGroup = geometry.geometryGroups[ g ];
  14361. addBuffer( scene.__webglObjects, geometryGroup, object );
  14362. }
  14363. }
  14364. } else if ( object instanceof THREE.Line ||
  14365. object instanceof THREE.ParticleSystem ) {
  14366. geometry = object.geometry;
  14367. addBuffer( scene.__webglObjects, geometry, object );
  14368. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14369. addBufferImmediate( scene.__webglObjectsImmediate, object );
  14370. } else if ( object instanceof THREE.Sprite ) {
  14371. scene.__webglSprites.push( object );
  14372. } else if ( object instanceof THREE.LensFlare ) {
  14373. scene.__webglFlares.push( object );
  14374. }
  14375. object.__webglActive = true;
  14376. }
  14377. };
  14378. function addBuffer( objlist, buffer, object ) {
  14379. objlist.push(
  14380. {
  14381. id: null,
  14382. buffer: buffer,
  14383. object: object,
  14384. opaque: null,
  14385. transparent: null,
  14386. z: 0
  14387. }
  14388. );
  14389. };
  14390. function addBufferImmediate( objlist, object ) {
  14391. objlist.push(
  14392. {
  14393. id: null,
  14394. object: object,
  14395. opaque: null,
  14396. transparent: null,
  14397. z: 0
  14398. }
  14399. );
  14400. };
  14401. // Objects updates
  14402. function updateObject( object ) {
  14403. var geometry = object.geometry,
  14404. geometryGroup, customAttributesDirty, material;
  14405. if ( geometry instanceof THREE.BufferGeometry ) {
  14406. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW );
  14407. } else if ( geometry instanceof THREE.Geometry2 ) {
  14408. setGeometry2Buffers( geometry, _gl.DYNAMIC_DRAW );
  14409. } else if ( object instanceof THREE.Mesh ) {
  14410. // check all geometry groups
  14411. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  14412. geometryGroup = geometry.geometryGroupsList[ i ];
  14413. material = getBufferMaterial( object, geometryGroup );
  14414. if ( geometry.buffersNeedUpdate ) {
  14415. initMeshBuffers( geometryGroup, object );
  14416. }
  14417. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14418. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  14419. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  14420. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  14421. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  14422. }
  14423. }
  14424. geometry.verticesNeedUpdate = false;
  14425. geometry.morphTargetsNeedUpdate = false;
  14426. geometry.elementsNeedUpdate = false;
  14427. geometry.uvsNeedUpdate = false;
  14428. geometry.normalsNeedUpdate = false;
  14429. geometry.colorsNeedUpdate = false;
  14430. geometry.tangentsNeedUpdate = false;
  14431. geometry.buffersNeedUpdate = false;
  14432. material.attributes && clearCustomAttributes( material );
  14433. } else if ( object instanceof THREE.Line ) {
  14434. material = getBufferMaterial( object, geometry );
  14435. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14436. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  14437. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  14438. }
  14439. geometry.verticesNeedUpdate = false;
  14440. geometry.colorsNeedUpdate = false;
  14441. geometry.lineDistancesNeedUpdate = false;
  14442. material.attributes && clearCustomAttributes( material );
  14443. } else if ( object instanceof THREE.ParticleSystem ) {
  14444. material = getBufferMaterial( object, geometry );
  14445. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14446. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  14447. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  14448. }
  14449. geometry.verticesNeedUpdate = false;
  14450. geometry.colorsNeedUpdate = false;
  14451. material.attributes && clearCustomAttributes( material );
  14452. }
  14453. };
  14454. // Objects updates - custom attributes check
  14455. function areCustomAttributesDirty( material ) {
  14456. for ( var a in material.attributes ) {
  14457. if ( material.attributes[ a ].needsUpdate ) return true;
  14458. }
  14459. return false;
  14460. };
  14461. function clearCustomAttributes( material ) {
  14462. for ( var a in material.attributes ) {
  14463. material.attributes[ a ].needsUpdate = false;
  14464. }
  14465. };
  14466. // Objects removal
  14467. function removeObject( object, scene ) {
  14468. if ( object instanceof THREE.Mesh ||
  14469. object instanceof THREE.ParticleSystem ||
  14470. object instanceof THREE.Line ) {
  14471. removeInstances( scene.__webglObjects, object );
  14472. } else if ( object instanceof THREE.Sprite ) {
  14473. removeInstancesDirect( scene.__webglSprites, object );
  14474. } else if ( object instanceof THREE.LensFlare ) {
  14475. removeInstancesDirect( scene.__webglFlares, object );
  14476. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14477. removeInstances( scene.__webglObjectsImmediate, object );
  14478. }
  14479. delete object.__webglActive;
  14480. };
  14481. function removeInstances( objlist, object ) {
  14482. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14483. if ( objlist[ o ].object === object ) {
  14484. objlist.splice( o, 1 );
  14485. }
  14486. }
  14487. };
  14488. function removeInstancesDirect( objlist, object ) {
  14489. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14490. if ( objlist[ o ] === object ) {
  14491. objlist.splice( o, 1 );
  14492. }
  14493. }
  14494. };
  14495. // Materials
  14496. this.initMaterial = function ( material, lights, fog, object ) {
  14497. material.addEventListener( 'dispose', onMaterialDispose );
  14498. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  14499. if ( material instanceof THREE.MeshDepthMaterial ) {
  14500. shaderID = 'depth';
  14501. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14502. shaderID = 'normal';
  14503. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  14504. shaderID = 'basic';
  14505. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14506. shaderID = 'lambert';
  14507. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14508. shaderID = 'phong';
  14509. } else if ( material instanceof THREE.LineBasicMaterial ) {
  14510. shaderID = 'basic';
  14511. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14512. shaderID = 'dashed';
  14513. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  14514. shaderID = 'particle_basic';
  14515. }
  14516. if ( shaderID ) {
  14517. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  14518. }
  14519. // heuristics to create shader parameters according to lights in the scene
  14520. // (not to blow over maxLights budget)
  14521. maxLightCount = allocateLights( lights );
  14522. maxShadows = allocateShadows( lights );
  14523. maxBones = allocateBones( object );
  14524. parameters = {
  14525. map: !!material.map,
  14526. envMap: !!material.envMap,
  14527. lightMap: !!material.lightMap,
  14528. bumpMap: !!material.bumpMap,
  14529. normalMap: !!material.normalMap,
  14530. specularMap: !!material.specularMap,
  14531. vertexColors: material.vertexColors,
  14532. fog: fog,
  14533. useFog: material.fog,
  14534. fogExp: fog instanceof THREE.FogExp2,
  14535. sizeAttenuation: material.sizeAttenuation,
  14536. skinning: material.skinning,
  14537. maxBones: maxBones,
  14538. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  14539. morphTargets: material.morphTargets,
  14540. morphNormals: material.morphNormals,
  14541. maxMorphTargets: this.maxMorphTargets,
  14542. maxMorphNormals: this.maxMorphNormals,
  14543. maxDirLights: maxLightCount.directional,
  14544. maxPointLights: maxLightCount.point,
  14545. maxSpotLights: maxLightCount.spot,
  14546. maxHemiLights: maxLightCount.hemi,
  14547. maxShadows: maxShadows,
  14548. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow && maxShadows > 0,
  14549. shadowMapType: this.shadowMapType,
  14550. shadowMapDebug: this.shadowMapDebug,
  14551. shadowMapCascade: this.shadowMapCascade,
  14552. alphaTest: material.alphaTest,
  14553. metal: material.metal,
  14554. wrapAround: material.wrapAround,
  14555. doubleSided: material.side === THREE.DoubleSide,
  14556. flipSided: material.side === THREE.BackSide
  14557. };
  14558. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters, material.index0AttributeName );
  14559. var attributes = material.program.attributes;
  14560. if ( material.morphTargets ) {
  14561. material.numSupportedMorphTargets = 0;
  14562. var id, base = "morphTarget";
  14563. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  14564. id = base + i;
  14565. if ( attributes[ id ] >= 0 ) {
  14566. material.numSupportedMorphTargets ++;
  14567. }
  14568. }
  14569. }
  14570. if ( material.morphNormals ) {
  14571. material.numSupportedMorphNormals = 0;
  14572. var id, base = "morphNormal";
  14573. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  14574. id = base + i;
  14575. if ( attributes[ id ] >= 0 ) {
  14576. material.numSupportedMorphNormals ++;
  14577. }
  14578. }
  14579. }
  14580. material.uniformsList = [];
  14581. for ( u in material.uniforms ) {
  14582. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  14583. }
  14584. };
  14585. function setMaterialShaders( material, shaders ) {
  14586. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  14587. material.vertexShader = shaders.vertexShader;
  14588. material.fragmentShader = shaders.fragmentShader;
  14589. };
  14590. function setProgram( camera, lights, fog, material, object ) {
  14591. _usedTextureUnits = 0;
  14592. if ( material.needsUpdate ) {
  14593. if ( material.program ) deallocateMaterial( material );
  14594. _this.initMaterial( material, lights, fog, object );
  14595. material.needsUpdate = false;
  14596. }
  14597. if ( material.morphTargets ) {
  14598. if ( ! object.__webglMorphTargetInfluences ) {
  14599. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  14600. }
  14601. }
  14602. var refreshMaterial = false;
  14603. var program = material.program,
  14604. p_uniforms = program.uniforms,
  14605. m_uniforms = material.uniforms;
  14606. if ( program !== _currentProgram ) {
  14607. _gl.useProgram( program );
  14608. _currentProgram = program;
  14609. refreshMaterial = true;
  14610. }
  14611. if ( material.id !== _currentMaterialId ) {
  14612. _currentMaterialId = material.id;
  14613. refreshMaterial = true;
  14614. }
  14615. if ( refreshMaterial || camera !== _currentCamera ) {
  14616. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  14617. if ( camera !== _currentCamera ) _currentCamera = camera;
  14618. }
  14619. // skinning uniforms must be set even if material didn't change
  14620. // auto-setting of texture unit for bone texture must go before other textures
  14621. // not sure why, but otherwise weird things happen
  14622. if ( material.skinning ) {
  14623. if ( _supportsBoneTextures && object.useVertexTexture ) {
  14624. if ( p_uniforms.boneTexture !== null ) {
  14625. var textureUnit = getTextureUnit();
  14626. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  14627. _this.setTexture( object.boneTexture, textureUnit );
  14628. }
  14629. if ( p_uniforms.boneTextureWidth !== null ) {
  14630. _gl.uniform1i( p_uniforms.boneTextureWidth, object.boneTextureWidth );
  14631. }
  14632. if ( p_uniforms.boneTextureHeight !== null ) {
  14633. _gl.uniform1i( p_uniforms.boneTextureHeight, object.boneTextureHeight );
  14634. }
  14635. } else {
  14636. if ( p_uniforms.boneGlobalMatrices !== null ) {
  14637. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  14638. }
  14639. }
  14640. }
  14641. if ( refreshMaterial ) {
  14642. // refresh uniforms common to several materials
  14643. if ( fog && material.fog ) {
  14644. refreshUniformsFog( m_uniforms, fog );
  14645. }
  14646. if ( material instanceof THREE.MeshPhongMaterial ||
  14647. material instanceof THREE.MeshLambertMaterial ||
  14648. material.lights ) {
  14649. if ( _lightsNeedUpdate ) {
  14650. setupLights( program, lights );
  14651. _lightsNeedUpdate = false;
  14652. }
  14653. refreshUniformsLights( m_uniforms, _lights );
  14654. }
  14655. if ( material instanceof THREE.MeshBasicMaterial ||
  14656. material instanceof THREE.MeshLambertMaterial ||
  14657. material instanceof THREE.MeshPhongMaterial ) {
  14658. refreshUniformsCommon( m_uniforms, material );
  14659. }
  14660. // refresh single material specific uniforms
  14661. if ( material instanceof THREE.LineBasicMaterial ) {
  14662. refreshUniformsLine( m_uniforms, material );
  14663. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14664. refreshUniformsLine( m_uniforms, material );
  14665. refreshUniformsDash( m_uniforms, material );
  14666. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  14667. refreshUniformsParticle( m_uniforms, material );
  14668. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14669. refreshUniformsPhong( m_uniforms, material );
  14670. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14671. refreshUniformsLambert( m_uniforms, material );
  14672. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  14673. m_uniforms.mNear.value = camera.near;
  14674. m_uniforms.mFar.value = camera.far;
  14675. m_uniforms.opacity.value = material.opacity;
  14676. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14677. m_uniforms.opacity.value = material.opacity;
  14678. }
  14679. if ( object.receiveShadow && ! material._shadowPass ) {
  14680. refreshUniformsShadow( m_uniforms, lights );
  14681. }
  14682. // load common uniforms
  14683. loadUniformsGeneric( program, material.uniformsList );
  14684. // load material specific uniforms
  14685. // (shader material also gets them for the sake of genericity)
  14686. if ( material instanceof THREE.ShaderMaterial ||
  14687. material instanceof THREE.MeshPhongMaterial ||
  14688. material.envMap ) {
  14689. if ( p_uniforms.cameraPosition !== null ) {
  14690. _vector3.setFromMatrixPosition( camera.matrixWorld );
  14691. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  14692. }
  14693. }
  14694. if ( material instanceof THREE.MeshPhongMaterial ||
  14695. material instanceof THREE.MeshLambertMaterial ||
  14696. material instanceof THREE.ShaderMaterial ||
  14697. material.skinning ) {
  14698. if ( p_uniforms.viewMatrix !== null ) {
  14699. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  14700. }
  14701. }
  14702. }
  14703. loadUniformsMatrices( p_uniforms, object );
  14704. if ( p_uniforms.modelMatrix !== null ) {
  14705. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  14706. }
  14707. return program;
  14708. };
  14709. // Uniforms (refresh uniforms objects)
  14710. function refreshUniformsCommon ( uniforms, material ) {
  14711. uniforms.opacity.value = material.opacity;
  14712. if ( _this.gammaInput ) {
  14713. uniforms.diffuse.value.copyGammaToLinear( material.color );
  14714. } else {
  14715. uniforms.diffuse.value = material.color;
  14716. }
  14717. uniforms.map.value = material.map;
  14718. uniforms.lightMap.value = material.lightMap;
  14719. uniforms.specularMap.value = material.specularMap;
  14720. if ( material.bumpMap ) {
  14721. uniforms.bumpMap.value = material.bumpMap;
  14722. uniforms.bumpScale.value = material.bumpScale;
  14723. }
  14724. if ( material.normalMap ) {
  14725. uniforms.normalMap.value = material.normalMap;
  14726. uniforms.normalScale.value.copy( material.normalScale );
  14727. }
  14728. // uv repeat and offset setting priorities
  14729. // 1. color map
  14730. // 2. specular map
  14731. // 3. normal map
  14732. // 4. bump map
  14733. var uvScaleMap;
  14734. if ( material.map ) {
  14735. uvScaleMap = material.map;
  14736. } else if ( material.specularMap ) {
  14737. uvScaleMap = material.specularMap;
  14738. } else if ( material.normalMap ) {
  14739. uvScaleMap = material.normalMap;
  14740. } else if ( material.bumpMap ) {
  14741. uvScaleMap = material.bumpMap;
  14742. }
  14743. if ( uvScaleMap !== undefined ) {
  14744. var offset = uvScaleMap.offset;
  14745. var repeat = uvScaleMap.repeat;
  14746. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  14747. }
  14748. uniforms.envMap.value = material.envMap;
  14749. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  14750. if ( _this.gammaInput ) {
  14751. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  14752. uniforms.reflectivity.value = material.reflectivity;
  14753. } else {
  14754. uniforms.reflectivity.value = material.reflectivity;
  14755. }
  14756. uniforms.refractionRatio.value = material.refractionRatio;
  14757. uniforms.combine.value = material.combine;
  14758. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  14759. };
  14760. function refreshUniformsLine ( uniforms, material ) {
  14761. uniforms.diffuse.value = material.color;
  14762. uniforms.opacity.value = material.opacity;
  14763. };
  14764. function refreshUniformsDash ( uniforms, material ) {
  14765. uniforms.dashSize.value = material.dashSize;
  14766. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14767. uniforms.scale.value = material.scale;
  14768. };
  14769. function refreshUniformsParticle ( uniforms, material ) {
  14770. uniforms.psColor.value = material.color;
  14771. uniforms.opacity.value = material.opacity;
  14772. uniforms.size.value = material.size;
  14773. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  14774. uniforms.map.value = material.map;
  14775. };
  14776. function refreshUniformsFog ( uniforms, fog ) {
  14777. uniforms.fogColor.value = fog.color;
  14778. if ( fog instanceof THREE.Fog ) {
  14779. uniforms.fogNear.value = fog.near;
  14780. uniforms.fogFar.value = fog.far;
  14781. } else if ( fog instanceof THREE.FogExp2 ) {
  14782. uniforms.fogDensity.value = fog.density;
  14783. }
  14784. };
  14785. function refreshUniformsPhong ( uniforms, material ) {
  14786. uniforms.shininess.value = material.shininess;
  14787. if ( _this.gammaInput ) {
  14788. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14789. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14790. uniforms.specular.value.copyGammaToLinear( material.specular );
  14791. } else {
  14792. uniforms.ambient.value = material.ambient;
  14793. uniforms.emissive.value = material.emissive;
  14794. uniforms.specular.value = material.specular;
  14795. }
  14796. if ( material.wrapAround ) {
  14797. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14798. }
  14799. };
  14800. function refreshUniformsLambert ( uniforms, material ) {
  14801. if ( _this.gammaInput ) {
  14802. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14803. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14804. } else {
  14805. uniforms.ambient.value = material.ambient;
  14806. uniforms.emissive.value = material.emissive;
  14807. }
  14808. if ( material.wrapAround ) {
  14809. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14810. }
  14811. };
  14812. function refreshUniformsLights ( uniforms, lights ) {
  14813. uniforms.ambientLightColor.value = lights.ambient;
  14814. uniforms.directionalLightColor.value = lights.directional.colors;
  14815. uniforms.directionalLightDirection.value = lights.directional.positions;
  14816. uniforms.pointLightColor.value = lights.point.colors;
  14817. uniforms.pointLightPosition.value = lights.point.positions;
  14818. uniforms.pointLightDistance.value = lights.point.distances;
  14819. uniforms.spotLightColor.value = lights.spot.colors;
  14820. uniforms.spotLightPosition.value = lights.spot.positions;
  14821. uniforms.spotLightDistance.value = lights.spot.distances;
  14822. uniforms.spotLightDirection.value = lights.spot.directions;
  14823. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  14824. uniforms.spotLightExponent.value = lights.spot.exponents;
  14825. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  14826. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  14827. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  14828. };
  14829. function refreshUniformsShadow ( uniforms, lights ) {
  14830. if ( uniforms.shadowMatrix ) {
  14831. var j = 0;
  14832. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14833. var light = lights[ i ];
  14834. if ( ! light.castShadow ) continue;
  14835. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  14836. uniforms.shadowMap.value[ j ] = light.shadowMap;
  14837. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  14838. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  14839. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  14840. uniforms.shadowBias.value[ j ] = light.shadowBias;
  14841. j ++;
  14842. }
  14843. }
  14844. }
  14845. };
  14846. // Uniforms (load to GPU)
  14847. function loadUniformsMatrices ( uniforms, object ) {
  14848. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14849. if ( uniforms.normalMatrix ) {
  14850. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14851. }
  14852. };
  14853. function getTextureUnit() {
  14854. var textureUnit = _usedTextureUnits;
  14855. if ( textureUnit >= _maxTextures ) {
  14856. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  14857. }
  14858. _usedTextureUnits += 1;
  14859. return textureUnit;
  14860. };
  14861. function loadUniformsGeneric ( program, uniforms ) {
  14862. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  14863. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14864. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14865. if ( !location ) continue;
  14866. uniform = uniforms[ j ][ 0 ];
  14867. type = uniform.type;
  14868. value = uniform.value;
  14869. if ( type === "i" ) { // single integer
  14870. _gl.uniform1i( location, value );
  14871. } else if ( type === "f" ) { // single float
  14872. _gl.uniform1f( location, value );
  14873. } else if ( type === "v2" ) { // single THREE.Vector2
  14874. _gl.uniform2f( location, value.x, value.y );
  14875. } else if ( type === "v3" ) { // single THREE.Vector3
  14876. _gl.uniform3f( location, value.x, value.y, value.z );
  14877. } else if ( type === "v4" ) { // single THREE.Vector4
  14878. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14879. } else if ( type === "c" ) { // single THREE.Color
  14880. _gl.uniform3f( location, value.r, value.g, value.b );
  14881. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  14882. _gl.uniform1iv( location, value );
  14883. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  14884. _gl.uniform3iv( location, value );
  14885. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  14886. _gl.uniform1fv( location, value );
  14887. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  14888. _gl.uniform3fv( location, value );
  14889. } else if ( type === "v2v" ) { // array of THREE.Vector2
  14890. if ( uniform._array === undefined ) {
  14891. uniform._array = new Float32Array( 2 * value.length );
  14892. }
  14893. for ( i = 0, il = value.length; i < il; i ++ ) {
  14894. offset = i * 2;
  14895. uniform._array[ offset ] = value[ i ].x;
  14896. uniform._array[ offset + 1 ] = value[ i ].y;
  14897. }
  14898. _gl.uniform2fv( location, uniform._array );
  14899. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14900. if ( uniform._array === undefined ) {
  14901. uniform._array = new Float32Array( 3 * value.length );
  14902. }
  14903. for ( i = 0, il = value.length; i < il; i ++ ) {
  14904. offset = i * 3;
  14905. uniform._array[ offset ] = value[ i ].x;
  14906. uniform._array[ offset + 1 ] = value[ i ].y;
  14907. uniform._array[ offset + 2 ] = value[ i ].z;
  14908. }
  14909. _gl.uniform3fv( location, uniform._array );
  14910. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14911. if ( uniform._array === undefined ) {
  14912. uniform._array = new Float32Array( 4 * value.length );
  14913. }
  14914. for ( i = 0, il = value.length; i < il; i ++ ) {
  14915. offset = i * 4;
  14916. uniform._array[ offset ] = value[ i ].x;
  14917. uniform._array[ offset + 1 ] = value[ i ].y;
  14918. uniform._array[ offset + 2 ] = value[ i ].z;
  14919. uniform._array[ offset + 3 ] = value[ i ].w;
  14920. }
  14921. _gl.uniform4fv( location, uniform._array );
  14922. } else if ( type === "m4") { // single THREE.Matrix4
  14923. if ( uniform._array === undefined ) {
  14924. uniform._array = new Float32Array( 16 );
  14925. }
  14926. value.flattenToArray( uniform._array );
  14927. _gl.uniformMatrix4fv( location, false, uniform._array );
  14928. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14929. if ( uniform._array === undefined ) {
  14930. uniform._array = new Float32Array( 16 * value.length );
  14931. }
  14932. for ( i = 0, il = value.length; i < il; i ++ ) {
  14933. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14934. }
  14935. _gl.uniformMatrix4fv( location, false, uniform._array );
  14936. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14937. texture = value;
  14938. textureUnit = getTextureUnit();
  14939. _gl.uniform1i( location, textureUnit );
  14940. if ( !texture ) continue;
  14941. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  14942. setCubeTexture( texture, textureUnit );
  14943. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14944. setCubeTextureDynamic( texture, textureUnit );
  14945. } else {
  14946. _this.setTexture( texture, textureUnit );
  14947. }
  14948. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  14949. if ( uniform._array === undefined ) {
  14950. uniform._array = [];
  14951. }
  14952. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14953. uniform._array[ i ] = getTextureUnit();
  14954. }
  14955. _gl.uniform1iv( location, uniform._array );
  14956. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14957. texture = uniform.value[ i ];
  14958. textureUnit = uniform._array[ i ];
  14959. if ( !texture ) continue;
  14960. _this.setTexture( texture, textureUnit );
  14961. }
  14962. } else {
  14963. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  14964. }
  14965. }
  14966. };
  14967. function setupMatrices ( object, camera ) {
  14968. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14969. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  14970. };
  14971. //
  14972. function setColorGamma( array, offset, color, intensitySq ) {
  14973. array[ offset ] = color.r * color.r * intensitySq;
  14974. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14975. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14976. };
  14977. function setColorLinear( array, offset, color, intensity ) {
  14978. array[ offset ] = color.r * intensity;
  14979. array[ offset + 1 ] = color.g * intensity;
  14980. array[ offset + 2 ] = color.b * intensity;
  14981. };
  14982. function setupLights ( program, lights ) {
  14983. var l, ll, light, n,
  14984. r = 0, g = 0, b = 0,
  14985. color, skyColor, groundColor,
  14986. intensity, intensitySq,
  14987. position,
  14988. distance,
  14989. zlights = _lights,
  14990. dirColors = zlights.directional.colors,
  14991. dirPositions = zlights.directional.positions,
  14992. pointColors = zlights.point.colors,
  14993. pointPositions = zlights.point.positions,
  14994. pointDistances = zlights.point.distances,
  14995. spotColors = zlights.spot.colors,
  14996. spotPositions = zlights.spot.positions,
  14997. spotDistances = zlights.spot.distances,
  14998. spotDirections = zlights.spot.directions,
  14999. spotAnglesCos = zlights.spot.anglesCos,
  15000. spotExponents = zlights.spot.exponents,
  15001. hemiSkyColors = zlights.hemi.skyColors,
  15002. hemiGroundColors = zlights.hemi.groundColors,
  15003. hemiPositions = zlights.hemi.positions,
  15004. dirLength = 0,
  15005. pointLength = 0,
  15006. spotLength = 0,
  15007. hemiLength = 0,
  15008. dirCount = 0,
  15009. pointCount = 0,
  15010. spotCount = 0,
  15011. hemiCount = 0,
  15012. dirOffset = 0,
  15013. pointOffset = 0,
  15014. spotOffset = 0,
  15015. hemiOffset = 0;
  15016. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  15017. light = lights[ l ];
  15018. if ( light.onlyShadow ) continue;
  15019. color = light.color;
  15020. intensity = light.intensity;
  15021. distance = light.distance;
  15022. if ( light instanceof THREE.AmbientLight ) {
  15023. if ( ! light.visible ) continue;
  15024. if ( _this.gammaInput ) {
  15025. r += color.r * color.r;
  15026. g += color.g * color.g;
  15027. b += color.b * color.b;
  15028. } else {
  15029. r += color.r;
  15030. g += color.g;
  15031. b += color.b;
  15032. }
  15033. } else if ( light instanceof THREE.DirectionalLight ) {
  15034. dirCount += 1;
  15035. if ( ! light.visible ) continue;
  15036. _direction.setFromMatrixPosition( light.matrixWorld );
  15037. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  15038. _direction.sub( _vector3 );
  15039. _direction.normalize();
  15040. // skip lights with undefined direction
  15041. // these create troubles in OpenGL (making pixel black)
  15042. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  15043. dirOffset = dirLength * 3;
  15044. dirPositions[ dirOffset ] = _direction.x;
  15045. dirPositions[ dirOffset + 1 ] = _direction.y;
  15046. dirPositions[ dirOffset + 2 ] = _direction.z;
  15047. if ( _this.gammaInput ) {
  15048. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  15049. } else {
  15050. setColorLinear( dirColors, dirOffset, color, intensity );
  15051. }
  15052. dirLength += 1;
  15053. } else if ( light instanceof THREE.PointLight ) {
  15054. pointCount += 1;
  15055. if ( ! light.visible ) continue;
  15056. pointOffset = pointLength * 3;
  15057. if ( _this.gammaInput ) {
  15058. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  15059. } else {
  15060. setColorLinear( pointColors, pointOffset, color, intensity );
  15061. }
  15062. _vector3.setFromMatrixPosition( light.matrixWorld );
  15063. pointPositions[ pointOffset ] = _vector3.x;
  15064. pointPositions[ pointOffset + 1 ] = _vector3.y;
  15065. pointPositions[ pointOffset + 2 ] = _vector3.z;
  15066. pointDistances[ pointLength ] = distance;
  15067. pointLength += 1;
  15068. } else if ( light instanceof THREE.SpotLight ) {
  15069. spotCount += 1;
  15070. if ( ! light.visible ) continue;
  15071. spotOffset = spotLength * 3;
  15072. if ( _this.gammaInput ) {
  15073. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  15074. } else {
  15075. setColorLinear( spotColors, spotOffset, color, intensity );
  15076. }
  15077. _vector3.setFromMatrixPosition( light.matrixWorld );
  15078. spotPositions[ spotOffset ] = _vector3.x;
  15079. spotPositions[ spotOffset + 1 ] = _vector3.y;
  15080. spotPositions[ spotOffset + 2 ] = _vector3.z;
  15081. spotDistances[ spotLength ] = distance;
  15082. _direction.copy( _vector3 );
  15083. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  15084. _direction.sub( _vector3 );
  15085. _direction.normalize();
  15086. spotDirections[ spotOffset ] = _direction.x;
  15087. spotDirections[ spotOffset + 1 ] = _direction.y;
  15088. spotDirections[ spotOffset + 2 ] = _direction.z;
  15089. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  15090. spotExponents[ spotLength ] = light.exponent;
  15091. spotLength += 1;
  15092. } else if ( light instanceof THREE.HemisphereLight ) {
  15093. hemiCount += 1;
  15094. if ( ! light.visible ) continue;
  15095. _direction.setFromMatrixPosition( light.matrixWorld );
  15096. _direction.normalize();
  15097. // skip lights with undefined direction
  15098. // these create troubles in OpenGL (making pixel black)
  15099. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  15100. hemiOffset = hemiLength * 3;
  15101. hemiPositions[ hemiOffset ] = _direction.x;
  15102. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  15103. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  15104. skyColor = light.color;
  15105. groundColor = light.groundColor;
  15106. if ( _this.gammaInput ) {
  15107. intensitySq = intensity * intensity;
  15108. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  15109. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  15110. } else {
  15111. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  15112. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  15113. }
  15114. hemiLength += 1;
  15115. }
  15116. }
  15117. // null eventual remains from removed lights
  15118. // (this is to avoid if in shader)
  15119. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  15120. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  15121. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  15122. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  15123. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  15124. zlights.directional.length = dirLength;
  15125. zlights.point.length = pointLength;
  15126. zlights.spot.length = spotLength;
  15127. zlights.hemi.length = hemiLength;
  15128. zlights.ambient[ 0 ] = r;
  15129. zlights.ambient[ 1 ] = g;
  15130. zlights.ambient[ 2 ] = b;
  15131. };
  15132. // GL state setting
  15133. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  15134. if ( cullFace === THREE.CullFaceNone ) {
  15135. _gl.disable( _gl.CULL_FACE );
  15136. } else {
  15137. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  15138. _gl.frontFace( _gl.CW );
  15139. } else {
  15140. _gl.frontFace( _gl.CCW );
  15141. }
  15142. if ( cullFace === THREE.CullFaceBack ) {
  15143. _gl.cullFace( _gl.BACK );
  15144. } else if ( cullFace === THREE.CullFaceFront ) {
  15145. _gl.cullFace( _gl.FRONT );
  15146. } else {
  15147. _gl.cullFace( _gl.FRONT_AND_BACK );
  15148. }
  15149. _gl.enable( _gl.CULL_FACE );
  15150. }
  15151. };
  15152. this.setMaterialFaces = function ( material ) {
  15153. var doubleSided = material.side === THREE.DoubleSide;
  15154. var flipSided = material.side === THREE.BackSide;
  15155. if ( _oldDoubleSided !== doubleSided ) {
  15156. if ( doubleSided ) {
  15157. _gl.disable( _gl.CULL_FACE );
  15158. } else {
  15159. _gl.enable( _gl.CULL_FACE );
  15160. }
  15161. _oldDoubleSided = doubleSided;
  15162. }
  15163. if ( _oldFlipSided !== flipSided ) {
  15164. if ( flipSided ) {
  15165. _gl.frontFace( _gl.CW );
  15166. } else {
  15167. _gl.frontFace( _gl.CCW );
  15168. }
  15169. _oldFlipSided = flipSided;
  15170. }
  15171. };
  15172. this.setDepthTest = function ( depthTest ) {
  15173. if ( _oldDepthTest !== depthTest ) {
  15174. if ( depthTest ) {
  15175. _gl.enable( _gl.DEPTH_TEST );
  15176. } else {
  15177. _gl.disable( _gl.DEPTH_TEST );
  15178. }
  15179. _oldDepthTest = depthTest;
  15180. }
  15181. };
  15182. this.setDepthWrite = function ( depthWrite ) {
  15183. if ( _oldDepthWrite !== depthWrite ) {
  15184. _gl.depthMask( depthWrite );
  15185. _oldDepthWrite = depthWrite;
  15186. }
  15187. };
  15188. function setLineWidth ( width ) {
  15189. if ( width !== _oldLineWidth ) {
  15190. _gl.lineWidth( width );
  15191. _oldLineWidth = width;
  15192. }
  15193. };
  15194. function setPolygonOffset ( polygonoffset, factor, units ) {
  15195. if ( _oldPolygonOffset !== polygonoffset ) {
  15196. if ( polygonoffset ) {
  15197. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  15198. } else {
  15199. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  15200. }
  15201. _oldPolygonOffset = polygonoffset;
  15202. }
  15203. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  15204. _gl.polygonOffset( factor, units );
  15205. _oldPolygonOffsetFactor = factor;
  15206. _oldPolygonOffsetUnits = units;
  15207. }
  15208. };
  15209. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  15210. if ( blending !== _oldBlending ) {
  15211. if ( blending === THREE.NoBlending ) {
  15212. _gl.disable( _gl.BLEND );
  15213. } else if ( blending === THREE.AdditiveBlending ) {
  15214. _gl.enable( _gl.BLEND );
  15215. _gl.blendEquation( _gl.FUNC_ADD );
  15216. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  15217. } else if ( blending === THREE.SubtractiveBlending ) {
  15218. // TODO: Find blendFuncSeparate() combination
  15219. _gl.enable( _gl.BLEND );
  15220. _gl.blendEquation( _gl.FUNC_ADD );
  15221. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  15222. } else if ( blending === THREE.MultiplyBlending ) {
  15223. // TODO: Find blendFuncSeparate() combination
  15224. _gl.enable( _gl.BLEND );
  15225. _gl.blendEquation( _gl.FUNC_ADD );
  15226. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  15227. } else if ( blending === THREE.CustomBlending ) {
  15228. _gl.enable( _gl.BLEND );
  15229. } else {
  15230. _gl.enable( _gl.BLEND );
  15231. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  15232. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  15233. }
  15234. _oldBlending = blending;
  15235. }
  15236. if ( blending === THREE.CustomBlending ) {
  15237. if ( blendEquation !== _oldBlendEquation ) {
  15238. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  15239. _oldBlendEquation = blendEquation;
  15240. }
  15241. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  15242. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  15243. _oldBlendSrc = blendSrc;
  15244. _oldBlendDst = blendDst;
  15245. }
  15246. } else {
  15247. _oldBlendEquation = null;
  15248. _oldBlendSrc = null;
  15249. _oldBlendDst = null;
  15250. }
  15251. };
  15252. // Defines
  15253. function generateDefines ( defines ) {
  15254. var value, chunk, chunks = [];
  15255. for ( var d in defines ) {
  15256. value = defines[ d ];
  15257. if ( value === false ) continue;
  15258. chunk = "#define " + d + " " + value;
  15259. chunks.push( chunk );
  15260. }
  15261. return chunks.join( "\n" );
  15262. };
  15263. // Shaders
  15264. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters, index0AttributeName ) {
  15265. var p, pl, d, program, code;
  15266. var chunks = [];
  15267. // Generate code
  15268. if ( shaderID ) {
  15269. chunks.push( shaderID );
  15270. } else {
  15271. chunks.push( fragmentShader );
  15272. chunks.push( vertexShader );
  15273. }
  15274. for ( d in defines ) {
  15275. chunks.push( d );
  15276. chunks.push( defines[ d ] );
  15277. }
  15278. for ( p in parameters ) {
  15279. chunks.push( p );
  15280. chunks.push( parameters[ p ] );
  15281. }
  15282. code = chunks.join();
  15283. // Check if code has been already compiled
  15284. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  15285. var programInfo = _programs[ p ];
  15286. if ( programInfo.code === code ) {
  15287. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  15288. programInfo.usedTimes ++;
  15289. return programInfo.program;
  15290. }
  15291. }
  15292. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  15293. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  15294. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  15295. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  15296. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  15297. }
  15298. // console.log( "building new program " );
  15299. //
  15300. var customDefines = generateDefines( defines );
  15301. //
  15302. program = _gl.createProgram();
  15303. var prefix_vertex = [
  15304. "precision " + _precision + " float;",
  15305. "precision " + _precision + " int;",
  15306. customDefines,
  15307. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  15308. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15309. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15310. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15311. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15312. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15313. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15314. "#define MAX_SHADOWS " + parameters.maxShadows,
  15315. "#define MAX_BONES " + parameters.maxBones,
  15316. parameters.map ? "#define USE_MAP" : "",
  15317. parameters.envMap ? "#define USE_ENVMAP" : "",
  15318. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15319. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15320. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15321. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15322. parameters.vertexColors ? "#define USE_COLOR" : "",
  15323. parameters.skinning ? "#define USE_SKINNING" : "",
  15324. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  15325. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  15326. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  15327. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15328. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15329. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15330. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15331. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15332. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15333. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15334. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  15335. "uniform mat4 modelMatrix;",
  15336. "uniform mat4 modelViewMatrix;",
  15337. "uniform mat4 projectionMatrix;",
  15338. "uniform mat4 viewMatrix;",
  15339. "uniform mat3 normalMatrix;",
  15340. "uniform vec3 cameraPosition;",
  15341. "attribute vec3 position;",
  15342. "attribute vec3 normal;",
  15343. "attribute vec2 uv;",
  15344. "attribute vec2 uv2;",
  15345. "#ifdef USE_COLOR",
  15346. "attribute vec3 color;",
  15347. "#endif",
  15348. "#ifdef USE_MORPHTARGETS",
  15349. "attribute vec3 morphTarget0;",
  15350. "attribute vec3 morphTarget1;",
  15351. "attribute vec3 morphTarget2;",
  15352. "attribute vec3 morphTarget3;",
  15353. "#ifdef USE_MORPHNORMALS",
  15354. "attribute vec3 morphNormal0;",
  15355. "attribute vec3 morphNormal1;",
  15356. "attribute vec3 morphNormal2;",
  15357. "attribute vec3 morphNormal3;",
  15358. "#else",
  15359. "attribute vec3 morphTarget4;",
  15360. "attribute vec3 morphTarget5;",
  15361. "attribute vec3 morphTarget6;",
  15362. "attribute vec3 morphTarget7;",
  15363. "#endif",
  15364. "#endif",
  15365. "#ifdef USE_SKINNING",
  15366. "attribute vec4 skinIndex;",
  15367. "attribute vec4 skinWeight;",
  15368. "#endif",
  15369. ""
  15370. ].join("\n");
  15371. var prefix_fragment = [
  15372. "precision " + _precision + " float;",
  15373. "precision " + _precision + " int;",
  15374. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  15375. customDefines,
  15376. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15377. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15378. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15379. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15380. "#define MAX_SHADOWS " + parameters.maxShadows,
  15381. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  15382. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15383. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15384. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  15385. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  15386. parameters.map ? "#define USE_MAP" : "",
  15387. parameters.envMap ? "#define USE_ENVMAP" : "",
  15388. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15389. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15390. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15391. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15392. parameters.vertexColors ? "#define USE_COLOR" : "",
  15393. parameters.metal ? "#define METAL" : "",
  15394. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15395. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15396. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15397. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15398. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15399. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15400. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15401. "uniform mat4 viewMatrix;",
  15402. "uniform vec3 cameraPosition;",
  15403. ""
  15404. ].join("\n");
  15405. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  15406. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  15407. _gl.attachShader( program, glVertexShader );
  15408. _gl.attachShader( program, glFragmentShader );
  15409. // Force a particular attribute to index 0.
  15410. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  15411. // And, color, for example is often automatically bound to index 0 so disabling it
  15412. if ( index0AttributeName !== undefined ) {
  15413. _gl.bindAttribLocation( program, 0, index0AttributeName );
  15414. } else {
  15415. _gl.bindAttribLocation( program, 0, 'position' );
  15416. }
  15417. _gl.linkProgram( program );
  15418. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  15419. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  15420. console.error( "Program Info Log: " + _gl.getProgramInfoLog( program ) );
  15421. }
  15422. // clean up
  15423. _gl.deleteShader( glFragmentShader );
  15424. _gl.deleteShader( glVertexShader );
  15425. // console.log( prefix_fragment + fragmentShader );
  15426. // console.log( prefix_vertex + vertexShader );
  15427. program.uniforms = {};
  15428. program.attributes = {};
  15429. var identifiers, u, a, i;
  15430. // cache uniform locations
  15431. identifiers = [
  15432. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  15433. 'morphTargetInfluences'
  15434. ];
  15435. if ( parameters.useVertexTexture ) {
  15436. identifiers.push( 'boneTexture' );
  15437. identifiers.push( 'boneTextureWidth' );
  15438. identifiers.push( 'boneTextureHeight' );
  15439. } else {
  15440. identifiers.push( 'boneGlobalMatrices' );
  15441. }
  15442. for ( u in uniforms ) {
  15443. identifiers.push( u );
  15444. }
  15445. cacheUniformLocations( program, identifiers );
  15446. // cache attributes locations
  15447. identifiers = [
  15448. "position", "normal", "uv", "uv2", "tangent", "color",
  15449. "skinIndex", "skinWeight", "lineDistance"
  15450. ];
  15451. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  15452. identifiers.push( "morphTarget" + i );
  15453. }
  15454. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  15455. identifiers.push( "morphNormal" + i );
  15456. }
  15457. for ( a in attributes ) {
  15458. identifiers.push( a );
  15459. }
  15460. cacheAttributeLocations( program, identifiers );
  15461. program.id = _programs_counter ++;
  15462. _programs.push( { program: program, code: code, usedTimes: 1 } );
  15463. _this.info.memory.programs = _programs.length;
  15464. return program;
  15465. };
  15466. // Shader parameters cache
  15467. function cacheUniformLocations ( program, identifiers ) {
  15468. var i, l, id;
  15469. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  15470. id = identifiers[ i ];
  15471. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  15472. }
  15473. };
  15474. function cacheAttributeLocations ( program, identifiers ) {
  15475. var i, l, id;
  15476. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  15477. id = identifiers[ i ];
  15478. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  15479. }
  15480. };
  15481. function addLineNumbers ( string ) {
  15482. var chunks = string.split( "\n" );
  15483. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  15484. // Chrome reports shader errors on lines
  15485. // starting counting from 1
  15486. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  15487. }
  15488. return chunks.join( "\n" );
  15489. };
  15490. function getShader ( type, string ) {
  15491. var shader;
  15492. if ( type === "fragment" ) {
  15493. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  15494. } else if ( type === "vertex" ) {
  15495. shader = _gl.createShader( _gl.VERTEX_SHADER );
  15496. }
  15497. _gl.shaderSource( shader, string );
  15498. _gl.compileShader( shader );
  15499. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  15500. console.error( _gl.getShaderInfoLog( shader ) );
  15501. console.error( addLineNumbers( string ) );
  15502. return null;
  15503. }
  15504. return shader;
  15505. };
  15506. // Textures
  15507. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  15508. if ( isImagePowerOfTwo ) {
  15509. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  15510. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  15511. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  15512. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  15513. } else {
  15514. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  15515. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  15516. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  15517. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  15518. }
  15519. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  15520. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  15521. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  15522. texture.__oldAnisotropy = texture.anisotropy;
  15523. }
  15524. }
  15525. };
  15526. this.setTexture = function ( texture, slot ) {
  15527. if ( texture.needsUpdate ) {
  15528. if ( ! texture.__webglInit ) {
  15529. texture.__webglInit = true;
  15530. texture.addEventListener( 'dispose', onTextureDispose );
  15531. texture.__webglTexture = _gl.createTexture();
  15532. _this.info.memory.textures ++;
  15533. }
  15534. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15535. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15536. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15537. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  15538. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  15539. var image = texture.image,
  15540. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  15541. glFormat = paramThreeToGL( texture.format ),
  15542. glType = paramThreeToGL( texture.type );
  15543. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  15544. var mipmap, mipmaps = texture.mipmaps;
  15545. if ( texture instanceof THREE.DataTexture ) {
  15546. // use manually created mipmaps if available
  15547. // if there are no manual mipmaps
  15548. // set 0 level mipmap and then use GL to generate other mipmap levels
  15549. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15550. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15551. mipmap = mipmaps[ i ];
  15552. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15553. }
  15554. texture.generateMipmaps = false;
  15555. } else {
  15556. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  15557. }
  15558. } else if ( texture instanceof THREE.CompressedTexture ) {
  15559. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15560. mipmap = mipmaps[ i ];
  15561. if ( texture.format!==THREE.RGBAFormat ) {
  15562. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15563. } else {
  15564. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15565. }
  15566. }
  15567. } else { // regular Texture (image, video, canvas)
  15568. // use manually created mipmaps if available
  15569. // if there are no manual mipmaps
  15570. // set 0 level mipmap and then use GL to generate other mipmap levels
  15571. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15572. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15573. mipmap = mipmaps[ i ];
  15574. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  15575. }
  15576. texture.generateMipmaps = false;
  15577. } else {
  15578. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  15579. }
  15580. }
  15581. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15582. texture.needsUpdate = false;
  15583. if ( texture.onUpdate ) texture.onUpdate();
  15584. } else {
  15585. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15586. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15587. }
  15588. };
  15589. function clampToMaxSize ( image, maxSize ) {
  15590. if ( image.width <= maxSize && image.height <= maxSize ) {
  15591. return image;
  15592. }
  15593. // Warning: Scaling through the canvas will only work with images that use
  15594. // premultiplied alpha.
  15595. var maxDimension = Math.max( image.width, image.height );
  15596. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  15597. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  15598. var canvas = document.createElement( 'canvas' );
  15599. canvas.width = newWidth;
  15600. canvas.height = newHeight;
  15601. var ctx = canvas.getContext( "2d" );
  15602. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  15603. return canvas;
  15604. }
  15605. function setCubeTexture ( texture, slot ) {
  15606. if ( texture.image.length === 6 ) {
  15607. if ( texture.needsUpdate ) {
  15608. if ( ! texture.image.__webglTextureCube ) {
  15609. texture.addEventListener( 'dispose', onTextureDispose );
  15610. texture.image.__webglTextureCube = _gl.createTexture();
  15611. _this.info.memory.textures ++;
  15612. }
  15613. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15614. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15615. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15616. var isCompressed = texture instanceof THREE.CompressedTexture;
  15617. var cubeImage = [];
  15618. for ( var i = 0; i < 6; i ++ ) {
  15619. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  15620. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  15621. } else {
  15622. cubeImage[ i ] = texture.image[ i ];
  15623. }
  15624. }
  15625. var image = cubeImage[ 0 ],
  15626. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  15627. glFormat = paramThreeToGL( texture.format ),
  15628. glType = paramThreeToGL( texture.type );
  15629. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  15630. for ( var i = 0; i < 6; i ++ ) {
  15631. if( !isCompressed ) {
  15632. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15633. } else {
  15634. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15635. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15636. mipmap = mipmaps[ j ];
  15637. if ( texture.format!==THREE.RGBAFormat ) {
  15638. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15639. } else {
  15640. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15641. }
  15642. }
  15643. }
  15644. }
  15645. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  15646. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15647. }
  15648. texture.needsUpdate = false;
  15649. if ( texture.onUpdate ) texture.onUpdate();
  15650. } else {
  15651. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15652. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15653. }
  15654. }
  15655. };
  15656. function setCubeTextureDynamic ( texture, slot ) {
  15657. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15658. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  15659. };
  15660. // Render targets
  15661. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  15662. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15663. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  15664. };
  15665. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  15666. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15667. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15668. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15669. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15670. /* For some reason this is not working. Defaulting to RGBA4.
  15671. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15672. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  15673. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15674. */
  15675. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15676. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15677. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15678. } else {
  15679. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15680. }
  15681. };
  15682. this.setRenderTarget = function ( renderTarget ) {
  15683. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  15684. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  15685. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  15686. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  15687. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15688. renderTarget.__webglTexture = _gl.createTexture();
  15689. _this.info.memory.textures ++;
  15690. // Setup texture, create render and frame buffers
  15691. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ),
  15692. glFormat = paramThreeToGL( renderTarget.format ),
  15693. glType = paramThreeToGL( renderTarget.type );
  15694. if ( isCube ) {
  15695. renderTarget.__webglFramebuffer = [];
  15696. renderTarget.__webglRenderbuffer = [];
  15697. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15698. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  15699. for ( var i = 0; i < 6; i ++ ) {
  15700. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15701. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  15702. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15703. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15704. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  15705. }
  15706. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15707. } else {
  15708. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  15709. if ( renderTarget.shareDepthFrom ) {
  15710. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  15711. } else {
  15712. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  15713. }
  15714. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15715. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  15716. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15717. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  15718. if ( renderTarget.shareDepthFrom ) {
  15719. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15720. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15721. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15722. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15723. }
  15724. } else {
  15725. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15726. }
  15727. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15728. }
  15729. // Release everything
  15730. if ( isCube ) {
  15731. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15732. } else {
  15733. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15734. }
  15735. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15736. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15737. }
  15738. var framebuffer, width, height, vx, vy;
  15739. if ( renderTarget ) {
  15740. if ( isCube ) {
  15741. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15742. } else {
  15743. framebuffer = renderTarget.__webglFramebuffer;
  15744. }
  15745. width = renderTarget.width;
  15746. height = renderTarget.height;
  15747. vx = 0;
  15748. vy = 0;
  15749. } else {
  15750. framebuffer = null;
  15751. width = _viewportWidth;
  15752. height = _viewportHeight;
  15753. vx = _viewportX;
  15754. vy = _viewportY;
  15755. }
  15756. if ( framebuffer !== _currentFramebuffer ) {
  15757. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15758. _gl.viewport( vx, vy, width, height );
  15759. _currentFramebuffer = framebuffer;
  15760. }
  15761. _currentWidth = width;
  15762. _currentHeight = height;
  15763. };
  15764. function updateRenderTargetMipmap ( renderTarget ) {
  15765. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15766. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15767. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15768. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15769. } else {
  15770. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15771. _gl.generateMipmap( _gl.TEXTURE_2D );
  15772. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15773. }
  15774. };
  15775. // Fallback filters for non-power-of-2 textures
  15776. function filterFallback ( f ) {
  15777. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15778. return _gl.NEAREST;
  15779. }
  15780. return _gl.LINEAR;
  15781. };
  15782. // Map three.js constants to WebGL constants
  15783. function paramThreeToGL ( p ) {
  15784. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15785. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15786. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15787. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15788. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15789. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15790. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15791. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15792. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15793. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15794. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15795. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15796. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15797. if ( p === THREE.ByteType ) return _gl.BYTE;
  15798. if ( p === THREE.ShortType ) return _gl.SHORT;
  15799. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15800. if ( p === THREE.IntType ) return _gl.INT;
  15801. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15802. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15803. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15804. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15805. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15806. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15807. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15808. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15809. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15810. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15811. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15812. if ( p === THREE.OneFactor ) return _gl.ONE;
  15813. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15814. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15815. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15816. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15817. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15818. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15819. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15820. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15821. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15822. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15823. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15824. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15825. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15826. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15827. }
  15828. return 0;
  15829. };
  15830. // Allocations
  15831. function allocateBones ( object ) {
  15832. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  15833. return 1024;
  15834. } else {
  15835. // default for when object is not specified
  15836. // ( for example when prebuilding shader
  15837. // to be used with multiple objects )
  15838. //
  15839. // - leave some extra space for other uniforms
  15840. // - limit here is ANGLE's 254 max uniform vectors
  15841. // (up to 54 should be safe)
  15842. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15843. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15844. var maxBones = nVertexMatrices;
  15845. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15846. maxBones = Math.min( object.bones.length, maxBones );
  15847. if ( maxBones < object.bones.length ) {
  15848. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  15849. }
  15850. }
  15851. return maxBones;
  15852. }
  15853. };
  15854. function allocateLights( lights ) {
  15855. var dirLights = 0;
  15856. var pointLights = 0;
  15857. var spotLights = 0;
  15858. var hemiLights = 0;
  15859. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15860. var light = lights[ l ];
  15861. if ( light.onlyShadow || light.visible === false ) continue;
  15862. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15863. if ( light instanceof THREE.PointLight ) pointLights ++;
  15864. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15865. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15866. }
  15867. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15868. };
  15869. function allocateShadows( lights ) {
  15870. var maxShadows = 0;
  15871. for ( var l = 0, ll = lights.length; l < ll; l++ ) {
  15872. var light = lights[ l ];
  15873. if ( ! light.castShadow ) continue;
  15874. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15875. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15876. }
  15877. return maxShadows;
  15878. };
  15879. // Initialization
  15880. function initGL() {
  15881. try {
  15882. var attributes = {
  15883. alpha: _alpha,
  15884. premultipliedAlpha: _premultipliedAlpha,
  15885. antialias: _antialias,
  15886. stencil: _stencil,
  15887. preserveDrawingBuffer: _preserveDrawingBuffer
  15888. };
  15889. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  15890. if ( _gl === null ) {
  15891. throw 'Error creating WebGL context.';
  15892. }
  15893. } catch ( error ) {
  15894. console.error( error );
  15895. }
  15896. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15897. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  15898. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15899. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15900. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15901. if ( ! _glExtensionTextureFloat ) {
  15902. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15903. }
  15904. if ( ! _glExtensionStandardDerivatives ) {
  15905. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15906. }
  15907. if ( ! _glExtensionTextureFilterAnisotropic ) {
  15908. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15909. }
  15910. if ( ! _glExtensionCompressedTextureS3TC ) {
  15911. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15912. }
  15913. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15914. _gl.getShaderPrecisionFormat = function() {
  15915. return {
  15916. "rangeMin" : 1,
  15917. "rangeMax" : 1,
  15918. "precision" : 1
  15919. };
  15920. }
  15921. }
  15922. };
  15923. function setDefaultGLState () {
  15924. _gl.clearColor( 0, 0, 0, 1 );
  15925. _gl.clearDepth( 1 );
  15926. _gl.clearStencil( 0 );
  15927. _gl.enable( _gl.DEPTH_TEST );
  15928. _gl.depthFunc( _gl.LEQUAL );
  15929. _gl.frontFace( _gl.CCW );
  15930. _gl.cullFace( _gl.BACK );
  15931. _gl.enable( _gl.CULL_FACE );
  15932. _gl.enable( _gl.BLEND );
  15933. _gl.blendEquation( _gl.FUNC_ADD );
  15934. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15935. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  15936. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15937. };
  15938. // default plugins (order is important)
  15939. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15940. this.addPrePlugin( this.shadowMapPlugin );
  15941. this.addPostPlugin( new THREE.SpritePlugin() );
  15942. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15943. };
  15944. /**
  15945. * @author szimek / https://github.com/szimek/
  15946. * @author alteredq / http://alteredqualia.com/
  15947. */
  15948. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15949. this.width = width;
  15950. this.height = height;
  15951. options = options || {};
  15952. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15953. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15954. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15955. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15956. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15957. this.offset = new THREE.Vector2( 0, 0 );
  15958. this.repeat = new THREE.Vector2( 1, 1 );
  15959. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15960. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15961. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15962. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15963. this.generateMipmaps = true;
  15964. this.shareDepthFrom = null;
  15965. };
  15966. THREE.WebGLRenderTarget.prototype = {
  15967. constructor: THREE.WebGLRenderTarget,
  15968. clone: function () {
  15969. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15970. tmp.wrapS = this.wrapS;
  15971. tmp.wrapT = this.wrapT;
  15972. tmp.magFilter = this.magFilter;
  15973. tmp.minFilter = this.minFilter;
  15974. tmp.anisotropy = this.anisotropy;
  15975. tmp.offset.copy( this.offset );
  15976. tmp.repeat.copy( this.repeat );
  15977. tmp.format = this.format;
  15978. tmp.type = this.type;
  15979. tmp.depthBuffer = this.depthBuffer;
  15980. tmp.stencilBuffer = this.stencilBuffer;
  15981. tmp.generateMipmaps = this.generateMipmaps;
  15982. tmp.shareDepthFrom = this.shareDepthFrom;
  15983. return tmp;
  15984. },
  15985. dispose: function () {
  15986. this.dispatchEvent( { type: 'dispose' } );
  15987. }
  15988. };
  15989. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  15990. /**
  15991. * @author alteredq / http://alteredqualia.com
  15992. */
  15993. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15994. THREE.WebGLRenderTarget.call( this, width, height, options );
  15995. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15996. };
  15997. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15998. /**
  15999. * @author mrdoob / http://mrdoob.com/
  16000. */
  16001. THREE.RenderableVertex = function () {
  16002. this.position = new THREE.Vector3();
  16003. this.positionWorld = new THREE.Vector3();
  16004. this.positionScreen = new THREE.Vector4();
  16005. this.visible = true;
  16006. };
  16007. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  16008. this.positionWorld.copy( vertex.positionWorld );
  16009. this.positionScreen.copy( vertex.positionScreen );
  16010. };
  16011. /**
  16012. * @author mrdoob / http://mrdoob.com/
  16013. */
  16014. THREE.RenderableFace = function () {
  16015. this.id = 0;
  16016. this.v1 = new THREE.RenderableVertex();
  16017. this.v2 = new THREE.RenderableVertex();
  16018. this.v3 = new THREE.RenderableVertex();
  16019. this.centroidModel = new THREE.Vector3();
  16020. this.normalModel = new THREE.Vector3();
  16021. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  16022. this.vertexNormalsLength = 0;
  16023. this.color = null;
  16024. this.material = null;
  16025. this.uvs = [[]];
  16026. this.z = 0;
  16027. };
  16028. /**
  16029. * @author mrdoob / http://mrdoob.com/
  16030. */
  16031. THREE.RenderableObject = function () {
  16032. this.id = 0;
  16033. this.object = null;
  16034. this.z = 0;
  16035. };
  16036. /**
  16037. * @author mrdoob / http://mrdoob.com/
  16038. */
  16039. THREE.RenderableSprite = function () {
  16040. this.id = 0;
  16041. this.object = null;
  16042. this.x = 0;
  16043. this.y = 0;
  16044. this.z = 0;
  16045. this.rotation = 0;
  16046. this.scale = new THREE.Vector2();
  16047. this.material = null;
  16048. };
  16049. /**
  16050. * @author mrdoob / http://mrdoob.com/
  16051. */
  16052. THREE.RenderableLine = function () {
  16053. this.id = 0;
  16054. this.v1 = new THREE.RenderableVertex();
  16055. this.v2 = new THREE.RenderableVertex();
  16056. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  16057. this.material = null;
  16058. this.z = 0;
  16059. };
  16060. /**
  16061. * @author mrdoob / http://mrdoob.com/
  16062. * @author alteredq / http://alteredqualia.com/
  16063. */
  16064. THREE.GeometryUtils = {
  16065. // Merge two geometries or geometry and geometry from object (using object's transform)
  16066. merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) {
  16067. var matrix, normalMatrix,
  16068. vertexOffset = geometry1.vertices.length,
  16069. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  16070. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  16071. vertices1 = geometry1.vertices,
  16072. vertices2 = geometry2.vertices,
  16073. faces1 = geometry1.faces,
  16074. faces2 = geometry2.faces,
  16075. uvs1 = geometry1.faceVertexUvs[ 0 ],
  16076. uvs2 = geometry2.faceVertexUvs[ 0 ];
  16077. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  16078. if ( object2 instanceof THREE.Mesh ) {
  16079. object2.matrixAutoUpdate && object2.updateMatrix();
  16080. matrix = object2.matrix;
  16081. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  16082. }
  16083. // vertices
  16084. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  16085. var vertex = vertices2[ i ];
  16086. var vertexCopy = vertex.clone();
  16087. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  16088. vertices1.push( vertexCopy );
  16089. }
  16090. // faces
  16091. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  16092. var face = faces2[ i ], faceCopy, normal, color,
  16093. faceVertexNormals = face.vertexNormals,
  16094. faceVertexColors = face.vertexColors;
  16095. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  16096. faceCopy.normal.copy( face.normal );
  16097. if ( normalMatrix ) {
  16098. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  16099. }
  16100. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  16101. normal = faceVertexNormals[ j ].clone();
  16102. if ( normalMatrix ) {
  16103. normal.applyMatrix3( normalMatrix ).normalize();
  16104. }
  16105. faceCopy.vertexNormals.push( normal );
  16106. }
  16107. faceCopy.color.copy( face.color );
  16108. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  16109. color = faceVertexColors[ j ];
  16110. faceCopy.vertexColors.push( color.clone() );
  16111. }
  16112. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  16113. faceCopy.centroid.copy( face.centroid );
  16114. if ( matrix ) {
  16115. faceCopy.centroid.applyMatrix4( matrix );
  16116. }
  16117. faces1.push( faceCopy );
  16118. }
  16119. // uvs
  16120. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  16121. var uv = uvs2[ i ], uvCopy = [];
  16122. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  16123. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  16124. }
  16125. uvs1.push( uvCopy );
  16126. }
  16127. },
  16128. // Get random point in triangle (via barycentric coordinates)
  16129. // (uniform distribution)
  16130. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  16131. randomPointInTriangle: function () {
  16132. var vector = new THREE.Vector3();
  16133. return function ( vectorA, vectorB, vectorC ) {
  16134. var point = new THREE.Vector3();
  16135. var a = THREE.Math.random16();
  16136. var b = THREE.Math.random16();
  16137. if ( ( a + b ) > 1 ) {
  16138. a = 1 - a;
  16139. b = 1 - b;
  16140. }
  16141. var c = 1 - a - b;
  16142. point.copy( vectorA );
  16143. point.multiplyScalar( a );
  16144. vector.copy( vectorB );
  16145. vector.multiplyScalar( b );
  16146. point.add( vector );
  16147. vector.copy( vectorC );
  16148. vector.multiplyScalar( c );
  16149. point.add( vector );
  16150. return point;
  16151. };
  16152. }(),
  16153. // Get random point in face (triangle / quad)
  16154. // (uniform distribution)
  16155. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  16156. var vA, vB, vC, vD;
  16157. vA = geometry.vertices[ face.a ];
  16158. vB = geometry.vertices[ face.b ];
  16159. vC = geometry.vertices[ face.c ];
  16160. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  16161. },
  16162. // Get uniformly distributed random points in mesh
  16163. // - create array with cumulative sums of face areas
  16164. // - pick random number from 0 to total area
  16165. // - find corresponding place in area array by binary search
  16166. // - get random point in face
  16167. randomPointsInGeometry: function ( geometry, n ) {
  16168. var face, i,
  16169. faces = geometry.faces,
  16170. vertices = geometry.vertices,
  16171. il = faces.length,
  16172. totalArea = 0,
  16173. cumulativeAreas = [],
  16174. vA, vB, vC, vD;
  16175. // precompute face areas
  16176. for ( i = 0; i < il; i ++ ) {
  16177. face = faces[ i ];
  16178. vA = vertices[ face.a ];
  16179. vB = vertices[ face.b ];
  16180. vC = vertices[ face.c ];
  16181. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  16182. totalArea += face._area;
  16183. cumulativeAreas[ i ] = totalArea;
  16184. }
  16185. // binary search cumulative areas array
  16186. function binarySearchIndices( value ) {
  16187. function binarySearch( start, end ) {
  16188. // return closest larger index
  16189. // if exact number is not found
  16190. if ( end < start )
  16191. return start;
  16192. var mid = start + Math.floor( ( end - start ) / 2 );
  16193. if ( cumulativeAreas[ mid ] > value ) {
  16194. return binarySearch( start, mid - 1 );
  16195. } else if ( cumulativeAreas[ mid ] < value ) {
  16196. return binarySearch( mid + 1, end );
  16197. } else {
  16198. return mid;
  16199. }
  16200. }
  16201. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  16202. return result;
  16203. }
  16204. // pick random face weighted by face area
  16205. var r, index,
  16206. result = [];
  16207. var stats = {};
  16208. for ( i = 0; i < n; i ++ ) {
  16209. r = THREE.Math.random16() * totalArea;
  16210. index = binarySearchIndices( r );
  16211. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  16212. if ( ! stats[ index ] ) {
  16213. stats[ index ] = 1;
  16214. } else {
  16215. stats[ index ] += 1;
  16216. }
  16217. }
  16218. return result;
  16219. },
  16220. // Get triangle area (half of parallelogram)
  16221. // http://mathworld.wolfram.com/TriangleArea.html
  16222. triangleArea: function () {
  16223. var vector1 = new THREE.Vector3();
  16224. var vector2 = new THREE.Vector3();
  16225. return function ( vectorA, vectorB, vectorC ) {
  16226. vector1.subVectors( vectorB, vectorA );
  16227. vector2.subVectors( vectorC, vectorA );
  16228. vector1.cross( vector2 );
  16229. return 0.5 * vector1.length();
  16230. };
  16231. }(),
  16232. // Center geometry so that 0,0,0 is in center of bounding box
  16233. center: function ( geometry ) {
  16234. geometry.computeBoundingBox();
  16235. var bb = geometry.boundingBox;
  16236. var offset = new THREE.Vector3();
  16237. offset.addVectors( bb.min, bb.max );
  16238. offset.multiplyScalar( -0.5 );
  16239. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  16240. geometry.computeBoundingBox();
  16241. return offset;
  16242. },
  16243. triangulateQuads: function ( geometry ) {
  16244. var i, il, j, jl;
  16245. var faces = [];
  16246. var faceVertexUvs = [];
  16247. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  16248. faceVertexUvs[ i ] = [];
  16249. }
  16250. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  16251. var face = geometry.faces[ i ];
  16252. faces.push( face );
  16253. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  16254. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  16255. }
  16256. }
  16257. geometry.faces = faces;
  16258. geometry.faceVertexUvs = faceVertexUvs;
  16259. geometry.computeCentroids();
  16260. geometry.computeFaceNormals();
  16261. geometry.computeVertexNormals();
  16262. if ( geometry.hasTangents ) geometry.computeTangents();
  16263. }
  16264. };
  16265. /**
  16266. * @author alteredq / http://alteredqualia.com/
  16267. * @author mrdoob / http://mrdoob.com/
  16268. */
  16269. THREE.ImageUtils = {
  16270. crossOrigin: undefined,
  16271. loadTexture: function ( url, mapping, onLoad, onError ) {
  16272. var loader = new THREE.ImageLoader();
  16273. loader.crossOrigin = this.crossOrigin;
  16274. var texture = new THREE.Texture( undefined, mapping );
  16275. var image = loader.load( url, function () {
  16276. texture.needsUpdate = true;
  16277. if ( onLoad ) onLoad( texture );
  16278. } );
  16279. texture.image = image;
  16280. texture.sourceFile = url;
  16281. return texture;
  16282. },
  16283. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  16284. var texture = new THREE.CompressedTexture();
  16285. texture.mapping = mapping;
  16286. var request = new XMLHttpRequest();
  16287. request.onload = function () {
  16288. var buffer = request.response;
  16289. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16290. texture.format = dds.format;
  16291. texture.mipmaps = dds.mipmaps;
  16292. texture.image.width = dds.width;
  16293. texture.image.height = dds.height;
  16294. // gl.generateMipmap fails for compressed textures
  16295. // mipmaps must be embedded in the DDS file
  16296. // or texture filters must not use mipmapping
  16297. texture.generateMipmaps = false;
  16298. texture.needsUpdate = true;
  16299. if ( onLoad ) onLoad( texture );
  16300. }
  16301. request.onerror = onError;
  16302. request.open( 'GET', url, true );
  16303. request.responseType = "arraybuffer";
  16304. request.send( null );
  16305. return texture;
  16306. },
  16307. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  16308. var images = [];
  16309. images.loadCount = 0;
  16310. var texture = new THREE.Texture();
  16311. texture.image = images;
  16312. if ( mapping !== undefined ) texture.mapping = mapping;
  16313. // no flipping needed for cube textures
  16314. texture.flipY = false;
  16315. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16316. var cubeImage = new Image();
  16317. images[ i ] = cubeImage;
  16318. cubeImage.onload = function () {
  16319. images.loadCount += 1;
  16320. if ( images.loadCount === 6 ) {
  16321. texture.needsUpdate = true;
  16322. if ( onLoad ) onLoad( texture );
  16323. }
  16324. };
  16325. cubeImage.onerror = onError;
  16326. cubeImage.crossOrigin = this.crossOrigin;
  16327. cubeImage.src = array[ i ];
  16328. }
  16329. return texture;
  16330. },
  16331. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  16332. var images = [];
  16333. images.loadCount = 0;
  16334. var texture = new THREE.CompressedTexture();
  16335. texture.image = images;
  16336. if ( mapping !== undefined ) texture.mapping = mapping;
  16337. // no flipping for cube textures
  16338. // (also flipping doesn't work for compressed textures )
  16339. texture.flipY = false;
  16340. // can't generate mipmaps for compressed textures
  16341. // mips must be embedded in DDS files
  16342. texture.generateMipmaps = false;
  16343. var generateCubeFaceCallback = function ( rq, img ) {
  16344. return function () {
  16345. var buffer = rq.response;
  16346. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16347. img.format = dds.format;
  16348. img.mipmaps = dds.mipmaps;
  16349. img.width = dds.width;
  16350. img.height = dds.height;
  16351. images.loadCount += 1;
  16352. if ( images.loadCount === 6 ) {
  16353. texture.format = dds.format;
  16354. texture.needsUpdate = true;
  16355. if ( onLoad ) onLoad( texture );
  16356. }
  16357. }
  16358. }
  16359. // compressed cubemap textures as 6 separate DDS files
  16360. if ( array instanceof Array ) {
  16361. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16362. var cubeImage = {};
  16363. images[ i ] = cubeImage;
  16364. var request = new XMLHttpRequest();
  16365. request.onload = generateCubeFaceCallback( request, cubeImage );
  16366. request.onerror = onError;
  16367. var url = array[ i ];
  16368. request.open( 'GET', url, true );
  16369. request.responseType = "arraybuffer";
  16370. request.send( null );
  16371. }
  16372. // compressed cubemap texture stored in a single DDS file
  16373. } else {
  16374. var url = array;
  16375. var request = new XMLHttpRequest();
  16376. request.onload = function( ) {
  16377. var buffer = request.response;
  16378. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16379. if ( dds.isCubemap ) {
  16380. var faces = dds.mipmaps.length / dds.mipmapCount;
  16381. for ( var f = 0; f < faces; f ++ ) {
  16382. images[ f ] = { mipmaps : [] };
  16383. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16384. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  16385. images[ f ].format = dds.format;
  16386. images[ f ].width = dds.width;
  16387. images[ f ].height = dds.height;
  16388. }
  16389. }
  16390. texture.format = dds.format;
  16391. texture.needsUpdate = true;
  16392. if ( onLoad ) onLoad( texture );
  16393. }
  16394. }
  16395. request.onerror = onError;
  16396. request.open( 'GET', url, true );
  16397. request.responseType = "arraybuffer";
  16398. request.send( null );
  16399. }
  16400. return texture;
  16401. },
  16402. loadDDSTexture: function ( url, mapping, onLoad, onError ) {
  16403. var images = [];
  16404. images.loadCount = 0;
  16405. var texture = new THREE.CompressedTexture();
  16406. texture.image = images;
  16407. if ( mapping !== undefined ) texture.mapping = mapping;
  16408. // no flipping for cube textures
  16409. // (also flipping doesn't work for compressed textures )
  16410. texture.flipY = false;
  16411. // can't generate mipmaps for compressed textures
  16412. // mips must be embedded in DDS files
  16413. texture.generateMipmaps = false;
  16414. {
  16415. var request = new XMLHttpRequest();
  16416. request.onload = function( ) {
  16417. var buffer = request.response;
  16418. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16419. if ( dds.isCubemap ) {
  16420. var faces = dds.mipmaps.length / dds.mipmapCount;
  16421. for ( var f = 0; f < faces; f ++ ) {
  16422. images[ f ] = { mipmaps : [] };
  16423. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16424. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  16425. images[ f ].format = dds.format;
  16426. images[ f ].width = dds.width;
  16427. images[ f ].height = dds.height;
  16428. }
  16429. }
  16430. } else {
  16431. texture.image.width = dds.width;
  16432. texture.image.height = dds.height;
  16433. texture.mipmaps = dds.mipmaps;
  16434. }
  16435. texture.format = dds.format;
  16436. texture.needsUpdate = true;
  16437. if ( onLoad ) onLoad( texture );
  16438. }
  16439. request.onerror = onError;
  16440. request.open( 'GET', url, true );
  16441. request.responseType = "arraybuffer";
  16442. request.send( null );
  16443. }
  16444. return texture;
  16445. },
  16446. parseDDS: function ( buffer, loadMipmaps ) {
  16447. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  16448. // Adapted from @toji's DDS utils
  16449. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  16450. // All values and structures referenced from:
  16451. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  16452. var DDS_MAGIC = 0x20534444;
  16453. var DDSD_CAPS = 0x1,
  16454. DDSD_HEIGHT = 0x2,
  16455. DDSD_WIDTH = 0x4,
  16456. DDSD_PITCH = 0x8,
  16457. DDSD_PIXELFORMAT = 0x1000,
  16458. DDSD_MIPMAPCOUNT = 0x20000,
  16459. DDSD_LINEARSIZE = 0x80000,
  16460. DDSD_DEPTH = 0x800000;
  16461. var DDSCAPS_COMPLEX = 0x8,
  16462. DDSCAPS_MIPMAP = 0x400000,
  16463. DDSCAPS_TEXTURE = 0x1000;
  16464. var DDSCAPS2_CUBEMAP = 0x200,
  16465. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  16466. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  16467. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  16468. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  16469. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  16470. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  16471. DDSCAPS2_VOLUME = 0x200000;
  16472. var DDPF_ALPHAPIXELS = 0x1,
  16473. DDPF_ALPHA = 0x2,
  16474. DDPF_FOURCC = 0x4,
  16475. DDPF_RGB = 0x40,
  16476. DDPF_YUV = 0x200,
  16477. DDPF_LUMINANCE = 0x20000;
  16478. function fourCCToInt32( value ) {
  16479. return value.charCodeAt(0) +
  16480. (value.charCodeAt(1) << 8) +
  16481. (value.charCodeAt(2) << 16) +
  16482. (value.charCodeAt(3) << 24);
  16483. }
  16484. function int32ToFourCC( value ) {
  16485. return String.fromCharCode(
  16486. value & 0xff,
  16487. (value >> 8) & 0xff,
  16488. (value >> 16) & 0xff,
  16489. (value >> 24) & 0xff
  16490. );
  16491. }
  16492. function loadARGBMip( buffer, dataOffset, width, height ) {
  16493. var dataLength = width*height*4;
  16494. var srcBuffer = new Uint8Array( buffer, dataOffset, dataLength );
  16495. var byteArray = new Uint8Array( dataLength );
  16496. var dst = 0;
  16497. var src = 0;
  16498. for ( var y = 0; y < height; y++ ) {
  16499. for ( var x = 0; x < width; x++ ) {
  16500. var b = srcBuffer[src]; src++;
  16501. var g = srcBuffer[src]; src++;
  16502. var r = srcBuffer[src]; src++;
  16503. var a = srcBuffer[src]; src++;
  16504. byteArray[dst] = r; dst++; //r
  16505. byteArray[dst] = g; dst++; //g
  16506. byteArray[dst] = b; dst++; //b
  16507. byteArray[dst] = a; dst++; //a
  16508. }
  16509. }
  16510. return byteArray;
  16511. }
  16512. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  16513. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  16514. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  16515. var headerLengthInt = 31; // The header length in 32 bit ints
  16516. // Offsets into the header array
  16517. var off_magic = 0;
  16518. var off_size = 1;
  16519. var off_flags = 2;
  16520. var off_height = 3;
  16521. var off_width = 4;
  16522. var off_mipmapCount = 7;
  16523. var off_pfFlags = 20;
  16524. var off_pfFourCC = 21;
  16525. var off_RGBBitCount = 22;
  16526. var off_RBitMask = 23;
  16527. var off_GBitMask = 24;
  16528. var off_BBitMask = 25;
  16529. var off_ABitMask = 26;
  16530. var off_caps = 27;
  16531. var off_caps2 = 28;
  16532. var off_caps3 = 29;
  16533. var off_caps4 = 30;
  16534. // Parse header
  16535. var header = new Int32Array( buffer, 0, headerLengthInt );
  16536. if ( header[ off_magic ] !== DDS_MAGIC ) {
  16537. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  16538. return dds;
  16539. }
  16540. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  16541. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  16542. return dds;
  16543. }
  16544. var blockBytes;
  16545. var fourCC = header[ off_pfFourCC ];
  16546. var isRGBAUncompressed = false;
  16547. switch ( fourCC ) {
  16548. case FOURCC_DXT1:
  16549. blockBytes = 8;
  16550. dds.format = THREE.RGB_S3TC_DXT1_Format;
  16551. break;
  16552. case FOURCC_DXT3:
  16553. blockBytes = 16;
  16554. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  16555. break;
  16556. case FOURCC_DXT5:
  16557. blockBytes = 16;
  16558. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  16559. break;
  16560. default:
  16561. if( header[off_RGBBitCount] ==32
  16562. && header[off_RBitMask]&0xff0000
  16563. && header[off_GBitMask]&0xff00
  16564. && header[off_BBitMask]&0xff
  16565. && header[off_ABitMask]&0xff000000 ) {
  16566. isRGBAUncompressed = true;
  16567. blockBytes = 64;
  16568. dds.format = THREE.RGBAFormat;
  16569. } else {
  16570. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  16571. return dds;
  16572. }
  16573. }
  16574. dds.mipmapCount = 1;
  16575. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  16576. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  16577. }
  16578. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  16579. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  16580. dds.width = header[ off_width ];
  16581. dds.height = header[ off_height ];
  16582. var dataOffset = header[ off_size ] + 4;
  16583. // Extract mipmaps buffers
  16584. var width = dds.width;
  16585. var height = dds.height;
  16586. var faces = dds.isCubemap ? 6 : 1;
  16587. for ( var face = 0; face < faces; face ++ ) {
  16588. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16589. if( isRGBAUncompressed ) {
  16590. var byteArray = loadARGBMip( buffer, dataOffset, width, height );
  16591. var dataLength = byteArray.length;
  16592. } else {
  16593. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  16594. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  16595. }
  16596. var mipmap = { "data": byteArray, "width": width, "height": height };
  16597. dds.mipmaps.push( mipmap );
  16598. dataOffset += dataLength;
  16599. width = Math.max( width * 0.5, 1 );
  16600. height = Math.max( height * 0.5, 1 );
  16601. }
  16602. width = dds.width;
  16603. height = dds.height;
  16604. }
  16605. return dds;
  16606. },
  16607. getNormalMap: function ( image, depth ) {
  16608. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  16609. var cross = function ( a, b ) {
  16610. 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 ] ];
  16611. }
  16612. var subtract = function ( a, b ) {
  16613. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  16614. }
  16615. var normalize = function ( a ) {
  16616. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  16617. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  16618. }
  16619. depth = depth | 1;
  16620. var width = image.width;
  16621. var height = image.height;
  16622. var canvas = document.createElement( 'canvas' );
  16623. canvas.width = width;
  16624. canvas.height = height;
  16625. var context = canvas.getContext( '2d' );
  16626. context.drawImage( image, 0, 0 );
  16627. var data = context.getImageData( 0, 0, width, height ).data;
  16628. var imageData = context.createImageData( width, height );
  16629. var output = imageData.data;
  16630. for ( var x = 0; x < width; x ++ ) {
  16631. for ( var y = 0; y < height; y ++ ) {
  16632. var ly = y - 1 < 0 ? 0 : y - 1;
  16633. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  16634. var lx = x - 1 < 0 ? 0 : x - 1;
  16635. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  16636. var points = [];
  16637. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  16638. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  16639. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  16640. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  16641. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  16642. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  16643. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  16644. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  16645. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  16646. var normals = [];
  16647. var num_points = points.length;
  16648. for ( var i = 0; i < num_points; i ++ ) {
  16649. var v1 = points[ i ];
  16650. var v2 = points[ ( i + 1 ) % num_points ];
  16651. v1 = subtract( v1, origin );
  16652. v2 = subtract( v2, origin );
  16653. normals.push( normalize( cross( v1, v2 ) ) );
  16654. }
  16655. var normal = [ 0, 0, 0 ];
  16656. for ( var i = 0; i < normals.length; i ++ ) {
  16657. normal[ 0 ] += normals[ i ][ 0 ];
  16658. normal[ 1 ] += normals[ i ][ 1 ];
  16659. normal[ 2 ] += normals[ i ][ 2 ];
  16660. }
  16661. normal[ 0 ] /= normals.length;
  16662. normal[ 1 ] /= normals.length;
  16663. normal[ 2 ] /= normals.length;
  16664. var idx = ( y * width + x ) * 4;
  16665. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16666. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16667. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  16668. output[ idx + 3 ] = 255;
  16669. }
  16670. }
  16671. context.putImageData( imageData, 0, 0 );
  16672. return canvas;
  16673. },
  16674. generateDataTexture: function ( width, height, color ) {
  16675. var size = width * height;
  16676. var data = new Uint8Array( 3 * size );
  16677. var r = Math.floor( color.r * 255 );
  16678. var g = Math.floor( color.g * 255 );
  16679. var b = Math.floor( color.b * 255 );
  16680. for ( var i = 0; i < size; i ++ ) {
  16681. data[ i * 3 ] = r;
  16682. data[ i * 3 + 1 ] = g;
  16683. data[ i * 3 + 2 ] = b;
  16684. }
  16685. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16686. texture.needsUpdate = true;
  16687. return texture;
  16688. }
  16689. };
  16690. /**
  16691. * @author alteredq / http://alteredqualia.com/
  16692. */
  16693. THREE.SceneUtils = {
  16694. createMultiMaterialObject: function ( geometry, materials ) {
  16695. var group = new THREE.Object3D();
  16696. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16697. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16698. }
  16699. return group;
  16700. },
  16701. detach : function ( child, parent, scene ) {
  16702. child.applyMatrix( parent.matrixWorld );
  16703. parent.remove( child );
  16704. scene.add( child );
  16705. },
  16706. attach: function ( child, scene, parent ) {
  16707. var matrixWorldInverse = new THREE.Matrix4();
  16708. matrixWorldInverse.getInverse( parent.matrixWorld );
  16709. child.applyMatrix( matrixWorldInverse );
  16710. scene.remove( child );
  16711. parent.add( child );
  16712. }
  16713. };
  16714. /**
  16715. * @author zz85 / http://www.lab4games.net/zz85/blog
  16716. * @author alteredq / http://alteredqualia.com/
  16717. *
  16718. * For Text operations in three.js (See TextGeometry)
  16719. *
  16720. * It uses techniques used in:
  16721. *
  16722. * typeface.js and canvastext
  16723. * For converting fonts and rendering with javascript
  16724. * http://typeface.neocracy.org
  16725. *
  16726. * Triangulation ported from AS3
  16727. * Simple Polygon Triangulation
  16728. * http://actionsnippet.com/?p=1462
  16729. *
  16730. * A Method to triangulate shapes with holes
  16731. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16732. *
  16733. */
  16734. THREE.FontUtils = {
  16735. faces : {},
  16736. // Just for now. face[weight][style]
  16737. face : "helvetiker",
  16738. weight: "normal",
  16739. style : "normal",
  16740. size : 150,
  16741. divisions : 10,
  16742. getFace : function() {
  16743. return this.faces[ this.face ][ this.weight ][ this.style ];
  16744. },
  16745. loadFace : function( data ) {
  16746. var family = data.familyName.toLowerCase();
  16747. var ThreeFont = this;
  16748. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16749. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16750. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16751. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16752. return data;
  16753. },
  16754. drawText : function( text ) {
  16755. var characterPts = [], allPts = [];
  16756. // RenderText
  16757. var i, p,
  16758. face = this.getFace(),
  16759. scale = this.size / face.resolution,
  16760. offset = 0,
  16761. chars = String( text ).split( '' ),
  16762. length = chars.length;
  16763. var fontPaths = [];
  16764. for ( i = 0; i < length; i ++ ) {
  16765. var path = new THREE.Path();
  16766. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16767. offset += ret.offset;
  16768. fontPaths.push( ret.path );
  16769. }
  16770. // get the width
  16771. var width = offset / 2;
  16772. //
  16773. // for ( p = 0; p < allPts.length; p++ ) {
  16774. //
  16775. // allPts[ p ].x -= width;
  16776. //
  16777. // }
  16778. //var extract = this.extractPoints( allPts, characterPts );
  16779. //extract.contour = allPts;
  16780. //extract.paths = fontPaths;
  16781. //extract.offset = width;
  16782. return { paths : fontPaths, offset : width };
  16783. },
  16784. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16785. var pts = [];
  16786. var i, i2, divisions,
  16787. outline, action, length,
  16788. scaleX, scaleY,
  16789. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16790. laste,
  16791. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16792. if ( !glyph ) return;
  16793. if ( glyph.o ) {
  16794. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16795. length = outline.length;
  16796. scaleX = scale;
  16797. scaleY = scale;
  16798. for ( i = 0; i < length; ) {
  16799. action = outline[ i ++ ];
  16800. //console.log( action );
  16801. switch( action ) {
  16802. case 'm':
  16803. // Move To
  16804. x = outline[ i++ ] * scaleX + offset;
  16805. y = outline[ i++ ] * scaleY;
  16806. path.moveTo( x, y );
  16807. break;
  16808. case 'l':
  16809. // Line To
  16810. x = outline[ i++ ] * scaleX + offset;
  16811. y = outline[ i++ ] * scaleY;
  16812. path.lineTo(x,y);
  16813. break;
  16814. case 'q':
  16815. // QuadraticCurveTo
  16816. cpx = outline[ i++ ] * scaleX + offset;
  16817. cpy = outline[ i++ ] * scaleY;
  16818. cpx1 = outline[ i++ ] * scaleX + offset;
  16819. cpy1 = outline[ i++ ] * scaleY;
  16820. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16821. laste = pts[ pts.length - 1 ];
  16822. if ( laste ) {
  16823. cpx0 = laste.x;
  16824. cpy0 = laste.y;
  16825. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16826. var t = i2 / divisions;
  16827. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16828. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16829. }
  16830. }
  16831. break;
  16832. case 'b':
  16833. // Cubic Bezier Curve
  16834. cpx = outline[ i++ ] * scaleX + offset;
  16835. cpy = outline[ i++ ] * scaleY;
  16836. cpx1 = outline[ i++ ] * scaleX + offset;
  16837. cpy1 = outline[ i++ ] * -scaleY;
  16838. cpx2 = outline[ i++ ] * scaleX + offset;
  16839. cpy2 = outline[ i++ ] * -scaleY;
  16840. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16841. laste = pts[ pts.length - 1 ];
  16842. if ( laste ) {
  16843. cpx0 = laste.x;
  16844. cpy0 = laste.y;
  16845. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16846. var t = i2 / divisions;
  16847. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16848. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16849. }
  16850. }
  16851. break;
  16852. }
  16853. }
  16854. }
  16855. return { offset: glyph.ha*scale, path:path};
  16856. }
  16857. };
  16858. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16859. // Parameters
  16860. parameters = parameters || {};
  16861. var size = parameters.size !== undefined ? parameters.size : 100;
  16862. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16863. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16864. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16865. var style = parameters.style !== undefined ? parameters.style : "normal";
  16866. THREE.FontUtils.size = size;
  16867. THREE.FontUtils.divisions = curveSegments;
  16868. THREE.FontUtils.face = font;
  16869. THREE.FontUtils.weight = weight;
  16870. THREE.FontUtils.style = style;
  16871. // Get a Font data json object
  16872. var data = THREE.FontUtils.drawText( text );
  16873. var paths = data.paths;
  16874. var shapes = [];
  16875. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16876. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16877. }
  16878. return shapes;
  16879. };
  16880. /**
  16881. * This code is a quick port of code written in C++ which was submitted to
  16882. * flipcode.com by John W. Ratcliff // July 22, 2000
  16883. * See original code and more information here:
  16884. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16885. *
  16886. * ported to actionscript by Zevan Rosser
  16887. * www.actionsnippet.com
  16888. *
  16889. * ported to javascript by Joshua Koo
  16890. * http://www.lab4games.net/zz85/blog
  16891. *
  16892. */
  16893. ( function( namespace ) {
  16894. var EPSILON = 0.0000000001;
  16895. // takes in an contour array and returns
  16896. var process = function( contour, indices ) {
  16897. var n = contour.length;
  16898. if ( n < 3 ) return null;
  16899. var result = [],
  16900. verts = [],
  16901. vertIndices = [];
  16902. /* we want a counter-clockwise polygon in verts */
  16903. var u, v, w;
  16904. if ( area( contour ) > 0.0 ) {
  16905. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16906. } else {
  16907. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16908. }
  16909. var nv = n;
  16910. /* remove nv - 2 vertices, creating 1 triangle every time */
  16911. var count = 2 * nv; /* error detection */
  16912. for( v = nv - 1; nv > 2; ) {
  16913. /* if we loop, it is probably a non-simple polygon */
  16914. if ( ( count-- ) <= 0 ) {
  16915. //** Triangulate: ERROR - probable bad polygon!
  16916. //throw ( "Warning, unable to triangulate polygon!" );
  16917. //return null;
  16918. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16919. console.log( "Warning, unable to triangulate polygon!" );
  16920. if ( indices ) return vertIndices;
  16921. return result;
  16922. }
  16923. /* three consecutive vertices in current polygon, <u,v,w> */
  16924. u = v; if ( nv <= u ) u = 0; /* previous */
  16925. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16926. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16927. if ( snip( contour, u, v, w, nv, verts ) ) {
  16928. var a, b, c, s, t;
  16929. /* true names of the vertices */
  16930. a = verts[ u ];
  16931. b = verts[ v ];
  16932. c = verts[ w ];
  16933. /* output Triangle */
  16934. result.push( [ contour[ a ],
  16935. contour[ b ],
  16936. contour[ c ] ] );
  16937. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16938. /* remove v from the remaining polygon */
  16939. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16940. verts[ s ] = verts[ t ];
  16941. }
  16942. nv--;
  16943. /* reset error detection counter */
  16944. count = 2 * nv;
  16945. }
  16946. }
  16947. if ( indices ) return vertIndices;
  16948. return result;
  16949. };
  16950. // calculate area of the contour polygon
  16951. var area = function ( contour ) {
  16952. var n = contour.length;
  16953. var a = 0.0;
  16954. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16955. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16956. }
  16957. return a * 0.5;
  16958. };
  16959. var snip = function ( contour, u, v, w, n, verts ) {
  16960. var p;
  16961. var ax, ay, bx, by;
  16962. var cx, cy, px, py;
  16963. ax = contour[ verts[ u ] ].x;
  16964. ay = contour[ verts[ u ] ].y;
  16965. bx = contour[ verts[ v ] ].x;
  16966. by = contour[ verts[ v ] ].y;
  16967. cx = contour[ verts[ w ] ].x;
  16968. cy = contour[ verts[ w ] ].y;
  16969. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16970. var aX, aY, bX, bY, cX, cY;
  16971. var apx, apy, bpx, bpy, cpx, cpy;
  16972. var cCROSSap, bCROSScp, aCROSSbp;
  16973. aX = cx - bx; aY = cy - by;
  16974. bX = ax - cx; bY = ay - cy;
  16975. cX = bx - ax; cY = by - ay;
  16976. for ( p = 0; p < n; p++ ) {
  16977. px = contour[ verts[ p ] ].x
  16978. py = contour[ verts[ p ] ].y
  16979. if ( ( (px === ax) && (py === ay) ) ||
  16980. ( (px === bx) && (py === by) ) ||
  16981. ( (px === cx) && (py === cy) ) ) continue;
  16982. apx = px - ax; apy = py - ay;
  16983. bpx = px - bx; bpy = py - by;
  16984. cpx = px - cx; cpy = py - cy;
  16985. // see if p is inside triangle abc
  16986. aCROSSbp = aX*bpy - aY*bpx;
  16987. cCROSSap = cX*apy - cY*apx;
  16988. bCROSScp = bX*cpy - bY*cpx;
  16989. if ( (aCROSSbp >= -EPSILON) && (bCROSScp >= -EPSILON) && (cCROSSap >= -EPSILON) ) return false;
  16990. }
  16991. return true;
  16992. };
  16993. namespace.Triangulate = process;
  16994. namespace.Triangulate.area = area;
  16995. return namespace;
  16996. })(THREE.FontUtils);
  16997. // To use the typeface.js face files, hook up the API
  16998. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  16999. THREE.typeface_js = self._typeface_js;
  17000. /**
  17001. * @author zz85 / http://www.lab4games.net/zz85/blog
  17002. * Extensible curve object
  17003. *
  17004. * Some common of Curve methods
  17005. * .getPoint(t), getTangent(t)
  17006. * .getPointAt(u), getTagentAt(u)
  17007. * .getPoints(), .getSpacedPoints()
  17008. * .getLength()
  17009. * .updateArcLengths()
  17010. *
  17011. * This following classes subclasses THREE.Curve:
  17012. *
  17013. * -- 2d classes --
  17014. * THREE.LineCurve
  17015. * THREE.QuadraticBezierCurve
  17016. * THREE.CubicBezierCurve
  17017. * THREE.SplineCurve
  17018. * THREE.ArcCurve
  17019. * THREE.EllipseCurve
  17020. *
  17021. * -- 3d classes --
  17022. * THREE.LineCurve3
  17023. * THREE.QuadraticBezierCurve3
  17024. * THREE.CubicBezierCurve3
  17025. * THREE.SplineCurve3
  17026. * THREE.ClosedSplineCurve3
  17027. *
  17028. * A series of curves can be represented as a THREE.CurvePath
  17029. *
  17030. **/
  17031. /**************************************************************
  17032. * Abstract Curve base class
  17033. **************************************************************/
  17034. THREE.Curve = function () {
  17035. };
  17036. // Virtual base class method to overwrite and implement in subclasses
  17037. // - t [0 .. 1]
  17038. THREE.Curve.prototype.getPoint = function ( t ) {
  17039. console.log( "Warning, getPoint() not implemented!" );
  17040. return null;
  17041. };
  17042. // Get point at relative position in curve according to arc length
  17043. // - u [0 .. 1]
  17044. THREE.Curve.prototype.getPointAt = function ( u ) {
  17045. var t = this.getUtoTmapping( u );
  17046. return this.getPoint( t );
  17047. };
  17048. // Get sequence of points using getPoint( t )
  17049. THREE.Curve.prototype.getPoints = function ( divisions ) {
  17050. if ( !divisions ) divisions = 5;
  17051. var d, pts = [];
  17052. for ( d = 0; d <= divisions; d ++ ) {
  17053. pts.push( this.getPoint( d / divisions ) );
  17054. }
  17055. return pts;
  17056. };
  17057. // Get sequence of points using getPointAt( u )
  17058. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  17059. if ( !divisions ) divisions = 5;
  17060. var d, pts = [];
  17061. for ( d = 0; d <= divisions; d ++ ) {
  17062. pts.push( this.getPointAt( d / divisions ) );
  17063. }
  17064. return pts;
  17065. };
  17066. // Get total curve arc length
  17067. THREE.Curve.prototype.getLength = function () {
  17068. var lengths = this.getLengths();
  17069. return lengths[ lengths.length - 1 ];
  17070. };
  17071. // Get list of cumulative segment lengths
  17072. THREE.Curve.prototype.getLengths = function ( divisions ) {
  17073. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  17074. if ( this.cacheArcLengths
  17075. && ( this.cacheArcLengths.length == divisions + 1 )
  17076. && !this.needsUpdate) {
  17077. //console.log( "cached", this.cacheArcLengths );
  17078. return this.cacheArcLengths;
  17079. }
  17080. this.needsUpdate = false;
  17081. var cache = [];
  17082. var current, last = this.getPoint( 0 );
  17083. var p, sum = 0;
  17084. cache.push( 0 );
  17085. for ( p = 1; p <= divisions; p ++ ) {
  17086. current = this.getPoint ( p / divisions );
  17087. sum += current.distanceTo( last );
  17088. cache.push( sum );
  17089. last = current;
  17090. }
  17091. this.cacheArcLengths = cache;
  17092. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  17093. };
  17094. THREE.Curve.prototype.updateArcLengths = function() {
  17095. this.needsUpdate = true;
  17096. this.getLengths();
  17097. };
  17098. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  17099. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  17100. var arcLengths = this.getLengths();
  17101. var i = 0, il = arcLengths.length;
  17102. var targetArcLength; // The targeted u distance value to get
  17103. if ( distance ) {
  17104. targetArcLength = distance;
  17105. } else {
  17106. targetArcLength = u * arcLengths[ il - 1 ];
  17107. }
  17108. //var time = Date.now();
  17109. // binary search for the index with largest value smaller than target u distance
  17110. var low = 0, high = il - 1, comparison;
  17111. while ( low <= high ) {
  17112. 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
  17113. comparison = arcLengths[ i ] - targetArcLength;
  17114. if ( comparison < 0 ) {
  17115. low = i + 1;
  17116. continue;
  17117. } else if ( comparison > 0 ) {
  17118. high = i - 1;
  17119. continue;
  17120. } else {
  17121. high = i;
  17122. break;
  17123. // DONE
  17124. }
  17125. }
  17126. i = high;
  17127. //console.log('b' , i, low, high, Date.now()- time);
  17128. if ( arcLengths[ i ] == targetArcLength ) {
  17129. var t = i / ( il - 1 );
  17130. return t;
  17131. }
  17132. // we could get finer grain at lengths, or use simple interpolatation between two points
  17133. var lengthBefore = arcLengths[ i ];
  17134. var lengthAfter = arcLengths[ i + 1 ];
  17135. var segmentLength = lengthAfter - lengthBefore;
  17136. // determine where we are between the 'before' and 'after' points
  17137. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  17138. // add that fractional amount to t
  17139. var t = ( i + segmentFraction ) / ( il -1 );
  17140. return t;
  17141. };
  17142. // Returns a unit vector tangent at t
  17143. // In case any sub curve does not implement its tangent derivation,
  17144. // 2 points a small delta apart will be used to find its gradient
  17145. // which seems to give a reasonable approximation
  17146. THREE.Curve.prototype.getTangent = function( t ) {
  17147. var delta = 0.0001;
  17148. var t1 = t - delta;
  17149. var t2 = t + delta;
  17150. // Capping in case of danger
  17151. if ( t1 < 0 ) t1 = 0;
  17152. if ( t2 > 1 ) t2 = 1;
  17153. var pt1 = this.getPoint( t1 );
  17154. var pt2 = this.getPoint( t2 );
  17155. var vec = pt2.clone().sub(pt1);
  17156. return vec.normalize();
  17157. };
  17158. THREE.Curve.prototype.getTangentAt = function ( u ) {
  17159. var t = this.getUtoTmapping( u );
  17160. return this.getTangent( t );
  17161. };
  17162. /**************************************************************
  17163. * Utils
  17164. **************************************************************/
  17165. THREE.Curve.Utils = {
  17166. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  17167. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  17168. },
  17169. // Puay Bing, thanks for helping with this derivative!
  17170. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  17171. return -3 * p0 * (1 - t) * (1 - t) +
  17172. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  17173. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  17174. 3 * t * t * p3;
  17175. },
  17176. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  17177. // To check if my formulas are correct
  17178. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  17179. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  17180. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  17181. var h11 = 3 * t * t - 2 * t; // t3 − t2
  17182. return h00 + h10 + h01 + h11;
  17183. },
  17184. // Catmull-Rom
  17185. interpolate: function( p0, p1, p2, p3, t ) {
  17186. var v0 = ( p2 - p0 ) * 0.5;
  17187. var v1 = ( p3 - p1 ) * 0.5;
  17188. var t2 = t * t;
  17189. var t3 = t * t2;
  17190. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17191. }
  17192. };
  17193. // TODO: Transformation for Curves?
  17194. /**************************************************************
  17195. * 3D Curves
  17196. **************************************************************/
  17197. // A Factory method for creating new curve subclasses
  17198. THREE.Curve.create = function ( constructor, getPointFunc ) {
  17199. constructor.prototype = Object.create( THREE.Curve.prototype );
  17200. constructor.prototype.getPoint = getPointFunc;
  17201. return constructor;
  17202. };
  17203. /**
  17204. * @author zz85 / http://www.lab4games.net/zz85/blog
  17205. *
  17206. **/
  17207. /**************************************************************
  17208. * Curved Path - a curve path is simply a array of connected
  17209. * curves, but retains the api of a curve
  17210. **************************************************************/
  17211. THREE.CurvePath = function () {
  17212. this.curves = [];
  17213. this.bends = [];
  17214. this.autoClose = false; // Automatically closes the path
  17215. };
  17216. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  17217. THREE.CurvePath.prototype.add = function ( curve ) {
  17218. this.curves.push( curve );
  17219. };
  17220. THREE.CurvePath.prototype.checkConnection = function() {
  17221. // TODO
  17222. // If the ending of curve is not connected to the starting
  17223. // or the next curve, then, this is not a real path
  17224. };
  17225. THREE.CurvePath.prototype.closePath = function() {
  17226. // TODO Test
  17227. // and verify for vector3 (needs to implement equals)
  17228. // Add a line curve if start and end of lines are not connected
  17229. var startPoint = this.curves[0].getPoint(0);
  17230. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  17231. if (!startPoint.equals(endPoint)) {
  17232. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  17233. }
  17234. };
  17235. // To get accurate point with reference to
  17236. // entire path distance at time t,
  17237. // following has to be done:
  17238. // 1. Length of each sub path have to be known
  17239. // 2. Locate and identify type of curve
  17240. // 3. Get t for the curve
  17241. // 4. Return curve.getPointAt(t')
  17242. THREE.CurvePath.prototype.getPoint = function( t ) {
  17243. var d = t * this.getLength();
  17244. var curveLengths = this.getCurveLengths();
  17245. var i = 0, diff, curve;
  17246. // To think about boundaries points.
  17247. while ( i < curveLengths.length ) {
  17248. if ( curveLengths[ i ] >= d ) {
  17249. diff = curveLengths[ i ] - d;
  17250. curve = this.curves[ i ];
  17251. var u = 1 - diff / curve.getLength();
  17252. return curve.getPointAt( u );
  17253. break;
  17254. }
  17255. i ++;
  17256. }
  17257. return null;
  17258. // loop where sum != 0, sum > d , sum+1 <d
  17259. };
  17260. /*
  17261. THREE.CurvePath.prototype.getTangent = function( t ) {
  17262. };*/
  17263. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  17264. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  17265. // getPoint() depends on getLength
  17266. THREE.CurvePath.prototype.getLength = function() {
  17267. var lens = this.getCurveLengths();
  17268. return lens[ lens.length - 1 ];
  17269. };
  17270. // Compute lengths and cache them
  17271. // We cannot overwrite getLengths() because UtoT mapping uses it.
  17272. THREE.CurvePath.prototype.getCurveLengths = function() {
  17273. // We use cache values if curves and cache array are same length
  17274. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  17275. return this.cacheLengths;
  17276. };
  17277. // Get length of subsurve
  17278. // Push sums into cached array
  17279. var lengths = [], sums = 0;
  17280. var i, il = this.curves.length;
  17281. for ( i = 0; i < il; i ++ ) {
  17282. sums += this.curves[ i ].getLength();
  17283. lengths.push( sums );
  17284. }
  17285. this.cacheLengths = lengths;
  17286. return lengths;
  17287. };
  17288. // Returns min and max coordinates, as well as centroid
  17289. THREE.CurvePath.prototype.getBoundingBox = function () {
  17290. var points = this.getPoints();
  17291. var maxX, maxY, maxZ;
  17292. var minX, minY, minZ;
  17293. maxX = maxY = Number.NEGATIVE_INFINITY;
  17294. minX = minY = Number.POSITIVE_INFINITY;
  17295. var p, i, il, sum;
  17296. var v3 = points[0] instanceof THREE.Vector3;
  17297. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  17298. for ( i = 0, il = points.length; i < il; i ++ ) {
  17299. p = points[ i ];
  17300. if ( p.x > maxX ) maxX = p.x;
  17301. else if ( p.x < minX ) minX = p.x;
  17302. if ( p.y > maxY ) maxY = p.y;
  17303. else if ( p.y < minY ) minY = p.y;
  17304. if ( v3 ) {
  17305. if ( p.z > maxZ ) maxZ = p.z;
  17306. else if ( p.z < minZ ) minZ = p.z;
  17307. }
  17308. sum.add( p );
  17309. }
  17310. var ret = {
  17311. minX: minX,
  17312. minY: minY,
  17313. maxX: maxX,
  17314. maxY: maxY,
  17315. centroid: sum.divideScalar( il )
  17316. };
  17317. if ( v3 ) {
  17318. ret.maxZ = maxZ;
  17319. ret.minZ = minZ;
  17320. }
  17321. return ret;
  17322. };
  17323. /**************************************************************
  17324. * Create Geometries Helpers
  17325. **************************************************************/
  17326. /// Generate geometry from path points (for Line or ParticleSystem objects)
  17327. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  17328. var pts = this.getPoints( divisions, true );
  17329. return this.createGeometry( pts );
  17330. };
  17331. // Generate geometry from equidistance sampling along the path
  17332. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  17333. var pts = this.getSpacedPoints( divisions, true );
  17334. return this.createGeometry( pts );
  17335. };
  17336. THREE.CurvePath.prototype.createGeometry = function( points ) {
  17337. var geometry = new THREE.Geometry();
  17338. for ( var i = 0; i < points.length; i ++ ) {
  17339. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  17340. }
  17341. return geometry;
  17342. };
  17343. /**************************************************************
  17344. * Bend / Wrap Helper Methods
  17345. **************************************************************/
  17346. // Wrap path / Bend modifiers?
  17347. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  17348. this.bends.push( bendpath );
  17349. };
  17350. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  17351. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  17352. var i, il;
  17353. if ( !bends ) {
  17354. bends = this.bends;
  17355. }
  17356. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17357. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17358. }
  17359. return oldPts;
  17360. };
  17361. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  17362. var oldPts = this.getSpacedPoints( segments );
  17363. var i, il;
  17364. if ( !bends ) {
  17365. bends = this.bends;
  17366. }
  17367. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17368. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17369. }
  17370. return oldPts;
  17371. };
  17372. // This returns getPoints() bend/wrapped around the contour of a path.
  17373. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  17374. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  17375. var bounds = this.getBoundingBox();
  17376. var i, il, p, oldX, oldY, xNorm;
  17377. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  17378. p = oldPts[ i ];
  17379. oldX = p.x;
  17380. oldY = p.y;
  17381. xNorm = oldX / bounds.maxX;
  17382. // If using actual distance, for length > path, requires line extrusions
  17383. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  17384. xNorm = path.getUtoTmapping( xNorm, oldX );
  17385. // check for out of bounds?
  17386. var pathPt = path.getPoint( xNorm );
  17387. var normal = path.getTangent( xNorm );
  17388. normal.set( -normal.y, normal.x ).multiplyScalar( oldY );
  17389. p.x = pathPt.x + normal.x;
  17390. p.y = pathPt.y + normal.y;
  17391. }
  17392. return oldPts;
  17393. };
  17394. /**
  17395. * @author alteredq / http://alteredqualia.com/
  17396. */
  17397. THREE.Gyroscope = function () {
  17398. THREE.Object3D.call( this );
  17399. };
  17400. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  17401. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  17402. this.matrixAutoUpdate && this.updateMatrix();
  17403. // update matrixWorld
  17404. if ( this.matrixWorldNeedsUpdate || force ) {
  17405. if ( this.parent ) {
  17406. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  17407. this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld );
  17408. this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject );
  17409. this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld );
  17410. } else {
  17411. this.matrixWorld.copy( this.matrix );
  17412. }
  17413. this.matrixWorldNeedsUpdate = false;
  17414. force = true;
  17415. }
  17416. // update children
  17417. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  17418. this.children[ i ].updateMatrixWorld( force );
  17419. }
  17420. };
  17421. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  17422. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  17423. THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion();
  17424. THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion();
  17425. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  17426. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  17427. /**
  17428. * @author zz85 / http://www.lab4games.net/zz85/blog
  17429. * Creates free form 2d path using series of points, lines or curves.
  17430. *
  17431. **/
  17432. THREE.Path = function ( points ) {
  17433. THREE.CurvePath.call(this);
  17434. this.actions = [];
  17435. if ( points ) {
  17436. this.fromPoints( points );
  17437. }
  17438. };
  17439. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  17440. THREE.PathActions = {
  17441. MOVE_TO: 'moveTo',
  17442. LINE_TO: 'lineTo',
  17443. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  17444. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  17445. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  17446. ARC: 'arc', // Circle
  17447. ELLIPSE: 'ellipse'
  17448. };
  17449. // TODO Clean up PATH API
  17450. // Create path using straight lines to connect all points
  17451. // - vectors: array of Vector2
  17452. THREE.Path.prototype.fromPoints = function ( vectors ) {
  17453. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  17454. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  17455. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  17456. };
  17457. };
  17458. // startPath() endPath()?
  17459. THREE.Path.prototype.moveTo = function ( x, y ) {
  17460. var args = Array.prototype.slice.call( arguments );
  17461. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  17462. };
  17463. THREE.Path.prototype.lineTo = function ( x, y ) {
  17464. var args = Array.prototype.slice.call( arguments );
  17465. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17466. var x0 = lastargs[ lastargs.length - 2 ];
  17467. var y0 = lastargs[ lastargs.length - 1 ];
  17468. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  17469. this.curves.push( curve );
  17470. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  17471. };
  17472. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  17473. var args = Array.prototype.slice.call( arguments );
  17474. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17475. var x0 = lastargs[ lastargs.length - 2 ];
  17476. var y0 = lastargs[ lastargs.length - 1 ];
  17477. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  17478. new THREE.Vector2( aCPx, aCPy ),
  17479. new THREE.Vector2( aX, aY ) );
  17480. this.curves.push( curve );
  17481. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  17482. };
  17483. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  17484. aCP2x, aCP2y,
  17485. aX, aY ) {
  17486. var args = Array.prototype.slice.call( arguments );
  17487. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17488. var x0 = lastargs[ lastargs.length - 2 ];
  17489. var y0 = lastargs[ lastargs.length - 1 ];
  17490. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  17491. new THREE.Vector2( aCP1x, aCP1y ),
  17492. new THREE.Vector2( aCP2x, aCP2y ),
  17493. new THREE.Vector2( aX, aY ) );
  17494. this.curves.push( curve );
  17495. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  17496. };
  17497. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  17498. var args = Array.prototype.slice.call( arguments );
  17499. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17500. var x0 = lastargs[ lastargs.length - 2 ];
  17501. var y0 = lastargs[ lastargs.length - 1 ];
  17502. //---
  17503. var npts = [ new THREE.Vector2( x0, y0 ) ];
  17504. Array.prototype.push.apply( npts, pts );
  17505. var curve = new THREE.SplineCurve( npts );
  17506. this.curves.push( curve );
  17507. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  17508. };
  17509. // FUTURE: Change the API or follow canvas API?
  17510. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  17511. aStartAngle, aEndAngle, aClockwise ) {
  17512. var lastargs = this.actions[ this.actions.length - 1].args;
  17513. var x0 = lastargs[ lastargs.length - 2 ];
  17514. var y0 = lastargs[ lastargs.length - 1 ];
  17515. this.absarc(aX + x0, aY + y0, aRadius,
  17516. aStartAngle, aEndAngle, aClockwise );
  17517. };
  17518. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  17519. aStartAngle, aEndAngle, aClockwise ) {
  17520. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17521. };
  17522. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  17523. aStartAngle, aEndAngle, aClockwise ) {
  17524. var lastargs = this.actions[ this.actions.length - 1].args;
  17525. var x0 = lastargs[ lastargs.length - 2 ];
  17526. var y0 = lastargs[ lastargs.length - 1 ];
  17527. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  17528. aStartAngle, aEndAngle, aClockwise );
  17529. };
  17530. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  17531. aStartAngle, aEndAngle, aClockwise ) {
  17532. var args = Array.prototype.slice.call( arguments );
  17533. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  17534. aStartAngle, aEndAngle, aClockwise );
  17535. this.curves.push( curve );
  17536. var lastPoint = curve.getPoint(1);
  17537. args.push(lastPoint.x);
  17538. args.push(lastPoint.y);
  17539. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17540. };
  17541. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17542. if ( ! divisions ) divisions = 40;
  17543. var points = [];
  17544. for ( var i = 0; i < divisions; i ++ ) {
  17545. points.push( this.getPoint( i / divisions ) );
  17546. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17547. }
  17548. // if ( closedPath ) {
  17549. //
  17550. // points.push( points[ 0 ] );
  17551. //
  17552. // }
  17553. return points;
  17554. };
  17555. /* Return an array of vectors based on contour of the path */
  17556. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17557. if (this.useSpacedPoints) {
  17558. console.log('tata');
  17559. return this.getSpacedPoints( divisions, closedPath );
  17560. }
  17561. divisions = divisions || 12;
  17562. var points = [];
  17563. var i, il, item, action, args;
  17564. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17565. laste, j,
  17566. t, tx, ty;
  17567. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17568. item = this.actions[ i ];
  17569. action = item.action;
  17570. args = item.args;
  17571. switch( action ) {
  17572. case THREE.PathActions.MOVE_TO:
  17573. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17574. break;
  17575. case THREE.PathActions.LINE_TO:
  17576. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17577. break;
  17578. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17579. cpx = args[ 2 ];
  17580. cpy = args[ 3 ];
  17581. cpx1 = args[ 0 ];
  17582. cpy1 = args[ 1 ];
  17583. if ( points.length > 0 ) {
  17584. laste = points[ points.length - 1 ];
  17585. cpx0 = laste.x;
  17586. cpy0 = laste.y;
  17587. } else {
  17588. laste = this.actions[ i - 1 ].args;
  17589. cpx0 = laste[ laste.length - 2 ];
  17590. cpy0 = laste[ laste.length - 1 ];
  17591. }
  17592. for ( j = 1; j <= divisions; j ++ ) {
  17593. t = j / divisions;
  17594. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17595. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17596. points.push( new THREE.Vector2( tx, ty ) );
  17597. }
  17598. break;
  17599. case THREE.PathActions.BEZIER_CURVE_TO:
  17600. cpx = args[ 4 ];
  17601. cpy = args[ 5 ];
  17602. cpx1 = args[ 0 ];
  17603. cpy1 = args[ 1 ];
  17604. cpx2 = args[ 2 ];
  17605. cpy2 = args[ 3 ];
  17606. if ( points.length > 0 ) {
  17607. laste = points[ points.length - 1 ];
  17608. cpx0 = laste.x;
  17609. cpy0 = laste.y;
  17610. } else {
  17611. laste = this.actions[ i - 1 ].args;
  17612. cpx0 = laste[ laste.length - 2 ];
  17613. cpy0 = laste[ laste.length - 1 ];
  17614. }
  17615. for ( j = 1; j <= divisions; j ++ ) {
  17616. t = j / divisions;
  17617. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17618. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17619. points.push( new THREE.Vector2( tx, ty ) );
  17620. }
  17621. break;
  17622. case THREE.PathActions.CSPLINE_THRU:
  17623. laste = this.actions[ i - 1 ].args;
  17624. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17625. var spts = [ last ];
  17626. var n = divisions * args[ 0 ].length;
  17627. spts = spts.concat( args[ 0 ] );
  17628. var spline = new THREE.SplineCurve( spts );
  17629. for ( j = 1; j <= n; j ++ ) {
  17630. points.push( spline.getPointAt( j / n ) ) ;
  17631. }
  17632. break;
  17633. case THREE.PathActions.ARC:
  17634. var aX = args[ 0 ], aY = args[ 1 ],
  17635. aRadius = args[ 2 ],
  17636. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17637. aClockwise = !!args[ 5 ];
  17638. var deltaAngle = aEndAngle - aStartAngle;
  17639. var angle;
  17640. var tdivisions = divisions * 2;
  17641. for ( j = 1; j <= tdivisions; j ++ ) {
  17642. t = j / tdivisions;
  17643. if ( ! aClockwise ) {
  17644. t = 1 - t;
  17645. }
  17646. angle = aStartAngle + t * deltaAngle;
  17647. tx = aX + aRadius * Math.cos( angle );
  17648. ty = aY + aRadius * Math.sin( angle );
  17649. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17650. points.push( new THREE.Vector2( tx, ty ) );
  17651. }
  17652. //console.log(points);
  17653. break;
  17654. case THREE.PathActions.ELLIPSE:
  17655. var aX = args[ 0 ], aY = args[ 1 ],
  17656. xRadius = args[ 2 ],
  17657. yRadius = args[ 3 ],
  17658. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17659. aClockwise = !!args[ 6 ];
  17660. var deltaAngle = aEndAngle - aStartAngle;
  17661. var angle;
  17662. var tdivisions = divisions * 2;
  17663. for ( j = 1; j <= tdivisions; j ++ ) {
  17664. t = j / tdivisions;
  17665. if ( ! aClockwise ) {
  17666. t = 1 - t;
  17667. }
  17668. angle = aStartAngle + t * deltaAngle;
  17669. tx = aX + xRadius * Math.cos( angle );
  17670. ty = aY + yRadius * Math.sin( angle );
  17671. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17672. points.push( new THREE.Vector2( tx, ty ) );
  17673. }
  17674. //console.log(points);
  17675. break;
  17676. } // end switch
  17677. }
  17678. // Normalize to remove the closing point by default.
  17679. var lastPoint = points[ points.length - 1];
  17680. var EPSILON = 0.0000000001;
  17681. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17682. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17683. points.splice( points.length - 1, 1);
  17684. if ( closedPath ) {
  17685. points.push( points[ 0 ] );
  17686. }
  17687. return points;
  17688. };
  17689. // Breaks path into shapes
  17690. THREE.Path.prototype.toShapes = function( isCCW ) {
  17691. function isPointInsidePolygon( inPt, inPolygon ) {
  17692. var EPSILON = 0.0000000001;
  17693. var polyLen = inPolygon.length;
  17694. // inPt on polygon contour => immediate success or
  17695. // toggling of inside/outside at every single! intersection point of an edge
  17696. // with the horizontal line through inPt, left of inPt
  17697. // not counting lowerY endpoints of edges and whole edges on that line
  17698. var inside = false;
  17699. for( var p = polyLen - 1, q = 0; q < polyLen; p = q++ ) {
  17700. var edgeLowPt = inPolygon[ p ];
  17701. var edgeHighPt = inPolygon[ q ];
  17702. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  17703. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  17704. if ( Math.abs(edgeDy) > EPSILON ) { // not parallel
  17705. if ( edgeDy < 0 ) {
  17706. edgeLowPt = inPolygon[ q ]; edgeDx = -edgeDx;
  17707. edgeHighPt = inPolygon[ p ]; edgeDy = -edgeDy;
  17708. }
  17709. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  17710. if ( inPt.y == edgeLowPt.y ) {
  17711. if ( inPt.x == edgeLowPt.x ) return true; // inPt is on contour ?
  17712. // continue; // no intersection or edgeLowPt => doesn't count !!!
  17713. } else {
  17714. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  17715. if ( perpEdge == 0 ) return true; // inPt is on contour ?
  17716. if ( perpEdge < 0 ) continue;
  17717. inside = !inside; // true intersection left of inPt
  17718. }
  17719. } else { // parallel or colinear
  17720. if ( inPt.y != edgeLowPt.y ) continue; // parallel
  17721. // egde lies on the same horizontal line as inPt
  17722. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  17723. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  17724. // continue;
  17725. }
  17726. }
  17727. return inside;
  17728. }
  17729. var i, il, item, action, args;
  17730. var subPaths = [], lastPath = new THREE.Path();
  17731. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17732. item = this.actions[ i ];
  17733. args = item.args;
  17734. action = item.action;
  17735. if ( action == THREE.PathActions.MOVE_TO ) {
  17736. if ( lastPath.actions.length != 0 ) {
  17737. subPaths.push( lastPath );
  17738. lastPath = new THREE.Path();
  17739. }
  17740. }
  17741. lastPath[ action ].apply( lastPath, args );
  17742. }
  17743. if ( lastPath.actions.length != 0 ) {
  17744. subPaths.push( lastPath );
  17745. }
  17746. // console.log(subPaths);
  17747. if ( subPaths.length == 0 ) return [];
  17748. var solid, tmpPath, tmpShape, shapes = [];
  17749. if ( subPaths.length == 1) {
  17750. tmpPath = subPaths[0];
  17751. tmpShape = new THREE.Shape();
  17752. tmpShape.actions = tmpPath.actions;
  17753. tmpShape.curves = tmpPath.curves;
  17754. shapes.push( tmpShape );
  17755. return shapes;
  17756. }
  17757. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17758. holesFirst = isCCW ? !holesFirst : holesFirst;
  17759. // console.log("Holes first", holesFirst);
  17760. var betterShapeHoles = [];
  17761. var newShapes = [];
  17762. var newShapeHoles = [];
  17763. var mainIdx = 0;
  17764. var tmpPoints;
  17765. newShapes[mainIdx] = undefined;
  17766. newShapeHoles[mainIdx] = [];
  17767. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17768. tmpPath = subPaths[ i ];
  17769. tmpPoints = tmpPath.getPoints();
  17770. solid = THREE.Shape.Utils.isClockWise( tmpPoints );
  17771. solid = isCCW ? !solid : solid;
  17772. if ( solid ) {
  17773. if ( (! holesFirst ) && ( newShapes[mainIdx] ) ) mainIdx++;
  17774. newShapes[mainIdx] = { s: new THREE.Shape(), p: tmpPoints };
  17775. newShapes[mainIdx].s.actions = tmpPath.actions;
  17776. newShapes[mainIdx].s.curves = tmpPath.curves;
  17777. if ( holesFirst ) mainIdx++;
  17778. newShapeHoles[mainIdx] = [];
  17779. //console.log('cw', i);
  17780. } else {
  17781. newShapeHoles[mainIdx].push( { h: tmpPath, p: tmpPoints[0] } );
  17782. //console.log('ccw', i);
  17783. }
  17784. }
  17785. if ( newShapes.length > 1 ) {
  17786. var ambigious = false;
  17787. var toChange = [];
  17788. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) {
  17789. betterShapeHoles[sIdx] = [];
  17790. }
  17791. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) {
  17792. var sh = newShapes[sIdx];
  17793. var sho = newShapeHoles[sIdx];
  17794. for (var hIdx = 0; hIdx < sho.length; hIdx++ ) {
  17795. var ho = sho[hIdx];
  17796. var hole_unassigned = true;
  17797. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++ ) {
  17798. if ( isPointInsidePolygon( ho.p, newShapes[s2Idx].p ) ) {
  17799. if ( sIdx != s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  17800. if ( hole_unassigned ) {
  17801. hole_unassigned = false;
  17802. betterShapeHoles[s2Idx].push( ho );
  17803. } else {
  17804. ambigious = true;
  17805. }
  17806. }
  17807. }
  17808. if ( hole_unassigned ) { betterShapeHoles[sIdx].push( ho ); }
  17809. }
  17810. }
  17811. // console.log("ambigious: ", ambigious);
  17812. if ( toChange.length > 0 ) {
  17813. // console.log("to change: ", toChange);
  17814. if (! ambigious) newShapeHoles = betterShapeHoles;
  17815. }
  17816. }
  17817. var tmpHoles, j, jl;
  17818. for ( i = 0, il = newShapes.length; i < il; i ++ ) {
  17819. tmpShape = newShapes[i].s;
  17820. shapes.push( tmpShape );
  17821. tmpHoles = newShapeHoles[i];
  17822. for ( j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  17823. tmpShape.holes.push( tmpHoles[j].h );
  17824. }
  17825. }
  17826. //console.log("shape", shapes);
  17827. return shapes;
  17828. };
  17829. /**
  17830. * @author zz85 / http://www.lab4games.net/zz85/blog
  17831. * Defines a 2d shape plane using paths.
  17832. **/
  17833. // STEP 1 Create a path.
  17834. // STEP 2 Turn path into shape.
  17835. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17836. // STEP 3a - Extract points from each shape, turn to vertices
  17837. // STEP 3b - Triangulate each shape, add faces.
  17838. THREE.Shape = function () {
  17839. THREE.Path.apply( this, arguments );
  17840. this.holes = [];
  17841. };
  17842. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17843. // Convenience method to return ExtrudeGeometry
  17844. THREE.Shape.prototype.extrude = function ( options ) {
  17845. var extruded = new THREE.ExtrudeGeometry( this, options );
  17846. return extruded;
  17847. };
  17848. // Convenience method to return ShapeGeometry
  17849. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17850. var geometry = new THREE.ShapeGeometry( this, options );
  17851. return geometry;
  17852. };
  17853. // Get points of holes
  17854. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17855. var i, il = this.holes.length, holesPts = [];
  17856. for ( i = 0; i < il; i ++ ) {
  17857. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17858. }
  17859. return holesPts;
  17860. };
  17861. // Get points of holes (spaced by regular distance)
  17862. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17863. var i, il = this.holes.length, holesPts = [];
  17864. for ( i = 0; i < il; i ++ ) {
  17865. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17866. }
  17867. return holesPts;
  17868. };
  17869. // Get points of shape and holes (keypoints based on segments parameter)
  17870. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17871. return {
  17872. shape: this.getTransformedPoints( divisions ),
  17873. holes: this.getPointsHoles( divisions )
  17874. };
  17875. };
  17876. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17877. if (this.useSpacedPoints) {
  17878. return this.extractAllSpacedPoints(divisions);
  17879. }
  17880. return this.extractAllPoints(divisions);
  17881. };
  17882. //
  17883. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17884. //
  17885. // return {
  17886. //
  17887. // shape: this.transform( bend, divisions ),
  17888. // holes: this.getPointsHoles( divisions, bend )
  17889. //
  17890. // };
  17891. //
  17892. // };
  17893. // Get points of shape and holes (spaced by regular distance)
  17894. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17895. return {
  17896. shape: this.getTransformedSpacedPoints( divisions ),
  17897. holes: this.getSpacedPointsHoles( divisions )
  17898. };
  17899. };
  17900. /**************************************************************
  17901. * Utils
  17902. **************************************************************/
  17903. THREE.Shape.Utils = {
  17904. triangulateShape: function ( contour, holes ) {
  17905. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  17906. // inOtherPt needs to be colinear to the inSegment
  17907. if ( inSegPt1.x != inSegPt2.x ) {
  17908. if ( inSegPt1.x < inSegPt2.x ) {
  17909. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  17910. } else {
  17911. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  17912. }
  17913. } else {
  17914. if ( inSegPt1.y < inSegPt2.y ) {
  17915. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  17916. } else {
  17917. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  17918. }
  17919. }
  17920. }
  17921. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  17922. var EPSILON = 0.0000000001;
  17923. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  17924. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  17925. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  17926. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  17927. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  17928. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  17929. if ( Math.abs(limit) > EPSILON ) { // not parallel
  17930. var perpSeg2;
  17931. if ( limit > 0 ) {
  17932. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  17933. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17934. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  17935. } else {
  17936. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  17937. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17938. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  17939. }
  17940. // i.e. to reduce rounding errors
  17941. // intersection at endpoint of segment#1?
  17942. if ( perpSeg2 == 0 ) {
  17943. if ( ( inExcludeAdjacentSegs ) &&
  17944. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17945. return [ inSeg1Pt1 ];
  17946. }
  17947. if ( perpSeg2 == limit ) {
  17948. if ( ( inExcludeAdjacentSegs ) &&
  17949. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17950. return [ inSeg1Pt2 ];
  17951. }
  17952. // intersection at endpoint of segment#2?
  17953. if ( perpSeg1 == 0 ) return [ inSeg2Pt1 ];
  17954. if ( perpSeg1 == limit ) return [ inSeg2Pt2 ];
  17955. // return real intersection point
  17956. var factorSeg1 = perpSeg2 / limit;
  17957. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  17958. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  17959. } else { // parallel or colinear
  17960. if ( ( perpSeg1 != 0 ) ||
  17961. ( seg2dy * seg1seg2dx != seg2dx * seg1seg2dy ) ) return [];
  17962. // they are collinear or degenerate
  17963. var seg1Pt = ( (seg1dx == 0) && (seg1dy == 0) ); // segment1 ist just a point?
  17964. var seg2Pt = ( (seg2dx == 0) && (seg2dy == 0) ); // segment2 ist just a point?
  17965. // both segments are points
  17966. if ( seg1Pt && seg2Pt ) {
  17967. if ( (inSeg1Pt1.x != inSeg2Pt1.x) ||
  17968. (inSeg1Pt1.y != inSeg2Pt1.y) ) return []; // they are distinct points
  17969. return [ inSeg1Pt1 ]; // they are the same point
  17970. }
  17971. // segment#1 is a single point
  17972. if ( seg1Pt ) {
  17973. if (! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  17974. return [ inSeg1Pt1 ];
  17975. }
  17976. // segment#2 is a single point
  17977. if ( seg2Pt ) {
  17978. if (! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  17979. return [ inSeg2Pt1 ];
  17980. }
  17981. // they are collinear segments, which might overlap
  17982. var seg1min, seg1max, seg1minVal, seg1maxVal;
  17983. var seg2min, seg2max, seg2minVal, seg2maxVal;
  17984. if (seg1dx != 0) { // the segments are NOT on a vertical line
  17985. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  17986. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  17987. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  17988. } else {
  17989. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  17990. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  17991. }
  17992. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  17993. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  17994. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  17995. } else {
  17996. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  17997. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  17998. }
  17999. } else { // the segments are on a vertical line
  18000. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  18001. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  18002. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  18003. } else {
  18004. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  18005. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  18006. }
  18007. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  18008. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  18009. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  18010. } else {
  18011. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  18012. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  18013. }
  18014. }
  18015. if ( seg1minVal <= seg2minVal ) {
  18016. if ( seg1maxVal < seg2minVal ) return [];
  18017. if ( seg1maxVal == seg2minVal ) {
  18018. if ( inExcludeAdjacentSegs ) return [];
  18019. return [ seg2min ];
  18020. }
  18021. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  18022. return [ seg2min, seg2max ];
  18023. } else {
  18024. if ( seg1minVal > seg2maxVal ) return [];
  18025. if ( seg1minVal == seg2maxVal ) {
  18026. if ( inExcludeAdjacentSegs ) return [];
  18027. return [ seg1min ];
  18028. }
  18029. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  18030. return [ seg1min, seg2max ];
  18031. }
  18032. }
  18033. }
  18034. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  18035. // The order of legs is important
  18036. var EPSILON = 0.0000000001;
  18037. // translation of all points, so that Vertex is at (0,0)
  18038. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  18039. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  18040. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  18041. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  18042. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  18043. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  18044. if ( Math.abs(from2toAngle) > EPSILON ) { // angle != 180 deg.
  18045. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  18046. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  18047. if ( from2toAngle > 0 ) { // main angle < 180 deg.
  18048. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  18049. } else { // main angle > 180 deg.
  18050. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  18051. }
  18052. } else { // angle == 180 deg.
  18053. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  18054. return ( from2otherAngle > 0 );
  18055. }
  18056. }
  18057. function removeHoles( contour, holes ) {
  18058. var shape = contour.concat(); // work on this shape
  18059. var hole;
  18060. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  18061. // Check if hole point lies within angle around shape point
  18062. var lastShapeIdx = shape.length - 1;
  18063. var prevShapeIdx = inShapeIdx - 1;
  18064. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  18065. var nextShapeIdx = inShapeIdx + 1;
  18066. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  18067. var insideAngle = isPointInsideAngle( shape[inShapeIdx], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[inHoleIdx] );
  18068. if (! insideAngle ) {
  18069. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  18070. return false;
  18071. }
  18072. // Check if shape point lies within angle around hole point
  18073. var lastHoleIdx = hole.length - 1;
  18074. var prevHoleIdx = inHoleIdx - 1;
  18075. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  18076. var nextHoleIdx = inHoleIdx + 1;
  18077. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  18078. insideAngle = isPointInsideAngle( hole[inHoleIdx], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[inShapeIdx] );
  18079. if (! insideAngle ) {
  18080. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  18081. return false;
  18082. }
  18083. return true;
  18084. }
  18085. function intersectsShapeEdge( inShapePt, inHolePt ) {
  18086. // checks for intersections with shape edges
  18087. var sIdx, nextIdx, intersection;
  18088. for ( sIdx = 0; sIdx < shape.length; sIdx++ ) {
  18089. nextIdx = sIdx+1; nextIdx %= shape.length;
  18090. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[sIdx], shape[nextIdx], true );
  18091. if ( intersection.length > 0 ) return true;
  18092. }
  18093. return false;
  18094. }
  18095. var indepHoles = [];
  18096. function intersectsHoleEdge( inShapePt, inHolePt ) {
  18097. // checks for intersections with hole edges
  18098. var ihIdx, chkHole,
  18099. hIdx, nextIdx, intersection;
  18100. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx++ ) {
  18101. chkHole = holes[indepHoles[ihIdx]];
  18102. for ( hIdx = 0; hIdx < chkHole.length; hIdx++ ) {
  18103. nextIdx = hIdx+1; nextIdx %= chkHole.length;
  18104. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[hIdx], chkHole[nextIdx], true );
  18105. if ( intersection.length > 0 ) return true;
  18106. }
  18107. }
  18108. return false;
  18109. }
  18110. var holeIndex, shapeIndex,
  18111. shapePt, holePt,
  18112. holeIdx, cutKey, failedCuts = [],
  18113. tmpShape1, tmpShape2,
  18114. tmpHole1, tmpHole2;
  18115. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  18116. indepHoles.push( h );
  18117. }
  18118. var counter = indepHoles.length * 2;
  18119. while ( indepHoles.length > 0 ) {
  18120. counter --;
  18121. if ( counter < 0 ) {
  18122. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  18123. break;
  18124. }
  18125. // search for shape-vertex and hole-vertex,
  18126. // which can be connected without intersections
  18127. for ( shapeIndex = 0; shapeIndex < shape.length; shapeIndex++ ) {
  18128. shapePt = shape[ shapeIndex ];
  18129. holeIndex = -1;
  18130. // search for hole which can be reached without intersections
  18131. for ( var h = 0; h < indepHoles.length; h ++ ) {
  18132. holeIdx = indepHoles[h];
  18133. // prevent multiple checks
  18134. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  18135. if ( failedCuts[cutKey] !== undefined ) continue;
  18136. hole = holes[holeIdx];
  18137. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  18138. holePt = hole[ h2 ];
  18139. if (! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  18140. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  18141. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  18142. holeIndex = h2;
  18143. indepHoles.splice(h,1);
  18144. tmpShape1 = shape.slice( 0, shapeIndex+1 );
  18145. tmpShape2 = shape.slice( shapeIndex );
  18146. tmpHole1 = hole.slice( holeIndex );
  18147. tmpHole2 = hole.slice( 0, holeIndex+1 );
  18148. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  18149. // Debug only, to show the selected cuts
  18150. // glob_CutLines.push( [ shapePt, holePt ] );
  18151. break;
  18152. }
  18153. if ( holeIndex >= 0 ) break; // hole-vertex found
  18154. failedCuts[cutKey] = true; // remember failure
  18155. }
  18156. if ( holeIndex >= 0 ) break; // hole-vertex found
  18157. }
  18158. }
  18159. return shape; /* shape with no holes */
  18160. }
  18161. var i, il, f, face,
  18162. key, index,
  18163. allPointsMap = {};
  18164. // 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.
  18165. var allpoints = contour.concat();
  18166. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  18167. Array.prototype.push.apply( allpoints, holes[h] );
  18168. }
  18169. //console.log( "allpoints",allpoints, allpoints.length );
  18170. // prepare all points map
  18171. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  18172. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  18173. if ( allPointsMap[ key ] !== undefined ) {
  18174. console.log( "Duplicate point", key );
  18175. }
  18176. allPointsMap[ key ] = i;
  18177. }
  18178. // remove holes by cutting paths to holes and adding them to the shape
  18179. var shapeWithoutHoles = removeHoles( contour, holes );
  18180. var triangles = THREE.FontUtils.Triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  18181. //console.log( "triangles",triangles, triangles.length );
  18182. // check all face vertices against all points map
  18183. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  18184. face = triangles[ i ];
  18185. for ( f = 0; f < 3; f ++ ) {
  18186. key = face[ f ].x + ":" + face[ f ].y;
  18187. index = allPointsMap[ key ];
  18188. if ( index !== undefined ) {
  18189. face[ f ] = index;
  18190. }
  18191. }
  18192. }
  18193. return triangles.concat();
  18194. },
  18195. isClockWise: function ( pts ) {
  18196. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  18197. },
  18198. // Bezier Curves formulas obtained from
  18199. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  18200. // Quad Bezier Functions
  18201. b2p0: function ( t, p ) {
  18202. var k = 1 - t;
  18203. return k * k * p;
  18204. },
  18205. b2p1: function ( t, p ) {
  18206. return 2 * ( 1 - t ) * t * p;
  18207. },
  18208. b2p2: function ( t, p ) {
  18209. return t * t * p;
  18210. },
  18211. b2: function ( t, p0, p1, p2 ) {
  18212. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  18213. },
  18214. // Cubic Bezier Functions
  18215. b3p0: function ( t, p ) {
  18216. var k = 1 - t;
  18217. return k * k * k * p;
  18218. },
  18219. b3p1: function ( t, p ) {
  18220. var k = 1 - t;
  18221. return 3 * k * k * t * p;
  18222. },
  18223. b3p2: function ( t, p ) {
  18224. var k = 1 - t;
  18225. return 3 * k * t * t * p;
  18226. },
  18227. b3p3: function ( t, p ) {
  18228. return t * t * t * p;
  18229. },
  18230. b3: function ( t, p0, p1, p2, p3 ) {
  18231. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  18232. }
  18233. };
  18234. /**************************************************************
  18235. * Line
  18236. **************************************************************/
  18237. THREE.LineCurve = function ( v1, v2 ) {
  18238. this.v1 = v1;
  18239. this.v2 = v2;
  18240. };
  18241. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  18242. THREE.LineCurve.prototype.getPoint = function ( t ) {
  18243. var point = this.v2.clone().sub(this.v1);
  18244. point.multiplyScalar( t ).add( this.v1 );
  18245. return point;
  18246. };
  18247. // Line curve is linear, so we can overwrite default getPointAt
  18248. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  18249. return this.getPoint( u );
  18250. };
  18251. THREE.LineCurve.prototype.getTangent = function( t ) {
  18252. var tangent = this.v2.clone().sub(this.v1);
  18253. return tangent.normalize();
  18254. };
  18255. /**************************************************************
  18256. * Quadratic Bezier curve
  18257. **************************************************************/
  18258. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  18259. this.v0 = v0;
  18260. this.v1 = v1;
  18261. this.v2 = v2;
  18262. };
  18263. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  18264. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  18265. var tx, ty;
  18266. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  18267. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  18268. return new THREE.Vector2( tx, ty );
  18269. };
  18270. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  18271. var tx, ty;
  18272. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  18273. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  18274. // returns unit vector
  18275. var tangent = new THREE.Vector2( tx, ty );
  18276. tangent.normalize();
  18277. return tangent;
  18278. };
  18279. /**************************************************************
  18280. * Cubic Bezier curve
  18281. **************************************************************/
  18282. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  18283. this.v0 = v0;
  18284. this.v1 = v1;
  18285. this.v2 = v2;
  18286. this.v3 = v3;
  18287. };
  18288. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  18289. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  18290. var tx, ty;
  18291. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18292. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18293. return new THREE.Vector2( tx, ty );
  18294. };
  18295. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  18296. var tx, ty;
  18297. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18298. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18299. var tangent = new THREE.Vector2( tx, ty );
  18300. tangent.normalize();
  18301. return tangent;
  18302. };
  18303. /**************************************************************
  18304. * Spline curve
  18305. **************************************************************/
  18306. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  18307. this.points = (points == undefined) ? [] : points;
  18308. };
  18309. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  18310. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  18311. var v = new THREE.Vector2();
  18312. var c = [];
  18313. var points = this.points, point, intPoint, weight;
  18314. point = ( points.length - 1 ) * t;
  18315. intPoint = Math.floor( point );
  18316. weight = point - intPoint;
  18317. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18318. c[ 1 ] = intPoint;
  18319. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  18320. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  18321. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  18322. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  18323. return v;
  18324. };
  18325. /**************************************************************
  18326. * Ellipse curve
  18327. **************************************************************/
  18328. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) {
  18329. this.aX = aX;
  18330. this.aY = aY;
  18331. this.xRadius = xRadius;
  18332. this.yRadius = yRadius;
  18333. this.aStartAngle = aStartAngle;
  18334. this.aEndAngle = aEndAngle;
  18335. this.aClockwise = aClockwise;
  18336. };
  18337. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  18338. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  18339. var angle;
  18340. var deltaAngle = this.aEndAngle - this.aStartAngle;
  18341. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  18342. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  18343. if ( this.aClockwise === true ) {
  18344. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  18345. } else {
  18346. angle = this.aStartAngle + t * deltaAngle;
  18347. }
  18348. var tx = this.aX + this.xRadius * Math.cos( angle );
  18349. var ty = this.aY + this.yRadius * Math.sin( angle );
  18350. return new THREE.Vector2( tx, ty );
  18351. };
  18352. /**************************************************************
  18353. * Arc curve
  18354. **************************************************************/
  18355. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18356. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18357. };
  18358. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  18359. /**************************************************************
  18360. * Line3D
  18361. **************************************************************/
  18362. THREE.LineCurve3 = THREE.Curve.create(
  18363. function ( v1, v2 ) {
  18364. this.v1 = v1;
  18365. this.v2 = v2;
  18366. },
  18367. function ( t ) {
  18368. var r = new THREE.Vector3();
  18369. r.subVectors( this.v2, this.v1 ); // diff
  18370. r.multiplyScalar( t );
  18371. r.add( this.v1 );
  18372. return r;
  18373. }
  18374. );
  18375. /**************************************************************
  18376. * Quadratic Bezier 3D curve
  18377. **************************************************************/
  18378. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  18379. function ( v0, v1, v2 ) {
  18380. this.v0 = v0;
  18381. this.v1 = v1;
  18382. this.v2 = v2;
  18383. },
  18384. function ( t ) {
  18385. var tx, ty, tz;
  18386. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  18387. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  18388. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  18389. return new THREE.Vector3( tx, ty, tz );
  18390. }
  18391. );
  18392. /**************************************************************
  18393. * Cubic Bezier 3D curve
  18394. **************************************************************/
  18395. THREE.CubicBezierCurve3 = THREE.Curve.create(
  18396. function ( v0, v1, v2, v3 ) {
  18397. this.v0 = v0;
  18398. this.v1 = v1;
  18399. this.v2 = v2;
  18400. this.v3 = v3;
  18401. },
  18402. function ( t ) {
  18403. var tx, ty, tz;
  18404. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18405. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18406. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  18407. return new THREE.Vector3( tx, ty, tz );
  18408. }
  18409. );
  18410. /**************************************************************
  18411. * Spline 3D curve
  18412. **************************************************************/
  18413. THREE.SplineCurve3 = THREE.Curve.create(
  18414. function ( points /* array of Vector3 */) {
  18415. this.points = (points == undefined) ? [] : points;
  18416. },
  18417. function ( t ) {
  18418. var v = new THREE.Vector3();
  18419. var c = [];
  18420. var points = this.points, point, intPoint, weight;
  18421. point = ( points.length - 1 ) * t;
  18422. intPoint = Math.floor( point );
  18423. weight = point - intPoint;
  18424. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18425. c[ 1 ] = intPoint;
  18426. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18427. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18428. var pt0 = points[ c[0] ],
  18429. pt1 = points[ c[1] ],
  18430. pt2 = points[ c[2] ],
  18431. pt3 = points[ c[3] ];
  18432. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  18433. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  18434. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  18435. return v;
  18436. }
  18437. );
  18438. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  18439. // var v = new THREE.Vector3();
  18440. // var c = [];
  18441. // var points = this.points, point, intPoint, weight;
  18442. // point = ( points.length - 1 ) * t;
  18443. // intPoint = Math.floor( point );
  18444. // weight = point - intPoint;
  18445. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18446. // c[ 1 ] = intPoint;
  18447. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18448. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18449. // var pt0 = points[ c[0] ],
  18450. // pt1 = points[ c[1] ],
  18451. // pt2 = points[ c[2] ],
  18452. // pt3 = points[ c[3] ];
  18453. // // t = weight;
  18454. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  18455. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  18456. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  18457. // return v;
  18458. // }
  18459. /**************************************************************
  18460. * Closed Spline 3D curve
  18461. **************************************************************/
  18462. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  18463. function ( points /* array of Vector3 */) {
  18464. this.points = (points == undefined) ? [] : points;
  18465. },
  18466. function ( t ) {
  18467. var v = new THREE.Vector3();
  18468. var c = [];
  18469. var points = this.points, point, intPoint, weight;
  18470. point = ( points.length - 0 ) * t;
  18471. // This needs to be from 0-length +1
  18472. intPoint = Math.floor( point );
  18473. weight = point - intPoint;
  18474. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  18475. c[ 0 ] = ( intPoint - 1 ) % points.length;
  18476. c[ 1 ] = ( intPoint ) % points.length;
  18477. c[ 2 ] = ( intPoint + 1 ) % points.length;
  18478. c[ 3 ] = ( intPoint + 2 ) % points.length;
  18479. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  18480. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  18481. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  18482. return v;
  18483. }
  18484. );
  18485. /**
  18486. * @author mikael emtinger / http://gomo.se/
  18487. */
  18488. THREE.AnimationHandler = (function() {
  18489. var playing = [];
  18490. var library = {};
  18491. var that = {};
  18492. //--- update ---
  18493. that.update = function( deltaTimeMS ) {
  18494. for( var i = 0; i < playing.length; i ++ )
  18495. playing[ i ].update( deltaTimeMS );
  18496. };
  18497. //--- add ---
  18498. that.addToUpdate = function( animation ) {
  18499. if ( playing.indexOf( animation ) === -1 )
  18500. playing.push( animation );
  18501. };
  18502. //--- remove ---
  18503. that.removeFromUpdate = function( animation ) {
  18504. var index = playing.indexOf( animation );
  18505. if( index !== -1 )
  18506. playing.splice( index, 1 );
  18507. };
  18508. //--- add ---
  18509. that.add = function( data ) {
  18510. if ( library[ data.name ] !== undefined )
  18511. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  18512. library[ data.name ] = data;
  18513. initData( data );
  18514. };
  18515. //--- get ---
  18516. that.get = function( name ) {
  18517. if ( typeof name === "string" ) {
  18518. if ( library[ name ] ) {
  18519. return library[ name ];
  18520. } else {
  18521. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  18522. return null;
  18523. }
  18524. } else {
  18525. // todo: add simple tween library
  18526. }
  18527. };
  18528. //--- parse ---
  18529. that.parse = function( root ) {
  18530. // setup hierarchy
  18531. var hierarchy = [];
  18532. if ( root instanceof THREE.SkinnedMesh ) {
  18533. for( var b = 0; b < root.bones.length; b++ ) {
  18534. hierarchy.push( root.bones[ b ] );
  18535. }
  18536. } else {
  18537. parseRecurseHierarchy( root, hierarchy );
  18538. }
  18539. return hierarchy;
  18540. };
  18541. var parseRecurseHierarchy = function( root, hierarchy ) {
  18542. hierarchy.push( root );
  18543. for( var c = 0; c < root.children.length; c++ )
  18544. parseRecurseHierarchy( root.children[ c ], hierarchy );
  18545. }
  18546. //--- init data ---
  18547. var initData = function( data ) {
  18548. if( data.initialized === true )
  18549. return;
  18550. // loop through all keys
  18551. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  18552. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18553. // remove minus times
  18554. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  18555. data.hierarchy[ h ].keys[ k ].time = 0;
  18556. // create quaternions
  18557. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  18558. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  18559. var quat = data.hierarchy[ h ].keys[ k ].rot;
  18560. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  18561. }
  18562. }
  18563. // prepare morph target keys
  18564. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  18565. // get all used
  18566. var usedMorphTargets = {};
  18567. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18568. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18569. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  18570. usedMorphTargets[ morphTargetName ] = -1;
  18571. }
  18572. }
  18573. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  18574. // set all used on all frames
  18575. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18576. var influences = {};
  18577. for ( var morphTargetName in usedMorphTargets ) {
  18578. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18579. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  18580. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  18581. break;
  18582. }
  18583. }
  18584. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  18585. influences[ morphTargetName ] = 0;
  18586. }
  18587. }
  18588. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  18589. }
  18590. }
  18591. // remove all keys that are on the same time
  18592. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18593. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  18594. data.hierarchy[ h ].keys.splice( k, 1 );
  18595. k --;
  18596. }
  18597. }
  18598. // set index
  18599. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18600. data.hierarchy[ h ].keys[ k ].index = k;
  18601. }
  18602. }
  18603. // done
  18604. data.initialized = true;
  18605. };
  18606. // interpolation types
  18607. that.LINEAR = 0;
  18608. that.CATMULLROM = 1;
  18609. that.CATMULLROM_FORWARD = 2;
  18610. return that;
  18611. }());
  18612. /**
  18613. * @author mikael emtinger / http://gomo.se/
  18614. * @author mrdoob / http://mrdoob.com/
  18615. * @author alteredq / http://alteredqualia.com/
  18616. */
  18617. THREE.Animation = function ( root, name ) {
  18618. this.root = root;
  18619. this.data = THREE.AnimationHandler.get( name );
  18620. this.hierarchy = THREE.AnimationHandler.parse( root );
  18621. this.currentTime = 0;
  18622. this.timeScale = 1;
  18623. this.isPlaying = false;
  18624. this.isPaused = true;
  18625. this.loop = true;
  18626. this.interpolationType = THREE.AnimationHandler.LINEAR;
  18627. this.points = [];
  18628. this.target = new THREE.Vector3();
  18629. };
  18630. THREE.Animation.prototype.play = function ( startTime ) {
  18631. this.currentTime = startTime !== undefined ? startTime : 0;
  18632. if ( this.isPlaying === false ) {
  18633. this.isPlaying = true;
  18634. this.reset();
  18635. this.update( 0 );
  18636. }
  18637. this.isPaused = false;
  18638. THREE.AnimationHandler.addToUpdate( this );
  18639. };
  18640. THREE.Animation.prototype.pause = function() {
  18641. if ( this.isPaused === true ) {
  18642. THREE.AnimationHandler.addToUpdate( this );
  18643. } else {
  18644. THREE.AnimationHandler.removeFromUpdate( this );
  18645. }
  18646. this.isPaused = !this.isPaused;
  18647. };
  18648. THREE.Animation.prototype.stop = function() {
  18649. this.isPlaying = false;
  18650. this.isPaused = false;
  18651. THREE.AnimationHandler.removeFromUpdate( this );
  18652. };
  18653. THREE.Animation.prototype.reset = function () {
  18654. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18655. var object = this.hierarchy[ h ];
  18656. object.matrixAutoUpdate = true;
  18657. if ( object.animationCache === undefined ) {
  18658. object.animationCache = {};
  18659. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  18660. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  18661. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18662. }
  18663. var prevKey = object.animationCache.prevKey;
  18664. var nextKey = object.animationCache.nextKey;
  18665. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  18666. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  18667. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  18668. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  18669. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  18670. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  18671. }
  18672. };
  18673. THREE.Animation.prototype.update = function ( delta ) {
  18674. if ( this.isPlaying === false ) return;
  18675. this.currentTime += delta * this.timeScale;
  18676. //
  18677. var vector;
  18678. var types = [ "pos", "rot", "scl" ];
  18679. var duration = this.data.length;
  18680. if ( this.loop === true && this.currentTime > duration ) {
  18681. this.currentTime %= duration;
  18682. this.reset();
  18683. }
  18684. this.currentTime = Math.min( this.currentTime, duration );
  18685. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18686. var object = this.hierarchy[ h ];
  18687. var animationCache = object.animationCache;
  18688. // loop through pos/rot/scl
  18689. for ( var t = 0; t < 3; t ++ ) {
  18690. // get keys
  18691. var type = types[ t ];
  18692. var prevKey = animationCache.prevKey[ type ];
  18693. var nextKey = animationCache.nextKey[ type ];
  18694. if ( nextKey.time <= this.currentTime ) {
  18695. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18696. nextKey = this.getNextKeyWith( type, h, 1 );
  18697. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18698. prevKey = nextKey;
  18699. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18700. }
  18701. animationCache.prevKey[ type ] = prevKey;
  18702. animationCache.nextKey[ type ] = nextKey;
  18703. }
  18704. object.matrixAutoUpdate = true;
  18705. object.matrixWorldNeedsUpdate = true;
  18706. var scale = ( this.currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18707. var prevXYZ = prevKey[ type ];
  18708. var nextXYZ = nextKey[ type ];
  18709. if ( scale < 0 ) scale = 0;
  18710. if ( scale > 1 ) scale = 1;
  18711. // interpolate
  18712. if ( type === "pos" ) {
  18713. vector = object.position;
  18714. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18715. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18716. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18717. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18718. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18719. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18720. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18721. this.points[ 1 ] = prevXYZ;
  18722. this.points[ 2 ] = nextXYZ;
  18723. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18724. scale = scale * 0.33 + 0.33;
  18725. var currentPoint = this.interpolateCatmullRom( this.points, scale );
  18726. vector.x = currentPoint[ 0 ];
  18727. vector.y = currentPoint[ 1 ];
  18728. vector.z = currentPoint[ 2 ];
  18729. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18730. var forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  18731. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18732. this.target.sub( vector );
  18733. this.target.y = 0;
  18734. this.target.normalize();
  18735. var angle = Math.atan2( this.target.x, this.target.z );
  18736. object.rotation.set( 0, angle, 0 );
  18737. }
  18738. }
  18739. } else if ( type === "rot" ) {
  18740. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  18741. } else if ( type === "scl" ) {
  18742. vector = object.scale;
  18743. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18744. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18745. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18746. }
  18747. }
  18748. }
  18749. if ( this.loop === false && this.currentTime > duration ) {
  18750. this.stop();
  18751. }
  18752. };
  18753. // Catmull-Rom spline
  18754. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  18755. var c = [], v3 = [],
  18756. point, intPoint, weight, w2, w3,
  18757. pa, pb, pc, pd;
  18758. point = ( points.length - 1 ) * scale;
  18759. intPoint = Math.floor( point );
  18760. weight = point - intPoint;
  18761. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18762. c[ 1 ] = intPoint;
  18763. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18764. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18765. pa = points[ c[ 0 ] ];
  18766. pb = points[ c[ 1 ] ];
  18767. pc = points[ c[ 2 ] ];
  18768. pd = points[ c[ 3 ] ];
  18769. w2 = weight * weight;
  18770. w3 = weight * w2;
  18771. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18772. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18773. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18774. return v3;
  18775. };
  18776. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18777. var v0 = ( p2 - p0 ) * 0.5,
  18778. v1 = ( p3 - p1 ) * 0.5;
  18779. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18780. };
  18781. // Get next key with
  18782. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18783. var keys = this.data.hierarchy[ h ].keys;
  18784. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18785. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18786. key = key < keys.length - 1 ? key : keys.length - 1;
  18787. } else {
  18788. key = key % keys.length;
  18789. }
  18790. for ( ; key < keys.length; key++ ) {
  18791. if ( keys[ key ][ type ] !== undefined ) {
  18792. return keys[ key ];
  18793. }
  18794. }
  18795. return this.data.hierarchy[ h ].keys[ 0 ];
  18796. };
  18797. // Get previous key with
  18798. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18799. var keys = this.data.hierarchy[ h ].keys;
  18800. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18801. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18802. key = key > 0 ? key : 0;
  18803. } else {
  18804. key = key >= 0 ? key : key + keys.length;
  18805. }
  18806. for ( ; key >= 0; key -- ) {
  18807. if ( keys[ key ][ type ] !== undefined ) {
  18808. return keys[ key ];
  18809. }
  18810. }
  18811. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18812. };
  18813. /**
  18814. * @author mikael emtinger / http://gomo.se/
  18815. * @author mrdoob / http://mrdoob.com/
  18816. * @author alteredq / http://alteredqualia.com/
  18817. * @author khang duong
  18818. * @author erik kitson
  18819. */
  18820. THREE.KeyFrameAnimation = function ( root, data ) {
  18821. this.root = root;
  18822. this.data = THREE.AnimationHandler.get( data );
  18823. this.hierarchy = THREE.AnimationHandler.parse( root );
  18824. this.currentTime = 0;
  18825. this.timeScale = 0.001;
  18826. this.isPlaying = false;
  18827. this.isPaused = true;
  18828. this.loop = true;
  18829. // initialize to first keyframes
  18830. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18831. var keys = this.data.hierarchy[h].keys,
  18832. sids = this.data.hierarchy[h].sids,
  18833. obj = this.hierarchy[h];
  18834. if ( keys.length && sids ) {
  18835. for ( var s = 0; s < sids.length; s++ ) {
  18836. var sid = sids[ s ],
  18837. next = this.getNextKeyWith( sid, h, 0 );
  18838. if ( next ) {
  18839. next.apply( sid );
  18840. }
  18841. }
  18842. obj.matrixAutoUpdate = false;
  18843. this.data.hierarchy[h].node.updateMatrix();
  18844. obj.matrixWorldNeedsUpdate = true;
  18845. }
  18846. }
  18847. };
  18848. // Play
  18849. THREE.KeyFrameAnimation.prototype.play = function ( startTime ) {
  18850. this.currentTime = startTime !== undefined ? startTime : 0;
  18851. if ( this.isPlaying === false ) {
  18852. this.isPlaying = true;
  18853. // reset key cache
  18854. var h, hl = this.hierarchy.length,
  18855. object,
  18856. node;
  18857. for ( h = 0; h < hl; h++ ) {
  18858. object = this.hierarchy[ h ];
  18859. node = this.data.hierarchy[ h ];
  18860. if ( node.animationCache === undefined ) {
  18861. node.animationCache = {};
  18862. node.animationCache.prevKey = null;
  18863. node.animationCache.nextKey = null;
  18864. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18865. }
  18866. var keys = this.data.hierarchy[h].keys;
  18867. if (keys.length) {
  18868. node.animationCache.prevKey = keys[ 0 ];
  18869. node.animationCache.nextKey = keys[ 1 ];
  18870. this.startTime = Math.min( keys[0].time, this.startTime );
  18871. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18872. }
  18873. }
  18874. this.update( 0 );
  18875. }
  18876. this.isPaused = false;
  18877. THREE.AnimationHandler.addToUpdate( this );
  18878. };
  18879. // Pause
  18880. THREE.KeyFrameAnimation.prototype.pause = function() {
  18881. if( this.isPaused ) {
  18882. THREE.AnimationHandler.addToUpdate( this );
  18883. } else {
  18884. THREE.AnimationHandler.removeFromUpdate( this );
  18885. }
  18886. this.isPaused = !this.isPaused;
  18887. };
  18888. // Stop
  18889. THREE.KeyFrameAnimation.prototype.stop = function() {
  18890. this.isPlaying = false;
  18891. this.isPaused = false;
  18892. THREE.AnimationHandler.removeFromUpdate( this );
  18893. // reset JIT matrix and remove cache
  18894. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18895. var obj = this.hierarchy[ h ];
  18896. var node = this.data.hierarchy[ h ];
  18897. if ( node.animationCache !== undefined ) {
  18898. var original = node.animationCache.originalMatrix;
  18899. if( obj instanceof THREE.Bone ) {
  18900. original.copy( obj.skinMatrix );
  18901. obj.skinMatrix = original;
  18902. } else {
  18903. original.copy( obj.matrix );
  18904. obj.matrix = original;
  18905. }
  18906. delete node.animationCache;
  18907. }
  18908. }
  18909. };
  18910. // Update
  18911. THREE.KeyFrameAnimation.prototype.update = function ( delta ) {
  18912. if ( this.isPlaying === false ) return;
  18913. this.currentTime += delta * this.timeScale;
  18914. //
  18915. var duration = this.data.length;
  18916. if ( this.loop === true && this.currentTime > duration ) {
  18917. this.currentTime %= duration;
  18918. }
  18919. this.currentTime = Math.min( this.currentTime, duration );
  18920. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18921. var object = this.hierarchy[ h ];
  18922. var node = this.data.hierarchy[ h ];
  18923. var keys = node.keys,
  18924. animationCache = node.animationCache;
  18925. if ( keys.length ) {
  18926. var prevKey = animationCache.prevKey;
  18927. var nextKey = animationCache.nextKey;
  18928. if ( nextKey.time <= this.currentTime ) {
  18929. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18930. prevKey = nextKey;
  18931. nextKey = keys[ prevKey.index + 1 ];
  18932. }
  18933. animationCache.prevKey = prevKey;
  18934. animationCache.nextKey = nextKey;
  18935. }
  18936. if ( nextKey.time >= this.currentTime ) {
  18937. prevKey.interpolate( nextKey, this.currentTime );
  18938. } else {
  18939. prevKey.interpolate( nextKey, nextKey.time );
  18940. }
  18941. this.data.hierarchy[ h ].node.updateMatrix();
  18942. object.matrixWorldNeedsUpdate = true;
  18943. }
  18944. }
  18945. };
  18946. // Get next key with
  18947. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18948. var keys = this.data.hierarchy[ h ].keys;
  18949. key = key % keys.length;
  18950. for ( ; key < keys.length; key++ ) {
  18951. if ( keys[ key ].hasTarget( sid ) ) {
  18952. return keys[ key ];
  18953. }
  18954. }
  18955. return keys[ 0 ];
  18956. };
  18957. // Get previous key with
  18958. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18959. var keys = this.data.hierarchy[ h ].keys;
  18960. key = key >= 0 ? key : key + keys.length;
  18961. for ( ; key >= 0; key-- ) {
  18962. if ( keys[ key ].hasTarget( sid ) ) {
  18963. return keys[ key ];
  18964. }
  18965. }
  18966. return keys[ keys.length - 1 ];
  18967. };
  18968. /**
  18969. * @author mrdoob / http://mrdoob.com
  18970. */
  18971. THREE.MorphAnimation = function ( mesh ) {
  18972. this.mesh = mesh;
  18973. this.frames = mesh.morphTargetInfluences.length;
  18974. this.currentTime = 0;
  18975. this.duration = 1000;
  18976. this.loop = true;
  18977. this.isPlaying = false;
  18978. };
  18979. THREE.MorphAnimation.prototype = {
  18980. play: function () {
  18981. this.isPlaying = true;
  18982. },
  18983. pause: function () {
  18984. this.isPlaying = false;
  18985. },
  18986. update: ( function () {
  18987. var lastFrame = 0;
  18988. var currentFrame = 0;
  18989. return function ( delta ) {
  18990. if ( this.isPlaying === false ) return;
  18991. this.currentTime += delta;
  18992. if ( this.loop === true && this.currentTime > this.duration ) {
  18993. this.currentTime %= this.duration;
  18994. }
  18995. this.currentTime = Math.min( this.currentTime, this.duration );
  18996. var interpolation = this.duration / this.frames;
  18997. var frame = Math.floor( this.currentTime / interpolation );
  18998. if ( frame != currentFrame ) {
  18999. this.mesh.morphTargetInfluences[ lastFrame ] = 0;
  19000. this.mesh.morphTargetInfluences[ currentFrame ] = 1;
  19001. this.mesh.morphTargetInfluences[ frame ] = 0;
  19002. lastFrame = currentFrame;
  19003. currentFrame = frame;
  19004. }
  19005. this.mesh.morphTargetInfluences[ frame ] = ( this.currentTime % interpolation ) / interpolation;
  19006. this.mesh.morphTargetInfluences[ lastFrame ] = 1 - this.mesh.morphTargetInfluences[ frame ];
  19007. }
  19008. } )()
  19009. };
  19010. /**
  19011. * Camera for rendering cube maps
  19012. * - renders scene into axis-aligned cube
  19013. *
  19014. * @author alteredq / http://alteredqualia.com/
  19015. */
  19016. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  19017. THREE.Object3D.call( this );
  19018. var fov = 90, aspect = 1;
  19019. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19020. cameraPX.up.set( 0, -1, 0 );
  19021. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  19022. this.add( cameraPX );
  19023. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19024. cameraNX.up.set( 0, -1, 0 );
  19025. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  19026. this.add( cameraNX );
  19027. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19028. cameraPY.up.set( 0, 0, 1 );
  19029. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  19030. this.add( cameraPY );
  19031. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19032. cameraNY.up.set( 0, 0, -1 );
  19033. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  19034. this.add( cameraNY );
  19035. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19036. cameraPZ.up.set( 0, -1, 0 );
  19037. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  19038. this.add( cameraPZ );
  19039. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19040. cameraNZ.up.set( 0, -1, 0 );
  19041. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  19042. this.add( cameraNZ );
  19043. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  19044. this.updateCubeMap = function ( renderer, scene ) {
  19045. var renderTarget = this.renderTarget;
  19046. var generateMipmaps = renderTarget.generateMipmaps;
  19047. renderTarget.generateMipmaps = false;
  19048. renderTarget.activeCubeFace = 0;
  19049. renderer.render( scene, cameraPX, renderTarget );
  19050. renderTarget.activeCubeFace = 1;
  19051. renderer.render( scene, cameraNX, renderTarget );
  19052. renderTarget.activeCubeFace = 2;
  19053. renderer.render( scene, cameraPY, renderTarget );
  19054. renderTarget.activeCubeFace = 3;
  19055. renderer.render( scene, cameraNY, renderTarget );
  19056. renderTarget.activeCubeFace = 4;
  19057. renderer.render( scene, cameraPZ, renderTarget );
  19058. renderTarget.generateMipmaps = generateMipmaps;
  19059. renderTarget.activeCubeFace = 5;
  19060. renderer.render( scene, cameraNZ, renderTarget );
  19061. };
  19062. };
  19063. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  19064. /**
  19065. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  19066. *
  19067. * A general perpose camera, for setting FOV, Lens Focal Length,
  19068. * and switching between perspective and orthographic views easily.
  19069. * Use this only if you do not wish to manage
  19070. * both a Orthographic and Perspective Camera
  19071. *
  19072. */
  19073. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  19074. THREE.Camera.call( this );
  19075. this.fov = fov;
  19076. this.left = -width / 2;
  19077. this.right = width / 2
  19078. this.top = height / 2;
  19079. this.bottom = -height / 2;
  19080. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  19081. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  19082. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  19083. this.zoom = 1;
  19084. this.toPerspective();
  19085. var aspect = width/height;
  19086. };
  19087. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  19088. THREE.CombinedCamera.prototype.toPerspective = function () {
  19089. // Switches to the Perspective Camera
  19090. this.near = this.cameraP.near;
  19091. this.far = this.cameraP.far;
  19092. this.cameraP.fov = this.fov / this.zoom ;
  19093. this.cameraP.updateProjectionMatrix();
  19094. this.projectionMatrix = this.cameraP.projectionMatrix;
  19095. this.inPerspectiveMode = true;
  19096. this.inOrthographicMode = false;
  19097. };
  19098. THREE.CombinedCamera.prototype.toOrthographic = function () {
  19099. // Switches to the Orthographic camera estimating viewport from Perspective
  19100. var fov = this.fov;
  19101. var aspect = this.cameraP.aspect;
  19102. var near = this.cameraP.near;
  19103. var far = this.cameraP.far;
  19104. // The size that we set is the mid plane of the viewing frustum
  19105. var hyperfocus = ( near + far ) / 2;
  19106. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  19107. var planeHeight = 2 * halfHeight;
  19108. var planeWidth = planeHeight * aspect;
  19109. var halfWidth = planeWidth / 2;
  19110. halfHeight /= this.zoom;
  19111. halfWidth /= this.zoom;
  19112. this.cameraO.left = -halfWidth;
  19113. this.cameraO.right = halfWidth;
  19114. this.cameraO.top = halfHeight;
  19115. this.cameraO.bottom = -halfHeight;
  19116. // this.cameraO.left = -farHalfWidth;
  19117. // this.cameraO.right = farHalfWidth;
  19118. // this.cameraO.top = farHalfHeight;
  19119. // this.cameraO.bottom = -farHalfHeight;
  19120. // this.cameraO.left = this.left / this.zoom;
  19121. // this.cameraO.right = this.right / this.zoom;
  19122. // this.cameraO.top = this.top / this.zoom;
  19123. // this.cameraO.bottom = this.bottom / this.zoom;
  19124. this.cameraO.updateProjectionMatrix();
  19125. this.near = this.cameraO.near;
  19126. this.far = this.cameraO.far;
  19127. this.projectionMatrix = this.cameraO.projectionMatrix;
  19128. this.inPerspectiveMode = false;
  19129. this.inOrthographicMode = true;
  19130. };
  19131. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  19132. this.cameraP.aspect = width / height;
  19133. this.left = -width / 2;
  19134. this.right = width / 2
  19135. this.top = height / 2;
  19136. this.bottom = -height / 2;
  19137. };
  19138. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  19139. this.fov = fov;
  19140. if ( this.inPerspectiveMode ) {
  19141. this.toPerspective();
  19142. } else {
  19143. this.toOrthographic();
  19144. }
  19145. };
  19146. // For mantaining similar API with PerspectiveCamera
  19147. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  19148. if ( this.inPerspectiveMode ) {
  19149. this.toPerspective();
  19150. } else {
  19151. this.toPerspective();
  19152. this.toOrthographic();
  19153. }
  19154. };
  19155. /*
  19156. * Uses Focal Length (in mm) to estimate and set FOV
  19157. * 35mm (fullframe) camera is used if frame size is not specified;
  19158. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  19159. */
  19160. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  19161. if ( frameHeight === undefined ) frameHeight = 24;
  19162. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  19163. this.setFov( fov );
  19164. return fov;
  19165. };
  19166. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  19167. this.zoom = zoom;
  19168. if ( this.inPerspectiveMode ) {
  19169. this.toPerspective();
  19170. } else {
  19171. this.toOrthographic();
  19172. }
  19173. };
  19174. THREE.CombinedCamera.prototype.toFrontView = function() {
  19175. this.rotation.x = 0;
  19176. this.rotation.y = 0;
  19177. this.rotation.z = 0;
  19178. // should we be modifing the matrix instead?
  19179. this.rotationAutoUpdate = false;
  19180. };
  19181. THREE.CombinedCamera.prototype.toBackView = function() {
  19182. this.rotation.x = 0;
  19183. this.rotation.y = Math.PI;
  19184. this.rotation.z = 0;
  19185. this.rotationAutoUpdate = false;
  19186. };
  19187. THREE.CombinedCamera.prototype.toLeftView = function() {
  19188. this.rotation.x = 0;
  19189. this.rotation.y = - Math.PI / 2;
  19190. this.rotation.z = 0;
  19191. this.rotationAutoUpdate = false;
  19192. };
  19193. THREE.CombinedCamera.prototype.toRightView = function() {
  19194. this.rotation.x = 0;
  19195. this.rotation.y = Math.PI / 2;
  19196. this.rotation.z = 0;
  19197. this.rotationAutoUpdate = false;
  19198. };
  19199. THREE.CombinedCamera.prototype.toTopView = function() {
  19200. this.rotation.x = - Math.PI / 2;
  19201. this.rotation.y = 0;
  19202. this.rotation.z = 0;
  19203. this.rotationAutoUpdate = false;
  19204. };
  19205. THREE.CombinedCamera.prototype.toBottomView = function() {
  19206. this.rotation.x = Math.PI / 2;
  19207. this.rotation.y = 0;
  19208. this.rotation.z = 0;
  19209. this.rotationAutoUpdate = false;
  19210. };
  19211. /**
  19212. * @author mrdoob / http://mrdoob.com/
  19213. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  19214. */
  19215. THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  19216. THREE.Geometry.call( this );
  19217. var scope = this;
  19218. this.width = width;
  19219. this.height = height;
  19220. this.depth = depth;
  19221. this.widthSegments = widthSegments || 1;
  19222. this.heightSegments = heightSegments || 1;
  19223. this.depthSegments = depthSegments || 1;
  19224. var width_half = this.width / 2;
  19225. var height_half = this.height / 2;
  19226. var depth_half = this.depth / 2;
  19227. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  19228. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  19229. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  19230. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  19231. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  19232. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  19233. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  19234. var w, ix, iy,
  19235. gridX = scope.widthSegments,
  19236. gridY = scope.heightSegments,
  19237. width_half = width / 2,
  19238. height_half = height / 2,
  19239. offset = scope.vertices.length;
  19240. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  19241. w = 'z';
  19242. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  19243. w = 'y';
  19244. gridY = scope.depthSegments;
  19245. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  19246. w = 'x';
  19247. gridX = scope.depthSegments;
  19248. }
  19249. var gridX1 = gridX + 1,
  19250. gridY1 = gridY + 1,
  19251. segment_width = width / gridX,
  19252. segment_height = height / gridY,
  19253. normal = new THREE.Vector3();
  19254. normal[ w ] = depth > 0 ? 1 : - 1;
  19255. for ( iy = 0; iy < gridY1; iy ++ ) {
  19256. for ( ix = 0; ix < gridX1; ix ++ ) {
  19257. var vector = new THREE.Vector3();
  19258. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  19259. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  19260. vector[ w ] = depth;
  19261. scope.vertices.push( vector );
  19262. }
  19263. }
  19264. for ( iy = 0; iy < gridY; iy++ ) {
  19265. for ( ix = 0; ix < gridX; ix++ ) {
  19266. var a = ix + gridX1 * iy;
  19267. var b = ix + gridX1 * ( iy + 1 );
  19268. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  19269. var d = ( ix + 1 ) + gridX1 * iy;
  19270. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  19271. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  19272. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  19273. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  19274. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  19275. face.normal.copy( normal );
  19276. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19277. face.materialIndex = materialIndex;
  19278. scope.faces.push( face );
  19279. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19280. face = new THREE.Face3( b + offset, c + offset, d + offset );
  19281. face.normal.copy( normal );
  19282. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19283. face.materialIndex = materialIndex;
  19284. scope.faces.push( face );
  19285. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19286. }
  19287. }
  19288. }
  19289. this.computeCentroids();
  19290. this.mergeVertices();
  19291. };
  19292. THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19293. /**
  19294. * @author hughes
  19295. */
  19296. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  19297. THREE.Geometry.call( this );
  19298. this.radius = radius = radius || 50;
  19299. this.segments = segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  19300. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19301. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19302. var i, uvs = [],
  19303. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  19304. this.vertices.push(center);
  19305. uvs.push( centerUV );
  19306. for ( i = 0; i <= segments; i ++ ) {
  19307. var vertex = new THREE.Vector3();
  19308. var segment = thetaStart + i / segments * thetaLength;
  19309. vertex.x = radius * Math.cos( segment );
  19310. vertex.y = radius * Math.sin( segment );
  19311. this.vertices.push( vertex );
  19312. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  19313. }
  19314. var n = new THREE.Vector3( 0, 0, 1 );
  19315. for ( i = 1; i <= segments; i ++ ) {
  19316. var v1 = i;
  19317. var v2 = i + 1 ;
  19318. var v3 = 0;
  19319. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19320. this.faceVertexUvs[ 0 ].push( [ uvs[ i ].clone(), uvs[ i + 1 ].clone(), centerUV.clone() ] );
  19321. }
  19322. this.computeCentroids();
  19323. this.computeFaceNormals();
  19324. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19325. };
  19326. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19327. // DEPRECATED
  19328. THREE.CubeGeometry = THREE.BoxGeometry;
  19329. /**
  19330. * @author mrdoob / http://mrdoob.com/
  19331. */
  19332. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
  19333. THREE.Geometry.call( this );
  19334. this.radiusTop = radiusTop = radiusTop !== undefined ? radiusTop : 20;
  19335. this.radiusBottom = radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  19336. this.height = height = height !== undefined ? height : 100;
  19337. this.radialSegments = radialSegments = radialSegments || 8;
  19338. this.heightSegments = heightSegments = heightSegments || 1;
  19339. this.openEnded = openEnded = openEnded !== undefined ? openEnded : false;
  19340. var heightHalf = height / 2;
  19341. var x, y, vertices = [], uvs = [];
  19342. for ( y = 0; y <= heightSegments; y ++ ) {
  19343. var verticesRow = [];
  19344. var uvsRow = [];
  19345. var v = y / heightSegments;
  19346. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  19347. for ( x = 0; x <= radialSegments; x ++ ) {
  19348. var u = x / radialSegments;
  19349. var vertex = new THREE.Vector3();
  19350. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  19351. vertex.y = - v * height + heightHalf;
  19352. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  19353. this.vertices.push( vertex );
  19354. verticesRow.push( this.vertices.length - 1 );
  19355. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19356. }
  19357. vertices.push( verticesRow );
  19358. uvs.push( uvsRow );
  19359. }
  19360. var tanTheta = ( radiusBottom - radiusTop ) / height;
  19361. var na, nb;
  19362. for ( x = 0; x < radialSegments; x ++ ) {
  19363. if ( radiusTop !== 0 ) {
  19364. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  19365. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  19366. } else {
  19367. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  19368. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  19369. }
  19370. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  19371. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  19372. for ( y = 0; y < heightSegments; y ++ ) {
  19373. var v1 = vertices[ y ][ x ];
  19374. var v2 = vertices[ y + 1 ][ x ];
  19375. var v3 = vertices[ y + 1 ][ x + 1 ];
  19376. var v4 = vertices[ y ][ x + 1 ];
  19377. var n1 = na.clone();
  19378. var n2 = na.clone();
  19379. var n3 = nb.clone();
  19380. var n4 = nb.clone();
  19381. var uv1 = uvs[ y ][ x ].clone();
  19382. var uv2 = uvs[ y + 1 ][ x ].clone();
  19383. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  19384. var uv4 = uvs[ y ][ x + 1 ].clone();
  19385. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19386. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19387. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  19388. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  19389. }
  19390. }
  19391. // top cap
  19392. if ( openEnded === false && radiusTop > 0 ) {
  19393. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  19394. for ( x = 0; x < radialSegments; x ++ ) {
  19395. var v1 = vertices[ 0 ][ x ];
  19396. var v2 = vertices[ 0 ][ x + 1 ];
  19397. var v3 = this.vertices.length - 1;
  19398. var n1 = new THREE.Vector3( 0, 1, 0 );
  19399. var n2 = new THREE.Vector3( 0, 1, 0 );
  19400. var n3 = new THREE.Vector3( 0, 1, 0 );
  19401. var uv1 = uvs[ 0 ][ x ].clone();
  19402. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  19403. var uv3 = new THREE.Vector2( uv2.x, 0 );
  19404. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19405. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19406. }
  19407. }
  19408. // bottom cap
  19409. if ( openEnded === false && radiusBottom > 0 ) {
  19410. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  19411. for ( x = 0; x < radialSegments; x ++ ) {
  19412. var v1 = vertices[ y ][ x + 1 ];
  19413. var v2 = vertices[ y ][ x ];
  19414. var v3 = this.vertices.length - 1;
  19415. var n1 = new THREE.Vector3( 0, - 1, 0 );
  19416. var n2 = new THREE.Vector3( 0, - 1, 0 );
  19417. var n3 = new THREE.Vector3( 0, - 1, 0 );
  19418. var uv1 = uvs[ y ][ x + 1 ].clone();
  19419. var uv2 = uvs[ y ][ x ].clone();
  19420. var uv3 = new THREE.Vector2( uv2.x, 1 );
  19421. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19422. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19423. }
  19424. }
  19425. this.computeCentroids();
  19426. this.computeFaceNormals();
  19427. }
  19428. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19429. /**
  19430. * @author zz85 / http://www.lab4games.net/zz85/blog
  19431. *
  19432. * Creates extruded geometry from a path shape.
  19433. *
  19434. * parameters = {
  19435. *
  19436. * curveSegments: <int>, // number of points on the curves
  19437. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  19438. * amount: <int>, // Depth to extrude the shape
  19439. *
  19440. * bevelEnabled: <bool>, // turn on bevel
  19441. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19442. * bevelSize: <float>, // how far from shape outline is bevel
  19443. * bevelSegments: <int>, // number of bevel layers
  19444. *
  19445. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  19446. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  19447. *
  19448. * material: <int> // material index for front and back faces
  19449. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  19450. * uvGenerator: <Object> // object that provides UV generator functions
  19451. *
  19452. * }
  19453. **/
  19454. THREE.ExtrudeGeometry = function ( shapes, options ) {
  19455. if ( typeof( shapes ) === "undefined" ) {
  19456. shapes = [];
  19457. return;
  19458. }
  19459. THREE.Geometry.call( this );
  19460. shapes = shapes instanceof Array ? shapes : [ shapes ];
  19461. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19462. this.addShapeList( shapes, options );
  19463. this.computeCentroids();
  19464. this.computeFaceNormals();
  19465. // can't really use automatic vertex normals
  19466. // as then front and back sides get smoothed too
  19467. // should do separate smoothing just for sides
  19468. //this.computeVertexNormals();
  19469. //console.log( "took", ( Date.now() - startTime ) );
  19470. };
  19471. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19472. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19473. var sl = shapes.length;
  19474. for ( var s = 0; s < sl; s ++ ) {
  19475. var shape = shapes[ s ];
  19476. this.addShape( shape, options );
  19477. }
  19478. };
  19479. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  19480. var amount = options.amount !== undefined ? options.amount : 100;
  19481. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  19482. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  19483. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19484. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  19485. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19486. var steps = options.steps !== undefined ? options.steps : 1;
  19487. var extrudePath = options.extrudePath;
  19488. var extrudePts, extrudeByPath = false;
  19489. var material = options.material;
  19490. var extrudeMaterial = options.extrudeMaterial;
  19491. // Use default WorldUVGenerator if no UV generators are specified.
  19492. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  19493. var shapebb = this.shapebb;
  19494. //shapebb = shape.getBoundingBox();
  19495. var splineTube, binormal, normal, position2;
  19496. if ( extrudePath ) {
  19497. extrudePts = extrudePath.getSpacedPoints( steps );
  19498. extrudeByPath = true;
  19499. bevelEnabled = false; // bevels not supported for path extrusion
  19500. // SETUP TNB variables
  19501. // Reuse TNB from TubeGeomtry for now.
  19502. // TODO1 - have a .isClosed in spline?
  19503. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  19504. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19505. binormal = new THREE.Vector3();
  19506. normal = new THREE.Vector3();
  19507. position2 = new THREE.Vector3();
  19508. }
  19509. // Safeguards if bevels are not enabled
  19510. if ( ! bevelEnabled ) {
  19511. bevelSegments = 0;
  19512. bevelThickness = 0;
  19513. bevelSize = 0;
  19514. }
  19515. // Variables initalization
  19516. var ahole, h, hl; // looping of holes
  19517. var scope = this;
  19518. var bevelPoints = [];
  19519. var shapesOffset = this.vertices.length;
  19520. var shapePoints = shape.extractPoints( curveSegments );
  19521. var vertices = shapePoints.shape;
  19522. var holes = shapePoints.holes;
  19523. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  19524. if ( reverse ) {
  19525. vertices = vertices.reverse();
  19526. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19527. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19528. ahole = holes[ h ];
  19529. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  19530. holes[ h ] = ahole.reverse();
  19531. }
  19532. }
  19533. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  19534. }
  19535. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  19536. /* Vertices */
  19537. var contour = vertices; // vertices has all points but contour has only points of circumference
  19538. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19539. ahole = holes[ h ];
  19540. vertices = vertices.concat( ahole );
  19541. }
  19542. function scalePt2 ( pt, vec, size ) {
  19543. if ( !vec ) console.log( "die" );
  19544. return vec.clone().multiplyScalar( size ).add( pt );
  19545. }
  19546. var b, bs, t, z,
  19547. vert, vlen = vertices.length,
  19548. face, flen = faces.length,
  19549. cont, clen = contour.length;
  19550. // Find directions for point movement
  19551. var RAD_TO_DEGREES = 180 / Math.PI;
  19552. function getBevelVec( inPt, inPrev, inNext ) {
  19553. var EPSILON = 0.0000000001;
  19554. var sign = THREE.Math.sign;
  19555. // computes for inPt the corresponding point inPt' on a new contour
  19556. // shiftet by 1 unit (length of normalized vector) to the left
  19557. // if we walk along contour clockwise, this new contour is outside the old one
  19558. //
  19559. // inPt' is the intersection of the two lines parallel to the two
  19560. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19561. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  19562. // good reading for geometry algorithms (here: line-line intersection)
  19563. // http://geomalgorithms.com/a05-_intersect-1.html
  19564. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  19565. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  19566. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  19567. // check for colinear edges
  19568. var colinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19569. if ( Math.abs( colinear0 ) > EPSILON ) { // not colinear
  19570. // length of vectors for normalizing
  19571. var v_prev_len = Math.sqrt( v_prev_lensq );
  19572. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  19573. // shift adjacent points by unit vectors to the left
  19574. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  19575. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  19576. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  19577. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  19578. // scaling factor for v_prev to intersection point
  19579. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  19580. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  19581. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19582. // vector from inPt to intersection point
  19583. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  19584. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  19585. // Don't normalize!, otherwise sharp corners become ugly
  19586. // but prevent crazy spikes
  19587. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y )
  19588. if ( v_trans_lensq <= 2 ) {
  19589. return new THREE.Vector2( v_trans_x, v_trans_y );
  19590. } else {
  19591. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  19592. }
  19593. } else { // handle special case of colinear edges
  19594. var direction_eq = false; // assumes: opposite
  19595. if ( v_prev_x > EPSILON ) {
  19596. if ( v_next_x > EPSILON ) { direction_eq = true; }
  19597. } else {
  19598. if ( v_prev_x < -EPSILON ) {
  19599. if ( v_next_x < -EPSILON ) { direction_eq = true; }
  19600. } else {
  19601. if ( sign(v_prev_y) == sign(v_next_y) ) { direction_eq = true; }
  19602. }
  19603. }
  19604. if ( direction_eq ) {
  19605. // console.log("Warning: lines are a straight sequence");
  19606. v_trans_x = -v_prev_y;
  19607. v_trans_y = v_prev_x;
  19608. shrink_by = Math.sqrt( v_prev_lensq );
  19609. } else {
  19610. // console.log("Warning: lines are a straight spike");
  19611. v_trans_x = v_prev_x;
  19612. v_trans_y = v_prev_y;
  19613. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  19614. }
  19615. }
  19616. return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  19617. }
  19618. var contourMovements = [];
  19619. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19620. if ( j === il ) j = 0;
  19621. if ( k === il ) k = 0;
  19622. // (j)---(i)---(k)
  19623. // console.log('i,j,k', i, j , k)
  19624. var pt_i = contour[ i ];
  19625. var pt_j = contour[ j ];
  19626. var pt_k = contour[ k ];
  19627. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19628. }
  19629. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  19630. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19631. ahole = holes[ h ];
  19632. oneHoleMovements = [];
  19633. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19634. if ( j === il ) j = 0;
  19635. if ( k === il ) k = 0;
  19636. // (j)---(i)---(k)
  19637. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19638. }
  19639. holesMovements.push( oneHoleMovements );
  19640. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19641. }
  19642. // Loop bevelSegments, 1 for the front, 1 for the back
  19643. for ( b = 0; b < bevelSegments; b ++ ) {
  19644. //for ( b = bevelSegments; b > 0; b -- ) {
  19645. t = b / bevelSegments;
  19646. z = bevelThickness * ( 1 - t );
  19647. //z = bevelThickness * t;
  19648. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  19649. //bs = bevelSize * t ; // linear
  19650. // contract shape
  19651. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19652. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19653. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  19654. v( vert.x, vert.y, - z );
  19655. }
  19656. // expand holes
  19657. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  19658. ahole = holes[ h ];
  19659. oneHoleMovements = holesMovements[ h ];
  19660. for ( i = 0, il = ahole.length; i < il; i++ ) {
  19661. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19662. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  19663. v( vert.x, vert.y, -z );
  19664. }
  19665. }
  19666. }
  19667. bs = bevelSize;
  19668. // Back facing vertices
  19669. for ( i = 0; i < vlen; i ++ ) {
  19670. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19671. if ( !extrudeByPath ) {
  19672. v( vert.x, vert.y, 0 );
  19673. } else {
  19674. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19675. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  19676. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  19677. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  19678. v( position2.x, position2.y, position2.z );
  19679. }
  19680. }
  19681. // Add stepped vertices...
  19682. // Including front facing vertices
  19683. var s;
  19684. for ( s = 1; s <= steps; s ++ ) {
  19685. for ( i = 0; i < vlen; i ++ ) {
  19686. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19687. if ( !extrudeByPath ) {
  19688. v( vert.x, vert.y, amount / steps * s );
  19689. } else {
  19690. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19691. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19692. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19693. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  19694. v( position2.x, position2.y, position2.z );
  19695. }
  19696. }
  19697. }
  19698. // Add bevel segments planes
  19699. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19700. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19701. t = b / bevelSegments;
  19702. z = bevelThickness * ( 1 - t );
  19703. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19704. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19705. // contract shape
  19706. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19707. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19708. v( vert.x, vert.y, amount + z );
  19709. }
  19710. // expand holes
  19711. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19712. ahole = holes[ h ];
  19713. oneHoleMovements = holesMovements[ h ];
  19714. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19715. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19716. if ( !extrudeByPath ) {
  19717. v( vert.x, vert.y, amount + z );
  19718. } else {
  19719. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19720. }
  19721. }
  19722. }
  19723. }
  19724. /* Faces */
  19725. // Top and bottom faces
  19726. buildLidFaces();
  19727. // Sides faces
  19728. buildSideFaces();
  19729. ///// Internal functions
  19730. function buildLidFaces() {
  19731. if ( bevelEnabled ) {
  19732. var layer = 0 ; // steps + 1
  19733. var offset = vlen * layer;
  19734. // Bottom faces
  19735. for ( i = 0; i < flen; i ++ ) {
  19736. face = faces[ i ];
  19737. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19738. }
  19739. layer = steps + bevelSegments * 2;
  19740. offset = vlen * layer;
  19741. // Top faces
  19742. for ( i = 0; i < flen; i ++ ) {
  19743. face = faces[ i ];
  19744. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19745. }
  19746. } else {
  19747. // Bottom faces
  19748. for ( i = 0; i < flen; i++ ) {
  19749. face = faces[ i ];
  19750. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19751. }
  19752. // Top faces
  19753. for ( i = 0; i < flen; i ++ ) {
  19754. face = faces[ i ];
  19755. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19756. }
  19757. }
  19758. }
  19759. // Create faces for the z-sides of the shape
  19760. function buildSideFaces() {
  19761. var layeroffset = 0;
  19762. sidewalls( contour, layeroffset );
  19763. layeroffset += contour.length;
  19764. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19765. ahole = holes[ h ];
  19766. sidewalls( ahole, layeroffset );
  19767. //, true
  19768. layeroffset += ahole.length;
  19769. }
  19770. }
  19771. function sidewalls( contour, layeroffset ) {
  19772. var j, k;
  19773. i = contour.length;
  19774. while ( --i >= 0 ) {
  19775. j = i;
  19776. k = i - 1;
  19777. if ( k < 0 ) k = contour.length - 1;
  19778. //console.log('b', i,j, i-1, k,vertices.length);
  19779. var s = 0, sl = steps + bevelSegments * 2;
  19780. for ( s = 0; s < sl; s ++ ) {
  19781. var slen1 = vlen * s;
  19782. var slen2 = vlen * ( s + 1 );
  19783. var a = layeroffset + j + slen1,
  19784. b = layeroffset + k + slen1,
  19785. c = layeroffset + k + slen2,
  19786. d = layeroffset + j + slen2;
  19787. f4( a, b, c, d, contour, s, sl, j, k );
  19788. }
  19789. }
  19790. }
  19791. function v( x, y, z ) {
  19792. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19793. }
  19794. function f3( a, b, c, isBottom ) {
  19795. a += shapesOffset;
  19796. b += shapesOffset;
  19797. c += shapesOffset;
  19798. // normal, color, material
  19799. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19800. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19801. scope.faceVertexUvs[ 0 ].push( uvs );
  19802. }
  19803. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19804. a += shapesOffset;
  19805. b += shapesOffset;
  19806. c += shapesOffset;
  19807. d += shapesOffset;
  19808. scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) );
  19809. scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) );
  19810. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19811. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19812. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  19813. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  19814. }
  19815. };
  19816. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19817. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19818. var ax = geometry.vertices[ indexA ].x,
  19819. ay = geometry.vertices[ indexA ].y,
  19820. bx = geometry.vertices[ indexB ].x,
  19821. by = geometry.vertices[ indexB ].y,
  19822. cx = geometry.vertices[ indexC ].x,
  19823. cy = geometry.vertices[ indexC ].y;
  19824. return [
  19825. new THREE.Vector2( ax, ay ),
  19826. new THREE.Vector2( bx, by ),
  19827. new THREE.Vector2( cx, cy )
  19828. ];
  19829. },
  19830. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19831. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19832. },
  19833. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19834. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19835. contourIndex1, contourIndex2 ) {
  19836. var ax = geometry.vertices[ indexA ].x,
  19837. ay = geometry.vertices[ indexA ].y,
  19838. az = geometry.vertices[ indexA ].z,
  19839. bx = geometry.vertices[ indexB ].x,
  19840. by = geometry.vertices[ indexB ].y,
  19841. bz = geometry.vertices[ indexB ].z,
  19842. cx = geometry.vertices[ indexC ].x,
  19843. cy = geometry.vertices[ indexC ].y,
  19844. cz = geometry.vertices[ indexC ].z,
  19845. dx = geometry.vertices[ indexD ].x,
  19846. dy = geometry.vertices[ indexD ].y,
  19847. dz = geometry.vertices[ indexD ].z;
  19848. if ( Math.abs( ay - by ) < 0.01 ) {
  19849. return [
  19850. new THREE.Vector2( ax, 1 - az ),
  19851. new THREE.Vector2( bx, 1 - bz ),
  19852. new THREE.Vector2( cx, 1 - cz ),
  19853. new THREE.Vector2( dx, 1 - dz )
  19854. ];
  19855. } else {
  19856. return [
  19857. new THREE.Vector2( ay, 1 - az ),
  19858. new THREE.Vector2( by, 1 - bz ),
  19859. new THREE.Vector2( cy, 1 - cz ),
  19860. new THREE.Vector2( dy, 1 - dz )
  19861. ];
  19862. }
  19863. }
  19864. };
  19865. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19866. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19867. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19868. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19869. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19870. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19871. /**
  19872. * @author jonobr1 / http://jonobr1.com
  19873. *
  19874. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19875. * ExtrudeGeometry.
  19876. *
  19877. * parameters = {
  19878. *
  19879. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19880. *
  19881. * material: <int> // material index for front and back faces
  19882. * uvGenerator: <Object> // object that provides UV generator functions
  19883. *
  19884. * }
  19885. **/
  19886. THREE.ShapeGeometry = function ( shapes, options ) {
  19887. THREE.Geometry.call( this );
  19888. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19889. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19890. this.addShapeList( shapes, options );
  19891. this.computeCentroids();
  19892. this.computeFaceNormals();
  19893. };
  19894. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19895. /**
  19896. * Add an array of shapes to THREE.ShapeGeometry.
  19897. */
  19898. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19899. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19900. this.addShape( shapes[ i ], options );
  19901. }
  19902. return this;
  19903. };
  19904. /**
  19905. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19906. */
  19907. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19908. if ( options === undefined ) options = {};
  19909. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19910. var material = options.material;
  19911. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19912. var shapebb = this.shapebb;
  19913. //
  19914. var i, l, hole, s;
  19915. var shapesOffset = this.vertices.length;
  19916. var shapePoints = shape.extractPoints( curveSegments );
  19917. var vertices = shapePoints.shape;
  19918. var holes = shapePoints.holes;
  19919. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19920. if ( reverse ) {
  19921. vertices = vertices.reverse();
  19922. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19923. for ( i = 0, l = holes.length; i < l; i++ ) {
  19924. hole = holes[ i ];
  19925. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19926. holes[ i ] = hole.reverse();
  19927. }
  19928. }
  19929. reverse = false;
  19930. }
  19931. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19932. // Vertices
  19933. var contour = vertices;
  19934. for ( i = 0, l = holes.length; i < l; i++ ) {
  19935. hole = holes[ i ];
  19936. vertices = vertices.concat( hole );
  19937. }
  19938. //
  19939. var vert, vlen = vertices.length;
  19940. var face, flen = faces.length;
  19941. var cont, clen = contour.length;
  19942. for ( i = 0; i < vlen; i++ ) {
  19943. vert = vertices[ i ];
  19944. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19945. }
  19946. for ( i = 0; i < flen; i++ ) {
  19947. face = faces[ i ];
  19948. var a = face[ 0 ] + shapesOffset;
  19949. var b = face[ 1 ] + shapesOffset;
  19950. var c = face[ 2 ] + shapesOffset;
  19951. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19952. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19953. }
  19954. };
  19955. /**
  19956. * @author astrodud / http://astrodud.isgreat.org/
  19957. * @author zz85 / https://github.com/zz85
  19958. * @author bhouston / http://exocortex.com
  19959. */
  19960. // points - to create a closed torus, one must use a set of points
  19961. // like so: [ a, b, c, d, a ], see first is the same as last.
  19962. // segments - the number of circumference segments to create
  19963. // phiStart - the starting radian
  19964. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19965. // 2*pi is a closed lathe, less than 2PI is a portion.
  19966. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19967. THREE.Geometry.call( this );
  19968. segments = segments || 12;
  19969. phiStart = phiStart || 0;
  19970. phiLength = phiLength || 2 * Math.PI;
  19971. var inversePointLength = 1.0 / ( points.length - 1 );
  19972. var inverseSegments = 1.0 / segments;
  19973. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19974. var phi = phiStart + i * inverseSegments * phiLength;
  19975. var c = Math.cos( phi ),
  19976. s = Math.sin( phi );
  19977. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19978. var pt = points[ j ];
  19979. var vertex = new THREE.Vector3();
  19980. vertex.x = c * pt.x - s * pt.y;
  19981. vertex.y = s * pt.x + c * pt.y;
  19982. vertex.z = pt.z;
  19983. this.vertices.push( vertex );
  19984. }
  19985. }
  19986. var np = points.length;
  19987. for ( var i = 0, il = segments; i < il; i ++ ) {
  19988. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19989. var base = j + np * i;
  19990. var a = base;
  19991. var b = base + np;
  19992. var c = base + 1 + np;
  19993. var d = base + 1;
  19994. var u0 = i * inverseSegments;
  19995. var v0 = j * inversePointLength;
  19996. var u1 = u0 + inverseSegments;
  19997. var v1 = v0 + inversePointLength;
  19998. this.faces.push( new THREE.Face3( a, b, d ) );
  19999. this.faceVertexUvs[ 0 ].push( [
  20000. new THREE.Vector2( u0, v0 ),
  20001. new THREE.Vector2( u1, v0 ),
  20002. new THREE.Vector2( u0, v1 )
  20003. ] );
  20004. this.faces.push( new THREE.Face3( b, c, d ) );
  20005. this.faceVertexUvs[ 0 ].push( [
  20006. new THREE.Vector2( u1, v0 ),
  20007. new THREE.Vector2( u1, v1 ),
  20008. new THREE.Vector2( u0, v1 )
  20009. ] );
  20010. }
  20011. }
  20012. this.mergeVertices();
  20013. this.computeCentroids();
  20014. this.computeFaceNormals();
  20015. this.computeVertexNormals();
  20016. };
  20017. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20018. /**
  20019. * @author mrdoob / http://mrdoob.com/
  20020. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  20021. */
  20022. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  20023. THREE.Geometry.call( this );
  20024. this.width = width;
  20025. this.height = height;
  20026. this.widthSegments = widthSegments || 1;
  20027. this.heightSegments = heightSegments || 1;
  20028. var ix, iz;
  20029. var width_half = width / 2;
  20030. var height_half = height / 2;
  20031. var gridX = this.widthSegments;
  20032. var gridZ = this.heightSegments;
  20033. var gridX1 = gridX + 1;
  20034. var gridZ1 = gridZ + 1;
  20035. var segment_width = this.width / gridX;
  20036. var segment_height = this.height / gridZ;
  20037. var normal = new THREE.Vector3( 0, 0, 1 );
  20038. for ( iz = 0; iz < gridZ1; iz ++ ) {
  20039. for ( ix = 0; ix < gridX1; ix ++ ) {
  20040. var x = ix * segment_width - width_half;
  20041. var y = iz * segment_height - height_half;
  20042. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  20043. }
  20044. }
  20045. for ( iz = 0; iz < gridZ; iz ++ ) {
  20046. for ( ix = 0; ix < gridX; ix ++ ) {
  20047. var a = ix + gridX1 * iz;
  20048. var b = ix + gridX1 * ( iz + 1 );
  20049. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  20050. var d = ( ix + 1 ) + gridX1 * iz;
  20051. var uva = new THREE.Vector2( ix / gridX, 1 - iz / gridZ );
  20052. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ );
  20053. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ );
  20054. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ );
  20055. var face = new THREE.Face3( a, b, d );
  20056. face.normal.copy( normal );
  20057. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  20058. this.faces.push( face );
  20059. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  20060. face = new THREE.Face3( b, c, d );
  20061. face.normal.copy( normal );
  20062. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  20063. this.faces.push( face );
  20064. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  20065. }
  20066. }
  20067. this.computeCentroids();
  20068. };
  20069. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20070. /**
  20071. * @author Kaleb Murphy
  20072. */
  20073. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  20074. THREE.Geometry.call( this );
  20075. innerRadius = innerRadius || 0;
  20076. outerRadius = outerRadius || 50;
  20077. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  20078. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  20079. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  20080. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  20081. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  20082. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  20083. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  20084. var vertex = new THREE.Vector3();
  20085. var segment = thetaStart + o / thetaSegments * thetaLength;
  20086. vertex.x = radius * Math.cos( segment );
  20087. vertex.y = radius * Math.sin( segment );
  20088. this.vertices.push( vertex );
  20089. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  20090. }
  20091. radius += radiusStep;
  20092. }
  20093. var n = new THREE.Vector3( 0, 0, 1 );
  20094. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  20095. var thetaSegment = i * thetaSegments;
  20096. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  20097. var segment = o + thetaSegment;
  20098. var v1 = segment + i;
  20099. var v2 = segment + thetaSegments + i;
  20100. var v3 = segment + thetaSegments + 1 + i;
  20101. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  20102. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  20103. v1 = segment + i;
  20104. v2 = segment + thetaSegments + 1 + i;
  20105. v3 = segment + 1 + i;
  20106. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  20107. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  20108. }
  20109. }
  20110. this.computeCentroids();
  20111. this.computeFaceNormals();
  20112. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20113. };
  20114. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20115. /**
  20116. * @author mrdoob / http://mrdoob.com/
  20117. */
  20118. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  20119. THREE.Geometry.call( this );
  20120. this.radius = radius = radius || 50;
  20121. this.widthSegments = widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  20122. this.heightSegments = heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  20123. this.phiStart = phiStart = phiStart !== undefined ? phiStart : 0;
  20124. this.phiLength = phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  20125. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  20126. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  20127. var x, y, vertices = [], uvs = [];
  20128. for ( y = 0; y <= heightSegments; y ++ ) {
  20129. var verticesRow = [];
  20130. var uvsRow = [];
  20131. for ( x = 0; x <= widthSegments; x ++ ) {
  20132. var u = x / widthSegments;
  20133. var v = y / heightSegments;
  20134. var vertex = new THREE.Vector3();
  20135. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20136. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  20137. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20138. this.vertices.push( vertex );
  20139. verticesRow.push( this.vertices.length - 1 );
  20140. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  20141. }
  20142. vertices.push( verticesRow );
  20143. uvs.push( uvsRow );
  20144. }
  20145. for ( y = 0; y < this.heightSegments; y ++ ) {
  20146. for ( x = 0; x < this.widthSegments; x ++ ) {
  20147. var v1 = vertices[ y ][ x + 1 ];
  20148. var v2 = vertices[ y ][ x ];
  20149. var v3 = vertices[ y + 1 ][ x ];
  20150. var v4 = vertices[ y + 1 ][ x + 1 ];
  20151. var n1 = this.vertices[ v1 ].clone().normalize();
  20152. var n2 = this.vertices[ v2 ].clone().normalize();
  20153. var n3 = this.vertices[ v3 ].clone().normalize();
  20154. var n4 = this.vertices[ v4 ].clone().normalize();
  20155. var uv1 = uvs[ y ][ x + 1 ].clone();
  20156. var uv2 = uvs[ y ][ x ].clone();
  20157. var uv3 = uvs[ y + 1 ][ x ].clone();
  20158. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  20159. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  20160. uv1.x = ( uv1.x + uv2.x ) / 2;
  20161. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  20162. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  20163. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  20164. uv3.x = ( uv3.x + uv4.x ) / 2;
  20165. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  20166. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  20167. } else {
  20168. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  20169. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  20170. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  20171. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  20172. }
  20173. }
  20174. }
  20175. this.computeCentroids();
  20176. this.computeFaceNormals();
  20177. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20178. };
  20179. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20180. /**
  20181. * @author zz85 / http://www.lab4games.net/zz85/blog
  20182. * @author alteredq / http://alteredqualia.com/
  20183. *
  20184. * For creating 3D text geometry in three.js
  20185. *
  20186. * Text = 3D Text
  20187. *
  20188. * parameters = {
  20189. * size: <float>, // size of the text
  20190. * height: <float>, // thickness to extrude text
  20191. * curveSegments: <int>, // number of points on the curves
  20192. *
  20193. * font: <string>, // font name
  20194. * weight: <string>, // font weight (normal, bold)
  20195. * style: <string>, // font style (normal, italics)
  20196. *
  20197. * bevelEnabled: <bool>, // turn on bevel
  20198. * bevelThickness: <float>, // how deep into text bevel goes
  20199. * bevelSize: <float>, // how far from text outline is bevel
  20200. * }
  20201. *
  20202. */
  20203. /* Usage Examples
  20204. // TextGeometry wrapper
  20205. var text3d = new TextGeometry( text, options );
  20206. // Complete manner
  20207. var textShapes = THREE.FontUtils.generateShapes( text, options );
  20208. var text3d = new ExtrudeGeometry( textShapes, options );
  20209. */
  20210. THREE.TextGeometry = function ( text, parameters ) {
  20211. parameters = parameters || {};
  20212. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  20213. // translate parameters to ExtrudeGeometry API
  20214. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  20215. // defaults
  20216. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  20217. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  20218. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  20219. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  20220. };
  20221. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  20222. /**
  20223. * @author oosmoxiecode
  20224. * @author mrdoob / http://mrdoob.com/
  20225. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  20226. */
  20227. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  20228. THREE.Geometry.call( this );
  20229. var scope = this;
  20230. this.radius = radius || 100;
  20231. this.tube = tube || 40;
  20232. this.radialSegments = radialSegments || 8;
  20233. this.tubularSegments = tubularSegments || 6;
  20234. this.arc = arc || Math.PI * 2;
  20235. var center = new THREE.Vector3(), uvs = [], normals = [];
  20236. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  20237. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  20238. var u = i / this.tubularSegments * this.arc;
  20239. var v = j / this.radialSegments * Math.PI * 2;
  20240. center.x = this.radius * Math.cos( u );
  20241. center.y = this.radius * Math.sin( u );
  20242. var vertex = new THREE.Vector3();
  20243. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  20244. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  20245. vertex.z = this.tube * Math.sin( v );
  20246. this.vertices.push( vertex );
  20247. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  20248. normals.push( vertex.clone().sub( center ).normalize() );
  20249. }
  20250. }
  20251. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  20252. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  20253. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  20254. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  20255. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  20256. var d = ( this.tubularSegments + 1 ) * j + i;
  20257. var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
  20258. this.faces.push( face );
  20259. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  20260. face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
  20261. this.faces.push( face );
  20262. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  20263. }
  20264. }
  20265. this.computeCentroids();
  20266. this.computeFaceNormals();
  20267. };
  20268. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20269. /**
  20270. * @author oosmoxiecode
  20271. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  20272. */
  20273. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  20274. THREE.Geometry.call( this );
  20275. var scope = this;
  20276. this.radius = radius || 100;
  20277. this.tube = tube || 40;
  20278. this.radialSegments = radialSegments || 64;
  20279. this.tubularSegments = tubularSegments || 8;
  20280. this.p = p || 2;
  20281. this.q = q || 3;
  20282. this.heightScale = heightScale || 1;
  20283. this.grid = new Array( this.radialSegments );
  20284. var tang = new THREE.Vector3();
  20285. var n = new THREE.Vector3();
  20286. var bitan = new THREE.Vector3();
  20287. for ( var i = 0; i < this.radialSegments; ++ i ) {
  20288. this.grid[ i ] = new Array( this.tubularSegments );
  20289. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  20290. var p1 = getPos( u, this.q, this.p, this.radius, this.heightScale );
  20291. var p2 = getPos( u + 0.01, this.q, this.p, this.radius, this.heightScale );
  20292. tang.subVectors( p2, p1 );
  20293. n.addVectors( p2, p1 );
  20294. bitan.crossVectors( tang, n );
  20295. n.crossVectors( bitan, tang );
  20296. bitan.normalize();
  20297. n.normalize();
  20298. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  20299. var v = j / this.tubularSegments * 2 * Math.PI;
  20300. var cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20301. var cy = this.tube * Math.sin( v );
  20302. var pos = new THREE.Vector3();
  20303. pos.x = p1.x + cx * n.x + cy * bitan.x;
  20304. pos.y = p1.y + cx * n.y + cy * bitan.y;
  20305. pos.z = p1.z + cx * n.z + cy * bitan.z;
  20306. this.grid[ i ][ j ] = scope.vertices.push( pos ) - 1;
  20307. }
  20308. }
  20309. for ( var i = 0; i < this.radialSegments; ++ i ) {
  20310. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  20311. var ip = ( i + 1 ) % this.radialSegments;
  20312. var jp = ( j + 1 ) % this.tubularSegments;
  20313. var a = this.grid[ i ][ j ];
  20314. var b = this.grid[ ip ][ j ];
  20315. var c = this.grid[ ip ][ jp ];
  20316. var d = this.grid[ i ][ jp ];
  20317. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  20318. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  20319. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  20320. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  20321. this.faces.push( new THREE.Face3( a, b, d ) );
  20322. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  20323. this.faces.push( new THREE.Face3( b, c, d ) );
  20324. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  20325. }
  20326. }
  20327. this.computeCentroids();
  20328. this.computeFaceNormals();
  20329. this.computeVertexNormals();
  20330. function getPos( u, in_q, in_p, radius, heightScale ) {
  20331. var cu = Math.cos( u );
  20332. var su = Math.sin( u );
  20333. var quOverP = in_q / in_p * u;
  20334. var cs = Math.cos( quOverP );
  20335. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  20336. var ty = radius * ( 2 + cs ) * su * 0.5;
  20337. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  20338. return new THREE.Vector3( tx, ty, tz );
  20339. }
  20340. };
  20341. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20342. /**
  20343. * @author WestLangley / https://github.com/WestLangley
  20344. * @author zz85 / https://github.com/zz85
  20345. * @author miningold / https://github.com/miningold
  20346. *
  20347. * Modified from the TorusKnotGeometry by @oosmoxiecode
  20348. *
  20349. * Creates a tube which extrudes along a 3d spline
  20350. *
  20351. * Uses parallel transport frames as described in
  20352. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20353. */
  20354. THREE.TubeGeometry = function( path, segments, radius, radialSegments, closed ) {
  20355. THREE.Geometry.call( this );
  20356. this.path = path;
  20357. this.segments = segments || 64;
  20358. this.radius = radius || 1;
  20359. this.radialSegments = radialSegments || 8;
  20360. this.closed = closed || false;
  20361. this.grid = [];
  20362. var scope = this,
  20363. tangent,
  20364. normal,
  20365. binormal,
  20366. numpoints = this.segments + 1,
  20367. x, y, z,
  20368. tx, ty, tz,
  20369. u, v,
  20370. cx, cy,
  20371. pos, pos2 = new THREE.Vector3(),
  20372. i, j,
  20373. ip, jp,
  20374. a, b, c, d,
  20375. uva, uvb, uvc, uvd;
  20376. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  20377. tangents = frames.tangents,
  20378. normals = frames.normals,
  20379. binormals = frames.binormals;
  20380. // proxy internals
  20381. this.tangents = tangents;
  20382. this.normals = normals;
  20383. this.binormals = binormals;
  20384. function vert( x, y, z ) {
  20385. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  20386. }
  20387. // consruct the grid
  20388. for ( i = 0; i < numpoints; i++ ) {
  20389. this.grid[ i ] = [];
  20390. u = i / ( numpoints - 1 );
  20391. pos = path.getPointAt( u );
  20392. tangent = tangents[ i ];
  20393. normal = normals[ i ];
  20394. binormal = binormals[ i ];
  20395. for ( j = 0; j < this.radialSegments; j++ ) {
  20396. v = j / this.radialSegments * 2 * Math.PI;
  20397. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20398. cy = this.radius * Math.sin( v );
  20399. pos2.copy( pos );
  20400. pos2.x += cx * normal.x + cy * binormal.x;
  20401. pos2.y += cx * normal.y + cy * binormal.y;
  20402. pos2.z += cx * normal.z + cy * binormal.z;
  20403. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  20404. }
  20405. }
  20406. // construct the mesh
  20407. for ( i = 0; i < this.segments; i++ ) {
  20408. for ( j = 0; j < this.radialSegments; j++ ) {
  20409. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  20410. jp = (j + 1) % this.radialSegments;
  20411. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  20412. b = this.grid[ ip ][ j ];
  20413. c = this.grid[ ip ][ jp ];
  20414. d = this.grid[ i ][ jp ];
  20415. uva = new THREE.Vector2( i / this.segments, j / this.radialSegments );
  20416. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radialSegments );
  20417. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radialSegments );
  20418. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radialSegments );
  20419. this.faces.push( new THREE.Face3( a, b, d ) );
  20420. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  20421. this.faces.push( new THREE.Face3( b, c, d ) );
  20422. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  20423. }
  20424. }
  20425. this.computeCentroids();
  20426. this.computeFaceNormals();
  20427. this.computeVertexNormals();
  20428. };
  20429. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20430. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  20431. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  20432. var tangent = new THREE.Vector3(),
  20433. normal = new THREE.Vector3(),
  20434. binormal = new THREE.Vector3(),
  20435. tangents = [],
  20436. normals = [],
  20437. binormals = [],
  20438. vec = new THREE.Vector3(),
  20439. mat = new THREE.Matrix4(),
  20440. numpoints = segments + 1,
  20441. theta,
  20442. epsilon = 0.0001,
  20443. smallest,
  20444. tx, ty, tz,
  20445. i, u, v;
  20446. // expose internals
  20447. this.tangents = tangents;
  20448. this.normals = normals;
  20449. this.binormals = binormals;
  20450. // compute the tangent vectors for each segment on the path
  20451. for ( i = 0; i < numpoints; i++ ) {
  20452. u = i / ( numpoints - 1 );
  20453. tangents[ i ] = path.getTangentAt( u );
  20454. tangents[ i ].normalize();
  20455. }
  20456. initialNormal3();
  20457. function initialNormal1(lastBinormal) {
  20458. // fixed start binormal. Has dangers of 0 vectors
  20459. normals[ 0 ] = new THREE.Vector3();
  20460. binormals[ 0 ] = new THREE.Vector3();
  20461. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  20462. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  20463. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20464. }
  20465. function initialNormal2() {
  20466. // This uses the Frenet-Serret formula for deriving binormal
  20467. var t2 = path.getTangentAt( epsilon );
  20468. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  20469. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  20470. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  20471. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20472. }
  20473. function initialNormal3() {
  20474. // select an initial normal vector perpenicular to the first tangent vector,
  20475. // and in the direction of the smallest tangent xyz component
  20476. normals[ 0 ] = new THREE.Vector3();
  20477. binormals[ 0 ] = new THREE.Vector3();
  20478. smallest = Number.MAX_VALUE;
  20479. tx = Math.abs( tangents[ 0 ].x );
  20480. ty = Math.abs( tangents[ 0 ].y );
  20481. tz = Math.abs( tangents[ 0 ].z );
  20482. if ( tx <= smallest ) {
  20483. smallest = tx;
  20484. normal.set( 1, 0, 0 );
  20485. }
  20486. if ( ty <= smallest ) {
  20487. smallest = ty;
  20488. normal.set( 0, 1, 0 );
  20489. }
  20490. if ( tz <= smallest ) {
  20491. normal.set( 0, 0, 1 );
  20492. }
  20493. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20494. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20495. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20496. }
  20497. // compute the slowly-varying normal and binormal vectors for each segment on the path
  20498. for ( i = 1; i < numpoints; i++ ) {
  20499. normals[ i ] = normals[ i-1 ].clone();
  20500. binormals[ i ] = binormals[ i-1 ].clone();
  20501. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  20502. if ( vec.length() > epsilon ) {
  20503. vec.normalize();
  20504. theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  20505. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20506. }
  20507. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20508. }
  20509. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20510. if ( closed ) {
  20511. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), -1, 1 ) );
  20512. theta /= ( numpoints - 1 );
  20513. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  20514. theta = -theta;
  20515. }
  20516. for ( i = 1; i < numpoints; i++ ) {
  20517. // twist a little...
  20518. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20519. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20520. }
  20521. }
  20522. };
  20523. /**
  20524. * @author clockworkgeek / https://github.com/clockworkgeek
  20525. * @author timothypratley / https://github.com/timothypratley
  20526. * @author WestLangley / http://github.com/WestLangley
  20527. */
  20528. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  20529. THREE.Geometry.call( this );
  20530. radius = radius || 1;
  20531. detail = detail || 0;
  20532. var that = this;
  20533. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  20534. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  20535. }
  20536. var midpoints = [], p = this.vertices;
  20537. var f = [];
  20538. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20539. var v1 = p[ faces[ i ][ 0 ] ];
  20540. var v2 = p[ faces[ i ][ 1 ] ];
  20541. var v3 = p[ faces[ i ][ 2 ] ];
  20542. f[ i ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20543. }
  20544. for ( var i = 0, l = f.length; i < l; i ++ ) {
  20545. subdivide(f[ i ], detail);
  20546. }
  20547. // Handle case when face straddles the seam
  20548. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  20549. var uvs = this.faceVertexUvs[ 0 ][ i ];
  20550. var x0 = uvs[ 0 ].x;
  20551. var x1 = uvs[ 1 ].x;
  20552. var x2 = uvs[ 2 ].x;
  20553. var max = Math.max( x0, Math.max( x1, x2 ) );
  20554. var min = Math.min( x0, Math.min( x1, x2 ) );
  20555. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  20556. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  20557. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  20558. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  20559. }
  20560. }
  20561. // Apply radius
  20562. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  20563. this.vertices[ i ].multiplyScalar( radius );
  20564. }
  20565. // Merge vertices
  20566. this.mergeVertices();
  20567. this.computeCentroids();
  20568. this.computeFaceNormals();
  20569. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20570. // Project vector onto sphere's surface
  20571. function prepare( vector ) {
  20572. var vertex = vector.normalize().clone();
  20573. vertex.index = that.vertices.push( vertex ) - 1;
  20574. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  20575. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  20576. var v = inclination( vector ) / Math.PI + 0.5;
  20577. vertex.uv = new THREE.Vector2( u, 1 - v );
  20578. return vertex;
  20579. }
  20580. // Approximate a curved face with recursively sub-divided triangles.
  20581. function make( v1, v2, v3 ) {
  20582. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20583. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  20584. that.faces.push( face );
  20585. var azi = azimuth( face.centroid );
  20586. that.faceVertexUvs[ 0 ].push( [
  20587. correctUV( v1.uv, v1, azi ),
  20588. correctUV( v2.uv, v2, azi ),
  20589. correctUV( v3.uv, v3, azi )
  20590. ] );
  20591. }
  20592. // Analytically subdivide a face to the required detail level.
  20593. function subdivide(face, detail ) {
  20594. var cols = Math.pow(2, detail);
  20595. var cells = Math.pow(4, detail);
  20596. var a = prepare( that.vertices[ face.a ] );
  20597. var b = prepare( that.vertices[ face.b ] );
  20598. var c = prepare( that.vertices[ face.c ] );
  20599. var v = [];
  20600. // Construct all of the vertices for this subdivision.
  20601. for ( var i = 0 ; i <= cols; i ++ ) {
  20602. v[ i ] = [];
  20603. var aj = prepare( a.clone().lerp( c, i / cols ) );
  20604. var bj = prepare( b.clone().lerp( c, i / cols ) );
  20605. var rows = cols - i;
  20606. for ( var j = 0; j <= rows; j ++) {
  20607. if ( j == 0 && i == cols ) {
  20608. v[ i ][ j ] = aj;
  20609. } else {
  20610. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  20611. }
  20612. }
  20613. }
  20614. // Construct all of the faces.
  20615. for ( var i = 0; i < cols ; i ++ ) {
  20616. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  20617. var k = Math.floor( j / 2 );
  20618. if ( j % 2 == 0 ) {
  20619. make(
  20620. v[ i ][ k + 1],
  20621. v[ i + 1 ][ k ],
  20622. v[ i ][ k ]
  20623. );
  20624. } else {
  20625. make(
  20626. v[ i ][ k + 1 ],
  20627. v[ i + 1][ k + 1],
  20628. v[ i + 1 ][ k ]
  20629. );
  20630. }
  20631. }
  20632. }
  20633. }
  20634. // Angle around the Y axis, counter-clockwise when looking from above.
  20635. function azimuth( vector ) {
  20636. return Math.atan2( vector.z, -vector.x );
  20637. }
  20638. // Angle above the XZ plane.
  20639. function inclination( vector ) {
  20640. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20641. }
  20642. // Texture fixing helper. Spheres have some odd behaviours.
  20643. function correctUV( uv, vector, azimuth ) {
  20644. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  20645. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  20646. return uv.clone();
  20647. }
  20648. };
  20649. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20650. /**
  20651. * @author timothypratley / https://github.com/timothypratley
  20652. */
  20653. THREE.IcosahedronGeometry = function ( radius, detail ) {
  20654. this.radius = radius;
  20655. this.detail = detail;
  20656. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20657. var vertices = [
  20658. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  20659. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  20660. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  20661. ];
  20662. var faces = [
  20663. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  20664. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  20665. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  20666. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  20667. ];
  20668. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20669. };
  20670. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20671. /**
  20672. * @author timothypratley / https://github.com/timothypratley
  20673. */
  20674. THREE.OctahedronGeometry = function ( radius, detail ) {
  20675. var vertices = [
  20676. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  20677. ];
  20678. var faces = [
  20679. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  20680. ];
  20681. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20682. };
  20683. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20684. /**
  20685. * @author timothypratley / https://github.com/timothypratley
  20686. */
  20687. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20688. var vertices = [
  20689. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  20690. ];
  20691. var faces = [
  20692. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  20693. ];
  20694. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20695. };
  20696. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20697. /**
  20698. * @author zz85 / https://github.com/zz85
  20699. * Parametric Surfaces Geometry
  20700. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20701. *
  20702. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  20703. *
  20704. */
  20705. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  20706. THREE.Geometry.call( this );
  20707. var verts = this.vertices;
  20708. var faces = this.faces;
  20709. var uvs = this.faceVertexUvs[ 0 ];
  20710. var i, il, j, p;
  20711. var u, v;
  20712. var stackCount = stacks + 1;
  20713. var sliceCount = slices + 1;
  20714. for ( i = 0; i <= stacks; i ++ ) {
  20715. v = i / stacks;
  20716. for ( j = 0; j <= slices; j ++ ) {
  20717. u = j / slices;
  20718. p = func( u, v );
  20719. verts.push( p );
  20720. }
  20721. }
  20722. var a, b, c, d;
  20723. var uva, uvb, uvc, uvd;
  20724. for ( i = 0; i < stacks; i ++ ) {
  20725. for ( j = 0; j < slices; j ++ ) {
  20726. a = i * sliceCount + j;
  20727. b = i * sliceCount + j + 1;
  20728. c = (i + 1) * sliceCount + j + 1;
  20729. d = (i + 1) * sliceCount + j;
  20730. uva = new THREE.Vector2( j / slices, i / stacks );
  20731. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20732. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20733. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20734. faces.push( new THREE.Face3( a, b, d ) );
  20735. uvs.push( [ uva, uvb, uvd ] );
  20736. faces.push( new THREE.Face3( b, c, d ) );
  20737. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  20738. }
  20739. }
  20740. // console.log(this);
  20741. // magic bullet
  20742. // var diff = this.mergeVertices();
  20743. // console.log('removed ', diff, ' vertices by merging');
  20744. this.computeCentroids();
  20745. this.computeFaceNormals();
  20746. this.computeVertexNormals();
  20747. };
  20748. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20749. /**
  20750. * @author sroucheray / http://sroucheray.org/
  20751. * @author mrdoob / http://mrdoob.com/
  20752. */
  20753. THREE.AxisHelper = function ( size ) {
  20754. size = size || 1;
  20755. var geometry = new THREE.Geometry();
  20756. geometry.vertices.push(
  20757. new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ),
  20758. new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ),
  20759. new THREE.Vector3(), new THREE.Vector3( 0, 0, size )
  20760. );
  20761. geometry.colors.push(
  20762. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20763. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20764. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20765. );
  20766. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20767. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20768. };
  20769. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20770. /**
  20771. * @author WestLangley / http://github.com/WestLangley
  20772. * @author zz85 / http://github.com/zz85
  20773. * @author bhouston / http://exocortex.com
  20774. *
  20775. * Creates an arrow for visualizing directions
  20776. *
  20777. * Parameters:
  20778. * dir - Vector3
  20779. * origin - Vector3
  20780. * length - Number
  20781. * hex - color in hex value
  20782. * headLength - Number
  20783. * headWidth - Number
  20784. */
  20785. THREE.ArrowHelper = function ( dir, origin, length, hex, headLength, headWidth ) {
  20786. // dir is assumed to be normalized
  20787. THREE.Object3D.call( this );
  20788. if ( hex === undefined ) hex = 0xffff00;
  20789. if ( length === undefined ) length = 1;
  20790. if ( headLength === undefined ) headLength = 0.2 * length;
  20791. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20792. this.position = origin;
  20793. var lineGeometry = new THREE.Geometry();
  20794. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20795. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20796. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20797. this.line.matrixAutoUpdate = false;
  20798. this.add( this.line );
  20799. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  20800. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  20801. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20802. this.cone.matrixAutoUpdate = false;
  20803. this.add( this.cone );
  20804. this.setDirection( dir );
  20805. this.setLength( length, headLength, headWidth );
  20806. };
  20807. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20808. THREE.ArrowHelper.prototype.setDirection = function () {
  20809. var axis = new THREE.Vector3();
  20810. var radians;
  20811. return function ( dir ) {
  20812. // dir is assumed to be normalized
  20813. if ( dir.y > 0.99999 ) {
  20814. this.quaternion.set( 0, 0, 0, 1 );
  20815. } else if ( dir.y < - 0.99999 ) {
  20816. this.quaternion.set( 1, 0, 0, 0 );
  20817. } else {
  20818. axis.set( dir.z, 0, - dir.x ).normalize();
  20819. radians = Math.acos( dir.y );
  20820. this.quaternion.setFromAxisAngle( axis, radians );
  20821. }
  20822. };
  20823. }();
  20824. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  20825. if ( headLength === undefined ) headLength = 0.2 * length;
  20826. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20827. this.line.scale.set( 1, length, 1 );
  20828. this.line.updateMatrix();
  20829. this.cone.scale.set( headWidth, headLength, headWidth );
  20830. this.cone.position.y = length;
  20831. this.cone.updateMatrix();
  20832. };
  20833. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20834. this.line.material.color.setHex( hex );
  20835. this.cone.material.color.setHex( hex );
  20836. };
  20837. /**
  20838. * @author mrdoob / http://mrdoob.com/
  20839. */
  20840. THREE.BoxHelper = function ( object ) {
  20841. // 5____4
  20842. // 1/___0/|
  20843. // | 6__|_7
  20844. // 2/___3/
  20845. var vertices = [
  20846. new THREE.Vector3( 1, 1, 1 ),
  20847. new THREE.Vector3( - 1, 1, 1 ),
  20848. new THREE.Vector3( - 1, - 1, 1 ),
  20849. new THREE.Vector3( 1, - 1, 1 ),
  20850. new THREE.Vector3( 1, 1, - 1 ),
  20851. new THREE.Vector3( - 1, 1, - 1 ),
  20852. new THREE.Vector3( - 1, - 1, - 1 ),
  20853. new THREE.Vector3( 1, - 1, - 1 )
  20854. ];
  20855. this.vertices = vertices;
  20856. // TODO: Wouldn't be nice if Line had .segments?
  20857. var geometry = new THREE.Geometry();
  20858. geometry.vertices.push(
  20859. vertices[ 0 ], vertices[ 1 ],
  20860. vertices[ 1 ], vertices[ 2 ],
  20861. vertices[ 2 ], vertices[ 3 ],
  20862. vertices[ 3 ], vertices[ 0 ],
  20863. vertices[ 4 ], vertices[ 5 ],
  20864. vertices[ 5 ], vertices[ 6 ],
  20865. vertices[ 6 ], vertices[ 7 ],
  20866. vertices[ 7 ], vertices[ 4 ],
  20867. vertices[ 0 ], vertices[ 4 ],
  20868. vertices[ 1 ], vertices[ 5 ],
  20869. vertices[ 2 ], vertices[ 6 ],
  20870. vertices[ 3 ], vertices[ 7 ]
  20871. );
  20872. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  20873. if ( object !== undefined ) {
  20874. this.update( object );
  20875. }
  20876. };
  20877. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20878. THREE.BoxHelper.prototype.update = function ( object ) {
  20879. var geometry = object.geometry;
  20880. if ( geometry.boundingBox === null ) {
  20881. geometry.computeBoundingBox();
  20882. }
  20883. var min = geometry.boundingBox.min;
  20884. var max = geometry.boundingBox.max;
  20885. var vertices = this.vertices;
  20886. vertices[ 0 ].set( max.x, max.y, max.z );
  20887. vertices[ 1 ].set( min.x, max.y, max.z );
  20888. vertices[ 2 ].set( min.x, min.y, max.z );
  20889. vertices[ 3 ].set( max.x, min.y, max.z );
  20890. vertices[ 4 ].set( max.x, max.y, min.z );
  20891. vertices[ 5 ].set( min.x, max.y, min.z );
  20892. vertices[ 6 ].set( min.x, min.y, min.z );
  20893. vertices[ 7 ].set( max.x, min.y, min.z );
  20894. this.geometry.computeBoundingSphere();
  20895. this.geometry.verticesNeedUpdate = true;
  20896. this.matrixAutoUpdate = false;
  20897. this.matrixWorld = object.matrixWorld;
  20898. };
  20899. /**
  20900. * @author WestLangley / http://github.com/WestLangley
  20901. */
  20902. // a helper to show the world-axis-aligned bounding box for an object
  20903. THREE.BoundingBoxHelper = function ( object, hex ) {
  20904. var color = ( hex !== undefined ) ? hex : 0x888888;
  20905. this.object = object;
  20906. this.box = new THREE.Box3();
  20907. THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20908. };
  20909. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20910. THREE.BoundingBoxHelper.prototype.update = function () {
  20911. this.box.setFromObject( this.object );
  20912. this.box.size( this.scale );
  20913. this.box.center( this.position );
  20914. };
  20915. /**
  20916. * @author alteredq / http://alteredqualia.com/
  20917. *
  20918. * - shows frustum, line of sight and up of the camera
  20919. * - suitable for fast updates
  20920. * - based on frustum visualization in lightgl.js shadowmap example
  20921. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20922. */
  20923. THREE.CameraHelper = function ( camera ) {
  20924. var geometry = new THREE.Geometry();
  20925. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20926. var pointMap = {};
  20927. // colors
  20928. var hexFrustum = 0xffaa00;
  20929. var hexCone = 0xff0000;
  20930. var hexUp = 0x00aaff;
  20931. var hexTarget = 0xffffff;
  20932. var hexCross = 0x333333;
  20933. // near
  20934. addLine( "n1", "n2", hexFrustum );
  20935. addLine( "n2", "n4", hexFrustum );
  20936. addLine( "n4", "n3", hexFrustum );
  20937. addLine( "n3", "n1", hexFrustum );
  20938. // far
  20939. addLine( "f1", "f2", hexFrustum );
  20940. addLine( "f2", "f4", hexFrustum );
  20941. addLine( "f4", "f3", hexFrustum );
  20942. addLine( "f3", "f1", hexFrustum );
  20943. // sides
  20944. addLine( "n1", "f1", hexFrustum );
  20945. addLine( "n2", "f2", hexFrustum );
  20946. addLine( "n3", "f3", hexFrustum );
  20947. addLine( "n4", "f4", hexFrustum );
  20948. // cone
  20949. addLine( "p", "n1", hexCone );
  20950. addLine( "p", "n2", hexCone );
  20951. addLine( "p", "n3", hexCone );
  20952. addLine( "p", "n4", hexCone );
  20953. // up
  20954. addLine( "u1", "u2", hexUp );
  20955. addLine( "u2", "u3", hexUp );
  20956. addLine( "u3", "u1", hexUp );
  20957. // target
  20958. addLine( "c", "t", hexTarget );
  20959. addLine( "p", "c", hexCross );
  20960. // cross
  20961. addLine( "cn1", "cn2", hexCross );
  20962. addLine( "cn3", "cn4", hexCross );
  20963. addLine( "cf1", "cf2", hexCross );
  20964. addLine( "cf3", "cf4", hexCross );
  20965. function addLine( a, b, hex ) {
  20966. addPoint( a, hex );
  20967. addPoint( b, hex );
  20968. }
  20969. function addPoint( id, hex ) {
  20970. geometry.vertices.push( new THREE.Vector3() );
  20971. geometry.colors.push( new THREE.Color( hex ) );
  20972. if ( pointMap[ id ] === undefined ) {
  20973. pointMap[ id ] = [];
  20974. }
  20975. pointMap[ id ].push( geometry.vertices.length - 1 );
  20976. }
  20977. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20978. this.camera = camera;
  20979. this.matrixWorld = camera.matrixWorld;
  20980. this.matrixAutoUpdate = false;
  20981. this.pointMap = pointMap;
  20982. this.update();
  20983. };
  20984. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20985. THREE.CameraHelper.prototype.update = function () {
  20986. var vector = new THREE.Vector3();
  20987. var camera = new THREE.Camera();
  20988. var projector = new THREE.Projector();
  20989. return function () {
  20990. var scope = this;
  20991. var w = 1, h = 1;
  20992. // we need just camera projection matrix
  20993. // world matrix must be identity
  20994. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20995. // center / target
  20996. setPoint( "c", 0, 0, -1 );
  20997. setPoint( "t", 0, 0, 1 );
  20998. // near
  20999. setPoint( "n1", -w, -h, -1 );
  21000. setPoint( "n2", w, -h, -1 );
  21001. setPoint( "n3", -w, h, -1 );
  21002. setPoint( "n4", w, h, -1 );
  21003. // far
  21004. setPoint( "f1", -w, -h, 1 );
  21005. setPoint( "f2", w, -h, 1 );
  21006. setPoint( "f3", -w, h, 1 );
  21007. setPoint( "f4", w, h, 1 );
  21008. // up
  21009. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  21010. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  21011. setPoint( "u3", 0, h * 2, -1 );
  21012. // cross
  21013. setPoint( "cf1", -w, 0, 1 );
  21014. setPoint( "cf2", w, 0, 1 );
  21015. setPoint( "cf3", 0, -h, 1 );
  21016. setPoint( "cf4", 0, h, 1 );
  21017. setPoint( "cn1", -w, 0, -1 );
  21018. setPoint( "cn2", w, 0, -1 );
  21019. setPoint( "cn3", 0, -h, -1 );
  21020. setPoint( "cn4", 0, h, -1 );
  21021. function setPoint( point, x, y, z ) {
  21022. vector.set( x, y, z );
  21023. projector.unprojectVector( vector, camera );
  21024. var points = scope.pointMap[ point ];
  21025. if ( points !== undefined ) {
  21026. for ( var i = 0, il = points.length; i < il; i ++ ) {
  21027. scope.geometry.vertices[ points[ i ] ].copy( vector );
  21028. }
  21029. }
  21030. }
  21031. this.geometry.verticesNeedUpdate = true;
  21032. };
  21033. }();
  21034. /**
  21035. * @author alteredq / http://alteredqualia.com/
  21036. * @author mrdoob / http://mrdoob.com/
  21037. * @author WestLangley / http://github.com/WestLangley
  21038. */
  21039. THREE.DirectionalLightHelper = function ( light, size ) {
  21040. THREE.Object3D.call( this );
  21041. this.light = light;
  21042. this.light.updateMatrixWorld();
  21043. this.matrixWorld = light.matrixWorld;
  21044. this.matrixAutoUpdate = false;
  21045. size = size || 1;
  21046. var geometry = new THREE.PlaneGeometry( size, size );
  21047. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  21048. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21049. this.lightPlane = new THREE.Mesh( geometry, material );
  21050. this.add( this.lightPlane );
  21051. geometry = new THREE.Geometry();
  21052. geometry.vertices.push( new THREE.Vector3() );
  21053. geometry.vertices.push( new THREE.Vector3() );
  21054. material = new THREE.LineBasicMaterial( { fog: false } );
  21055. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21056. this.targetLine = new THREE.Line( geometry, material );
  21057. this.add( this.targetLine );
  21058. this.update();
  21059. };
  21060. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21061. THREE.DirectionalLightHelper.prototype.dispose = function () {
  21062. this.lightPlane.geometry.dispose();
  21063. this.lightPlane.material.dispose();
  21064. this.targetLine.geometry.dispose();
  21065. this.targetLine.material.dispose();
  21066. };
  21067. THREE.DirectionalLightHelper.prototype.update = function () {
  21068. var v1 = new THREE.Vector3();
  21069. var v2 = new THREE.Vector3();
  21070. var v3 = new THREE.Vector3();
  21071. return function () {
  21072. v1.setFromMatrixPosition( this.light.matrixWorld );
  21073. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  21074. v3.subVectors( v2, v1 );
  21075. this.lightPlane.lookAt( v3 );
  21076. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21077. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  21078. this.targetLine.geometry.verticesNeedUpdate = true;
  21079. this.targetLine.material.color.copy( this.lightPlane.material.color );
  21080. }
  21081. }();
  21082. /**
  21083. * @author WestLangley / http://github.com/WestLangley
  21084. */
  21085. THREE.EdgesHelper = function ( object, hex ) {
  21086. var color = ( hex !== undefined ) ? hex : 0xffffff;
  21087. var edge = [ 0, 0 ], hash = {};
  21088. var sortFunction = function ( a, b ) { return a - b };
  21089. var keys = [ 'a', 'b', 'c' ];
  21090. var geometry = new THREE.BufferGeometry();
  21091. var geometry2 = object.geometry.clone();
  21092. geometry2.mergeVertices();
  21093. geometry2.computeFaceNormals();
  21094. var vertices = geometry2.vertices;
  21095. var faces = geometry2.faces;
  21096. var numEdges = 0;
  21097. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21098. var face = faces[ i ];
  21099. for ( var j = 0; j < 3; j ++ ) {
  21100. edge[ 0 ] = face[ keys[ j ] ];
  21101. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  21102. edge.sort( sortFunction );
  21103. var key = edge.toString();
  21104. if ( hash[ key ] === undefined ) {
  21105. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  21106. numEdges ++;
  21107. } else {
  21108. hash[ key ].face2 = i;
  21109. }
  21110. }
  21111. }
  21112. geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 );
  21113. var coords = geometry.attributes.position.array;
  21114. var index = 0;
  21115. for ( var key in hash ) {
  21116. var h = hash[ key ];
  21117. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) < 0.9999 ) { // hardwired const OK
  21118. var vertex = vertices[ h.vert1 ];
  21119. coords[ index ++ ] = vertex.x;
  21120. coords[ index ++ ] = vertex.y;
  21121. coords[ index ++ ] = vertex.z;
  21122. vertex = vertices[ h.vert2 ];
  21123. coords[ index ++ ] = vertex.x;
  21124. coords[ index ++ ] = vertex.y;
  21125. coords[ index ++ ] = vertex.z;
  21126. }
  21127. }
  21128. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  21129. this.matrixAutoUpdate = false;
  21130. this.matrixWorld = object.matrixWorld;
  21131. };
  21132. THREE.EdgesHelper.prototype = Object.create( THREE.Line.prototype );
  21133. /**
  21134. * @author mrdoob / http://mrdoob.com/
  21135. * @author WestLangley / http://github.com/WestLangley
  21136. */
  21137. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  21138. this.object = object;
  21139. this.size = ( size !== undefined ) ? size : 1;
  21140. var color = ( hex !== undefined ) ? hex : 0xffff00;
  21141. var width = ( linewidth !== undefined ) ? linewidth : 1;
  21142. var geometry = new THREE.Geometry();
  21143. var faces = this.object.geometry.faces;
  21144. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21145. geometry.vertices.push( new THREE.Vector3() );
  21146. geometry.vertices.push( new THREE.Vector3() );
  21147. }
  21148. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21149. this.matrixAutoUpdate = false;
  21150. this.normalMatrix = new THREE.Matrix3();
  21151. this.update();
  21152. };
  21153. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  21154. THREE.FaceNormalsHelper.prototype.update = ( function ( object ) {
  21155. var v1 = new THREE.Vector3();
  21156. return function ( object ) {
  21157. this.object.updateMatrixWorld( true );
  21158. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  21159. var vertices = this.geometry.vertices;
  21160. var faces = this.object.geometry.faces;
  21161. var worldMatrix = this.object.matrixWorld;
  21162. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21163. var face = faces[ i ];
  21164. v1.copy( face.normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  21165. var idx = 2 * i;
  21166. vertices[ idx ].copy( face.centroid ).applyMatrix4( worldMatrix );
  21167. vertices[ idx + 1 ].addVectors( vertices[ idx ], v1 );
  21168. }
  21169. this.geometry.verticesNeedUpdate = true;
  21170. return this;
  21171. }
  21172. }());
  21173. /**
  21174. * @author mrdoob / http://mrdoob.com/
  21175. */
  21176. THREE.GridHelper = function ( size, step ) {
  21177. var geometry = new THREE.Geometry();
  21178. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  21179. this.color1 = new THREE.Color( 0x444444 );
  21180. this.color2 = new THREE.Color( 0x888888 );
  21181. for ( var i = - size; i <= size; i += step ) {
  21182. geometry.vertices.push(
  21183. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  21184. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  21185. );
  21186. var color = i === 0 ? this.color1 : this.color2;
  21187. geometry.colors.push( color, color, color, color );
  21188. }
  21189. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  21190. };
  21191. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  21192. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  21193. this.color1.set( colorCenterLine );
  21194. this.color2.set( colorGrid );
  21195. this.geometry.colorsNeedUpdate = true;
  21196. }
  21197. /**
  21198. * @author alteredq / http://alteredqualia.com/
  21199. * @author mrdoob / http://mrdoob.com/
  21200. */
  21201. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  21202. THREE.Object3D.call( this );
  21203. this.light = light;
  21204. this.light.updateMatrixWorld();
  21205. this.matrixWorld = light.matrixWorld;
  21206. this.matrixAutoUpdate = false;
  21207. this.colors = [ new THREE.Color(), new THREE.Color() ];
  21208. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21209. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  21210. for ( var i = 0, il = 8; i < il; i ++ ) {
  21211. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  21212. }
  21213. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  21214. this.lightSphere = new THREE.Mesh( geometry, material );
  21215. this.add( this.lightSphere );
  21216. this.update();
  21217. };
  21218. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21219. THREE.HemisphereLightHelper.prototype.dispose = function () {
  21220. this.lightSphere.geometry.dispose();
  21221. this.lightSphere.material.dispose();
  21222. };
  21223. THREE.HemisphereLightHelper.prototype.update = function () {
  21224. var vector = new THREE.Vector3();
  21225. return function () {
  21226. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  21227. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  21228. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  21229. this.lightSphere.geometry.colorsNeedUpdate = true;
  21230. }
  21231. }();
  21232. /**
  21233. * @author alteredq / http://alteredqualia.com/
  21234. * @author mrdoob / http://mrdoob.com/
  21235. */
  21236. THREE.PointLightHelper = function ( light, sphereSize ) {
  21237. this.light = light;
  21238. this.light.updateMatrixWorld();
  21239. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21240. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  21241. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21242. THREE.Mesh.call( this, geometry, material );
  21243. this.matrixWorld = this.light.matrixWorld;
  21244. this.matrixAutoUpdate = false;
  21245. /*
  21246. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  21247. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  21248. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  21249. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  21250. var d = light.distance;
  21251. if ( d === 0.0 ) {
  21252. this.lightDistance.visible = false;
  21253. } else {
  21254. this.lightDistance.scale.set( d, d, d );
  21255. }
  21256. this.add( this.lightDistance );
  21257. */
  21258. };
  21259. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  21260. THREE.PointLightHelper.prototype.dispose = function () {
  21261. this.geometry.dispose();
  21262. this.material.dispose();
  21263. };
  21264. THREE.PointLightHelper.prototype.update = function () {
  21265. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21266. /*
  21267. var d = this.light.distance;
  21268. if ( d === 0.0 ) {
  21269. this.lightDistance.visible = false;
  21270. } else {
  21271. this.lightDistance.visible = true;
  21272. this.lightDistance.scale.set( d, d, d );
  21273. }
  21274. */
  21275. };
  21276. /**
  21277. * @author alteredq / http://alteredqualia.com/
  21278. * @author mrdoob / http://mrdoob.com/
  21279. * @author WestLangley / http://github.com/WestLangley
  21280. */
  21281. THREE.SpotLightHelper = function ( light ) {
  21282. THREE.Object3D.call( this );
  21283. this.light = light;
  21284. this.light.updateMatrixWorld();
  21285. this.matrixWorld = light.matrixWorld;
  21286. this.matrixAutoUpdate = false;
  21287. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  21288. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
  21289. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  21290. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  21291. this.cone = new THREE.Mesh( geometry, material );
  21292. this.add( this.cone );
  21293. this.update();
  21294. };
  21295. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21296. THREE.SpotLightHelper.prototype.dispose = function () {
  21297. this.cone.geometry.dispose();
  21298. this.cone.material.dispose();
  21299. };
  21300. THREE.SpotLightHelper.prototype.update = function () {
  21301. var vector = new THREE.Vector3();
  21302. var vector2 = new THREE.Vector3();
  21303. return function () {
  21304. var coneLength = this.light.distance ? this.light.distance : 10000;
  21305. var coneWidth = coneLength * Math.tan( this.light.angle );
  21306. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  21307. vector.setFromMatrixPosition( this.light.matrixWorld );
  21308. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  21309. this.cone.lookAt( vector2.sub( vector ) );
  21310. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21311. };
  21312. }();
  21313. /**
  21314. * @author mrdoob / http://mrdoob.com/
  21315. * @author WestLangley / http://github.com/WestLangley
  21316. */
  21317. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  21318. this.object = object;
  21319. this.size = ( size !== undefined ) ? size : 1;
  21320. var color = ( hex !== undefined ) ? hex : 0xff0000;
  21321. var width = ( linewidth !== undefined ) ? linewidth : 1;
  21322. var geometry = new THREE.Geometry();
  21323. var vertices = object.geometry.vertices;
  21324. var faces = object.geometry.faces;
  21325. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21326. var face = faces[ i ];
  21327. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21328. geometry.vertices.push( new THREE.Vector3() );
  21329. geometry.vertices.push( new THREE.Vector3() );
  21330. }
  21331. }
  21332. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21333. this.matrixAutoUpdate = false;
  21334. this.normalMatrix = new THREE.Matrix3();
  21335. this.update();
  21336. };
  21337. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  21338. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  21339. var v1 = new THREE.Vector3();
  21340. return function( object ) {
  21341. var keys = [ 'a', 'b', 'c', 'd' ];
  21342. this.object.updateMatrixWorld( true );
  21343. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  21344. var vertices = this.geometry.vertices;
  21345. var verts = this.object.geometry.vertices;
  21346. var faces = this.object.geometry.faces;
  21347. var worldMatrix = this.object.matrixWorld;
  21348. var idx = 0;
  21349. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21350. var face = faces[ i ];
  21351. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21352. var vertexId = face[ keys[ j ] ];
  21353. var vertex = verts[ vertexId ];
  21354. var normal = face.vertexNormals[ j ];
  21355. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21356. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  21357. v1.add( vertices[ idx ] );
  21358. idx = idx + 1;
  21359. vertices[ idx ].copy( v1 );
  21360. idx = idx + 1;
  21361. }
  21362. }
  21363. this.geometry.verticesNeedUpdate = true;
  21364. return this;
  21365. }
  21366. }());
  21367. /**
  21368. * @author mrdoob / http://mrdoob.com/
  21369. * @author WestLangley / http://github.com/WestLangley
  21370. */
  21371. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  21372. this.object = object;
  21373. this.size = ( size !== undefined ) ? size : 1;
  21374. var color = ( hex !== undefined ) ? hex : 0x0000ff;
  21375. var width = ( linewidth !== undefined ) ? linewidth : 1;
  21376. var geometry = new THREE.Geometry();
  21377. var vertices = object.geometry.vertices;
  21378. var faces = object.geometry.faces;
  21379. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21380. var face = faces[ i ];
  21381. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21382. geometry.vertices.push( new THREE.Vector3() );
  21383. geometry.vertices.push( new THREE.Vector3() );
  21384. }
  21385. }
  21386. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21387. this.matrixAutoUpdate = false;
  21388. this.update();
  21389. };
  21390. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  21391. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  21392. var v1 = new THREE.Vector3();
  21393. return function( object ) {
  21394. var keys = [ 'a', 'b', 'c', 'd' ];
  21395. this.object.updateMatrixWorld( true );
  21396. var vertices = this.geometry.vertices;
  21397. var verts = this.object.geometry.vertices;
  21398. var faces = this.object.geometry.faces;
  21399. var worldMatrix = this.object.matrixWorld;
  21400. var idx = 0;
  21401. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21402. var face = faces[ i ];
  21403. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21404. var vertexId = face[ keys[ j ] ];
  21405. var vertex = verts[ vertexId ];
  21406. var tangent = face.vertexTangents[ j ];
  21407. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21408. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  21409. v1.add( vertices[ idx ] );
  21410. idx = idx + 1;
  21411. vertices[ idx ].copy( v1 );
  21412. idx = idx + 1;
  21413. }
  21414. }
  21415. this.geometry.verticesNeedUpdate = true;
  21416. return this;
  21417. }
  21418. }());
  21419. /**
  21420. * @author mrdoob / http://mrdoob.com/
  21421. */
  21422. THREE.WireframeHelper = function ( object, hex ) {
  21423. var color = ( hex !== undefined ) ? hex : 0xffffff;
  21424. var edge = [ 0, 0 ], hash = {};
  21425. var sortFunction = function ( a, b ) { return a - b };
  21426. var keys = [ 'a', 'b', 'c' ];
  21427. var geometry = new THREE.BufferGeometry();
  21428. if ( object.geometry instanceof THREE.Geometry ) {
  21429. var vertices = object.geometry.vertices;
  21430. var faces = object.geometry.faces;
  21431. var numEdges = 0;
  21432. // allocate maximal size
  21433. var edges = new Uint32Array( 6 * faces.length );
  21434. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21435. var face = faces[ i ];
  21436. for ( var j = 0; j < 3; j ++ ) {
  21437. edge[ 0 ] = face[ keys[ j ] ];
  21438. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  21439. edge.sort( sortFunction );
  21440. var key = edge.toString();
  21441. if ( hash[ key ] === undefined ) {
  21442. edges[ 2 * numEdges ] = edge[ 0 ];
  21443. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  21444. hash[ key ] = true;
  21445. numEdges ++;
  21446. }
  21447. }
  21448. }
  21449. geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 );
  21450. var coords = geometry.attributes.position.array;
  21451. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  21452. for ( var j = 0; j < 2; j ++ ) {
  21453. var vertex = vertices[ edges [ 2 * i + j] ];
  21454. var index = 6 * i + 3 * j;
  21455. coords[ index + 0 ] = vertex.x;
  21456. coords[ index + 1 ] = vertex.y;
  21457. coords[ index + 2 ] = vertex.z;
  21458. }
  21459. }
  21460. } else if ( object.geometry instanceof THREE.BufferGeometry && object.geometry.attributes.index !== undefined ) { // indexed BufferGeometry
  21461. var vertices = object.geometry.attributes.position.array;
  21462. var indices = object.geometry.attributes.index.array;
  21463. var offsets = object.geometry.offsets;
  21464. var numEdges = 0;
  21465. // allocate maximal size
  21466. var edges = new Uint32Array( 2 * indices.length );
  21467. for ( var o = 0, ol = offsets.length; o < ol; ++ o ) {
  21468. var start = offsets[ o ].start;
  21469. var count = offsets[ o ].count;
  21470. var index = offsets[ o ].index;
  21471. for ( var i = start, il = start + count; i < il; i += 3 ) {
  21472. for ( var j = 0; j < 3; j ++ ) {
  21473. edge[ 0 ] = index + indices[ i + j ];
  21474. edge[ 1 ] = index + indices[ i + ( j + 1 ) % 3 ];
  21475. edge.sort( sortFunction );
  21476. var key = edge.toString();
  21477. if ( hash[ key ] === undefined ) {
  21478. edges[ 2 * numEdges ] = edge[ 0 ];
  21479. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  21480. hash[ key ] = true;
  21481. numEdges ++;
  21482. }
  21483. }
  21484. }
  21485. }
  21486. geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 );
  21487. var coords = geometry.attributes.position.array;
  21488. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  21489. for ( var j = 0; j < 2; j ++ ) {
  21490. var index = 6 * i + 3 * j;
  21491. var index2 = 3 * edges[ 2 * i + j];
  21492. coords[ index + 0 ] = vertices[ index2 ];
  21493. coords[ index + 1 ] = vertices[ index2 + 1 ];
  21494. coords[ index + 2 ] = vertices[ index2 + 2 ];
  21495. }
  21496. }
  21497. } else if ( object.geometry instanceof THREE.BufferGeometry ) { // non-indexed BufferGeometry
  21498. var vertices = object.geometry.attributes.position.array;
  21499. var numEdges = vertices.length / 3;
  21500. var numTris = numEdges / 3;
  21501. geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 );
  21502. var coords = geometry.attributes.position.array;
  21503. for ( var i = 0, l = numTris; i < l; i ++ ) {
  21504. for ( var j = 0; j < 3; j ++ ) {
  21505. var index = 18 * i + 6 * j;
  21506. var index1 = 9 * i + 3 * j;
  21507. coords[ index + 0 ] = vertices[ index1 ];
  21508. coords[ index + 1 ] = vertices[ index1 + 1 ];
  21509. coords[ index + 2 ] = vertices[ index1 + 2 ];
  21510. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  21511. coords[ index + 3 ] = vertices[ index2 ];
  21512. coords[ index + 4 ] = vertices[ index2 + 1 ];
  21513. coords[ index + 5 ] = vertices[ index2 + 2 ];
  21514. }
  21515. }
  21516. }
  21517. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  21518. this.matrixAutoUpdate = false;
  21519. this.matrixWorld = object.matrixWorld;
  21520. };
  21521. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  21522. /**
  21523. * @author alteredq / http://alteredqualia.com/
  21524. */
  21525. THREE.ImmediateRenderObject = function () {
  21526. THREE.Object3D.call( this );
  21527. this.render = function ( renderCallback ) { };
  21528. };
  21529. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  21530. /**
  21531. * @author mikael emtinger / http://gomo.se/
  21532. * @author alteredq / http://alteredqualia.com/
  21533. */
  21534. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  21535. THREE.Object3D.call( this );
  21536. this.lensFlares = [];
  21537. this.positionScreen = new THREE.Vector3();
  21538. this.customUpdateCallback = undefined;
  21539. if( texture !== undefined ) {
  21540. this.add( texture, size, distance, blending, color );
  21541. }
  21542. };
  21543. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  21544. /*
  21545. * Add: adds another flare
  21546. */
  21547. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  21548. if( size === undefined ) size = -1;
  21549. if( distance === undefined ) distance = 0;
  21550. if( opacity === undefined ) opacity = 1;
  21551. if( color === undefined ) color = new THREE.Color( 0xffffff );
  21552. if( blending === undefined ) blending = THREE.NormalBlending;
  21553. distance = Math.min( distance, Math.max( 0, distance ) );
  21554. this.lensFlares.push( { texture: texture, // THREE.Texture
  21555. size: size, // size in pixels (-1 = use texture.width)
  21556. distance: distance, // distance (0-1) from light source (0=at light source)
  21557. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  21558. scale: 1, // scale
  21559. rotation: 1, // rotation
  21560. opacity: opacity, // opacity
  21561. color: color, // color
  21562. blending: blending } ); // blending
  21563. };
  21564. /*
  21565. * Update lens flares update positions on all flares based on the screen position
  21566. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  21567. */
  21568. THREE.LensFlare.prototype.updateLensFlares = function () {
  21569. var f, fl = this.lensFlares.length;
  21570. var flare;
  21571. var vecX = -this.positionScreen.x * 2;
  21572. var vecY = -this.positionScreen.y * 2;
  21573. for( f = 0; f < fl; f ++ ) {
  21574. flare = this.lensFlares[ f ];
  21575. flare.x = this.positionScreen.x + vecX * flare.distance;
  21576. flare.y = this.positionScreen.y + vecY * flare.distance;
  21577. flare.wantedRotation = flare.x * Math.PI * 0.25;
  21578. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  21579. }
  21580. };
  21581. /**
  21582. * @author alteredq / http://alteredqualia.com/
  21583. */
  21584. THREE.MorphBlendMesh = function( geometry, material ) {
  21585. THREE.Mesh.call( this, geometry, material );
  21586. this.animationsMap = {};
  21587. this.animationsList = [];
  21588. // prepare default animation
  21589. // (all frames played together in 1 second)
  21590. var numFrames = this.geometry.morphTargets.length;
  21591. var name = "__default";
  21592. var startFrame = 0;
  21593. var endFrame = numFrames - 1;
  21594. var fps = numFrames / 1;
  21595. this.createAnimation( name, startFrame, endFrame, fps );
  21596. this.setAnimationWeight( name, 1 );
  21597. };
  21598. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  21599. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  21600. var animation = {
  21601. startFrame: start,
  21602. endFrame: end,
  21603. length: end - start + 1,
  21604. fps: fps,
  21605. duration: ( end - start ) / fps,
  21606. lastFrame: 0,
  21607. currentFrame: 0,
  21608. active: false,
  21609. time: 0,
  21610. direction: 1,
  21611. weight: 1,
  21612. directionBackwards: false,
  21613. mirroredLoop: false
  21614. };
  21615. this.animationsMap[ name ] = animation;
  21616. this.animationsList.push( animation );
  21617. };
  21618. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21619. var pattern = /([a-z]+)(\d+)/;
  21620. var firstAnimation, frameRanges = {};
  21621. var geometry = this.geometry;
  21622. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21623. var morph = geometry.morphTargets[ i ];
  21624. var chunks = morph.name.match( pattern );
  21625. if ( chunks && chunks.length > 1 ) {
  21626. var name = chunks[ 1 ];
  21627. var num = chunks[ 2 ];
  21628. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  21629. var range = frameRanges[ name ];
  21630. if ( i < range.start ) range.start = i;
  21631. if ( i > range.end ) range.end = i;
  21632. if ( ! firstAnimation ) firstAnimation = name;
  21633. }
  21634. }
  21635. for ( var name in frameRanges ) {
  21636. var range = frameRanges[ name ];
  21637. this.createAnimation( name, range.start, range.end, fps );
  21638. }
  21639. this.firstAnimation = firstAnimation;
  21640. };
  21641. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  21642. var animation = this.animationsMap[ name ];
  21643. if ( animation ) {
  21644. animation.direction = 1;
  21645. animation.directionBackwards = false;
  21646. }
  21647. };
  21648. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  21649. var animation = this.animationsMap[ name ];
  21650. if ( animation ) {
  21651. animation.direction = -1;
  21652. animation.directionBackwards = true;
  21653. }
  21654. };
  21655. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  21656. var animation = this.animationsMap[ name ];
  21657. if ( animation ) {
  21658. animation.fps = fps;
  21659. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21660. }
  21661. };
  21662. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21663. var animation = this.animationsMap[ name ];
  21664. if ( animation ) {
  21665. animation.duration = duration;
  21666. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21667. }
  21668. };
  21669. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21670. var animation = this.animationsMap[ name ];
  21671. if ( animation ) {
  21672. animation.weight = weight;
  21673. }
  21674. };
  21675. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21676. var animation = this.animationsMap[ name ];
  21677. if ( animation ) {
  21678. animation.time = time;
  21679. }
  21680. };
  21681. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21682. var time = 0;
  21683. var animation = this.animationsMap[ name ];
  21684. if ( animation ) {
  21685. time = animation.time;
  21686. }
  21687. return time;
  21688. };
  21689. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21690. var duration = -1;
  21691. var animation = this.animationsMap[ name ];
  21692. if ( animation ) {
  21693. duration = animation.duration;
  21694. }
  21695. return duration;
  21696. };
  21697. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21698. var animation = this.animationsMap[ name ];
  21699. if ( animation ) {
  21700. animation.time = 0;
  21701. animation.active = true;
  21702. } else {
  21703. console.warn( "animation[" + name + "] undefined" );
  21704. }
  21705. };
  21706. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21707. var animation = this.animationsMap[ name ];
  21708. if ( animation ) {
  21709. animation.active = false;
  21710. }
  21711. };
  21712. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  21713. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21714. var animation = this.animationsList[ i ];
  21715. if ( ! animation.active ) continue;
  21716. var frameTime = animation.duration / animation.length;
  21717. animation.time += animation.direction * delta;
  21718. if ( animation.mirroredLoop ) {
  21719. if ( animation.time > animation.duration || animation.time < 0 ) {
  21720. animation.direction *= -1;
  21721. if ( animation.time > animation.duration ) {
  21722. animation.time = animation.duration;
  21723. animation.directionBackwards = true;
  21724. }
  21725. if ( animation.time < 0 ) {
  21726. animation.time = 0;
  21727. animation.directionBackwards = false;
  21728. }
  21729. }
  21730. } else {
  21731. animation.time = animation.time % animation.duration;
  21732. if ( animation.time < 0 ) animation.time += animation.duration;
  21733. }
  21734. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21735. var weight = animation.weight;
  21736. if ( keyframe !== animation.currentFrame ) {
  21737. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21738. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21739. this.morphTargetInfluences[ keyframe ] = 0;
  21740. animation.lastFrame = animation.currentFrame;
  21741. animation.currentFrame = keyframe;
  21742. }
  21743. var mix = ( animation.time % frameTime ) / frameTime;
  21744. if ( animation.directionBackwards ) mix = 1 - mix;
  21745. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21746. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21747. }
  21748. };
  21749. /**
  21750. * @author mikael emtinger / http://gomo.se/
  21751. * @author alteredq / http://alteredqualia.com/
  21752. */
  21753. THREE.LensFlarePlugin = function () {
  21754. var _gl, _renderer, _precision, _lensFlare = {};
  21755. this.init = function ( renderer ) {
  21756. _gl = renderer.context;
  21757. _renderer = renderer;
  21758. _precision = renderer.getPrecision();
  21759. _lensFlare.vertices = new Float32Array( 8 + 8 );
  21760. _lensFlare.faces = new Uint16Array( 6 );
  21761. var i = 0;
  21762. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  21763. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  21764. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  21765. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  21766. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21767. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21768. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  21769. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  21770. i = 0;
  21771. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  21772. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  21773. // buffers
  21774. _lensFlare.vertexBuffer = _gl.createBuffer();
  21775. _lensFlare.elementBuffer = _gl.createBuffer();
  21776. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21777. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  21778. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21779. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  21780. // textures
  21781. _lensFlare.tempTexture = _gl.createTexture();
  21782. _lensFlare.occlusionTexture = _gl.createTexture();
  21783. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21784. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21785. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21786. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21787. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21788. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21789. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21790. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21791. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21792. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21793. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21794. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21795. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21796. _lensFlare.hasVertexTexture = false;
  21797. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  21798. } else {
  21799. _lensFlare.hasVertexTexture = true;
  21800. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  21801. }
  21802. _lensFlare.attributes = {};
  21803. _lensFlare.uniforms = {};
  21804. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21805. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21806. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21807. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21808. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21809. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21810. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21811. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21812. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21813. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21814. };
  21815. /*
  21816. * Render lens flares
  21817. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21818. * reads these back and calculates occlusion.
  21819. * Then _lensFlare.update_lensFlares() is called to re-position and
  21820. * update transparency of flares. Then they are rendered.
  21821. *
  21822. */
  21823. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21824. var flares = scene.__webglFlares,
  21825. nFlares = flares.length;
  21826. if ( ! nFlares ) return;
  21827. var tempPosition = new THREE.Vector3();
  21828. var invAspect = viewportHeight / viewportWidth,
  21829. halfViewportWidth = viewportWidth * 0.5,
  21830. halfViewportHeight = viewportHeight * 0.5;
  21831. var size = 16 / viewportHeight,
  21832. scale = new THREE.Vector2( size * invAspect, size );
  21833. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21834. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21835. var uniforms = _lensFlare.uniforms,
  21836. attributes = _lensFlare.attributes;
  21837. // set _lensFlare program and reset blending
  21838. _gl.useProgram( _lensFlare.program );
  21839. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21840. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21841. // loop through all lens flares to update their occlusion and positions
  21842. // setup gl and common used attribs/unforms
  21843. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21844. _gl.uniform1i( uniforms.map, 1 );
  21845. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21846. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21847. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21848. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21849. _gl.disable( _gl.CULL_FACE );
  21850. _gl.depthMask( false );
  21851. var i, j, jl, flare, sprite;
  21852. for ( i = 0; i < nFlares; i ++ ) {
  21853. size = 16 / viewportHeight;
  21854. scale.set( size * invAspect, size );
  21855. // calc object screen position
  21856. flare = flares[ i ];
  21857. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21858. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  21859. tempPosition.applyProjection( camera.projectionMatrix );
  21860. // setup arrays for gl programs
  21861. screenPosition.copy( tempPosition )
  21862. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21863. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21864. // screen cull
  21865. if ( _lensFlare.hasVertexTexture || (
  21866. screenPositionPixels.x > 0 &&
  21867. screenPositionPixels.x < viewportWidth &&
  21868. screenPositionPixels.y > 0 &&
  21869. screenPositionPixels.y < viewportHeight ) ) {
  21870. // save current RGB to temp texture
  21871. _gl.activeTexture( _gl.TEXTURE1 );
  21872. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21873. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21874. // render pink quad
  21875. _gl.uniform1i( uniforms.renderType, 0 );
  21876. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21877. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21878. _gl.disable( _gl.BLEND );
  21879. _gl.enable( _gl.DEPTH_TEST );
  21880. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21881. // copy result to occlusionMap
  21882. _gl.activeTexture( _gl.TEXTURE0 );
  21883. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21884. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21885. // restore graphics
  21886. _gl.uniform1i( uniforms.renderType, 1 );
  21887. _gl.disable( _gl.DEPTH_TEST );
  21888. _gl.activeTexture( _gl.TEXTURE1 );
  21889. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21890. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21891. // update object positions
  21892. flare.positionScreen.copy( screenPosition )
  21893. if ( flare.customUpdateCallback ) {
  21894. flare.customUpdateCallback( flare );
  21895. } else {
  21896. flare.updateLensFlares();
  21897. }
  21898. // render flares
  21899. _gl.uniform1i( uniforms.renderType, 2 );
  21900. _gl.enable( _gl.BLEND );
  21901. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21902. sprite = flare.lensFlares[ j ];
  21903. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21904. screenPosition.x = sprite.x;
  21905. screenPosition.y = sprite.y;
  21906. screenPosition.z = sprite.z;
  21907. size = sprite.size * sprite.scale / viewportHeight;
  21908. scale.x = size * invAspect;
  21909. scale.y = size;
  21910. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21911. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21912. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21913. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21914. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21915. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21916. _renderer.setTexture( sprite.texture, 1 );
  21917. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21918. }
  21919. }
  21920. }
  21921. }
  21922. // restore gl
  21923. _gl.enable( _gl.CULL_FACE );
  21924. _gl.enable( _gl.DEPTH_TEST );
  21925. _gl.depthMask( true );
  21926. };
  21927. function createProgram ( shader, precision ) {
  21928. var program = _gl.createProgram();
  21929. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21930. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21931. var prefix = "precision " + precision + " float;\n";
  21932. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21933. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21934. _gl.compileShader( fragmentShader );
  21935. _gl.compileShader( vertexShader );
  21936. _gl.attachShader( program, fragmentShader );
  21937. _gl.attachShader( program, vertexShader );
  21938. _gl.linkProgram( program );
  21939. return program;
  21940. };
  21941. };
  21942. /**
  21943. * @author alteredq / http://alteredqualia.com/
  21944. */
  21945. THREE.ShadowMapPlugin = function () {
  21946. var _gl,
  21947. _renderer,
  21948. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21949. _frustum = new THREE.Frustum(),
  21950. _projScreenMatrix = new THREE.Matrix4(),
  21951. _min = new THREE.Vector3(),
  21952. _max = new THREE.Vector3(),
  21953. _matrixPosition = new THREE.Vector3();
  21954. this.init = function ( renderer ) {
  21955. _gl = renderer.context;
  21956. _renderer = renderer;
  21957. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21958. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21959. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21960. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21961. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21962. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21963. _depthMaterial._shadowPass = true;
  21964. _depthMaterialMorph._shadowPass = true;
  21965. _depthMaterialSkin._shadowPass = true;
  21966. _depthMaterialMorphSkin._shadowPass = true;
  21967. };
  21968. this.render = function ( scene, camera ) {
  21969. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21970. this.update( scene, camera );
  21971. };
  21972. this.update = function ( scene, camera ) {
  21973. var i, il, j, jl, n,
  21974. shadowMap, shadowMatrix, shadowCamera,
  21975. program, buffer, material,
  21976. webglObject, object, light,
  21977. renderList,
  21978. lights = [],
  21979. k = 0,
  21980. fog = null;
  21981. // set GL state for depth map
  21982. _gl.clearColor( 1, 1, 1, 1 );
  21983. _gl.disable( _gl.BLEND );
  21984. _gl.enable( _gl.CULL_FACE );
  21985. _gl.frontFace( _gl.CCW );
  21986. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21987. _gl.cullFace( _gl.FRONT );
  21988. } else {
  21989. _gl.cullFace( _gl.BACK );
  21990. }
  21991. _renderer.setDepthTest( true );
  21992. // preprocess lights
  21993. // - skip lights that are not casting shadows
  21994. // - create virtual lights for cascaded shadow maps
  21995. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21996. light = scene.__lights[ i ];
  21997. if ( ! light.castShadow ) continue;
  21998. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21999. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  22000. var virtualLight;
  22001. if ( ! light.shadowCascadeArray[ n ] ) {
  22002. virtualLight = createVirtualLight( light, n );
  22003. virtualLight.originalCamera = camera;
  22004. var gyro = new THREE.Gyroscope();
  22005. gyro.position = light.shadowCascadeOffset;
  22006. gyro.add( virtualLight );
  22007. gyro.add( virtualLight.target );
  22008. camera.add( gyro );
  22009. light.shadowCascadeArray[ n ] = virtualLight;
  22010. console.log( "Created virtualLight", virtualLight );
  22011. } else {
  22012. virtualLight = light.shadowCascadeArray[ n ];
  22013. }
  22014. updateVirtualLight( light, n );
  22015. lights[ k ] = virtualLight;
  22016. k ++;
  22017. }
  22018. } else {
  22019. lights[ k ] = light;
  22020. k ++;
  22021. }
  22022. }
  22023. // render depth map
  22024. for ( i = 0, il = lights.length; i < il; i ++ ) {
  22025. light = lights[ i ];
  22026. if ( ! light.shadowMap ) {
  22027. var shadowFilter = THREE.LinearFilter;
  22028. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  22029. shadowFilter = THREE.NearestFilter;
  22030. }
  22031. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  22032. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  22033. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  22034. light.shadowMatrix = new THREE.Matrix4();
  22035. }
  22036. if ( ! light.shadowCamera ) {
  22037. if ( light instanceof THREE.SpotLight ) {
  22038. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  22039. } else if ( light instanceof THREE.DirectionalLight ) {
  22040. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  22041. } else {
  22042. console.error( "Unsupported light type for shadow" );
  22043. continue;
  22044. }
  22045. scene.add( light.shadowCamera );
  22046. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  22047. }
  22048. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  22049. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  22050. light.shadowCamera.add( light.cameraHelper );
  22051. }
  22052. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  22053. updateShadowCamera( camera, light );
  22054. }
  22055. shadowMap = light.shadowMap;
  22056. shadowMatrix = light.shadowMatrix;
  22057. shadowCamera = light.shadowCamera;
  22058. shadowCamera.position.setFromMatrixPosition( light.matrixWorld );
  22059. _matrixPosition.setFromMatrixPosition( light.target.matrixWorld );
  22060. shadowCamera.lookAt( _matrixPosition );
  22061. shadowCamera.updateMatrixWorld();
  22062. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  22063. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  22064. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  22065. // compute shadow matrix
  22066. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  22067. 0.0, 0.5, 0.0, 0.5,
  22068. 0.0, 0.0, 0.5, 0.5,
  22069. 0.0, 0.0, 0.0, 1.0 );
  22070. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  22071. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  22072. // update camera matrices and frustum
  22073. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  22074. _frustum.setFromMatrix( _projScreenMatrix );
  22075. // render shadow map
  22076. _renderer.setRenderTarget( shadowMap );
  22077. _renderer.clear();
  22078. // set object matrices & frustum culling
  22079. renderList = scene.__webglObjects;
  22080. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22081. webglObject = renderList[ j ];
  22082. object = webglObject.object;
  22083. webglObject.render = false;
  22084. if ( object.visible && object.castShadow ) {
  22085. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  22086. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  22087. webglObject.render = true;
  22088. }
  22089. }
  22090. }
  22091. // render regular objects
  22092. var objectMaterial, useMorphing, useSkinning;
  22093. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22094. webglObject = renderList[ j ];
  22095. if ( webglObject.render ) {
  22096. object = webglObject.object;
  22097. buffer = webglObject.buffer;
  22098. // culling is overriden globally for all objects
  22099. // while rendering depth map
  22100. // need to deal with MeshFaceMaterial somehow
  22101. // in that case just use the first of material.materials for now
  22102. // (proper solution would require to break objects by materials
  22103. // similarly to regular rendering and then set corresponding
  22104. // depth materials per each chunk instead of just once per object)
  22105. objectMaterial = getObjectMaterial( object );
  22106. useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  22107. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  22108. if ( object.customDepthMaterial ) {
  22109. material = object.customDepthMaterial;
  22110. } else if ( useSkinning ) {
  22111. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  22112. } else if ( useMorphing ) {
  22113. material = _depthMaterialMorph;
  22114. } else {
  22115. material = _depthMaterial;
  22116. }
  22117. if ( buffer instanceof THREE.BufferGeometry ) {
  22118. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  22119. } else {
  22120. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  22121. }
  22122. }
  22123. }
  22124. // set matrices and render immediate objects
  22125. renderList = scene.__webglObjectsImmediate;
  22126. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22127. webglObject = renderList[ j ];
  22128. object = webglObject.object;
  22129. if ( object.visible && object.castShadow ) {
  22130. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  22131. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  22132. }
  22133. }
  22134. }
  22135. // restore GL state
  22136. var clearColor = _renderer.getClearColor(),
  22137. clearAlpha = _renderer.getClearAlpha();
  22138. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  22139. _gl.enable( _gl.BLEND );
  22140. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  22141. _gl.cullFace( _gl.BACK );
  22142. }
  22143. };
  22144. function createVirtualLight( light, cascade ) {
  22145. var virtualLight = new THREE.DirectionalLight();
  22146. virtualLight.isVirtual = true;
  22147. virtualLight.onlyShadow = true;
  22148. virtualLight.castShadow = true;
  22149. virtualLight.shadowCameraNear = light.shadowCameraNear;
  22150. virtualLight.shadowCameraFar = light.shadowCameraFar;
  22151. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  22152. virtualLight.shadowCameraRight = light.shadowCameraRight;
  22153. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  22154. virtualLight.shadowCameraTop = light.shadowCameraTop;
  22155. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  22156. virtualLight.shadowDarkness = light.shadowDarkness;
  22157. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  22158. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  22159. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  22160. virtualLight.pointsWorld = [];
  22161. virtualLight.pointsFrustum = [];
  22162. var pointsWorld = virtualLight.pointsWorld,
  22163. pointsFrustum = virtualLight.pointsFrustum;
  22164. for ( var i = 0; i < 8; i ++ ) {
  22165. pointsWorld[ i ] = new THREE.Vector3();
  22166. pointsFrustum[ i ] = new THREE.Vector3();
  22167. }
  22168. var nearZ = light.shadowCascadeNearZ[ cascade ];
  22169. var farZ = light.shadowCascadeFarZ[ cascade ];
  22170. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  22171. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  22172. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  22173. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  22174. pointsFrustum[ 4 ].set( -1, -1, farZ );
  22175. pointsFrustum[ 5 ].set( 1, -1, farZ );
  22176. pointsFrustum[ 6 ].set( -1, 1, farZ );
  22177. pointsFrustum[ 7 ].set( 1, 1, farZ );
  22178. return virtualLight;
  22179. }
  22180. // Synchronize virtual light with the original light
  22181. function updateVirtualLight( light, cascade ) {
  22182. var virtualLight = light.shadowCascadeArray[ cascade ];
  22183. virtualLight.position.copy( light.position );
  22184. virtualLight.target.position.copy( light.target.position );
  22185. virtualLight.lookAt( virtualLight.target );
  22186. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  22187. virtualLight.shadowDarkness = light.shadowDarkness;
  22188. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  22189. var nearZ = light.shadowCascadeNearZ[ cascade ];
  22190. var farZ = light.shadowCascadeFarZ[ cascade ];
  22191. var pointsFrustum = virtualLight.pointsFrustum;
  22192. pointsFrustum[ 0 ].z = nearZ;
  22193. pointsFrustum[ 1 ].z = nearZ;
  22194. pointsFrustum[ 2 ].z = nearZ;
  22195. pointsFrustum[ 3 ].z = nearZ;
  22196. pointsFrustum[ 4 ].z = farZ;
  22197. pointsFrustum[ 5 ].z = farZ;
  22198. pointsFrustum[ 6 ].z = farZ;
  22199. pointsFrustum[ 7 ].z = farZ;
  22200. }
  22201. // Fit shadow camera's ortho frustum to camera frustum
  22202. function updateShadowCamera( camera, light ) {
  22203. var shadowCamera = light.shadowCamera,
  22204. pointsFrustum = light.pointsFrustum,
  22205. pointsWorld = light.pointsWorld;
  22206. _min.set( Infinity, Infinity, Infinity );
  22207. _max.set( -Infinity, -Infinity, -Infinity );
  22208. for ( var i = 0; i < 8; i ++ ) {
  22209. var p = pointsWorld[ i ];
  22210. p.copy( pointsFrustum[ i ] );
  22211. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  22212. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  22213. if ( p.x < _min.x ) _min.x = p.x;
  22214. if ( p.x > _max.x ) _max.x = p.x;
  22215. if ( p.y < _min.y ) _min.y = p.y;
  22216. if ( p.y > _max.y ) _max.y = p.y;
  22217. if ( p.z < _min.z ) _min.z = p.z;
  22218. if ( p.z > _max.z ) _max.z = p.z;
  22219. }
  22220. shadowCamera.left = _min.x;
  22221. shadowCamera.right = _max.x;
  22222. shadowCamera.top = _max.y;
  22223. shadowCamera.bottom = _min.y;
  22224. // can't really fit near/far
  22225. //shadowCamera.near = _min.z;
  22226. //shadowCamera.far = _max.z;
  22227. shadowCamera.updateProjectionMatrix();
  22228. }
  22229. // For the moment just ignore objects that have multiple materials with different animation methods
  22230. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  22231. function getObjectMaterial( object ) {
  22232. return object.material instanceof THREE.MeshFaceMaterial
  22233. ? object.material.materials[ 0 ]
  22234. : object.material;
  22235. };
  22236. };
  22237. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  22238. /**
  22239. * @author mikael emtinger / http://gomo.se/
  22240. * @author alteredq / http://alteredqualia.com/
  22241. */
  22242. THREE.SpritePlugin = function () {
  22243. var _gl, _renderer, _texture;
  22244. var vertices, faces, vertexBuffer, elementBuffer;
  22245. var program, attributes, uniforms;
  22246. this.init = function ( renderer ) {
  22247. _gl = renderer.context;
  22248. _renderer = renderer;
  22249. vertices = new Float32Array( [
  22250. - 0.5, - 0.5, 0, 0,
  22251. 0.5, - 0.5, 1, 0,
  22252. 0.5, 0.5, 1, 1,
  22253. - 0.5, 0.5, 0, 1
  22254. ] );
  22255. faces = new Uint16Array( [
  22256. 0, 1, 2,
  22257. 0, 2, 3
  22258. ] );
  22259. vertexBuffer = _gl.createBuffer();
  22260. elementBuffer = _gl.createBuffer();
  22261. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  22262. _gl.bufferData( _gl.ARRAY_BUFFER, vertices, _gl.STATIC_DRAW );
  22263. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  22264. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faces, _gl.STATIC_DRAW );
  22265. program = createProgram();
  22266. attributes = {
  22267. position: _gl.getAttribLocation ( program, 'position' ),
  22268. uv: _gl.getAttribLocation ( program, 'uv' )
  22269. };
  22270. uniforms = {
  22271. uvOffset: _gl.getUniformLocation( program, 'uvOffset' ),
  22272. uvScale: _gl.getUniformLocation( program, 'uvScale' ),
  22273. rotation: _gl.getUniformLocation( program, 'rotation' ),
  22274. scale: _gl.getUniformLocation( program, 'scale' ),
  22275. color: _gl.getUniformLocation( program, 'color' ),
  22276. map: _gl.getUniformLocation( program, 'map' ),
  22277. opacity: _gl.getUniformLocation( program, 'opacity' ),
  22278. modelViewMatrix: _gl.getUniformLocation( program, 'modelViewMatrix' ),
  22279. projectionMatrix: _gl.getUniformLocation( program, 'projectionMatrix' ),
  22280. fogType: _gl.getUniformLocation( program, 'fogType' ),
  22281. fogDensity: _gl.getUniformLocation( program, 'fogDensity' ),
  22282. fogNear: _gl.getUniformLocation( program, 'fogNear' ),
  22283. fogFar: _gl.getUniformLocation( program, 'fogFar' ),
  22284. fogColor: _gl.getUniformLocation( program, 'fogColor' ),
  22285. alphaTest: _gl.getUniformLocation( program, 'alphaTest' )
  22286. };
  22287. var canvas = document.createElement( 'canvas' );
  22288. canvas.width = 8;
  22289. canvas.height = 8;
  22290. var context = canvas.getContext( '2d' );
  22291. context.fillStyle = '#ffffff';
  22292. context.fillRect( 0, 0, canvas.width, canvas.height );
  22293. _texture = new THREE.Texture( canvas );
  22294. _texture.needsUpdate = true;
  22295. };
  22296. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  22297. var sprites = scene.__webglSprites,
  22298. nSprites = sprites.length;
  22299. if ( ! nSprites ) return;
  22300. // setup gl
  22301. _gl.useProgram( program );
  22302. _gl.enableVertexAttribArray( attributes.position );
  22303. _gl.enableVertexAttribArray( attributes.uv );
  22304. _gl.disable( _gl.CULL_FACE );
  22305. _gl.enable( _gl.BLEND );
  22306. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  22307. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  22308. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  22309. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  22310. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  22311. _gl.activeTexture( _gl.TEXTURE0 );
  22312. _gl.uniform1i( uniforms.map, 0 );
  22313. var oldFogType = 0;
  22314. var sceneFogType = 0;
  22315. var fog = scene.fog;
  22316. if ( fog ) {
  22317. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  22318. if ( fog instanceof THREE.Fog ) {
  22319. _gl.uniform1f( uniforms.fogNear, fog.near );
  22320. _gl.uniform1f( uniforms.fogFar, fog.far );
  22321. _gl.uniform1i( uniforms.fogType, 1 );
  22322. oldFogType = 1;
  22323. sceneFogType = 1;
  22324. } else if ( fog instanceof THREE.FogExp2 ) {
  22325. _gl.uniform1f( uniforms.fogDensity, fog.density );
  22326. _gl.uniform1i( uniforms.fogType, 2 );
  22327. oldFogType = 2;
  22328. sceneFogType = 2;
  22329. }
  22330. } else {
  22331. _gl.uniform1i( uniforms.fogType, 0 );
  22332. oldFogType = 0;
  22333. sceneFogType = 0;
  22334. }
  22335. // update positions and sort
  22336. var i, sprite, material, fogType, scale = [];
  22337. for( i = 0; i < nSprites; i ++ ) {
  22338. sprite = sprites[ i ];
  22339. material = sprite.material;
  22340. if ( sprite.visible === false ) continue;
  22341. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  22342. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  22343. }
  22344. sprites.sort( painterSortStable );
  22345. // render all sprites
  22346. for( i = 0; i < nSprites; i ++ ) {
  22347. sprite = sprites[ i ];
  22348. if ( sprite.visible === false ) continue;
  22349. material = sprite.material;
  22350. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  22351. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  22352. scale[ 0 ] = sprite.scale.x;
  22353. scale[ 1 ] = sprite.scale.y;
  22354. if ( scene.fog && material.fog ) {
  22355. fogType = sceneFogType;
  22356. } else {
  22357. fogType = 0;
  22358. }
  22359. if ( oldFogType !== fogType ) {
  22360. _gl.uniform1i( uniforms.fogType, fogType );
  22361. oldFogType = fogType;
  22362. }
  22363. if ( material.map !== null ) {
  22364. _gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  22365. _gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  22366. } else {
  22367. _gl.uniform2f( uniforms.uvOffset, 0, 0 );
  22368. _gl.uniform2f( uniforms.uvScale, 1, 1 );
  22369. }
  22370. _gl.uniform1f( uniforms.opacity, material.opacity );
  22371. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  22372. _gl.uniform1f( uniforms.rotation, material.rotation );
  22373. _gl.uniform2fv( uniforms.scale, scale );
  22374. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  22375. _renderer.setDepthTest( material.depthTest );
  22376. _renderer.setDepthWrite( material.depthWrite );
  22377. if ( material.map && material.map.image && material.map.image.width ) {
  22378. _renderer.setTexture( material.map, 0 );
  22379. } else {
  22380. _renderer.setTexture( _texture, 0 );
  22381. }
  22382. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  22383. }
  22384. // restore gl
  22385. _gl.enable( _gl.CULL_FACE );
  22386. };
  22387. function createProgram () {
  22388. var program = _gl.createProgram();
  22389. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  22390. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  22391. _gl.shaderSource( vertexShader, [
  22392. 'precision ' + _renderer.getPrecision() + ' float;',
  22393. 'uniform mat4 modelViewMatrix;',
  22394. 'uniform mat4 projectionMatrix;',
  22395. 'uniform float rotation;',
  22396. 'uniform vec2 scale;',
  22397. 'uniform vec2 uvOffset;',
  22398. 'uniform vec2 uvScale;',
  22399. 'attribute vec2 position;',
  22400. 'attribute vec2 uv;',
  22401. 'varying vec2 vUV;',
  22402. 'void main() {',
  22403. 'vUV = uvOffset + uv * uvScale;',
  22404. 'vec2 alignedPosition = position * scale;',
  22405. 'vec2 rotatedPosition;',
  22406. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  22407. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  22408. 'vec4 finalPosition;',
  22409. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  22410. 'finalPosition.xy += rotatedPosition;',
  22411. 'finalPosition = projectionMatrix * finalPosition;',
  22412. 'gl_Position = finalPosition;',
  22413. '}'
  22414. ].join( '\n' ) );
  22415. _gl.shaderSource( fragmentShader, [
  22416. 'precision ' + _renderer.getPrecision() + ' float;',
  22417. 'uniform vec3 color;',
  22418. 'uniform sampler2D map;',
  22419. 'uniform float opacity;',
  22420. 'uniform int fogType;',
  22421. 'uniform vec3 fogColor;',
  22422. 'uniform float fogDensity;',
  22423. 'uniform float fogNear;',
  22424. 'uniform float fogFar;',
  22425. 'uniform float alphaTest;',
  22426. 'varying vec2 vUV;',
  22427. 'void main() {',
  22428. 'vec4 texture = texture2D( map, vUV );',
  22429. 'if ( texture.a < alphaTest ) discard;',
  22430. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  22431. 'if ( fogType > 0 ) {',
  22432. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  22433. 'float fogFactor = 0.0;',
  22434. 'if ( fogType == 1 ) {',
  22435. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  22436. '} else {',
  22437. 'const float LOG2 = 1.442695;',
  22438. 'float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  22439. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  22440. '}',
  22441. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  22442. '}',
  22443. '}'
  22444. ].join( '\n' ) );
  22445. _gl.compileShader( vertexShader );
  22446. _gl.compileShader( fragmentShader );
  22447. _gl.attachShader( program, vertexShader );
  22448. _gl.attachShader( program, fragmentShader );
  22449. _gl.linkProgram( program );
  22450. return program;
  22451. };
  22452. function painterSortStable ( a, b ) {
  22453. if ( a.z !== b.z ) {
  22454. return b.z - a.z;
  22455. } else {
  22456. return b.id - a.id;
  22457. }
  22458. };
  22459. };
  22460. /**
  22461. * @author alteredq / http://alteredqualia.com/
  22462. */
  22463. THREE.DepthPassPlugin = function () {
  22464. this.enabled = false;
  22465. this.renderTarget = null;
  22466. var _gl,
  22467. _renderer,
  22468. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  22469. _frustum = new THREE.Frustum(),
  22470. _projScreenMatrix = new THREE.Matrix4();
  22471. this.init = function ( renderer ) {
  22472. _gl = renderer.context;
  22473. _renderer = renderer;
  22474. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  22475. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  22476. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  22477. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  22478. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  22479. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  22480. _depthMaterial._shadowPass = true;
  22481. _depthMaterialMorph._shadowPass = true;
  22482. _depthMaterialSkin._shadowPass = true;
  22483. _depthMaterialMorphSkin._shadowPass = true;
  22484. };
  22485. this.render = function ( scene, camera ) {
  22486. if ( ! this.enabled ) return;
  22487. this.update( scene, camera );
  22488. };
  22489. this.update = function ( scene, camera ) {
  22490. var i, il, j, jl, n,
  22491. program, buffer, material,
  22492. webglObject, object, light,
  22493. renderList,
  22494. fog = null;
  22495. // set GL state for depth map
  22496. _gl.clearColor( 1, 1, 1, 1 );
  22497. _gl.disable( _gl.BLEND );
  22498. _renderer.setDepthTest( true );
  22499. // update scene
  22500. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  22501. // update camera matrices and frustum
  22502. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  22503. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  22504. _frustum.setFromMatrix( _projScreenMatrix );
  22505. // render depth map
  22506. _renderer.setRenderTarget( this.renderTarget );
  22507. _renderer.clear();
  22508. // set object matrices & frustum culling
  22509. renderList = scene.__webglObjects;
  22510. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22511. webglObject = renderList[ j ];
  22512. object = webglObject.object;
  22513. webglObject.render = false;
  22514. if ( object.visible ) {
  22515. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  22516. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22517. webglObject.render = true;
  22518. }
  22519. }
  22520. }
  22521. // render regular objects
  22522. var objectMaterial, useMorphing, useSkinning;
  22523. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22524. webglObject = renderList[ j ];
  22525. if ( webglObject.render ) {
  22526. object = webglObject.object;
  22527. buffer = webglObject.buffer;
  22528. // todo: create proper depth material for particles
  22529. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  22530. objectMaterial = getObjectMaterial( object );
  22531. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  22532. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  22533. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  22534. if ( object.customDepthMaterial ) {
  22535. material = object.customDepthMaterial;
  22536. } else if ( useSkinning ) {
  22537. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  22538. } else if ( useMorphing ) {
  22539. material = _depthMaterialMorph;
  22540. } else {
  22541. material = _depthMaterial;
  22542. }
  22543. if ( buffer instanceof THREE.BufferGeometry ) {
  22544. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  22545. } else {
  22546. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  22547. }
  22548. }
  22549. }
  22550. // set matrices and render immediate objects
  22551. renderList = scene.__webglObjectsImmediate;
  22552. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22553. webglObject = renderList[ j ];
  22554. object = webglObject.object;
  22555. if ( object.visible ) {
  22556. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22557. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  22558. }
  22559. }
  22560. // restore GL state
  22561. var clearColor = _renderer.getClearColor(),
  22562. clearAlpha = _renderer.getClearAlpha();
  22563. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  22564. _gl.enable( _gl.BLEND );
  22565. };
  22566. // For the moment just ignore objects that have multiple materials with different animation methods
  22567. // Only the first material will be taken into account for deciding which depth material to use
  22568. function getObjectMaterial( object ) {
  22569. return object.material instanceof THREE.MeshFaceMaterial
  22570. ? object.material.materials[ 0 ]
  22571. : object.material;
  22572. };
  22573. };
  22574. /**
  22575. * @author mikael emtinger / http://gomo.se/
  22576. */
  22577. THREE.ShaderFlares = {
  22578. 'lensFlareVertexTexture': {
  22579. vertexShader: [
  22580. "uniform lowp int renderType;",
  22581. "uniform vec3 screenPosition;",
  22582. "uniform vec2 scale;",
  22583. "uniform float rotation;",
  22584. "uniform sampler2D occlusionMap;",
  22585. "attribute vec2 position;",
  22586. "attribute vec2 uv;",
  22587. "varying vec2 vUV;",
  22588. "varying float vVisibility;",
  22589. "void main() {",
  22590. "vUV = uv;",
  22591. "vec2 pos = position;",
  22592. "if( renderType == 2 ) {",
  22593. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  22594. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  22595. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  22596. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  22597. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  22598. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  22599. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  22600. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  22601. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  22602. "vVisibility = visibility.r / 9.0;",
  22603. "vVisibility *= 1.0 - visibility.g / 9.0;",
  22604. "vVisibility *= visibility.b / 9.0;",
  22605. "vVisibility *= 1.0 - visibility.a / 9.0;",
  22606. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22607. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22608. "}",
  22609. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22610. "}"
  22611. ].join( "\n" ),
  22612. fragmentShader: [
  22613. "uniform lowp int renderType;",
  22614. "uniform sampler2D map;",
  22615. "uniform float opacity;",
  22616. "uniform vec3 color;",
  22617. "varying vec2 vUV;",
  22618. "varying float vVisibility;",
  22619. "void main() {",
  22620. // pink square
  22621. "if( renderType == 0 ) {",
  22622. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  22623. // restore
  22624. "} else if( renderType == 1 ) {",
  22625. "gl_FragColor = texture2D( map, vUV );",
  22626. // flare
  22627. "} else {",
  22628. "vec4 texture = texture2D( map, vUV );",
  22629. "texture.a *= opacity * vVisibility;",
  22630. "gl_FragColor = texture;",
  22631. "gl_FragColor.rgb *= color;",
  22632. "}",
  22633. "}"
  22634. ].join( "\n" )
  22635. },
  22636. 'lensFlare': {
  22637. vertexShader: [
  22638. "uniform lowp int renderType;",
  22639. "uniform vec3 screenPosition;",
  22640. "uniform vec2 scale;",
  22641. "uniform float rotation;",
  22642. "attribute vec2 position;",
  22643. "attribute vec2 uv;",
  22644. "varying vec2 vUV;",
  22645. "void main() {",
  22646. "vUV = uv;",
  22647. "vec2 pos = position;",
  22648. "if( renderType == 2 ) {",
  22649. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22650. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22651. "}",
  22652. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22653. "}"
  22654. ].join( "\n" ),
  22655. fragmentShader: [
  22656. "precision mediump float;",
  22657. "uniform lowp int renderType;",
  22658. "uniform sampler2D map;",
  22659. "uniform sampler2D occlusionMap;",
  22660. "uniform float opacity;",
  22661. "uniform vec3 color;",
  22662. "varying vec2 vUV;",
  22663. "void main() {",
  22664. // pink square
  22665. "if( renderType == 0 ) {",
  22666. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  22667. // restore
  22668. "} else if( renderType == 1 ) {",
  22669. "gl_FragColor = texture2D( map, vUV );",
  22670. // flare
  22671. "} else {",
  22672. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  22673. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  22674. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  22675. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  22676. "visibility = ( 1.0 - visibility / 4.0 );",
  22677. "vec4 texture = texture2D( map, vUV );",
  22678. "texture.a *= opacity * visibility;",
  22679. "gl_FragColor = texture;",
  22680. "gl_FragColor.rgb *= color;",
  22681. "}",
  22682. "}"
  22683. ].join( "\n" )
  22684. }
  22685. };