three.js 806 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090
  1. // You shouldn't edit this build file.
  2. // The following source code is build from the src folder.
  3. // File:src/Three.js
  4. /**
  5. * @author mrdoob / http://mrdoob.com/
  6. */
  7. var THREE = { REVISION: '68dev' };
  8. // browserify support
  9. if ( typeof module === 'object' ) {
  10. module.exports = THREE;
  11. }
  12. // GL STATE CONSTANTS
  13. THREE.CullFaceNone = 0;
  14. THREE.CullFaceBack = 1;
  15. THREE.CullFaceFront = 2;
  16. THREE.CullFaceFrontBack = 3;
  17. THREE.FrontFaceDirectionCW = 0;
  18. THREE.FrontFaceDirectionCCW = 1;
  19. // SHADOWING TYPES
  20. THREE.BasicShadowMap = 0;
  21. THREE.PCFShadowMap = 1;
  22. THREE.PCFSoftShadowMap = 2;
  23. // MATERIAL CONSTANTS
  24. // side
  25. THREE.FrontSide = 0;
  26. THREE.BackSide = 1;
  27. THREE.DoubleSide = 2;
  28. // shading
  29. THREE.NoShading = 0;
  30. THREE.FlatShading = 1;
  31. THREE.SmoothShading = 2;
  32. // colors
  33. THREE.NoColors = 0;
  34. THREE.FaceColors = 1;
  35. THREE.VertexColors = 2;
  36. // blending modes
  37. THREE.NoBlending = 0;
  38. THREE.NormalBlending = 1;
  39. THREE.AdditiveBlending = 2;
  40. THREE.SubtractiveBlending = 3;
  41. THREE.MultiplyBlending = 4;
  42. THREE.CustomBlending = 5;
  43. // custom blending equations
  44. // (numbers start from 100 not to clash with other
  45. // mappings to OpenGL constants defined in Texture.js)
  46. THREE.AddEquation = 100;
  47. THREE.SubtractEquation = 101;
  48. THREE.ReverseSubtractEquation = 102;
  49. // custom blending destination factors
  50. THREE.ZeroFactor = 200;
  51. THREE.OneFactor = 201;
  52. THREE.SrcColorFactor = 202;
  53. THREE.OneMinusSrcColorFactor = 203;
  54. THREE.SrcAlphaFactor = 204;
  55. THREE.OneMinusSrcAlphaFactor = 205;
  56. THREE.DstAlphaFactor = 206;
  57. THREE.OneMinusDstAlphaFactor = 207;
  58. // custom blending source factors
  59. //THREE.ZeroFactor = 200;
  60. //THREE.OneFactor = 201;
  61. //THREE.SrcAlphaFactor = 204;
  62. //THREE.OneMinusSrcAlphaFactor = 205;
  63. //THREE.DstAlphaFactor = 206;
  64. //THREE.OneMinusDstAlphaFactor = 207;
  65. THREE.DstColorFactor = 208;
  66. THREE.OneMinusDstColorFactor = 209;
  67. THREE.SrcAlphaSaturateFactor = 210;
  68. // TEXTURE CONSTANTS
  69. THREE.MultiplyOperation = 0;
  70. THREE.MixOperation = 1;
  71. THREE.AddOperation = 2;
  72. // Mapping modes
  73. THREE.UVMapping = function () {};
  74. THREE.CubeReflectionMapping = function () {};
  75. THREE.CubeRefractionMapping = function () {};
  76. THREE.SphericalReflectionMapping = function () {};
  77. THREE.SphericalRefractionMapping = function () {};
  78. // Wrapping modes
  79. THREE.RepeatWrapping = 1000;
  80. THREE.ClampToEdgeWrapping = 1001;
  81. THREE.MirroredRepeatWrapping = 1002;
  82. // Filters
  83. THREE.NearestFilter = 1003;
  84. THREE.NearestMipMapNearestFilter = 1004;
  85. THREE.NearestMipMapLinearFilter = 1005;
  86. THREE.LinearFilter = 1006;
  87. THREE.LinearMipMapNearestFilter = 1007;
  88. THREE.LinearMipMapLinearFilter = 1008;
  89. // Data types
  90. THREE.UnsignedByteType = 1009;
  91. THREE.ByteType = 1010;
  92. THREE.ShortType = 1011;
  93. THREE.UnsignedShortType = 1012;
  94. THREE.IntType = 1013;
  95. THREE.UnsignedIntType = 1014;
  96. THREE.FloatType = 1015;
  97. // Pixel types
  98. //THREE.UnsignedByteType = 1009;
  99. THREE.UnsignedShort4444Type = 1016;
  100. THREE.UnsignedShort5551Type = 1017;
  101. THREE.UnsignedShort565Type = 1018;
  102. // Pixel formats
  103. THREE.AlphaFormat = 1019;
  104. THREE.RGBFormat = 1020;
  105. THREE.RGBAFormat = 1021;
  106. THREE.LuminanceFormat = 1022;
  107. THREE.LuminanceAlphaFormat = 1023;
  108. // Compressed texture formats
  109. THREE.RGB_S3TC_DXT1_Format = 2001;
  110. THREE.RGBA_S3TC_DXT1_Format = 2002;
  111. THREE.RGBA_S3TC_DXT3_Format = 2003;
  112. THREE.RGBA_S3TC_DXT5_Format = 2004;
  113. /*
  114. // Potential future PVRTC compressed texture formats
  115. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  116. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  117. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  118. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  119. */
  120. // File:src/math/Color.js
  121. /**
  122. * @author mrdoob / http://mrdoob.com/
  123. */
  124. THREE.Color = function ( color ) {
  125. if ( arguments.length === 3 ) {
  126. return this.setRGB( arguments[ 0 ], arguments[ 1 ], arguments[ 2 ] );
  127. }
  128. return this.set( color )
  129. };
  130. THREE.Color.prototype = {
  131. constructor: THREE.Color,
  132. r: 1, g: 1, b: 1,
  133. set: function ( value ) {
  134. if ( value instanceof THREE.Color ) {
  135. this.copy( value );
  136. } else if ( typeof value === 'number' ) {
  137. this.setHex( value );
  138. } else if ( typeof value === 'string' ) {
  139. this.setStyle( value );
  140. }
  141. return this;
  142. },
  143. setHex: function ( hex ) {
  144. hex = Math.floor( hex );
  145. this.r = ( hex >> 16 & 255 ) / 255;
  146. this.g = ( hex >> 8 & 255 ) / 255;
  147. this.b = ( hex & 255 ) / 255;
  148. return this;
  149. },
  150. setRGB: function ( r, g, b ) {
  151. this.r = r;
  152. this.g = g;
  153. this.b = b;
  154. return this;
  155. },
  156. setHSL: function ( h, s, l ) {
  157. // h,s,l ranges are in 0.0 - 1.0
  158. if ( s === 0 ) {
  159. this.r = this.g = this.b = l;
  160. } else {
  161. var hue2rgb = function ( p, q, t ) {
  162. if ( t < 0 ) t += 1;
  163. if ( t > 1 ) t -= 1;
  164. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  165. if ( t < 1 / 2 ) return q;
  166. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  167. return p;
  168. };
  169. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  170. var q = ( 2 * l ) - p;
  171. this.r = hue2rgb( q, p, h + 1 / 3 );
  172. this.g = hue2rgb( q, p, h );
  173. this.b = hue2rgb( q, p, h - 1 / 3 );
  174. }
  175. return this;
  176. },
  177. setStyle: function ( style ) {
  178. // rgb(255,0,0)
  179. if ( /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.test( style ) ) {
  180. var color = /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.exec( style );
  181. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  182. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  183. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  184. return this;
  185. }
  186. // rgb(100%,0%,0%)
  187. if ( /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.test( style ) ) {
  188. var color = /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.exec( style );
  189. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  190. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  191. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  192. return this;
  193. }
  194. // #ff0000
  195. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  196. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  197. this.setHex( parseInt( color[ 1 ], 16 ) );
  198. return this;
  199. }
  200. // #f00
  201. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  202. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  203. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  204. return this;
  205. }
  206. // red
  207. if ( /^(\w+)$/i.test( style ) ) {
  208. this.setHex( THREE.ColorKeywords[ style ] );
  209. return this;
  210. }
  211. },
  212. copy: function ( color ) {
  213. this.r = color.r;
  214. this.g = color.g;
  215. this.b = color.b;
  216. return this;
  217. },
  218. copyGammaToLinear: function ( color ) {
  219. this.r = color.r * color.r;
  220. this.g = color.g * color.g;
  221. this.b = color.b * color.b;
  222. return this;
  223. },
  224. copyLinearToGamma: function ( color ) {
  225. this.r = Math.sqrt( color.r );
  226. this.g = Math.sqrt( color.g );
  227. this.b = Math.sqrt( color.b );
  228. return this;
  229. },
  230. convertGammaToLinear: function () {
  231. var r = this.r, g = this.g, b = this.b;
  232. this.r = r * r;
  233. this.g = g * g;
  234. this.b = b * b;
  235. return this;
  236. },
  237. convertLinearToGamma: function () {
  238. this.r = Math.sqrt( this.r );
  239. this.g = Math.sqrt( this.g );
  240. this.b = Math.sqrt( this.b );
  241. return this;
  242. },
  243. getHex: function () {
  244. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  245. },
  246. getHexString: function () {
  247. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  248. },
  249. getHSL: function ( optionalTarget ) {
  250. // h,s,l ranges are in 0.0 - 1.0
  251. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  252. var r = this.r, g = this.g, b = this.b;
  253. var max = Math.max( r, g, b );
  254. var min = Math.min( r, g, b );
  255. var hue, saturation;
  256. var lightness = ( min + max ) / 2.0;
  257. if ( min === max ) {
  258. hue = 0;
  259. saturation = 0;
  260. } else {
  261. var delta = max - min;
  262. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  263. switch ( max ) {
  264. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  265. case g: hue = ( b - r ) / delta + 2; break;
  266. case b: hue = ( r - g ) / delta + 4; break;
  267. }
  268. hue /= 6;
  269. }
  270. hsl.h = hue;
  271. hsl.s = saturation;
  272. hsl.l = lightness;
  273. return hsl;
  274. },
  275. getStyle: function () {
  276. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  277. },
  278. offsetHSL: function ( h, s, l ) {
  279. var hsl = this.getHSL();
  280. hsl.h += h; hsl.s += s; hsl.l += l;
  281. this.setHSL( hsl.h, hsl.s, hsl.l );
  282. return this;
  283. },
  284. add: function ( color ) {
  285. this.r += color.r;
  286. this.g += color.g;
  287. this.b += color.b;
  288. return this;
  289. },
  290. addColors: function ( color1, color2 ) {
  291. this.r = color1.r + color2.r;
  292. this.g = color1.g + color2.g;
  293. this.b = color1.b + color2.b;
  294. return this;
  295. },
  296. addScalar: function ( s ) {
  297. this.r += s;
  298. this.g += s;
  299. this.b += s;
  300. return this;
  301. },
  302. multiply: function ( color ) {
  303. this.r *= color.r;
  304. this.g *= color.g;
  305. this.b *= color.b;
  306. return this;
  307. },
  308. multiplyScalar: function ( s ) {
  309. this.r *= s;
  310. this.g *= s;
  311. this.b *= s;
  312. return this;
  313. },
  314. lerp: function ( color, alpha ) {
  315. this.r += ( color.r - this.r ) * alpha;
  316. this.g += ( color.g - this.g ) * alpha;
  317. this.b += ( color.b - this.b ) * alpha;
  318. return this;
  319. },
  320. equals: function ( c ) {
  321. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  322. },
  323. fromArray: function ( array ) {
  324. this.r = array[ 0 ];
  325. this.g = array[ 1 ];
  326. this.b = array[ 2 ];
  327. return this;
  328. },
  329. toArray: function () {
  330. return [ this.r, this.g, this.b ];
  331. },
  332. clone: function () {
  333. return new THREE.Color().setRGB( this.r, this.g, this.b );
  334. }
  335. };
  336. THREE.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  337. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  338. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  339. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  340. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  341. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  342. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  343. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  344. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  345. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  346. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  347. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  348. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  349. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  350. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  351. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  352. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  353. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  354. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  355. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  356. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  357. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  358. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  359. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  360. // File:src/math/Quaternion.js
  361. /**
  362. * @author mikael emtinger / http://gomo.se/
  363. * @author alteredq / http://alteredqualia.com/
  364. * @author WestLangley / http://github.com/WestLangley
  365. * @author bhouston / http://exocortex.com
  366. */
  367. THREE.Quaternion = function ( x, y, z, w ) {
  368. this._x = x || 0;
  369. this._y = y || 0;
  370. this._z = z || 0;
  371. this._w = ( w !== undefined ) ? w : 1;
  372. };
  373. THREE.Quaternion.prototype = {
  374. constructor: THREE.Quaternion,
  375. _x: 0,_y: 0, _z: 0, _w: 0,
  376. get x () {
  377. return this._x;
  378. },
  379. set x ( value ) {
  380. this._x = value;
  381. this.onChangeCallback();
  382. },
  383. get y () {
  384. return this._y;
  385. },
  386. set y ( value ) {
  387. this._y = value;
  388. this.onChangeCallback();
  389. },
  390. get z () {
  391. return this._z;
  392. },
  393. set z ( value ) {
  394. this._z = value;
  395. this.onChangeCallback();
  396. },
  397. get w () {
  398. return this._w;
  399. },
  400. set w ( value ) {
  401. this._w = value;
  402. this.onChangeCallback();
  403. },
  404. set: function ( x, y, z, w ) {
  405. this._x = x;
  406. this._y = y;
  407. this._z = z;
  408. this._w = w;
  409. this.onChangeCallback();
  410. return this;
  411. },
  412. copy: function ( quaternion ) {
  413. this._x = quaternion.x;
  414. this._y = quaternion.y;
  415. this._z = quaternion.z;
  416. this._w = quaternion.w;
  417. this.onChangeCallback();
  418. return this;
  419. },
  420. setFromEuler: function ( euler, update ) {
  421. if ( euler instanceof THREE.Euler === false ) {
  422. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  423. }
  424. // http://www.mathworks.com/matlabcentral/fileexchange/
  425. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  426. // content/SpinCalc.m
  427. var c1 = Math.cos( euler._x / 2 );
  428. var c2 = Math.cos( euler._y / 2 );
  429. var c3 = Math.cos( euler._z / 2 );
  430. var s1 = Math.sin( euler._x / 2 );
  431. var s2 = Math.sin( euler._y / 2 );
  432. var s3 = Math.sin( euler._z / 2 );
  433. if ( euler.order === 'XYZ' ) {
  434. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  435. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  436. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  437. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  438. } else if ( euler.order === 'YXZ' ) {
  439. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  440. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  441. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  442. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  443. } else if ( euler.order === 'ZXY' ) {
  444. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  445. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  446. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  447. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  448. } else if ( euler.order === 'ZYX' ) {
  449. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  450. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  451. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  452. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  453. } else if ( euler.order === 'YZX' ) {
  454. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  455. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  456. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  457. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  458. } else if ( euler.order === 'XZY' ) {
  459. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  460. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  461. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  462. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  463. }
  464. if ( update !== false ) this.onChangeCallback();
  465. return this;
  466. },
  467. setFromAxisAngle: function ( axis, angle ) {
  468. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  469. // assumes axis is normalized
  470. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  471. this._x = axis.x * s;
  472. this._y = axis.y * s;
  473. this._z = axis.z * s;
  474. this._w = Math.cos( halfAngle );
  475. this.onChangeCallback();
  476. return this;
  477. },
  478. setFromRotationMatrix: function ( m ) {
  479. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  480. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  481. var te = m.elements,
  482. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  483. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  484. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  485. trace = m11 + m22 + m33,
  486. s;
  487. if ( trace > 0 ) {
  488. s = 0.5 / Math.sqrt( trace + 1.0 );
  489. this._w = 0.25 / s;
  490. this._x = ( m32 - m23 ) * s;
  491. this._y = ( m13 - m31 ) * s;
  492. this._z = ( m21 - m12 ) * s;
  493. } else if ( m11 > m22 && m11 > m33 ) {
  494. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  495. this._w = ( m32 - m23 ) / s;
  496. this._x = 0.25 * s;
  497. this._y = ( m12 + m21 ) / s;
  498. this._z = ( m13 + m31 ) / s;
  499. } else if ( m22 > m33 ) {
  500. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  501. this._w = ( m13 - m31 ) / s;
  502. this._x = ( m12 + m21 ) / s;
  503. this._y = 0.25 * s;
  504. this._z = ( m23 + m32 ) / s;
  505. } else {
  506. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  507. this._w = ( m21 - m12 ) / s;
  508. this._x = ( m13 + m31 ) / s;
  509. this._y = ( m23 + m32 ) / s;
  510. this._z = 0.25 * s;
  511. }
  512. this.onChangeCallback();
  513. return this;
  514. },
  515. setFromUnitVectors: function () {
  516. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  517. // assumes direction vectors vFrom and vTo are normalized
  518. var v1, r;
  519. var EPS = 0.000001;
  520. return function ( vFrom, vTo ) {
  521. if ( v1 === undefined ) v1 = new THREE.Vector3();
  522. r = vFrom.dot( vTo ) + 1;
  523. if ( r < EPS ) {
  524. r = 0;
  525. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  526. v1.set( - vFrom.y, vFrom.x, 0 );
  527. } else {
  528. v1.set( 0, - vFrom.z, vFrom.y );
  529. }
  530. } else {
  531. v1.crossVectors( vFrom, vTo );
  532. }
  533. this._x = v1.x;
  534. this._y = v1.y;
  535. this._z = v1.z;
  536. this._w = r;
  537. this.normalize();
  538. return this;
  539. }
  540. }(),
  541. inverse: function () {
  542. this.conjugate().normalize();
  543. return this;
  544. },
  545. conjugate: function () {
  546. this._x *= - 1;
  547. this._y *= - 1;
  548. this._z *= - 1;
  549. this.onChangeCallback();
  550. return this;
  551. },
  552. dot: function ( v ) {
  553. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  554. },
  555. lengthSq: function () {
  556. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  557. },
  558. length: function () {
  559. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  560. },
  561. normalize: function () {
  562. var l = this.length();
  563. if ( l === 0 ) {
  564. this._x = 0;
  565. this._y = 0;
  566. this._z = 0;
  567. this._w = 1;
  568. } else {
  569. l = 1 / l;
  570. this._x = this._x * l;
  571. this._y = this._y * l;
  572. this._z = this._z * l;
  573. this._w = this._w * l;
  574. }
  575. this.onChangeCallback();
  576. return this;
  577. },
  578. multiply: function ( q, p ) {
  579. if ( p !== undefined ) {
  580. console.warn( 'THREE.Quaternion: .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.onChangeCallback();
  594. return this;
  595. },
  596. multiplyVector3: function ( vector ) {
  597. console.warn( 'THREE.Quaternion: .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.onChangeCallback();
  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.onChangeCallback();
  647. return this;
  648. },
  649. toArray: function () {
  650. return [ this._x, this._y, this._z, this._w ];
  651. },
  652. onChange: function ( callback ) {
  653. this.onChangeCallback = callback;
  654. return this;
  655. },
  656. onChangeCallback: function () {},
  657. clone: function () {
  658. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  659. }
  660. };
  661. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  662. return qm.copy( qa ).slerp( qb, t );
  663. }
  664. // File:src/math/Vector2.js
  665. /**
  666. * @author mrdoob / http://mrdoob.com/
  667. * @author philogb / http://blog.thejit.org/
  668. * @author egraether / http://egraether.com/
  669. * @author zz85 / http://www.lab4games.net/zz85/blog
  670. */
  671. THREE.Vector2 = function ( x, y ) {
  672. this.x = x || 0;
  673. this.y = y || 0;
  674. };
  675. THREE.Vector2.prototype = {
  676. constructor: THREE.Vector2,
  677. set: function ( x, y ) {
  678. this.x = x;
  679. this.y = y;
  680. return this;
  681. },
  682. setX: function ( x ) {
  683. this.x = x;
  684. return this;
  685. },
  686. setY: function ( y ) {
  687. this.y = y;
  688. return this;
  689. },
  690. setComponent: function ( index, value ) {
  691. switch ( index ) {
  692. case 0: this.x = value; break;
  693. case 1: this.y = value; break;
  694. default: throw new Error( 'index is out of range: ' + index );
  695. }
  696. },
  697. getComponent: function ( index ) {
  698. switch ( index ) {
  699. case 0: return this.x;
  700. case 1: return this.y;
  701. default: throw new Error( 'index is out of range: ' + index );
  702. }
  703. },
  704. copy: function ( v ) {
  705. this.x = v.x;
  706. this.y = v.y;
  707. return this;
  708. },
  709. add: function ( v, w ) {
  710. if ( w !== undefined ) {
  711. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  712. return this.addVectors( v, w );
  713. }
  714. this.x += v.x;
  715. this.y += v.y;
  716. return this;
  717. },
  718. addVectors: function ( a, b ) {
  719. this.x = a.x + b.x;
  720. this.y = a.y + b.y;
  721. return this;
  722. },
  723. addScalar: function ( s ) {
  724. this.x += s;
  725. this.y += s;
  726. return this;
  727. },
  728. sub: function ( v, w ) {
  729. if ( w !== undefined ) {
  730. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  731. return this.subVectors( v, w );
  732. }
  733. this.x -= v.x;
  734. this.y -= v.y;
  735. return this;
  736. },
  737. subVectors: function ( a, b ) {
  738. this.x = a.x - b.x;
  739. this.y = a.y - b.y;
  740. return this;
  741. },
  742. multiply: function ( v ) {
  743. this.x *= v.x;
  744. this.y *= v.y;
  745. return this;
  746. },
  747. multiplyScalar: function ( s ) {
  748. this.x *= s;
  749. this.y *= s;
  750. return this;
  751. },
  752. divide: function ( v ) {
  753. this.x /= v.x;
  754. this.y /= v.y;
  755. return this;
  756. },
  757. divideScalar: function ( scalar ) {
  758. if ( scalar !== 0 ) {
  759. var invScalar = 1 / scalar;
  760. this.x *= invScalar;
  761. this.y *= invScalar;
  762. } else {
  763. this.x = 0;
  764. this.y = 0;
  765. }
  766. return this;
  767. },
  768. min: function ( v ) {
  769. if ( this.x > v.x ) {
  770. this.x = v.x;
  771. }
  772. if ( this.y > v.y ) {
  773. this.y = v.y;
  774. }
  775. return this;
  776. },
  777. max: function ( v ) {
  778. if ( this.x < v.x ) {
  779. this.x = v.x;
  780. }
  781. if ( this.y < v.y ) {
  782. this.y = v.y;
  783. }
  784. return this;
  785. },
  786. clamp: function ( min, max ) {
  787. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  788. if ( this.x < min.x ) {
  789. this.x = min.x;
  790. } else if ( this.x > max.x ) {
  791. this.x = max.x;
  792. }
  793. if ( this.y < min.y ) {
  794. this.y = min.y;
  795. } else if ( this.y > max.y ) {
  796. this.y = max.y;
  797. }
  798. return this;
  799. },
  800. clampScalar: ( function () {
  801. var min, max;
  802. return function ( minVal, maxVal ) {
  803. if ( min === undefined ) {
  804. min = new THREE.Vector2();
  805. max = new THREE.Vector2();
  806. }
  807. min.set( minVal, minVal );
  808. max.set( maxVal, maxVal );
  809. return this.clamp( min, max );
  810. };
  811. } )(),
  812. floor: function () {
  813. this.x = Math.floor( this.x );
  814. this.y = Math.floor( this.y );
  815. return this;
  816. },
  817. ceil: function () {
  818. this.x = Math.ceil( this.x );
  819. this.y = Math.ceil( this.y );
  820. return this;
  821. },
  822. round: function () {
  823. this.x = Math.round( this.x );
  824. this.y = Math.round( this.y );
  825. return this;
  826. },
  827. roundToZero: function () {
  828. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  829. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  830. return this;
  831. },
  832. negate: function () {
  833. return this.multiplyScalar( - 1 );
  834. },
  835. dot: function ( v ) {
  836. return this.x * v.x + this.y * v.y;
  837. },
  838. lengthSq: function () {
  839. return this.x * this.x + this.y * this.y;
  840. },
  841. length: function () {
  842. return Math.sqrt( this.x * this.x + this.y * this.y );
  843. },
  844. normalize: function () {
  845. return this.divideScalar( this.length() );
  846. },
  847. distanceTo: function ( v ) {
  848. return Math.sqrt( this.distanceToSquared( v ) );
  849. },
  850. distanceToSquared: function ( v ) {
  851. var dx = this.x - v.x, dy = this.y - v.y;
  852. return dx * dx + dy * dy;
  853. },
  854. setLength: function ( l ) {
  855. var oldLength = this.length();
  856. if ( oldLength !== 0 && l !== oldLength ) {
  857. this.multiplyScalar( l / oldLength );
  858. }
  859. return this;
  860. },
  861. lerp: function ( v, alpha ) {
  862. this.x += ( v.x - this.x ) * alpha;
  863. this.y += ( v.y - this.y ) * alpha;
  864. return this;
  865. },
  866. equals: function ( v ) {
  867. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  868. },
  869. fromArray: function ( array ) {
  870. this.x = array[ 0 ];
  871. this.y = array[ 1 ];
  872. return this;
  873. },
  874. toArray: function () {
  875. return [ this.x, this.y ];
  876. },
  877. clone: function () {
  878. return new THREE.Vector2( this.x, this.y );
  879. }
  880. };
  881. // File:src/math/Vector3.js
  882. /**
  883. * @author mrdoob / http://mrdoob.com/
  884. * @author *kile / http://kile.stravaganza.org/
  885. * @author philogb / http://blog.thejit.org/
  886. * @author mikael emtinger / http://gomo.se/
  887. * @author egraether / http://egraether.com/
  888. * @author WestLangley / http://github.com/WestLangley
  889. */
  890. THREE.Vector3 = function ( x, y, z ) {
  891. this.x = x || 0;
  892. this.y = y || 0;
  893. this.z = z || 0;
  894. };
  895. THREE.Vector3.prototype = {
  896. constructor: THREE.Vector3,
  897. set: function ( x, y, z ) {
  898. this.x = x;
  899. this.y = y;
  900. this.z = z;
  901. return this;
  902. },
  903. setX: function ( x ) {
  904. this.x = x;
  905. return this;
  906. },
  907. setY: function ( y ) {
  908. this.y = y;
  909. return this;
  910. },
  911. setZ: function ( z ) {
  912. this.z = z;
  913. return this;
  914. },
  915. setComponent: function ( index, value ) {
  916. switch ( index ) {
  917. case 0: this.x = value; break;
  918. case 1: this.y = value; break;
  919. case 2: this.z = value; break;
  920. default: throw new Error( 'index is out of range: ' + index );
  921. }
  922. },
  923. getComponent: function ( index ) {
  924. switch ( index ) {
  925. case 0: return this.x;
  926. case 1: return this.y;
  927. case 2: return this.z;
  928. default: throw new Error( 'index is out of range: ' + index );
  929. }
  930. },
  931. copy: function ( v ) {
  932. this.x = v.x;
  933. this.y = v.y;
  934. this.z = v.z;
  935. return this;
  936. },
  937. add: function ( v, w ) {
  938. if ( w !== undefined ) {
  939. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  940. return this.addVectors( v, w );
  941. }
  942. this.x += v.x;
  943. this.y += v.y;
  944. this.z += v.z;
  945. return this;
  946. },
  947. addScalar: function ( s ) {
  948. this.x += s;
  949. this.y += s;
  950. this.z += s;
  951. return this;
  952. },
  953. addVectors: function ( a, b ) {
  954. this.x = a.x + b.x;
  955. this.y = a.y + b.y;
  956. this.z = a.z + b.z;
  957. return this;
  958. },
  959. sub: function ( v, w ) {
  960. if ( w !== undefined ) {
  961. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  962. return this.subVectors( v, w );
  963. }
  964. this.x -= v.x;
  965. this.y -= v.y;
  966. this.z -= v.z;
  967. return this;
  968. },
  969. subVectors: function ( a, b ) {
  970. this.x = a.x - b.x;
  971. this.y = a.y - b.y;
  972. this.z = a.z - b.z;
  973. return this;
  974. },
  975. multiply: function ( v, w ) {
  976. if ( w !== undefined ) {
  977. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  978. return this.multiplyVectors( v, w );
  979. }
  980. this.x *= v.x;
  981. this.y *= v.y;
  982. this.z *= v.z;
  983. return this;
  984. },
  985. multiplyScalar: function ( scalar ) {
  986. this.x *= scalar;
  987. this.y *= scalar;
  988. this.z *= scalar;
  989. return this;
  990. },
  991. multiplyVectors: function ( a, b ) {
  992. this.x = a.x * b.x;
  993. this.y = a.y * b.y;
  994. this.z = a.z * b.z;
  995. return this;
  996. },
  997. applyEuler: function () {
  998. var quaternion;
  999. return function ( euler ) {
  1000. if ( euler instanceof THREE.Euler === false ) {
  1001. console.error( 'THREE.Vector3: .applyEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  1002. }
  1003. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1004. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1005. return this;
  1006. };
  1007. }(),
  1008. applyAxisAngle: function () {
  1009. var quaternion;
  1010. return function ( axis, angle ) {
  1011. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1012. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1013. return this;
  1014. };
  1015. }(),
  1016. applyMatrix3: function ( m ) {
  1017. var x = this.x;
  1018. var y = this.y;
  1019. var z = this.z;
  1020. var e = m.elements;
  1021. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1022. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1023. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1024. return this;
  1025. },
  1026. applyMatrix4: function ( m ) {
  1027. // input: THREE.Matrix4 affine matrix
  1028. var x = this.x, y = this.y, z = this.z;
  1029. var e = m.elements;
  1030. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  1031. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  1032. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  1033. return this;
  1034. },
  1035. applyProjection: function ( m ) {
  1036. // input: THREE.Matrix4 projection matrix
  1037. var x = this.x, y = this.y, z = this.z;
  1038. var e = m.elements;
  1039. var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide
  1040. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d;
  1041. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d;
  1042. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d;
  1043. return this;
  1044. },
  1045. applyQuaternion: function ( q ) {
  1046. var x = this.x;
  1047. var y = this.y;
  1048. var z = this.z;
  1049. var qx = q.x;
  1050. var qy = q.y;
  1051. var qz = q.z;
  1052. var qw = q.w;
  1053. // calculate quat * vector
  1054. var ix = qw * x + qy * z - qz * y;
  1055. var iy = qw * y + qz * x - qx * z;
  1056. var iz = qw * z + qx * y - qy * x;
  1057. var iw = - qx * x - qy * y - qz * z;
  1058. // calculate result * inverse quat
  1059. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1060. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1061. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1062. return this;
  1063. },
  1064. transformDirection: function ( m ) {
  1065. // input: THREE.Matrix4 affine matrix
  1066. // vector interpreted as a direction
  1067. var x = this.x, y = this.y, z = this.z;
  1068. var e = m.elements;
  1069. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1070. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1071. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1072. this.normalize();
  1073. return this;
  1074. },
  1075. divide: function ( v ) {
  1076. this.x /= v.x;
  1077. this.y /= v.y;
  1078. this.z /= v.z;
  1079. return this;
  1080. },
  1081. divideScalar: function ( scalar ) {
  1082. if ( scalar !== 0 ) {
  1083. var invScalar = 1 / scalar;
  1084. this.x *= invScalar;
  1085. this.y *= invScalar;
  1086. this.z *= invScalar;
  1087. } else {
  1088. this.x = 0;
  1089. this.y = 0;
  1090. this.z = 0;
  1091. }
  1092. return this;
  1093. },
  1094. min: function ( v ) {
  1095. if ( this.x > v.x ) {
  1096. this.x = v.x;
  1097. }
  1098. if ( this.y > v.y ) {
  1099. this.y = v.y;
  1100. }
  1101. if ( this.z > v.z ) {
  1102. this.z = v.z;
  1103. }
  1104. return this;
  1105. },
  1106. max: function ( v ) {
  1107. if ( this.x < v.x ) {
  1108. this.x = v.x;
  1109. }
  1110. if ( this.y < v.y ) {
  1111. this.y = v.y;
  1112. }
  1113. if ( this.z < v.z ) {
  1114. this.z = v.z;
  1115. }
  1116. return this;
  1117. },
  1118. clamp: function ( min, max ) {
  1119. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1120. if ( this.x < min.x ) {
  1121. this.x = min.x;
  1122. } else if ( this.x > max.x ) {
  1123. this.x = max.x;
  1124. }
  1125. if ( this.y < min.y ) {
  1126. this.y = min.y;
  1127. } else if ( this.y > max.y ) {
  1128. this.y = max.y;
  1129. }
  1130. if ( this.z < min.z ) {
  1131. this.z = min.z;
  1132. } else if ( this.z > max.z ) {
  1133. this.z = max.z;
  1134. }
  1135. return this;
  1136. },
  1137. clampScalar: ( function () {
  1138. var min, max;
  1139. return function ( minVal, maxVal ) {
  1140. if ( min === undefined ) {
  1141. min = new THREE.Vector3();
  1142. max = new THREE.Vector3();
  1143. }
  1144. min.set( minVal, minVal, minVal );
  1145. max.set( maxVal, maxVal, maxVal );
  1146. return this.clamp( min, max );
  1147. };
  1148. } )(),
  1149. floor: function () {
  1150. this.x = Math.floor( this.x );
  1151. this.y = Math.floor( this.y );
  1152. this.z = Math.floor( this.z );
  1153. return this;
  1154. },
  1155. ceil: function () {
  1156. this.x = Math.ceil( this.x );
  1157. this.y = Math.ceil( this.y );
  1158. this.z = Math.ceil( this.z );
  1159. return this;
  1160. },
  1161. round: function () {
  1162. this.x = Math.round( this.x );
  1163. this.y = Math.round( this.y );
  1164. this.z = Math.round( this.z );
  1165. return this;
  1166. },
  1167. roundToZero: function () {
  1168. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1169. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1170. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1171. return this;
  1172. },
  1173. negate: function () {
  1174. return this.multiplyScalar( - 1 );
  1175. },
  1176. dot: function ( v ) {
  1177. return this.x * v.x + this.y * v.y + this.z * v.z;
  1178. },
  1179. lengthSq: function () {
  1180. return this.x * this.x + this.y * this.y + this.z * this.z;
  1181. },
  1182. length: function () {
  1183. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1184. },
  1185. lengthManhattan: function () {
  1186. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1187. },
  1188. normalize: function () {
  1189. return this.divideScalar( this.length() );
  1190. },
  1191. setLength: function ( l ) {
  1192. var oldLength = this.length();
  1193. if ( oldLength !== 0 && l !== oldLength ) {
  1194. this.multiplyScalar( l / oldLength );
  1195. }
  1196. return this;
  1197. },
  1198. lerp: function ( v, alpha ) {
  1199. this.x += ( v.x - this.x ) * alpha;
  1200. this.y += ( v.y - this.y ) * alpha;
  1201. this.z += ( v.z - this.z ) * alpha;
  1202. return this;
  1203. },
  1204. cross: function ( v, w ) {
  1205. if ( w !== undefined ) {
  1206. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1207. return this.crossVectors( v, w );
  1208. }
  1209. var x = this.x, y = this.y, z = this.z;
  1210. this.x = y * v.z - z * v.y;
  1211. this.y = z * v.x - x * v.z;
  1212. this.z = x * v.y - y * v.x;
  1213. return this;
  1214. },
  1215. crossVectors: function ( a, b ) {
  1216. var ax = a.x, ay = a.y, az = a.z;
  1217. var bx = b.x, by = b.y, bz = b.z;
  1218. this.x = ay * bz - az * by;
  1219. this.y = az * bx - ax * bz;
  1220. this.z = ax * by - ay * bx;
  1221. return this;
  1222. },
  1223. projectOnVector: function () {
  1224. var v1, dot;
  1225. return function ( vector ) {
  1226. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1227. v1.copy( vector ).normalize();
  1228. dot = this.dot( v1 );
  1229. return this.copy( v1 ).multiplyScalar( dot );
  1230. };
  1231. }(),
  1232. projectOnPlane: function () {
  1233. var v1;
  1234. return function ( planeNormal ) {
  1235. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1236. v1.copy( this ).projectOnVector( planeNormal );
  1237. return this.sub( v1 );
  1238. }
  1239. }(),
  1240. reflect: function () {
  1241. // reflect incident vector off plane orthogonal to normal
  1242. // normal is assumed to have unit length
  1243. var v1;
  1244. return function ( normal ) {
  1245. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1246. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1247. }
  1248. }(),
  1249. angleTo: function ( v ) {
  1250. var theta = this.dot( v ) / ( this.length() * v.length() );
  1251. // clamp, to handle numerical problems
  1252. return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) );
  1253. },
  1254. distanceTo: function ( v ) {
  1255. return Math.sqrt( this.distanceToSquared( v ) );
  1256. },
  1257. distanceToSquared: function ( v ) {
  1258. var dx = this.x - v.x;
  1259. var dy = this.y - v.y;
  1260. var dz = this.z - v.z;
  1261. return dx * dx + dy * dy + dz * dz;
  1262. },
  1263. setEulerFromRotationMatrix: function ( m, order ) {
  1264. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  1265. },
  1266. setEulerFromQuaternion: function ( q, order ) {
  1267. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  1268. },
  1269. getPositionFromMatrix: function ( m ) {
  1270. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  1271. return this.setFromMatrixPosition( m );
  1272. },
  1273. getScaleFromMatrix: function ( m ) {
  1274. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  1275. return this.setFromMatrixScale( m );
  1276. },
  1277. getColumnFromMatrix: function ( index, matrix ) {
  1278. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  1279. return this.setFromMatrixColumn( index, matrix );
  1280. },
  1281. setFromMatrixPosition: function ( m ) {
  1282. this.x = m.elements[ 12 ];
  1283. this.y = m.elements[ 13 ];
  1284. this.z = m.elements[ 14 ];
  1285. return this;
  1286. },
  1287. setFromMatrixScale: function ( m ) {
  1288. var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
  1289. var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
  1290. var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
  1291. this.x = sx;
  1292. this.y = sy;
  1293. this.z = sz;
  1294. return this;
  1295. },
  1296. setFromMatrixColumn: function ( index, matrix ) {
  1297. var offset = index * 4;
  1298. var me = matrix.elements;
  1299. this.x = me[ offset ];
  1300. this.y = me[ offset + 1 ];
  1301. this.z = me[ offset + 2 ];
  1302. return this;
  1303. },
  1304. equals: function ( v ) {
  1305. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1306. },
  1307. fromArray: function ( array ) {
  1308. this.x = array[ 0 ];
  1309. this.y = array[ 1 ];
  1310. this.z = array[ 2 ];
  1311. return this;
  1312. },
  1313. toArray: function () {
  1314. return [ this.x, this.y, this.z ];
  1315. },
  1316. clone: function () {
  1317. return new THREE.Vector3( this.x, this.y, this.z );
  1318. }
  1319. };
  1320. // File:src/math/Vector4.js
  1321. /**
  1322. * @author supereggbert / http://www.paulbrunt.co.uk/
  1323. * @author philogb / http://blog.thejit.org/
  1324. * @author mikael emtinger / http://gomo.se/
  1325. * @author egraether / http://egraether.com/
  1326. * @author WestLangley / http://github.com/WestLangley
  1327. */
  1328. THREE.Vector4 = function ( x, y, z, w ) {
  1329. this.x = x || 0;
  1330. this.y = y || 0;
  1331. this.z = z || 0;
  1332. this.w = ( w !== undefined ) ? w : 1;
  1333. };
  1334. THREE.Vector4.prototype = {
  1335. constructor: THREE.Vector4,
  1336. set: function ( x, y, z, w ) {
  1337. this.x = x;
  1338. this.y = y;
  1339. this.z = z;
  1340. this.w = w;
  1341. return this;
  1342. },
  1343. setX: function ( x ) {
  1344. this.x = x;
  1345. return this;
  1346. },
  1347. setY: function ( y ) {
  1348. this.y = y;
  1349. return this;
  1350. },
  1351. setZ: function ( z ) {
  1352. this.z = z;
  1353. return this;
  1354. },
  1355. setW: function ( w ) {
  1356. this.w = w;
  1357. return this;
  1358. },
  1359. setComponent: function ( index, value ) {
  1360. switch ( index ) {
  1361. case 0: this.x = value; break;
  1362. case 1: this.y = value; break;
  1363. case 2: this.z = value; break;
  1364. case 3: this.w = value; break;
  1365. default: throw new Error( 'index is out of range: ' + index );
  1366. }
  1367. },
  1368. getComponent: function ( index ) {
  1369. switch ( index ) {
  1370. case 0: return this.x;
  1371. case 1: return this.y;
  1372. case 2: return this.z;
  1373. case 3: return this.w;
  1374. default: throw new Error( 'index is out of range: ' + index );
  1375. }
  1376. },
  1377. copy: function ( v ) {
  1378. this.x = v.x;
  1379. this.y = v.y;
  1380. this.z = v.z;
  1381. this.w = ( v.w !== undefined ) ? v.w : 1;
  1382. return this;
  1383. },
  1384. add: function ( v, w ) {
  1385. if ( w !== undefined ) {
  1386. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1387. return this.addVectors( v, w );
  1388. }
  1389. this.x += v.x;
  1390. this.y += v.y;
  1391. this.z += v.z;
  1392. this.w += v.w;
  1393. return this;
  1394. },
  1395. addScalar: function ( s ) {
  1396. this.x += s;
  1397. this.y += s;
  1398. this.z += s;
  1399. this.w += s;
  1400. return this;
  1401. },
  1402. addVectors: 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. sub: function ( v, w ) {
  1410. if ( w !== undefined ) {
  1411. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1412. return this.subVectors( v, w );
  1413. }
  1414. this.x -= v.x;
  1415. this.y -= v.y;
  1416. this.z -= v.z;
  1417. this.w -= v.w;
  1418. return this;
  1419. },
  1420. subVectors: function ( a, b ) {
  1421. this.x = a.x - b.x;
  1422. this.y = a.y - b.y;
  1423. this.z = a.z - b.z;
  1424. this.w = a.w - b.w;
  1425. return this;
  1426. },
  1427. multiplyScalar: function ( scalar ) {
  1428. this.x *= scalar;
  1429. this.y *= scalar;
  1430. this.z *= scalar;
  1431. this.w *= scalar;
  1432. return this;
  1433. },
  1434. applyMatrix4: function ( m ) {
  1435. var x = this.x;
  1436. var y = this.y;
  1437. var z = this.z;
  1438. var w = this.w;
  1439. var e = m.elements;
  1440. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1441. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1442. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1443. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1444. return this;
  1445. },
  1446. divideScalar: function ( scalar ) {
  1447. if ( scalar !== 0 ) {
  1448. var invScalar = 1 / scalar;
  1449. this.x *= invScalar;
  1450. this.y *= invScalar;
  1451. this.z *= invScalar;
  1452. this.w *= invScalar;
  1453. } else {
  1454. this.x = 0;
  1455. this.y = 0;
  1456. this.z = 0;
  1457. this.w = 1;
  1458. }
  1459. return this;
  1460. },
  1461. setAxisAngleFromQuaternion: function ( q ) {
  1462. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1463. // q is assumed to be normalized
  1464. this.w = 2 * Math.acos( q.w );
  1465. var s = Math.sqrt( 1 - q.w * q.w );
  1466. if ( s < 0.0001 ) {
  1467. this.x = 1;
  1468. this.y = 0;
  1469. this.z = 0;
  1470. } else {
  1471. this.x = q.x / s;
  1472. this.y = q.y / s;
  1473. this.z = q.z / s;
  1474. }
  1475. return this;
  1476. },
  1477. setAxisAngleFromRotationMatrix: function ( m ) {
  1478. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1479. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1480. var angle, x, y, z, // variables for result
  1481. epsilon = 0.01, // margin to allow for rounding errors
  1482. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1483. te = m.elements,
  1484. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1485. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1486. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1487. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1488. && ( Math.abs( m13 - m31 ) < epsilon )
  1489. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1490. // singularity found
  1491. // first check for identity matrix which must have +1 for all terms
  1492. // in leading diagonal and zero in other terms
  1493. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1494. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1495. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1496. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1497. // this singularity is identity matrix so angle = 0
  1498. this.set( 1, 0, 0, 0 );
  1499. return this; // zero angle, arbitrary axis
  1500. }
  1501. // otherwise this singularity is angle = 180
  1502. angle = Math.PI;
  1503. var xx = ( m11 + 1 ) / 2;
  1504. var yy = ( m22 + 1 ) / 2;
  1505. var zz = ( m33 + 1 ) / 2;
  1506. var xy = ( m12 + m21 ) / 4;
  1507. var xz = ( m13 + m31 ) / 4;
  1508. var yz = ( m23 + m32 ) / 4;
  1509. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1510. if ( xx < epsilon ) {
  1511. x = 0;
  1512. y = 0.707106781;
  1513. z = 0.707106781;
  1514. } else {
  1515. x = Math.sqrt( xx );
  1516. y = xy / x;
  1517. z = xz / x;
  1518. }
  1519. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1520. if ( yy < epsilon ) {
  1521. x = 0.707106781;
  1522. y = 0;
  1523. z = 0.707106781;
  1524. } else {
  1525. y = Math.sqrt( yy );
  1526. x = xy / y;
  1527. z = yz / y;
  1528. }
  1529. } else { // m33 is the largest diagonal term so base result on this
  1530. if ( zz < epsilon ) {
  1531. x = 0.707106781;
  1532. y = 0.707106781;
  1533. z = 0;
  1534. } else {
  1535. z = Math.sqrt( zz );
  1536. x = xz / z;
  1537. y = yz / z;
  1538. }
  1539. }
  1540. this.set( x, y, z, angle );
  1541. return this; // return 180 deg rotation
  1542. }
  1543. // as we have reached here there are no singularities so we can handle normally
  1544. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1545. + ( m13 - m31 ) * ( m13 - m31 )
  1546. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1547. if ( Math.abs( s ) < 0.001 ) s = 1;
  1548. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1549. // caught by singularity test above, but I've left it in just in case
  1550. this.x = ( m32 - m23 ) / s;
  1551. this.y = ( m13 - m31 ) / s;
  1552. this.z = ( m21 - m12 ) / s;
  1553. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1554. return this;
  1555. },
  1556. min: function ( v ) {
  1557. if ( this.x > v.x ) {
  1558. this.x = v.x;
  1559. }
  1560. if ( this.y > v.y ) {
  1561. this.y = v.y;
  1562. }
  1563. if ( this.z > v.z ) {
  1564. this.z = v.z;
  1565. }
  1566. if ( this.w > v.w ) {
  1567. this.w = v.w;
  1568. }
  1569. return this;
  1570. },
  1571. max: function ( v ) {
  1572. if ( this.x < v.x ) {
  1573. this.x = v.x;
  1574. }
  1575. if ( this.y < v.y ) {
  1576. this.y = v.y;
  1577. }
  1578. if ( this.z < v.z ) {
  1579. this.z = v.z;
  1580. }
  1581. if ( this.w < v.w ) {
  1582. this.w = v.w;
  1583. }
  1584. return this;
  1585. },
  1586. clamp: function ( min, max ) {
  1587. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1588. if ( this.x < min.x ) {
  1589. this.x = min.x;
  1590. } else if ( this.x > max.x ) {
  1591. this.x = max.x;
  1592. }
  1593. if ( this.y < min.y ) {
  1594. this.y = min.y;
  1595. } else if ( this.y > max.y ) {
  1596. this.y = max.y;
  1597. }
  1598. if ( this.z < min.z ) {
  1599. this.z = min.z;
  1600. } else if ( this.z > max.z ) {
  1601. this.z = max.z;
  1602. }
  1603. if ( this.w < min.w ) {
  1604. this.w = min.w;
  1605. } else if ( this.w > max.w ) {
  1606. this.w = max.w;
  1607. }
  1608. return this;
  1609. },
  1610. clampScalar: ( function () {
  1611. var min, max;
  1612. return function ( minVal, maxVal ) {
  1613. if ( min === undefined ) {
  1614. min = new THREE.Vector4();
  1615. max = new THREE.Vector4();
  1616. }
  1617. min.set( minVal, minVal, minVal, minVal );
  1618. max.set( maxVal, maxVal, maxVal, maxVal );
  1619. return this.clamp( min, max );
  1620. };
  1621. } )(),
  1622. floor: function () {
  1623. this.x = Math.floor( this.x );
  1624. this.y = Math.floor( this.y );
  1625. this.z = Math.floor( this.z );
  1626. this.w = Math.floor( this.w );
  1627. return this;
  1628. },
  1629. ceil: function () {
  1630. this.x = Math.ceil( this.x );
  1631. this.y = Math.ceil( this.y );
  1632. this.z = Math.ceil( this.z );
  1633. this.w = Math.ceil( this.w );
  1634. return this;
  1635. },
  1636. round: function () {
  1637. this.x = Math.round( this.x );
  1638. this.y = Math.round( this.y );
  1639. this.z = Math.round( this.z );
  1640. this.w = Math.round( this.w );
  1641. return this;
  1642. },
  1643. roundToZero: function () {
  1644. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1645. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1646. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1647. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1648. return this;
  1649. },
  1650. negate: function () {
  1651. return this.multiplyScalar( - 1 );
  1652. },
  1653. dot: function ( v ) {
  1654. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1655. },
  1656. lengthSq: function () {
  1657. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1658. },
  1659. length: function () {
  1660. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1661. },
  1662. lengthManhattan: function () {
  1663. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1664. },
  1665. normalize: function () {
  1666. return this.divideScalar( this.length() );
  1667. },
  1668. setLength: function ( l ) {
  1669. var oldLength = this.length();
  1670. if ( oldLength !== 0 && l !== oldLength ) {
  1671. this.multiplyScalar( l / oldLength );
  1672. }
  1673. return this;
  1674. },
  1675. lerp: function ( v, alpha ) {
  1676. this.x += ( v.x - this.x ) * alpha;
  1677. this.y += ( v.y - this.y ) * alpha;
  1678. this.z += ( v.z - this.z ) * alpha;
  1679. this.w += ( v.w - this.w ) * alpha;
  1680. return this;
  1681. },
  1682. equals: function ( v ) {
  1683. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1684. },
  1685. fromArray: function ( array ) {
  1686. this.x = array[ 0 ];
  1687. this.y = array[ 1 ];
  1688. this.z = array[ 2 ];
  1689. this.w = array[ 3 ];
  1690. return this;
  1691. },
  1692. toArray: function () {
  1693. return [ this.x, this.y, this.z, this.w ];
  1694. },
  1695. clone: function () {
  1696. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1697. }
  1698. };
  1699. // File:src/math/Euler.js
  1700. /**
  1701. * @author mrdoob / http://mrdoob.com/
  1702. * @author WestLangley / http://github.com/WestLangley
  1703. * @author bhouston / http://exocortex.com
  1704. */
  1705. THREE.Euler = function ( x, y, z, order ) {
  1706. this._x = x || 0;
  1707. this._y = y || 0;
  1708. this._z = z || 0;
  1709. this._order = order || THREE.Euler.DefaultOrder;
  1710. };
  1711. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1712. THREE.Euler.DefaultOrder = 'XYZ';
  1713. THREE.Euler.prototype = {
  1714. constructor: THREE.Euler,
  1715. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1716. get x () {
  1717. return this._x;
  1718. },
  1719. set x ( value ) {
  1720. this._x = value;
  1721. this.onChangeCallback();
  1722. },
  1723. get y () {
  1724. return this._y;
  1725. },
  1726. set y ( value ) {
  1727. this._y = value;
  1728. this.onChangeCallback();
  1729. },
  1730. get z () {
  1731. return this._z;
  1732. },
  1733. set z ( value ) {
  1734. this._z = value;
  1735. this.onChangeCallback();
  1736. },
  1737. get order () {
  1738. return this._order;
  1739. },
  1740. set order ( value ) {
  1741. this._order = value;
  1742. this.onChangeCallback();
  1743. },
  1744. set: function ( x, y, z, order ) {
  1745. this._x = x;
  1746. this._y = y;
  1747. this._z = z;
  1748. this._order = order || this._order;
  1749. this.onChangeCallback();
  1750. return this;
  1751. },
  1752. copy: function ( euler ) {
  1753. this._x = euler._x;
  1754. this._y = euler._y;
  1755. this._z = euler._z;
  1756. this._order = euler._order;
  1757. this.onChangeCallback();
  1758. return this;
  1759. },
  1760. setFromRotationMatrix: function ( m, order ) {
  1761. var clamp = THREE.Math.clamp;
  1762. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1763. var te = m.elements;
  1764. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  1765. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  1766. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1767. order = order || this._order;
  1768. if ( order === 'XYZ' ) {
  1769. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  1770. if ( Math.abs( m13 ) < 0.99999 ) {
  1771. this._x = Math.atan2( - m23, m33 );
  1772. this._z = Math.atan2( - m12, m11 );
  1773. } else {
  1774. this._x = Math.atan2( m32, m22 );
  1775. this._z = 0;
  1776. }
  1777. } else if ( order === 'YXZ' ) {
  1778. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  1779. if ( Math.abs( m23 ) < 0.99999 ) {
  1780. this._y = Math.atan2( m13, m33 );
  1781. this._z = Math.atan2( m21, m22 );
  1782. } else {
  1783. this._y = Math.atan2( - m31, m11 );
  1784. this._z = 0;
  1785. }
  1786. } else if ( order === 'ZXY' ) {
  1787. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  1788. if ( Math.abs( m32 ) < 0.99999 ) {
  1789. this._y = Math.atan2( - m31, m33 );
  1790. this._z = Math.atan2( - m12, m22 );
  1791. } else {
  1792. this._y = 0;
  1793. this._z = Math.atan2( m21, m11 );
  1794. }
  1795. } else if ( order === 'ZYX' ) {
  1796. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  1797. if ( Math.abs( m31 ) < 0.99999 ) {
  1798. this._x = Math.atan2( m32, m33 );
  1799. this._z = Math.atan2( m21, m11 );
  1800. } else {
  1801. this._x = 0;
  1802. this._z = Math.atan2( - m12, m22 );
  1803. }
  1804. } else if ( order === 'YZX' ) {
  1805. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  1806. if ( Math.abs( m21 ) < 0.99999 ) {
  1807. this._x = Math.atan2( - m23, m22 );
  1808. this._y = Math.atan2( - m31, m11 );
  1809. } else {
  1810. this._x = 0;
  1811. this._y = Math.atan2( m13, m33 );
  1812. }
  1813. } else if ( order === 'XZY' ) {
  1814. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  1815. if ( Math.abs( m12 ) < 0.99999 ) {
  1816. this._x = Math.atan2( m32, m22 );
  1817. this._y = Math.atan2( m13, m11 );
  1818. } else {
  1819. this._x = Math.atan2( - m23, m33 );
  1820. this._y = 0;
  1821. }
  1822. } else {
  1823. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order )
  1824. }
  1825. this._order = order;
  1826. this.onChangeCallback();
  1827. return this;
  1828. },
  1829. setFromQuaternion: function ( q, order, update ) {
  1830. var clamp = THREE.Math.clamp;
  1831. // q is assumed to be normalized
  1832. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1833. var sqx = q.x * q.x;
  1834. var sqy = q.y * q.y;
  1835. var sqz = q.z * q.z;
  1836. var sqw = q.w * q.w;
  1837. order = order || this._order;
  1838. if ( order === 'XYZ' ) {
  1839. this._x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1840. this._y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ), - 1, 1 ) );
  1841. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1842. } else if ( order === 'YXZ' ) {
  1843. this._x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ), - 1, 1 ) );
  1844. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1845. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1846. } else if ( order === 'ZXY' ) {
  1847. this._x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ), - 1, 1 ) );
  1848. this._y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1849. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1850. } else if ( order === 'ZYX' ) {
  1851. this._x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1852. this._y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ), - 1, 1 ) );
  1853. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1854. } else if ( order === 'YZX' ) {
  1855. this._x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1856. this._y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1857. this._z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ), - 1, 1 ) );
  1858. } else if ( order === 'XZY' ) {
  1859. this._x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1860. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1861. this._z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ), - 1, 1 ) );
  1862. } else {
  1863. console.warn( 'THREE.Euler: .setFromQuaternion() given unsupported order: ' + order )
  1864. }
  1865. this._order = order;
  1866. if ( update !== false ) this.onChangeCallback();
  1867. return this;
  1868. },
  1869. reorder: function () {
  1870. // WARNING: this discards revolution information -bhouston
  1871. var q = new THREE.Quaternion();
  1872. return function ( newOrder ) {
  1873. q.setFromEuler( this );
  1874. this.setFromQuaternion( q, newOrder );
  1875. };
  1876. }(),
  1877. equals: function ( euler ) {
  1878. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  1879. },
  1880. fromArray: function ( array ) {
  1881. this._x = array[ 0 ];
  1882. this._y = array[ 1 ];
  1883. this._z = array[ 2 ];
  1884. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  1885. this.onChangeCallback();
  1886. return this;
  1887. },
  1888. toArray: function () {
  1889. return [ this._x, this._y, this._z, this._order ];
  1890. },
  1891. onChange: function ( callback ) {
  1892. this.onChangeCallback = callback;
  1893. return this;
  1894. },
  1895. onChangeCallback: function () {},
  1896. clone: function () {
  1897. return new THREE.Euler( this._x, this._y, this._z, this._order );
  1898. }
  1899. };
  1900. // File:src/math/Line3.js
  1901. /**
  1902. * @author bhouston / http://exocortex.com
  1903. */
  1904. THREE.Line3 = function ( start, end ) {
  1905. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1906. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1907. };
  1908. THREE.Line3.prototype = {
  1909. constructor: THREE.Line3,
  1910. set: function ( start, end ) {
  1911. this.start.copy( start );
  1912. this.end.copy( end );
  1913. return this;
  1914. },
  1915. copy: function ( line ) {
  1916. this.start.copy( line.start );
  1917. this.end.copy( line.end );
  1918. return this;
  1919. },
  1920. center: function ( optionalTarget ) {
  1921. var result = optionalTarget || new THREE.Vector3();
  1922. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1923. },
  1924. delta: function ( optionalTarget ) {
  1925. var result = optionalTarget || new THREE.Vector3();
  1926. return result.subVectors( this.end, this.start );
  1927. },
  1928. distanceSq: function () {
  1929. return this.start.distanceToSquared( this.end );
  1930. },
  1931. distance: function () {
  1932. return this.start.distanceTo( this.end );
  1933. },
  1934. at: function ( t, optionalTarget ) {
  1935. var result = optionalTarget || new THREE.Vector3();
  1936. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1937. },
  1938. closestPointToPointParameter: function () {
  1939. var startP = new THREE.Vector3();
  1940. var startEnd = new THREE.Vector3();
  1941. return function ( point, clampToLine ) {
  1942. startP.subVectors( point, this.start );
  1943. startEnd.subVectors( this.end, this.start );
  1944. var startEnd2 = startEnd.dot( startEnd );
  1945. var startEnd_startP = startEnd.dot( startP );
  1946. var t = startEnd_startP / startEnd2;
  1947. if ( clampToLine ) {
  1948. t = THREE.Math.clamp( t, 0, 1 );
  1949. }
  1950. return t;
  1951. };
  1952. }(),
  1953. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1954. var t = this.closestPointToPointParameter( point, clampToLine );
  1955. var result = optionalTarget || new THREE.Vector3();
  1956. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1957. },
  1958. applyMatrix4: function ( matrix ) {
  1959. this.start.applyMatrix4( matrix );
  1960. this.end.applyMatrix4( matrix );
  1961. return this;
  1962. },
  1963. equals: function ( line ) {
  1964. return line.start.equals( this.start ) && line.end.equals( this.end );
  1965. },
  1966. clone: function () {
  1967. return new THREE.Line3().copy( this );
  1968. }
  1969. };
  1970. // File:src/math/Box2.js
  1971. /**
  1972. * @author bhouston / http://exocortex.com
  1973. */
  1974. THREE.Box2 = function ( min, max ) {
  1975. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1976. this.max = ( max !== undefined ) ? max : new THREE.Vector2( - Infinity, - Infinity );
  1977. };
  1978. THREE.Box2.prototype = {
  1979. constructor: THREE.Box2,
  1980. set: function ( min, max ) {
  1981. this.min.copy( min );
  1982. this.max.copy( max );
  1983. return this;
  1984. },
  1985. setFromPoints: function ( points ) {
  1986. this.makeEmpty();
  1987. for ( var i = 0, il = points.length; i < il; i ++ ) {
  1988. this.expandByPoint( points[ i ] )
  1989. }
  1990. return this;
  1991. },
  1992. setFromCenterAndSize: function () {
  1993. var v1 = new THREE.Vector2();
  1994. return function ( center, size ) {
  1995. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1996. this.min.copy( center ).sub( halfSize );
  1997. this.max.copy( center ).add( halfSize );
  1998. return this;
  1999. };
  2000. }(),
  2001. copy: function ( box ) {
  2002. this.min.copy( box.min );
  2003. this.max.copy( box.max );
  2004. return this;
  2005. },
  2006. makeEmpty: function () {
  2007. this.min.x = this.min.y = Infinity;
  2008. this.max.x = this.max.y = - Infinity;
  2009. return this;
  2010. },
  2011. empty: function () {
  2012. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2013. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  2014. },
  2015. center: function ( optionalTarget ) {
  2016. var result = optionalTarget || new THREE.Vector2();
  2017. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2018. },
  2019. size: function ( optionalTarget ) {
  2020. var result = optionalTarget || new THREE.Vector2();
  2021. return result.subVectors( this.max, this.min );
  2022. },
  2023. expandByPoint: function ( point ) {
  2024. this.min.min( point );
  2025. this.max.max( point );
  2026. return this;
  2027. },
  2028. expandByVector: function ( vector ) {
  2029. this.min.sub( vector );
  2030. this.max.add( vector );
  2031. return this;
  2032. },
  2033. expandByScalar: function ( scalar ) {
  2034. this.min.addScalar( - scalar );
  2035. this.max.addScalar( scalar );
  2036. return this;
  2037. },
  2038. containsPoint: function ( point ) {
  2039. if ( point.x < this.min.x || point.x > this.max.x ||
  2040. point.y < this.min.y || point.y > this.max.y ) {
  2041. return false;
  2042. }
  2043. return true;
  2044. },
  2045. containsBox: function ( box ) {
  2046. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2047. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  2048. return true;
  2049. }
  2050. return false;
  2051. },
  2052. getParameter: function ( point, optionalTarget ) {
  2053. // This can potentially have a divide by zero if the box
  2054. // has a size dimension of 0.
  2055. var result = optionalTarget || new THREE.Vector2();
  2056. return result.set(
  2057. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2058. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  2059. );
  2060. },
  2061. isIntersectionBox: function ( box ) {
  2062. // using 6 splitting planes to rule out intersections.
  2063. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2064. box.max.y < this.min.y || box.min.y > this.max.y ) {
  2065. return false;
  2066. }
  2067. return true;
  2068. },
  2069. clampPoint: function ( point, optionalTarget ) {
  2070. var result = optionalTarget || new THREE.Vector2();
  2071. return result.copy( point ).clamp( this.min, this.max );
  2072. },
  2073. distanceToPoint: function () {
  2074. var v1 = new THREE.Vector2();
  2075. return function ( point ) {
  2076. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2077. return clampedPoint.sub( point ).length();
  2078. };
  2079. }(),
  2080. intersect: function ( box ) {
  2081. this.min.max( box.min );
  2082. this.max.min( box.max );
  2083. return this;
  2084. },
  2085. union: function ( box ) {
  2086. this.min.min( box.min );
  2087. this.max.max( box.max );
  2088. return this;
  2089. },
  2090. translate: function ( offset ) {
  2091. this.min.add( offset );
  2092. this.max.add( offset );
  2093. return this;
  2094. },
  2095. equals: function ( box ) {
  2096. return box.min.equals( this.min ) && box.max.equals( this.max );
  2097. },
  2098. clone: function () {
  2099. return new THREE.Box2().copy( this );
  2100. }
  2101. };
  2102. // File:src/math/Box3.js
  2103. /**
  2104. * @author bhouston / http://exocortex.com
  2105. * @author WestLangley / http://github.com/WestLangley
  2106. */
  2107. THREE.Box3 = function ( min, max ) {
  2108. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2109. this.max = ( max !== undefined ) ? max : new THREE.Vector3( - Infinity, - Infinity, - Infinity );
  2110. };
  2111. THREE.Box3.prototype = {
  2112. constructor: THREE.Box3,
  2113. set: function ( min, max ) {
  2114. this.min.copy( min );
  2115. this.max.copy( max );
  2116. return this;
  2117. },
  2118. setFromPoints: function ( points ) {
  2119. this.makeEmpty();
  2120. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2121. this.expandByPoint( points[ i ] )
  2122. }
  2123. return this;
  2124. },
  2125. setFromCenterAndSize: function () {
  2126. var v1 = new THREE.Vector3();
  2127. return function ( center, size ) {
  2128. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2129. this.min.copy( center ).sub( halfSize );
  2130. this.max.copy( center ).add( halfSize );
  2131. return this;
  2132. };
  2133. }(),
  2134. setFromObject: function () {
  2135. // Computes the world-axis-aligned bounding box of an object (including its children),
  2136. // accounting for both the object's, and childrens', world transforms
  2137. var v1 = new THREE.Vector3();
  2138. return function ( object ) {
  2139. var scope = this;
  2140. object.updateMatrixWorld( true );
  2141. this.makeEmpty();
  2142. object.traverse( function ( node ) {
  2143. if ( node.geometry !== undefined && node.geometry.vertices !== undefined ) {
  2144. var vertices = node.geometry.vertices;
  2145. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  2146. v1.copy( vertices[ i ] );
  2147. v1.applyMatrix4( node.matrixWorld );
  2148. scope.expandByPoint( v1 );
  2149. }
  2150. }
  2151. } );
  2152. return this;
  2153. };
  2154. }(),
  2155. copy: function ( box ) {
  2156. this.min.copy( box.min );
  2157. this.max.copy( box.max );
  2158. return this;
  2159. },
  2160. makeEmpty: function () {
  2161. this.min.x = this.min.y = this.min.z = Infinity;
  2162. this.max.x = this.max.y = this.max.z = - Infinity;
  2163. return this;
  2164. },
  2165. empty: function () {
  2166. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2167. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2168. },
  2169. center: function ( optionalTarget ) {
  2170. var result = optionalTarget || new THREE.Vector3();
  2171. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2172. },
  2173. size: function ( optionalTarget ) {
  2174. var result = optionalTarget || new THREE.Vector3();
  2175. return result.subVectors( this.max, this.min );
  2176. },
  2177. expandByPoint: function ( point ) {
  2178. this.min.min( point );
  2179. this.max.max( point );
  2180. return this;
  2181. },
  2182. expandByVector: function ( vector ) {
  2183. this.min.sub( vector );
  2184. this.max.add( vector );
  2185. return this;
  2186. },
  2187. expandByScalar: function ( scalar ) {
  2188. this.min.addScalar( - scalar );
  2189. this.max.addScalar( scalar );
  2190. return this;
  2191. },
  2192. containsPoint: function ( point ) {
  2193. if ( point.x < this.min.x || point.x > this.max.x ||
  2194. point.y < this.min.y || point.y > this.max.y ||
  2195. point.z < this.min.z || point.z > this.max.z ) {
  2196. return false;
  2197. }
  2198. return true;
  2199. },
  2200. containsBox: function ( box ) {
  2201. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2202. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2203. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2204. return true;
  2205. }
  2206. return false;
  2207. },
  2208. getParameter: function ( point, optionalTarget ) {
  2209. // This can potentially have a divide by zero if the box
  2210. // has a size dimension of 0.
  2211. var result = optionalTarget || new THREE.Vector3();
  2212. return result.set(
  2213. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2214. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2215. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2216. );
  2217. },
  2218. isIntersectionBox: function ( box ) {
  2219. // using 6 splitting planes to rule out intersections.
  2220. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2221. box.max.y < this.min.y || box.min.y > this.max.y ||
  2222. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2223. return false;
  2224. }
  2225. return true;
  2226. },
  2227. clampPoint: function ( point, optionalTarget ) {
  2228. var result = optionalTarget || new THREE.Vector3();
  2229. return result.copy( point ).clamp( this.min, this.max );
  2230. },
  2231. distanceToPoint: function () {
  2232. var v1 = new THREE.Vector3();
  2233. return function ( point ) {
  2234. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2235. return clampedPoint.sub( point ).length();
  2236. };
  2237. }(),
  2238. getBoundingSphere: function () {
  2239. var v1 = new THREE.Vector3();
  2240. return function ( optionalTarget ) {
  2241. var result = optionalTarget || new THREE.Sphere();
  2242. result.center = this.center();
  2243. result.radius = this.size( v1 ).length() * 0.5;
  2244. return result;
  2245. };
  2246. }(),
  2247. intersect: function ( box ) {
  2248. this.min.max( box.min );
  2249. this.max.min( box.max );
  2250. return this;
  2251. },
  2252. union: function ( box ) {
  2253. this.min.min( box.min );
  2254. this.max.max( box.max );
  2255. return this;
  2256. },
  2257. applyMatrix4: function () {
  2258. var points = [
  2259. new THREE.Vector3(),
  2260. new THREE.Vector3(),
  2261. new THREE.Vector3(),
  2262. new THREE.Vector3(),
  2263. new THREE.Vector3(),
  2264. new THREE.Vector3(),
  2265. new THREE.Vector3(),
  2266. new THREE.Vector3()
  2267. ];
  2268. return function ( matrix ) {
  2269. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2270. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2271. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2272. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2273. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2274. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2275. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2276. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2277. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2278. this.makeEmpty();
  2279. this.setFromPoints( points );
  2280. return this;
  2281. };
  2282. }(),
  2283. translate: function ( offset ) {
  2284. this.min.add( offset );
  2285. this.max.add( offset );
  2286. return this;
  2287. },
  2288. equals: function ( box ) {
  2289. return box.min.equals( this.min ) && box.max.equals( this.max );
  2290. },
  2291. clone: function () {
  2292. return new THREE.Box3().copy( this );
  2293. }
  2294. };
  2295. // File:src/math/Matrix3.js
  2296. /**
  2297. * @author alteredq / http://alteredqualia.com/
  2298. * @author WestLangley / http://github.com/WestLangley
  2299. * @author bhouston / http://exocortex.com
  2300. */
  2301. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2302. this.elements = new Float32Array( 9 );
  2303. var te = this.elements;
  2304. te[ 0 ] = ( n11 !== undefined ) ? n11 : 1; te[ 3 ] = n12 || 0; te[ 6 ] = n13 || 0;
  2305. te[ 1 ] = n21 || 0; te[ 4 ] = ( n22 !== undefined ) ? n22 : 1; te[ 7 ] = n23 || 0;
  2306. te[ 2 ] = n31 || 0; te[ 5 ] = n32 || 0; te[ 8 ] = ( n33 !== undefined ) ? n33 : 1;
  2307. };
  2308. THREE.Matrix3.prototype = {
  2309. constructor: THREE.Matrix3,
  2310. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2311. var te = this.elements;
  2312. te[ 0 ] = n11; te[ 3 ] = n12; te[ 6 ] = n13;
  2313. te[ 1 ] = n21; te[ 4 ] = n22; te[ 7 ] = n23;
  2314. te[ 2 ] = n31; te[ 5 ] = n32; te[ 8 ] = n33;
  2315. return this;
  2316. },
  2317. identity: function () {
  2318. this.set(
  2319. 1, 0, 0,
  2320. 0, 1, 0,
  2321. 0, 0, 1
  2322. );
  2323. return this;
  2324. },
  2325. copy: function ( m ) {
  2326. var me = m.elements;
  2327. this.set(
  2328. me[ 0 ], me[ 3 ], me[ 6 ],
  2329. me[ 1 ], me[ 4 ], me[ 7 ],
  2330. me[ 2 ], me[ 5 ], me[ 8 ]
  2331. );
  2332. return this;
  2333. },
  2334. multiplyVector3: function ( vector ) {
  2335. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2336. return vector.applyMatrix3( this );
  2337. },
  2338. multiplyVector3Array: function ( a ) {
  2339. console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2340. return this.applyToVector3Array( a );
  2341. },
  2342. applyToVector3Array: function () {
  2343. var v1 = new THREE.Vector3();
  2344. return function ( array, offset, length ) {
  2345. if ( offset === undefined ) offset = 0;
  2346. if ( length === undefined ) length = array.length;
  2347. for ( var i = 0, j = offset, il; i < length; i += 3, j += 3 ) {
  2348. v1.x = array[ j ];
  2349. v1.y = array[ j + 1 ];
  2350. v1.z = array[ j + 2 ];
  2351. v1.applyMatrix3( this );
  2352. array[ j ] = v1.x;
  2353. array[ j + 1 ] = v1.y;
  2354. array[ j + 2 ] = v1.z;
  2355. }
  2356. return array;
  2357. };
  2358. }(),
  2359. multiplyScalar: function ( s ) {
  2360. var te = this.elements;
  2361. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  2362. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  2363. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  2364. return this;
  2365. },
  2366. determinant: function () {
  2367. var te = this.elements;
  2368. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  2369. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  2370. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  2371. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  2372. },
  2373. getInverse: function ( matrix, throwOnInvertible ) {
  2374. // input: THREE.Matrix4
  2375. // ( based on http://code.google.com/p/webgl-mjs/ )
  2376. var me = matrix.elements;
  2377. var te = this.elements;
  2378. te[ 0 ] = me[ 10 ] * me[ 5 ] - me[ 6 ] * me[ 9 ];
  2379. te[ 1 ] = - me[ 10 ] * me[ 1 ] + me[ 2 ] * me[ 9 ];
  2380. te[ 2 ] = me[ 6 ] * me[ 1 ] - me[ 2 ] * me[ 5 ];
  2381. te[ 3 ] = - me[ 10 ] * me[ 4 ] + me[ 6 ] * me[ 8 ];
  2382. te[ 4 ] = me[ 10 ] * me[ 0 ] - me[ 2 ] * me[ 8 ];
  2383. te[ 5 ] = - me[ 6 ] * me[ 0 ] + me[ 2 ] * me[ 4 ];
  2384. te[ 6 ] = me[ 9 ] * me[ 4 ] - me[ 5 ] * me[ 8 ];
  2385. te[ 7 ] = - me[ 9 ] * me[ 0 ] + me[ 1 ] * me[ 8 ];
  2386. te[ 8 ] = me[ 5 ] * me[ 0 ] - me[ 1 ] * me[ 4 ];
  2387. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2388. // no inverse
  2389. if ( det === 0 ) {
  2390. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2391. if ( throwOnInvertible || false ) {
  2392. throw new Error( msg );
  2393. } else {
  2394. console.warn( msg );
  2395. }
  2396. this.identity();
  2397. return this;
  2398. }
  2399. this.multiplyScalar( 1.0 / det );
  2400. return this;
  2401. },
  2402. transpose: function () {
  2403. var tmp, m = this.elements;
  2404. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  2405. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  2406. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  2407. return this;
  2408. },
  2409. flattenToArrayOffset: function ( array, offset ) {
  2410. var te = this.elements;
  2411. array[ offset ] = te[ 0 ];
  2412. array[ offset + 1 ] = te[ 1 ];
  2413. array[ offset + 2 ] = te[ 2 ];
  2414. array[ offset + 3 ] = te[ 3 ];
  2415. array[ offset + 4 ] = te[ 4 ];
  2416. array[ offset + 5 ] = te[ 5 ];
  2417. array[ offset + 6 ] = te[ 6 ];
  2418. array[ offset + 7 ] = te[ 7 ];
  2419. array[ offset + 8 ] = te[ 8 ];
  2420. return array;
  2421. },
  2422. getNormalMatrix: function ( m ) {
  2423. // input: THREE.Matrix4
  2424. this.getInverse( m ).transpose();
  2425. return this;
  2426. },
  2427. transposeIntoArray: function ( r ) {
  2428. var m = this.elements;
  2429. r[ 0 ] = m[ 0 ];
  2430. r[ 1 ] = m[ 3 ];
  2431. r[ 2 ] = m[ 6 ];
  2432. r[ 3 ] = m[ 1 ];
  2433. r[ 4 ] = m[ 4 ];
  2434. r[ 5 ] = m[ 7 ];
  2435. r[ 6 ] = m[ 2 ];
  2436. r[ 7 ] = m[ 5 ];
  2437. r[ 8 ] = m[ 8 ];
  2438. return this;
  2439. },
  2440. fromArray: function ( array ) {
  2441. this.elements.set( array );
  2442. return this;
  2443. },
  2444. toArray: function () {
  2445. var te = this.elements;
  2446. return [
  2447. te[ 0 ], te[ 1 ], te[ 2 ],
  2448. te[ 3 ], te[ 4 ], te[ 5 ],
  2449. te[ 6 ], te[ 7 ], te[ 8 ]
  2450. ];
  2451. },
  2452. clone: function () {
  2453. var te = this.elements;
  2454. return new THREE.Matrix3(
  2455. te[ 0 ], te[ 3 ], te[ 6 ],
  2456. te[ 1 ], te[ 4 ], te[ 7 ],
  2457. te[ 2 ], te[ 5 ], te[ 8 ]
  2458. );
  2459. }
  2460. };
  2461. // File:src/math/Matrix4.js
  2462. /**
  2463. * @author mrdoob / http://mrdoob.com/
  2464. * @author supereggbert / http://www.paulbrunt.co.uk/
  2465. * @author philogb / http://blog.thejit.org/
  2466. * @author jordi_ros / http://plattsoft.com
  2467. * @author D1plo1d / http://github.com/D1plo1d
  2468. * @author alteredq / http://alteredqualia.com/
  2469. * @author mikael emtinger / http://gomo.se/
  2470. * @author timknip / http://www.floorplanner.com/
  2471. * @author bhouston / http://exocortex.com
  2472. * @author WestLangley / http://github.com/WestLangley
  2473. */
  2474. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2475. this.elements = new Float32Array( 16 );
  2476. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2477. // we should not support semi specification of Matrix4, it is just weird.
  2478. var te = this.elements;
  2479. te[ 0 ] = ( n11 !== undefined ) ? n11 : 1; te[ 4 ] = n12 || 0; te[ 8 ] = n13 || 0; te[ 12 ] = n14 || 0;
  2480. te[ 1 ] = n21 || 0; te[ 5 ] = ( n22 !== undefined ) ? n22 : 1; te[ 9 ] = n23 || 0; te[ 13 ] = n24 || 0;
  2481. te[ 2 ] = n31 || 0; te[ 6 ] = n32 || 0; te[ 10 ] = ( n33 !== undefined ) ? n33 : 1; te[ 14 ] = n34 || 0;
  2482. te[ 3 ] = n41 || 0; te[ 7 ] = n42 || 0; te[ 11 ] = n43 || 0; te[ 15 ] = ( n44 !== undefined ) ? n44 : 1;
  2483. };
  2484. THREE.Matrix4.prototype = {
  2485. constructor: THREE.Matrix4,
  2486. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2487. var te = this.elements;
  2488. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  2489. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  2490. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  2491. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  2492. return this;
  2493. },
  2494. identity: function () {
  2495. this.set(
  2496. 1, 0, 0, 0,
  2497. 0, 1, 0, 0,
  2498. 0, 0, 1, 0,
  2499. 0, 0, 0, 1
  2500. );
  2501. return this;
  2502. },
  2503. copy: function ( m ) {
  2504. this.elements.set( m.elements );
  2505. return this;
  2506. },
  2507. extractPosition: function ( m ) {
  2508. console.warn( 'THREEMatrix4: .extractPosition() has been renamed to .copyPosition().' );
  2509. return this.copyPosition( m );
  2510. },
  2511. copyPosition: function ( m ) {
  2512. var te = this.elements;
  2513. var me = m.elements;
  2514. te[ 12 ] = me[ 12 ];
  2515. te[ 13 ] = me[ 13 ];
  2516. te[ 14 ] = me[ 14 ];
  2517. return this;
  2518. },
  2519. extractRotation: function () {
  2520. var v1 = new THREE.Vector3();
  2521. return function ( m ) {
  2522. var te = this.elements;
  2523. var me = m.elements;
  2524. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  2525. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  2526. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  2527. te[ 0 ] = me[ 0 ] * scaleX;
  2528. te[ 1 ] = me[ 1 ] * scaleX;
  2529. te[ 2 ] = me[ 2 ] * scaleX;
  2530. te[ 4 ] = me[ 4 ] * scaleY;
  2531. te[ 5 ] = me[ 5 ] * scaleY;
  2532. te[ 6 ] = me[ 6 ] * scaleY;
  2533. te[ 8 ] = me[ 8 ] * scaleZ;
  2534. te[ 9 ] = me[ 9 ] * scaleZ;
  2535. te[ 10 ] = me[ 10 ] * scaleZ;
  2536. return this;
  2537. };
  2538. }(),
  2539. makeRotationFromEuler: function ( euler ) {
  2540. if ( euler instanceof THREE.Euler === false ) {
  2541. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  2542. }
  2543. var te = this.elements;
  2544. var x = euler.x, y = euler.y, z = euler.z;
  2545. var a = Math.cos( x ), b = Math.sin( x );
  2546. var c = Math.cos( y ), d = Math.sin( y );
  2547. var e = Math.cos( z ), f = Math.sin( z );
  2548. if ( euler.order === 'XYZ' ) {
  2549. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2550. te[ 0 ] = c * e;
  2551. te[ 4 ] = - c * f;
  2552. te[ 8 ] = d;
  2553. te[ 1 ] = af + be * d;
  2554. te[ 5 ] = ae - bf * d;
  2555. te[ 9 ] = - b * c;
  2556. te[ 2 ] = bf - ae * d;
  2557. te[ 6 ] = be + af * d;
  2558. te[ 10 ] = a * c;
  2559. } else if ( euler.order === 'YXZ' ) {
  2560. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2561. te[ 0 ] = ce + df * b;
  2562. te[ 4 ] = de * b - cf;
  2563. te[ 8 ] = a * d;
  2564. te[ 1 ] = a * f;
  2565. te[ 5 ] = a * e;
  2566. te[ 9 ] = - b;
  2567. te[ 2 ] = cf * b - de;
  2568. te[ 6 ] = df + ce * b;
  2569. te[ 10 ] = a * c;
  2570. } else if ( euler.order === 'ZXY' ) {
  2571. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2572. te[ 0 ] = ce - df * b;
  2573. te[ 4 ] = - a * f;
  2574. te[ 8 ] = de + cf * b;
  2575. te[ 1 ] = cf + de * b;
  2576. te[ 5 ] = a * e;
  2577. te[ 9 ] = df - ce * b;
  2578. te[ 2 ] = - a * d;
  2579. te[ 6 ] = b;
  2580. te[ 10 ] = a * c;
  2581. } else if ( euler.order === 'ZYX' ) {
  2582. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2583. te[ 0 ] = c * e;
  2584. te[ 4 ] = be * d - af;
  2585. te[ 8 ] = ae * d + bf;
  2586. te[ 1 ] = c * f;
  2587. te[ 5 ] = bf * d + ae;
  2588. te[ 9 ] = af * d - be;
  2589. te[ 2 ] = - d;
  2590. te[ 6 ] = b * c;
  2591. te[ 10 ] = a * c;
  2592. } else if ( euler.order === 'YZX' ) {
  2593. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2594. te[ 0 ] = c * e;
  2595. te[ 4 ] = bd - ac * f;
  2596. te[ 8 ] = bc * f + ad;
  2597. te[ 1 ] = f;
  2598. te[ 5 ] = a * e;
  2599. te[ 9 ] = - b * e;
  2600. te[ 2 ] = - d * e;
  2601. te[ 6 ] = ad * f + bc;
  2602. te[ 10 ] = ac - bd * f;
  2603. } else if ( euler.order === 'XZY' ) {
  2604. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2605. te[ 0 ] = c * e;
  2606. te[ 4 ] = - f;
  2607. te[ 8 ] = d * e;
  2608. te[ 1 ] = ac * f + bd;
  2609. te[ 5 ] = a * e;
  2610. te[ 9 ] = ad * f - bc;
  2611. te[ 2 ] = bc * f - ad;
  2612. te[ 6 ] = b * e;
  2613. te[ 10 ] = bd * f + ac;
  2614. }
  2615. // last column
  2616. te[ 3 ] = 0;
  2617. te[ 7 ] = 0;
  2618. te[ 11 ] = 0;
  2619. // bottom row
  2620. te[ 12 ] = 0;
  2621. te[ 13 ] = 0;
  2622. te[ 14 ] = 0;
  2623. te[ 15 ] = 1;
  2624. return this;
  2625. },
  2626. setRotationFromQuaternion: function ( q ) {
  2627. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  2628. return this.makeRotationFromQuaternion( q );
  2629. },
  2630. makeRotationFromQuaternion: function ( q ) {
  2631. var te = this.elements;
  2632. var x = q.x, y = q.y, z = q.z, w = q.w;
  2633. var x2 = x + x, y2 = y + y, z2 = z + z;
  2634. var xx = x * x2, xy = x * y2, xz = x * z2;
  2635. var yy = y * y2, yz = y * z2, zz = z * z2;
  2636. var wx = w * x2, wy = w * y2, wz = w * z2;
  2637. te[ 0 ] = 1 - ( yy + zz );
  2638. te[ 4 ] = xy - wz;
  2639. te[ 8 ] = xz + wy;
  2640. te[ 1 ] = xy + wz;
  2641. te[ 5 ] = 1 - ( xx + zz );
  2642. te[ 9 ] = yz - wx;
  2643. te[ 2 ] = xz - wy;
  2644. te[ 6 ] = yz + wx;
  2645. te[ 10 ] = 1 - ( xx + yy );
  2646. // last column
  2647. te[ 3 ] = 0;
  2648. te[ 7 ] = 0;
  2649. te[ 11 ] = 0;
  2650. // bottom row
  2651. te[ 12 ] = 0;
  2652. te[ 13 ] = 0;
  2653. te[ 14 ] = 0;
  2654. te[ 15 ] = 1;
  2655. return this;
  2656. },
  2657. lookAt: function () {
  2658. var x = new THREE.Vector3();
  2659. var y = new THREE.Vector3();
  2660. var z = new THREE.Vector3();
  2661. return function ( eye, target, up ) {
  2662. var te = this.elements;
  2663. z.subVectors( eye, target ).normalize();
  2664. if ( z.length() === 0 ) {
  2665. z.z = 1;
  2666. }
  2667. x.crossVectors( up, z ).normalize();
  2668. if ( x.length() === 0 ) {
  2669. z.x += 0.0001;
  2670. x.crossVectors( up, z ).normalize();
  2671. }
  2672. y.crossVectors( z, x );
  2673. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  2674. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  2675. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  2676. return this;
  2677. };
  2678. }(),
  2679. multiply: function ( m, n ) {
  2680. if ( n !== undefined ) {
  2681. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2682. return this.multiplyMatrices( m, n );
  2683. }
  2684. return this.multiplyMatrices( this, m );
  2685. },
  2686. multiplyMatrices: function ( a, b ) {
  2687. var ae = a.elements;
  2688. var be = b.elements;
  2689. var te = this.elements;
  2690. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  2691. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  2692. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  2693. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  2694. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  2695. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  2696. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  2697. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  2698. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2699. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2700. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2701. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2702. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2703. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2704. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2705. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2706. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2707. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2708. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2709. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2710. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2711. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2712. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2713. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2714. return this;
  2715. },
  2716. multiplyToArray: function ( a, b, r ) {
  2717. var te = this.elements;
  2718. this.multiplyMatrices( a, b );
  2719. r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ];
  2720. r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ];
  2721. r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ];
  2722. r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ];
  2723. return this;
  2724. },
  2725. multiplyScalar: function ( s ) {
  2726. var te = this.elements;
  2727. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  2728. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  2729. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  2730. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  2731. return this;
  2732. },
  2733. multiplyVector3: function ( vector ) {
  2734. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2735. return vector.applyProjection( this );
  2736. },
  2737. multiplyVector4: function ( vector ) {
  2738. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2739. return vector.applyMatrix4( this );
  2740. },
  2741. multiplyVector3Array: function ( a ) {
  2742. console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2743. return this.applyToVector3Array( a );
  2744. },
  2745. applyToVector3Array: function () {
  2746. var v1 = new THREE.Vector3();
  2747. return function ( array, offset, length ) {
  2748. if ( offset === undefined ) offset = 0;
  2749. if ( length === undefined ) length = array.length;
  2750. for ( var i = 0, j = offset, il; i < length; i += 3, j += 3 ) {
  2751. v1.x = array[ j ];
  2752. v1.y = array[ j + 1 ];
  2753. v1.z = array[ j + 2 ];
  2754. v1.applyMatrix4( this );
  2755. array[ j ] = v1.x;
  2756. array[ j + 1 ] = v1.y;
  2757. array[ j + 2 ] = v1.z;
  2758. }
  2759. return array;
  2760. };
  2761. }(),
  2762. rotateAxis: function ( v ) {
  2763. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2764. v.transformDirection( this );
  2765. },
  2766. crossVector: function ( vector ) {
  2767. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2768. return vector.applyMatrix4( this );
  2769. },
  2770. determinant: function () {
  2771. var te = this.elements;
  2772. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  2773. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  2774. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  2775. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  2776. //TODO: make this more efficient
  2777. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2778. return (
  2779. n41 * (
  2780. + n14 * n23 * n32
  2781. - n13 * n24 * n32
  2782. - n14 * n22 * n33
  2783. + n12 * n24 * n33
  2784. + n13 * n22 * n34
  2785. - n12 * n23 * n34
  2786. ) +
  2787. n42 * (
  2788. + n11 * n23 * n34
  2789. - n11 * n24 * n33
  2790. + n14 * n21 * n33
  2791. - n13 * n21 * n34
  2792. + n13 * n24 * n31
  2793. - n14 * n23 * n31
  2794. ) +
  2795. n43 * (
  2796. + n11 * n24 * n32
  2797. - n11 * n22 * n34
  2798. - n14 * n21 * n32
  2799. + n12 * n21 * n34
  2800. + n14 * n22 * n31
  2801. - n12 * n24 * n31
  2802. ) +
  2803. n44 * (
  2804. - n13 * n22 * n31
  2805. - n11 * n23 * n32
  2806. + n11 * n22 * n33
  2807. + n13 * n21 * n32
  2808. - n12 * n21 * n33
  2809. + n12 * n23 * n31
  2810. )
  2811. );
  2812. },
  2813. transpose: function () {
  2814. var te = this.elements;
  2815. var tmp;
  2816. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  2817. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  2818. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  2819. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  2820. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  2821. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  2822. return this;
  2823. },
  2824. flattenToArrayOffset: function ( array, offset ) {
  2825. var te = this.elements;
  2826. array[ offset ] = te[ 0 ];
  2827. array[ offset + 1 ] = te[ 1 ];
  2828. array[ offset + 2 ] = te[ 2 ];
  2829. array[ offset + 3 ] = te[ 3 ];
  2830. array[ offset + 4 ] = te[ 4 ];
  2831. array[ offset + 5 ] = te[ 5 ];
  2832. array[ offset + 6 ] = te[ 6 ];
  2833. array[ offset + 7 ] = te[ 7 ];
  2834. array[ offset + 8 ] = te[ 8 ];
  2835. array[ offset + 9 ] = te[ 9 ];
  2836. array[ offset + 10 ] = te[ 10 ];
  2837. array[ offset + 11 ] = te[ 11 ];
  2838. array[ offset + 12 ] = te[ 12 ];
  2839. array[ offset + 13 ] = te[ 13 ];
  2840. array[ offset + 14 ] = te[ 14 ];
  2841. array[ offset + 15 ] = te[ 15 ];
  2842. return array;
  2843. },
  2844. getPosition: function () {
  2845. var v1 = new THREE.Vector3();
  2846. return function () {
  2847. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  2848. var te = this.elements;
  2849. return v1.set( te[ 12 ], te[ 13 ], te[ 14 ] );
  2850. };
  2851. }(),
  2852. setPosition: function ( v ) {
  2853. var te = this.elements;
  2854. te[ 12 ] = v.x;
  2855. te[ 13 ] = v.y;
  2856. te[ 14 ] = v.z;
  2857. return this;
  2858. },
  2859. getInverse: function ( m, throwOnInvertible ) {
  2860. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2861. var te = this.elements;
  2862. var me = m.elements;
  2863. var n11 = me[ 0 ], n12 = me[ 4 ], n13 = me[ 8 ], n14 = me[ 12 ];
  2864. var n21 = me[ 1 ], n22 = me[ 5 ], n23 = me[ 9 ], n24 = me[ 13 ];
  2865. var n31 = me[ 2 ], n32 = me[ 6 ], n33 = me[ 10 ], n34 = me[ 14 ];
  2866. var n41 = me[ 3 ], n42 = me[ 7 ], n43 = me[ 11 ], n44 = me[ 15 ];
  2867. te[ 0 ] = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44;
  2868. te[ 4 ] = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44;
  2869. te[ 8 ] = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44;
  2870. te[ 12 ] = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  2871. te[ 1 ] = n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44;
  2872. te[ 5 ] = n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44;
  2873. te[ 9 ] = n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44;
  2874. te[ 13 ] = n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34;
  2875. te[ 2 ] = n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44;
  2876. te[ 6 ] = n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44;
  2877. te[ 10 ] = n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44;
  2878. te[ 14 ] = n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34;
  2879. te[ 3 ] = n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43;
  2880. te[ 7 ] = n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43;
  2881. te[ 11 ] = n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43;
  2882. te[ 15 ] = n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33;
  2883. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  2884. if ( det == 0 ) {
  2885. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2886. if ( throwOnInvertible || false ) {
  2887. throw new Error( msg );
  2888. } else {
  2889. console.warn( msg );
  2890. }
  2891. this.identity();
  2892. return this;
  2893. }
  2894. this.multiplyScalar( 1 / det );
  2895. return this;
  2896. },
  2897. translate: function ( v ) {
  2898. console.warn( 'THREE.Matrix4: .translate() has been removed.' );
  2899. },
  2900. rotateX: function ( angle ) {
  2901. console.warn( 'THREE.Matrix4: .rotateX() has been removed.' );
  2902. },
  2903. rotateY: function ( angle ) {
  2904. console.warn( 'THREE.Matrix4: .rotateY() has been removed.' );
  2905. },
  2906. rotateZ: function ( angle ) {
  2907. console.warn( 'THREE.Matrix4: .rotateZ() has been removed.' );
  2908. },
  2909. rotateByAxis: function ( axis, angle ) {
  2910. console.warn( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  2911. },
  2912. scale: function ( v ) {
  2913. var te = this.elements;
  2914. var x = v.x, y = v.y, z = v.z;
  2915. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  2916. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  2917. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  2918. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  2919. return this;
  2920. },
  2921. getMaxScaleOnAxis: function () {
  2922. var te = this.elements;
  2923. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  2924. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  2925. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  2926. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2927. },
  2928. makeTranslation: function ( x, y, z ) {
  2929. this.set(
  2930. 1, 0, 0, x,
  2931. 0, 1, 0, y,
  2932. 0, 0, 1, z,
  2933. 0, 0, 0, 1
  2934. );
  2935. return this;
  2936. },
  2937. makeRotationX: function ( theta ) {
  2938. var c = Math.cos( theta ), s = Math.sin( theta );
  2939. this.set(
  2940. 1, 0, 0, 0,
  2941. 0, c, - s, 0,
  2942. 0, s, c, 0,
  2943. 0, 0, 0, 1
  2944. );
  2945. return this;
  2946. },
  2947. makeRotationY: function ( theta ) {
  2948. var c = Math.cos( theta ), s = Math.sin( theta );
  2949. this.set(
  2950. c, 0, s, 0,
  2951. 0, 1, 0, 0,
  2952. - s, 0, c, 0,
  2953. 0, 0, 0, 1
  2954. );
  2955. return this;
  2956. },
  2957. makeRotationZ: function ( theta ) {
  2958. var c = Math.cos( theta ), s = Math.sin( theta );
  2959. this.set(
  2960. c, - s, 0, 0,
  2961. s, c, 0, 0,
  2962. 0, 0, 1, 0,
  2963. 0, 0, 0, 1
  2964. );
  2965. return this;
  2966. },
  2967. makeRotationAxis: function ( axis, angle ) {
  2968. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2969. var c = Math.cos( angle );
  2970. var s = Math.sin( angle );
  2971. var t = 1 - c;
  2972. var x = axis.x, y = axis.y, z = axis.z;
  2973. var tx = t * x, ty = t * y;
  2974. this.set(
  2975. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2976. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2977. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2978. 0, 0, 0, 1
  2979. );
  2980. return this;
  2981. },
  2982. makeScale: function ( x, y, z ) {
  2983. this.set(
  2984. x, 0, 0, 0,
  2985. 0, y, 0, 0,
  2986. 0, 0, z, 0,
  2987. 0, 0, 0, 1
  2988. );
  2989. return this;
  2990. },
  2991. compose: function ( position, quaternion, scale ) {
  2992. this.makeRotationFromQuaternion( quaternion );
  2993. this.scale( scale );
  2994. this.setPosition( position );
  2995. return this;
  2996. },
  2997. decompose: function () {
  2998. var vector = new THREE.Vector3();
  2999. var matrix = new THREE.Matrix4();
  3000. return function ( position, quaternion, scale ) {
  3001. var te = this.elements;
  3002. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3003. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3004. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3005. // if determine is negative, we need to invert one scale
  3006. var det = this.determinant();
  3007. if ( det < 0 ) {
  3008. sx = - sx;
  3009. }
  3010. position.x = te[ 12 ];
  3011. position.y = te[ 13 ];
  3012. position.z = te[ 14 ];
  3013. // scale the rotation part
  3014. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  3015. var invSX = 1 / sx;
  3016. var invSY = 1 / sy;
  3017. var invSZ = 1 / sz;
  3018. matrix.elements[ 0 ] *= invSX;
  3019. matrix.elements[ 1 ] *= invSX;
  3020. matrix.elements[ 2 ] *= invSX;
  3021. matrix.elements[ 4 ] *= invSY;
  3022. matrix.elements[ 5 ] *= invSY;
  3023. matrix.elements[ 6 ] *= invSY;
  3024. matrix.elements[ 8 ] *= invSZ;
  3025. matrix.elements[ 9 ] *= invSZ;
  3026. matrix.elements[ 10 ] *= invSZ;
  3027. quaternion.setFromRotationMatrix( matrix );
  3028. scale.x = sx;
  3029. scale.y = sy;
  3030. scale.z = sz;
  3031. return this;
  3032. };
  3033. }(),
  3034. makeFrustum: function ( left, right, bottom, top, near, far ) {
  3035. var te = this.elements;
  3036. var x = 2 * near / ( right - left );
  3037. var y = 2 * near / ( top - bottom );
  3038. var a = ( right + left ) / ( right - left );
  3039. var b = ( top + bottom ) / ( top - bottom );
  3040. var c = - ( far + near ) / ( far - near );
  3041. var d = - 2 * far * near / ( far - near );
  3042. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3043. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3044. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3045. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3046. return this;
  3047. },
  3048. makePerspective: function ( fov, aspect, near, far ) {
  3049. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  3050. var ymin = - ymax;
  3051. var xmin = ymin * aspect;
  3052. var xmax = ymax * aspect;
  3053. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  3054. },
  3055. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  3056. var te = this.elements;
  3057. var w = right - left;
  3058. var h = top - bottom;
  3059. var p = far - near;
  3060. var x = ( right + left ) / w;
  3061. var y = ( top + bottom ) / h;
  3062. var z = ( far + near ) / p;
  3063. te[ 0 ] = 2 / w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3064. te[ 1 ] = 0; te[ 5 ] = 2 / h; te[ 9 ] = 0; te[ 13 ] = - y;
  3065. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 / p; te[ 14 ] = - z;
  3066. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3067. return this;
  3068. },
  3069. fromArray: function ( array ) {
  3070. this.elements.set( array );
  3071. return this;
  3072. },
  3073. toArray: function () {
  3074. var te = this.elements;
  3075. return [
  3076. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  3077. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  3078. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  3079. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  3080. ];
  3081. },
  3082. clone: function () {
  3083. var te = this.elements;
  3084. return new THREE.Matrix4(
  3085. te[ 0 ], te[ 4 ], te[ 8 ], te[ 12 ],
  3086. te[ 1 ], te[ 5 ], te[ 9 ], te[ 13 ],
  3087. te[ 2 ], te[ 6 ], te[ 10 ], te[ 14 ],
  3088. te[ 3 ], te[ 7 ], te[ 11 ], te[ 15 ]
  3089. );
  3090. }
  3091. };
  3092. // File:src/math/Ray.js
  3093. /**
  3094. * @author bhouston / http://exocortex.com
  3095. */
  3096. THREE.Ray = function ( origin, direction ) {
  3097. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  3098. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  3099. };
  3100. THREE.Ray.prototype = {
  3101. constructor: THREE.Ray,
  3102. set: function ( origin, direction ) {
  3103. this.origin.copy( origin );
  3104. this.direction.copy( direction );
  3105. return this;
  3106. },
  3107. copy: function ( ray ) {
  3108. this.origin.copy( ray.origin );
  3109. this.direction.copy( ray.direction );
  3110. return this;
  3111. },
  3112. at: function ( t, optionalTarget ) {
  3113. var result = optionalTarget || new THREE.Vector3();
  3114. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3115. },
  3116. recast: function () {
  3117. var v1 = new THREE.Vector3();
  3118. return function ( t ) {
  3119. this.origin.copy( this.at( t, v1 ) );
  3120. return this;
  3121. };
  3122. }(),
  3123. closestPointToPoint: function ( point, optionalTarget ) {
  3124. var result = optionalTarget || new THREE.Vector3();
  3125. result.subVectors( point, this.origin );
  3126. var directionDistance = result.dot( this.direction );
  3127. if ( directionDistance < 0 ) {
  3128. return result.copy( this.origin );
  3129. }
  3130. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3131. },
  3132. distanceToPoint: function () {
  3133. var v1 = new THREE.Vector3();
  3134. return function ( point ) {
  3135. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3136. // point behind the ray
  3137. if ( directionDistance < 0 ) {
  3138. return this.origin.distanceTo( point );
  3139. }
  3140. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3141. return v1.distanceTo( point );
  3142. };
  3143. }(),
  3144. distanceSqToSegment: function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3145. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3146. // It returns the min distance between the ray and the segment
  3147. // defined by v0 and v1
  3148. // It can also set two optional targets :
  3149. // - The closest point on the ray
  3150. // - The closest point on the segment
  3151. var segCenter = v0.clone().add( v1 ).multiplyScalar( 0.5 );
  3152. var segDir = v1.clone().sub( v0 ).normalize();
  3153. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3154. var diff = this.origin.clone().sub( segCenter );
  3155. var a01 = - this.direction.dot( segDir );
  3156. var b0 = diff.dot( this.direction );
  3157. var b1 = - diff.dot( segDir );
  3158. var c = diff.lengthSq();
  3159. var det = Math.abs( 1 - a01 * a01 );
  3160. var s0, s1, sqrDist, extDet;
  3161. if ( det >= 0 ) {
  3162. // The ray and segment are not parallel.
  3163. s0 = a01 * b1 - b0;
  3164. s1 = a01 * b0 - b1;
  3165. extDet = segExtent * det;
  3166. if ( s0 >= 0 ) {
  3167. if ( s1 >= - extDet ) {
  3168. if ( s1 <= extDet ) {
  3169. // region 0
  3170. // Minimum at interior points of ray and segment.
  3171. var invDet = 1 / det;
  3172. s0 *= invDet;
  3173. s1 *= invDet;
  3174. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3175. } else {
  3176. // region 1
  3177. s1 = segExtent;
  3178. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3179. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3180. }
  3181. } else {
  3182. // region 5
  3183. s1 = - segExtent;
  3184. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3185. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3186. }
  3187. } else {
  3188. if ( s1 <= - extDet ) {
  3189. // region 4
  3190. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3191. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3192. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3193. } else if ( s1 <= extDet ) {
  3194. // region 3
  3195. s0 = 0;
  3196. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3197. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3198. } else {
  3199. // region 2
  3200. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3201. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3202. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3203. }
  3204. }
  3205. } else {
  3206. // Ray and segment are parallel.
  3207. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3208. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3209. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3210. }
  3211. if ( optionalPointOnRay ) {
  3212. optionalPointOnRay.copy( this.direction.clone().multiplyScalar( s0 ).add( this.origin ) );
  3213. }
  3214. if ( optionalPointOnSegment ) {
  3215. optionalPointOnSegment.copy( segDir.clone().multiplyScalar( s1 ).add( segCenter ) );
  3216. }
  3217. return sqrDist;
  3218. },
  3219. isIntersectionSphere: function ( sphere ) {
  3220. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3221. },
  3222. intersectSphere: function () {
  3223. // from http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-sphere-intersection/
  3224. var v1 = new THREE.Vector3();
  3225. return function ( sphere, optionalTarget ) {
  3226. v1.subVectors( sphere.center, this.origin );
  3227. var tca = v1.dot( this.direction );
  3228. var d2 = v1.dot( v1 ) - tca * tca;
  3229. var radius2 = sphere.radius * sphere.radius;
  3230. if ( d2 > radius2 ) return null;
  3231. var thc = Math.sqrt( radius2 - d2 );
  3232. // t0 = first intersect point - entrance on front of sphere
  3233. var t0 = tca - thc;
  3234. // t1 = second intersect point - exit point on back of sphere
  3235. var t1 = tca + thc;
  3236. // test to see if both t0 and t1 are behind the ray - if so, return null
  3237. if ( t0 < 0 && t1 < 0 ) return null;
  3238. // test to see if t0 is behind the ray:
  3239. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3240. // in order to always return an intersect point that is in front of the ray.
  3241. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  3242. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3243. return this.at( t0, optionalTarget );
  3244. }
  3245. }(),
  3246. isIntersectionPlane: function ( plane ) {
  3247. // check if the ray lies on the plane first
  3248. var distToPoint = plane.distanceToPoint( this.origin );
  3249. if ( distToPoint === 0 ) {
  3250. return true;
  3251. }
  3252. var denominator = plane.normal.dot( this.direction );
  3253. if ( denominator * distToPoint < 0 ) {
  3254. return true;
  3255. }
  3256. // ray origin is behind the plane (and is pointing behind it)
  3257. return false;
  3258. },
  3259. distanceToPlane: function ( plane ) {
  3260. var denominator = plane.normal.dot( this.direction );
  3261. if ( denominator == 0 ) {
  3262. // line is coplanar, return origin
  3263. if ( plane.distanceToPoint( this.origin ) == 0 ) {
  3264. return 0;
  3265. }
  3266. // Null is preferable to undefined since undefined means.... it is undefined
  3267. return null;
  3268. }
  3269. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3270. // Return if the ray never intersects the plane
  3271. return t >= 0 ? t : null;
  3272. },
  3273. intersectPlane: function ( plane, optionalTarget ) {
  3274. var t = this.distanceToPlane( plane );
  3275. if ( t === null ) {
  3276. return null;
  3277. }
  3278. return this.at( t, optionalTarget );
  3279. },
  3280. isIntersectionBox: function () {
  3281. var v = new THREE.Vector3();
  3282. return function ( box ) {
  3283. return this.intersectBox( box, v ) !== null;
  3284. };
  3285. }(),
  3286. intersectBox: function ( box , optionalTarget ) {
  3287. // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
  3288. var tmin,tmax,tymin,tymax,tzmin,tzmax;
  3289. var invdirx = 1 / this.direction.x,
  3290. invdiry = 1 / this.direction.y,
  3291. invdirz = 1 / this.direction.z;
  3292. var origin = this.origin;
  3293. if ( invdirx >= 0 ) {
  3294. tmin = ( box.min.x - origin.x ) * invdirx;
  3295. tmax = ( box.max.x - origin.x ) * invdirx;
  3296. } else {
  3297. tmin = ( box.max.x - origin.x ) * invdirx;
  3298. tmax = ( box.min.x - origin.x ) * invdirx;
  3299. }
  3300. if ( invdiry >= 0 ) {
  3301. tymin = ( box.min.y - origin.y ) * invdiry;
  3302. tymax = ( box.max.y - origin.y ) * invdiry;
  3303. } else {
  3304. tymin = ( box.max.y - origin.y ) * invdiry;
  3305. tymax = ( box.min.y - origin.y ) * invdiry;
  3306. }
  3307. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3308. // These lines also handle the case where tmin or tmax is NaN
  3309. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3310. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3311. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3312. if ( invdirz >= 0 ) {
  3313. tzmin = ( box.min.z - origin.z ) * invdirz;
  3314. tzmax = ( box.max.z - origin.z ) * invdirz;
  3315. } else {
  3316. tzmin = ( box.max.z - origin.z ) * invdirz;
  3317. tzmax = ( box.min.z - origin.z ) * invdirz;
  3318. }
  3319. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3320. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3321. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3322. //return point closest to the ray (positive side)
  3323. if ( tmax < 0 ) return null;
  3324. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3325. },
  3326. intersectTriangle: function () {
  3327. // Compute the offset origin, edges, and normal.
  3328. var diff = new THREE.Vector3();
  3329. var edge1 = new THREE.Vector3();
  3330. var edge2 = new THREE.Vector3();
  3331. var normal = new THREE.Vector3();
  3332. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3333. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3334. edge1.subVectors( b, a );
  3335. edge2.subVectors( c, a );
  3336. normal.crossVectors( edge1, edge2 );
  3337. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3338. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3339. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3340. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3341. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3342. var DdN = this.direction.dot( normal );
  3343. var sign;
  3344. if ( DdN > 0 ) {
  3345. if ( backfaceCulling ) return null;
  3346. sign = 1;
  3347. } else if ( DdN < 0 ) {
  3348. sign = - 1;
  3349. DdN = - DdN;
  3350. } else {
  3351. return null;
  3352. }
  3353. diff.subVectors( this.origin, a );
  3354. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3355. // b1 < 0, no intersection
  3356. if ( DdQxE2 < 0 ) {
  3357. return null;
  3358. }
  3359. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3360. // b2 < 0, no intersection
  3361. if ( DdE1xQ < 0 ) {
  3362. return null;
  3363. }
  3364. // b1+b2 > 1, no intersection
  3365. if ( DdQxE2 + DdE1xQ > DdN ) {
  3366. return null;
  3367. }
  3368. // Line intersects triangle, check if ray does.
  3369. var QdN = - sign * diff.dot( normal );
  3370. // t < 0, no intersection
  3371. if ( QdN < 0 ) {
  3372. return null;
  3373. }
  3374. // Ray intersects triangle.
  3375. return this.at( QdN / DdN, optionalTarget );
  3376. };
  3377. }(),
  3378. applyMatrix4: function ( matrix4 ) {
  3379. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3380. this.origin.applyMatrix4( matrix4 );
  3381. this.direction.sub( this.origin );
  3382. this.direction.normalize();
  3383. return this;
  3384. },
  3385. equals: function ( ray ) {
  3386. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3387. },
  3388. clone: function () {
  3389. return new THREE.Ray().copy( this );
  3390. }
  3391. };
  3392. // File:src/math/Sphere.js
  3393. /**
  3394. * @author bhouston / http://exocortex.com
  3395. * @author mrdoob / http://mrdoob.com/
  3396. */
  3397. THREE.Sphere = function ( center, radius ) {
  3398. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3399. this.radius = ( radius !== undefined ) ? radius : 0;
  3400. };
  3401. THREE.Sphere.prototype = {
  3402. constructor: THREE.Sphere,
  3403. set: function ( center, radius ) {
  3404. this.center.copy( center );
  3405. this.radius = radius;
  3406. return this;
  3407. },
  3408. setFromPoints: function () {
  3409. var box = new THREE.Box3();
  3410. return function ( points, optionalCenter ) {
  3411. var center = this.center;
  3412. if ( optionalCenter !== undefined ) {
  3413. center.copy( optionalCenter );
  3414. } else {
  3415. box.setFromPoints( points ).center( center );
  3416. }
  3417. var maxRadiusSq = 0;
  3418. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3419. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3420. }
  3421. this.radius = Math.sqrt( maxRadiusSq );
  3422. return this;
  3423. };
  3424. }(),
  3425. copy: function ( sphere ) {
  3426. this.center.copy( sphere.center );
  3427. this.radius = sphere.radius;
  3428. return this;
  3429. },
  3430. empty: function () {
  3431. return ( this.radius <= 0 );
  3432. },
  3433. containsPoint: function ( point ) {
  3434. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3435. },
  3436. distanceToPoint: function ( point ) {
  3437. return ( point.distanceTo( this.center ) - this.radius );
  3438. },
  3439. intersectsSphere: function ( sphere ) {
  3440. var radiusSum = this.radius + sphere.radius;
  3441. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3442. },
  3443. clampPoint: function ( point, optionalTarget ) {
  3444. var deltaLengthSq = this.center.distanceToSquared( point );
  3445. var result = optionalTarget || new THREE.Vector3();
  3446. result.copy( point );
  3447. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3448. result.sub( this.center ).normalize();
  3449. result.multiplyScalar( this.radius ).add( this.center );
  3450. }
  3451. return result;
  3452. },
  3453. getBoundingBox: function ( optionalTarget ) {
  3454. var box = optionalTarget || new THREE.Box3();
  3455. box.set( this.center, this.center );
  3456. box.expandByScalar( this.radius );
  3457. return box;
  3458. },
  3459. applyMatrix4: function ( matrix ) {
  3460. this.center.applyMatrix4( matrix );
  3461. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3462. return this;
  3463. },
  3464. translate: function ( offset ) {
  3465. this.center.add( offset );
  3466. return this;
  3467. },
  3468. equals: function ( sphere ) {
  3469. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3470. },
  3471. clone: function () {
  3472. return new THREE.Sphere().copy( this );
  3473. }
  3474. };
  3475. // File:src/math/Frustum.js
  3476. /**
  3477. * @author mrdoob / http://mrdoob.com/
  3478. * @author alteredq / http://alteredqualia.com/
  3479. * @author bhouston / http://exocortex.com
  3480. */
  3481. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3482. this.planes = [
  3483. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3484. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3485. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3486. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3487. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3488. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3489. ];
  3490. };
  3491. THREE.Frustum.prototype = {
  3492. constructor: THREE.Frustum,
  3493. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3494. var planes = this.planes;
  3495. planes[ 0 ].copy( p0 );
  3496. planes[ 1 ].copy( p1 );
  3497. planes[ 2 ].copy( p2 );
  3498. planes[ 3 ].copy( p3 );
  3499. planes[ 4 ].copy( p4 );
  3500. planes[ 5 ].copy( p5 );
  3501. return this;
  3502. },
  3503. copy: function ( frustum ) {
  3504. var planes = this.planes;
  3505. for ( var i = 0; i < 6; i ++ ) {
  3506. planes[ i ].copy( frustum.planes[ i ] );
  3507. }
  3508. return this;
  3509. },
  3510. setFromMatrix: function ( m ) {
  3511. var planes = this.planes;
  3512. var me = m.elements;
  3513. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  3514. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  3515. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  3516. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  3517. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3518. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3519. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3520. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3521. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3522. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3523. return this;
  3524. },
  3525. intersectsObject: function () {
  3526. var sphere = new THREE.Sphere();
  3527. return function ( object ) {
  3528. var geometry = object.geometry;
  3529. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3530. sphere.copy( geometry.boundingSphere );
  3531. sphere.applyMatrix4( object.matrixWorld );
  3532. return this.intersectsSphere( sphere );
  3533. };
  3534. }(),
  3535. intersectsSphere: function ( sphere ) {
  3536. var planes = this.planes;
  3537. var center = sphere.center;
  3538. var negRadius = - sphere.radius;
  3539. for ( var i = 0; i < 6; i ++ ) {
  3540. var distance = planes[ i ].distanceToPoint( center );
  3541. if ( distance < negRadius ) {
  3542. return false;
  3543. }
  3544. }
  3545. return true;
  3546. },
  3547. intersectsBox: function () {
  3548. var p1 = new THREE.Vector3(),
  3549. p2 = new THREE.Vector3();
  3550. return function ( box ) {
  3551. var planes = this.planes;
  3552. for ( var i = 0; i < 6 ; i ++ ) {
  3553. var plane = planes[ i ];
  3554. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3555. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3556. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3557. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3558. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3559. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3560. var d1 = plane.distanceToPoint( p1 );
  3561. var d2 = plane.distanceToPoint( p2 );
  3562. // if both outside plane, no intersection
  3563. if ( d1 < 0 && d2 < 0 ) {
  3564. return false;
  3565. }
  3566. }
  3567. return true;
  3568. };
  3569. }(),
  3570. containsPoint: function ( point ) {
  3571. var planes = this.planes;
  3572. for ( var i = 0; i < 6; i ++ ) {
  3573. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3574. return false;
  3575. }
  3576. }
  3577. return true;
  3578. },
  3579. clone: function () {
  3580. return new THREE.Frustum().copy( this );
  3581. }
  3582. };
  3583. // File:src/math/Plane.js
  3584. /**
  3585. * @author bhouston / http://exocortex.com
  3586. */
  3587. THREE.Plane = function ( normal, constant ) {
  3588. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3589. this.constant = ( constant !== undefined ) ? constant : 0;
  3590. };
  3591. THREE.Plane.prototype = {
  3592. constructor: THREE.Plane,
  3593. set: function ( normal, constant ) {
  3594. this.normal.copy( normal );
  3595. this.constant = constant;
  3596. return this;
  3597. },
  3598. setComponents: function ( x, y, z, w ) {
  3599. this.normal.set( x, y, z );
  3600. this.constant = w;
  3601. return this;
  3602. },
  3603. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3604. this.normal.copy( normal );
  3605. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3606. return this;
  3607. },
  3608. setFromCoplanarPoints: function () {
  3609. var v1 = new THREE.Vector3();
  3610. var v2 = new THREE.Vector3();
  3611. return function ( a, b, c ) {
  3612. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3613. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3614. this.setFromNormalAndCoplanarPoint( normal, a );
  3615. return this;
  3616. };
  3617. }(),
  3618. copy: function ( plane ) {
  3619. this.normal.copy( plane.normal );
  3620. this.constant = plane.constant;
  3621. return this;
  3622. },
  3623. normalize: function () {
  3624. // Note: will lead to a divide by zero if the plane is invalid.
  3625. var inverseNormalLength = 1.0 / this.normal.length();
  3626. this.normal.multiplyScalar( inverseNormalLength );
  3627. this.constant *= inverseNormalLength;
  3628. return this;
  3629. },
  3630. negate: function () {
  3631. this.constant *= - 1;
  3632. this.normal.negate();
  3633. return this;
  3634. },
  3635. distanceToPoint: function ( point ) {
  3636. return this.normal.dot( point ) + this.constant;
  3637. },
  3638. distanceToSphere: function ( sphere ) {
  3639. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3640. },
  3641. projectPoint: function ( point, optionalTarget ) {
  3642. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3643. },
  3644. orthoPoint: function ( point, optionalTarget ) {
  3645. var perpendicularMagnitude = this.distanceToPoint( point );
  3646. var result = optionalTarget || new THREE.Vector3();
  3647. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3648. },
  3649. isIntersectionLine: function ( line ) {
  3650. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3651. var startSign = this.distanceToPoint( line.start );
  3652. var endSign = this.distanceToPoint( line.end );
  3653. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3654. },
  3655. intersectLine: function () {
  3656. var v1 = new THREE.Vector3();
  3657. return function ( line, optionalTarget ) {
  3658. var result = optionalTarget || new THREE.Vector3();
  3659. var direction = line.delta( v1 );
  3660. var denominator = this.normal.dot( direction );
  3661. if ( denominator == 0 ) {
  3662. // line is coplanar, return origin
  3663. if ( this.distanceToPoint( line.start ) == 0 ) {
  3664. return result.copy( line.start );
  3665. }
  3666. // Unsure if this is the correct method to handle this case.
  3667. return undefined;
  3668. }
  3669. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3670. if ( t < 0 || t > 1 ) {
  3671. return undefined;
  3672. }
  3673. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3674. };
  3675. }(),
  3676. coplanarPoint: function ( optionalTarget ) {
  3677. var result = optionalTarget || new THREE.Vector3();
  3678. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3679. },
  3680. applyMatrix4: function () {
  3681. var v1 = new THREE.Vector3();
  3682. var v2 = new THREE.Vector3();
  3683. var m1 = new THREE.Matrix3();
  3684. return function ( matrix, optionalNormalMatrix ) {
  3685. // compute new normal based on theory here:
  3686. // http://www.songho.ca/opengl/gl_normaltransform.html
  3687. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  3688. var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix );
  3689. var newCoplanarPoint = this.coplanarPoint( v2 );
  3690. newCoplanarPoint.applyMatrix4( matrix );
  3691. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3692. return this;
  3693. };
  3694. }(),
  3695. translate: function ( offset ) {
  3696. this.constant = this.constant - offset.dot( this.normal );
  3697. return this;
  3698. },
  3699. equals: function ( plane ) {
  3700. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3701. },
  3702. clone: function () {
  3703. return new THREE.Plane().copy( this );
  3704. }
  3705. };
  3706. // File:src/math/Math.js
  3707. /**
  3708. * @author alteredq / http://alteredqualia.com/
  3709. * @author mrdoob / http://mrdoob.com/
  3710. */
  3711. THREE.Math = {
  3712. generateUUID: function () {
  3713. // http://www.broofa.com/Tools/Math.uuid.htm
  3714. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  3715. var uuid = new Array( 36 );
  3716. var rnd = 0, r;
  3717. return function () {
  3718. for ( var i = 0; i < 36; i ++ ) {
  3719. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3720. uuid[ i ] = '-';
  3721. } else if ( i == 14 ) {
  3722. uuid[ i ] = '4';
  3723. } else {
  3724. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  3725. r = rnd & 0xf;
  3726. rnd = rnd >> 4;
  3727. uuid[ i ] = chars[ ( i == 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  3728. }
  3729. }
  3730. return uuid.join( '' );
  3731. };
  3732. }(),
  3733. // Clamp value to range <a, b>
  3734. clamp: function ( x, a, b ) {
  3735. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3736. },
  3737. // Clamp value to range <a, inf)
  3738. clampBottom: function ( x, a ) {
  3739. return x < a ? a : x;
  3740. },
  3741. // Linear mapping from range <a1, a2> to range <b1, b2>
  3742. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3743. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3744. },
  3745. // http://en.wikipedia.org/wiki/Smoothstep
  3746. smoothstep: function ( x, min, max ) {
  3747. if ( x <= min ) return 0;
  3748. if ( x >= max ) return 1;
  3749. x = ( x - min ) / ( max - min );
  3750. return x * x * ( 3 - 2 * x );
  3751. },
  3752. smootherstep: function ( x, min, max ) {
  3753. if ( x <= min ) return 0;
  3754. if ( x >= max ) return 1;
  3755. x = ( x - min ) / ( max - min );
  3756. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  3757. },
  3758. // Random float from <0, 1> with 16 bits of randomness
  3759. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3760. random16: function () {
  3761. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3762. },
  3763. // Random integer from <low, high> interval
  3764. randInt: function ( low, high ) {
  3765. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3766. },
  3767. // Random float from <low, high> interval
  3768. randFloat: function ( low, high ) {
  3769. return low + Math.random() * ( high - low );
  3770. },
  3771. // Random float from <-range/2, range/2> interval
  3772. randFloatSpread: function ( range ) {
  3773. return range * ( 0.5 - Math.random() );
  3774. },
  3775. sign: function ( x ) {
  3776. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : 0;
  3777. },
  3778. degToRad: function () {
  3779. var degreeToRadiansFactor = Math.PI / 180;
  3780. return function ( degrees ) {
  3781. return degrees * degreeToRadiansFactor;
  3782. };
  3783. }(),
  3784. radToDeg: function () {
  3785. var radianToDegreesFactor = 180 / Math.PI;
  3786. return function ( radians ) {
  3787. return radians * radianToDegreesFactor;
  3788. };
  3789. }(),
  3790. isPowerOfTwo: function ( value ) {
  3791. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  3792. }
  3793. };
  3794. // File:src/math/Spline.js
  3795. /**
  3796. * Spline from Tween.js, slightly optimized (and trashed)
  3797. * http://sole.github.com/tween.js/examples/05_spline.html
  3798. *
  3799. * @author mrdoob / http://mrdoob.com/
  3800. * @author alteredq / http://alteredqualia.com/
  3801. */
  3802. THREE.Spline = function ( points ) {
  3803. this.points = points;
  3804. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3805. point, intPoint, weight, w2, w3,
  3806. pa, pb, pc, pd;
  3807. this.initFromArray = function ( a ) {
  3808. this.points = [];
  3809. for ( var i = 0; i < a.length; i ++ ) {
  3810. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3811. }
  3812. };
  3813. this.getPoint = function ( k ) {
  3814. point = ( this.points.length - 1 ) * k;
  3815. intPoint = Math.floor( point );
  3816. weight = point - intPoint;
  3817. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3818. c[ 1 ] = intPoint;
  3819. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3820. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3821. pa = this.points[ c[ 0 ] ];
  3822. pb = this.points[ c[ 1 ] ];
  3823. pc = this.points[ c[ 2 ] ];
  3824. pd = this.points[ c[ 3 ] ];
  3825. w2 = weight * weight;
  3826. w3 = weight * w2;
  3827. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3828. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3829. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3830. return v3;
  3831. };
  3832. this.getControlPointsArray = function () {
  3833. var i, p, l = this.points.length,
  3834. coords = [];
  3835. for ( i = 0; i < l; i ++ ) {
  3836. p = this.points[ i ];
  3837. coords[ i ] = [ p.x, p.y, p.z ];
  3838. }
  3839. return coords;
  3840. };
  3841. // approximate length by summing linear segments
  3842. this.getLength = function ( nSubDivisions ) {
  3843. var i, index, nSamples, position,
  3844. point = 0, intPoint = 0, oldIntPoint = 0,
  3845. oldPosition = new THREE.Vector3(),
  3846. tmpVec = new THREE.Vector3(),
  3847. chunkLengths = [],
  3848. totalLength = 0;
  3849. // first point has 0 length
  3850. chunkLengths[ 0 ] = 0;
  3851. if ( ! nSubDivisions ) nSubDivisions = 100;
  3852. nSamples = this.points.length * nSubDivisions;
  3853. oldPosition.copy( this.points[ 0 ] );
  3854. for ( i = 1; i < nSamples; i ++ ) {
  3855. index = i / nSamples;
  3856. position = this.getPoint( index );
  3857. tmpVec.copy( position );
  3858. totalLength += tmpVec.distanceTo( oldPosition );
  3859. oldPosition.copy( position );
  3860. point = ( this.points.length - 1 ) * index;
  3861. intPoint = Math.floor( point );
  3862. if ( intPoint != oldIntPoint ) {
  3863. chunkLengths[ intPoint ] = totalLength;
  3864. oldIntPoint = intPoint;
  3865. }
  3866. }
  3867. // last point ends with total length
  3868. chunkLengths[ chunkLengths.length ] = totalLength;
  3869. return { chunks: chunkLengths, total: totalLength };
  3870. };
  3871. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3872. var i, j,
  3873. index, indexCurrent, indexNext,
  3874. linearDistance, realDistance,
  3875. sampling, position,
  3876. newpoints = [],
  3877. tmpVec = new THREE.Vector3(),
  3878. sl = this.getLength();
  3879. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3880. for ( i = 1; i < this.points.length; i ++ ) {
  3881. //tmpVec.copy( this.points[ i - 1 ] );
  3882. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3883. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3884. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3885. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3886. indexNext = i / ( this.points.length - 1 );
  3887. for ( j = 1; j < sampling - 1; j ++ ) {
  3888. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3889. position = this.getPoint( index );
  3890. newpoints.push( tmpVec.copy( position ).clone() );
  3891. }
  3892. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3893. }
  3894. this.points = newpoints;
  3895. };
  3896. // Catmull-Rom
  3897. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3898. var v0 = ( p2 - p0 ) * 0.5,
  3899. v1 = ( p3 - p1 ) * 0.5;
  3900. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3901. };
  3902. };
  3903. // File:src/math/Triangle.js
  3904. /**
  3905. * @author bhouston / http://exocortex.com
  3906. * @author mrdoob / http://mrdoob.com/
  3907. */
  3908. THREE.Triangle = function ( a, b, c ) {
  3909. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3910. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3911. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3912. };
  3913. THREE.Triangle.normal = function () {
  3914. var v0 = new THREE.Vector3();
  3915. return function ( a, b, c, optionalTarget ) {
  3916. var result = optionalTarget || new THREE.Vector3();
  3917. result.subVectors( c, b );
  3918. v0.subVectors( a, b );
  3919. result.cross( v0 );
  3920. var resultLengthSq = result.lengthSq();
  3921. if ( resultLengthSq > 0 ) {
  3922. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3923. }
  3924. return result.set( 0, 0, 0 );
  3925. };
  3926. }();
  3927. // static/instance method to calculate barycoordinates
  3928. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3929. THREE.Triangle.barycoordFromPoint = function () {
  3930. var v0 = new THREE.Vector3();
  3931. var v1 = new THREE.Vector3();
  3932. var v2 = new THREE.Vector3();
  3933. return function ( point, a, b, c, optionalTarget ) {
  3934. v0.subVectors( c, a );
  3935. v1.subVectors( b, a );
  3936. v2.subVectors( point, a );
  3937. var dot00 = v0.dot( v0 );
  3938. var dot01 = v0.dot( v1 );
  3939. var dot02 = v0.dot( v2 );
  3940. var dot11 = v1.dot( v1 );
  3941. var dot12 = v1.dot( v2 );
  3942. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3943. var result = optionalTarget || new THREE.Vector3();
  3944. // colinear or singular triangle
  3945. if ( denom == 0 ) {
  3946. // arbitrary location outside of triangle?
  3947. // not sure if this is the best idea, maybe should be returning undefined
  3948. return result.set( - 2, - 1, - 1 );
  3949. }
  3950. var invDenom = 1 / denom;
  3951. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3952. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3953. // barycoordinates must always sum to 1
  3954. return result.set( 1 - u - v, v, u );
  3955. };
  3956. }();
  3957. THREE.Triangle.containsPoint = function () {
  3958. var v1 = new THREE.Vector3();
  3959. return function ( point, a, b, c ) {
  3960. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3961. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3962. };
  3963. }();
  3964. THREE.Triangle.prototype = {
  3965. constructor: THREE.Triangle,
  3966. set: function ( a, b, c ) {
  3967. this.a.copy( a );
  3968. this.b.copy( b );
  3969. this.c.copy( c );
  3970. return this;
  3971. },
  3972. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3973. this.a.copy( points[ i0 ] );
  3974. this.b.copy( points[ i1 ] );
  3975. this.c.copy( points[ i2 ] );
  3976. return this;
  3977. },
  3978. copy: function ( triangle ) {
  3979. this.a.copy( triangle.a );
  3980. this.b.copy( triangle.b );
  3981. this.c.copy( triangle.c );
  3982. return this;
  3983. },
  3984. area: function () {
  3985. var v0 = new THREE.Vector3();
  3986. var v1 = new THREE.Vector3();
  3987. return function () {
  3988. v0.subVectors( this.c, this.b );
  3989. v1.subVectors( this.a, this.b );
  3990. return v0.cross( v1 ).length() * 0.5;
  3991. };
  3992. }(),
  3993. midpoint: function ( optionalTarget ) {
  3994. var result = optionalTarget || new THREE.Vector3();
  3995. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3996. },
  3997. normal: function ( optionalTarget ) {
  3998. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3999. },
  4000. plane: function ( optionalTarget ) {
  4001. var result = optionalTarget || new THREE.Plane();
  4002. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  4003. },
  4004. barycoordFromPoint: function ( point, optionalTarget ) {
  4005. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  4006. },
  4007. containsPoint: function ( point ) {
  4008. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  4009. },
  4010. equals: function ( triangle ) {
  4011. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4012. },
  4013. clone: function () {
  4014. return new THREE.Triangle().copy( this );
  4015. }
  4016. };
  4017. // File:src/core/Clock.js
  4018. /**
  4019. * @author alteredq / http://alteredqualia.com/
  4020. */
  4021. THREE.Clock = function ( autoStart ) {
  4022. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  4023. this.startTime = 0;
  4024. this.oldTime = 0;
  4025. this.elapsedTime = 0;
  4026. this.running = false;
  4027. };
  4028. THREE.Clock.prototype = {
  4029. constructor: THREE.Clock,
  4030. start: function () {
  4031. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  4032. ? self.performance.now()
  4033. : Date.now();
  4034. this.oldTime = this.startTime;
  4035. this.running = true;
  4036. },
  4037. stop: function () {
  4038. this.getElapsedTime();
  4039. this.running = false;
  4040. },
  4041. getElapsedTime: function () {
  4042. this.getDelta();
  4043. return this.elapsedTime;
  4044. },
  4045. getDelta: function () {
  4046. var diff = 0;
  4047. if ( this.autoStart && ! this.running ) {
  4048. this.start();
  4049. }
  4050. if ( this.running ) {
  4051. var newTime = self.performance !== undefined && self.performance.now !== undefined
  4052. ? self.performance.now()
  4053. : Date.now();
  4054. diff = 0.001 * ( newTime - this.oldTime );
  4055. this.oldTime = newTime;
  4056. this.elapsedTime += diff;
  4057. }
  4058. return diff;
  4059. }
  4060. };
  4061. // File:src/core/EventDispatcher.js
  4062. /**
  4063. * https://github.com/mrdoob/eventdispatcher.js/
  4064. */
  4065. THREE.EventDispatcher = function () {}
  4066. THREE.EventDispatcher.prototype = {
  4067. constructor: THREE.EventDispatcher,
  4068. apply: function ( object ) {
  4069. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  4070. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  4071. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  4072. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  4073. },
  4074. addEventListener: function ( type, listener ) {
  4075. if ( this._listeners === undefined ) this._listeners = {};
  4076. var listeners = this._listeners;
  4077. if ( listeners[ type ] === undefined ) {
  4078. listeners[ type ] = [];
  4079. }
  4080. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4081. listeners[ type ].push( listener );
  4082. }
  4083. },
  4084. hasEventListener: function ( type, listener ) {
  4085. if ( this._listeners === undefined ) return false;
  4086. var listeners = this._listeners;
  4087. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  4088. return true;
  4089. }
  4090. return false;
  4091. },
  4092. removeEventListener: function ( type, listener ) {
  4093. if ( this._listeners === undefined ) return;
  4094. var listeners = this._listeners;
  4095. var listenerArray = listeners[ type ];
  4096. if ( listenerArray !== undefined ) {
  4097. var index = listenerArray.indexOf( listener );
  4098. if ( index !== - 1 ) {
  4099. listenerArray.splice( index, 1 );
  4100. }
  4101. }
  4102. },
  4103. dispatchEvent: function ( event ) {
  4104. if ( this._listeners === undefined ) return;
  4105. var listeners = this._listeners;
  4106. var listenerArray = listeners[ event.type ];
  4107. if ( listenerArray !== undefined ) {
  4108. event.target = this;
  4109. var array = [];
  4110. var length = listenerArray.length;
  4111. for ( var i = 0; i < length; i ++ ) {
  4112. array[ i ] = listenerArray[ i ];
  4113. }
  4114. for ( var i = 0; i < length; i ++ ) {
  4115. array[ i ].call( this, event );
  4116. }
  4117. }
  4118. }
  4119. };
  4120. // File:src/core/Raycaster.js
  4121. /**
  4122. * @author mrdoob / http://mrdoob.com/
  4123. * @author bhouston / http://exocortex.com/
  4124. * @author stephomi / http://stephaneginier.com/
  4125. */
  4126. ( function ( THREE ) {
  4127. THREE.Raycaster = function ( origin, direction, near, far ) {
  4128. this.ray = new THREE.Ray( origin, direction );
  4129. // direction is assumed to be normalized (for accurate distance calculations)
  4130. this.near = near || 0;
  4131. this.far = far || Infinity;
  4132. this.params = {
  4133. Sprite: {},
  4134. Mesh: {},
  4135. PointCloud: { threshold: 1 },
  4136. LOD: {},
  4137. Line: {}
  4138. };
  4139. };
  4140. var descSort = function ( a, b ) {
  4141. return a.distance - b.distance;
  4142. };
  4143. var intersectObject = function ( object, raycaster, intersects, recursive ) {
  4144. object.raycast( raycaster, intersects );
  4145. if ( recursive === true ) {
  4146. var children = object.children;
  4147. for ( var i = 0, l = children.length; i < l; i ++ ) {
  4148. intersectObject( children[ i ], raycaster, intersects, true );
  4149. }
  4150. }
  4151. };
  4152. //
  4153. THREE.Raycaster.prototype = {
  4154. constructor: THREE.Raycaster,
  4155. precision: 0.0001,
  4156. linePrecision: 1,
  4157. set: function ( origin, direction ) {
  4158. this.ray.set( origin, direction );
  4159. // direction is assumed to be normalized (for accurate distance calculations)
  4160. },
  4161. intersectObject: function ( object, recursive ) {
  4162. var intersects = [];
  4163. intersectObject( object, this, intersects, recursive );
  4164. intersects.sort( descSort );
  4165. return intersects;
  4166. },
  4167. intersectObjects: function ( objects, recursive ) {
  4168. var intersects = [];
  4169. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4170. intersectObject( objects[ i ], this, intersects, recursive );
  4171. }
  4172. intersects.sort( descSort );
  4173. return intersects;
  4174. }
  4175. };
  4176. }( THREE ) );
  4177. // File:src/core/Object3D.js
  4178. /**
  4179. * @author mrdoob / http://mrdoob.com/
  4180. * @author mikael emtinger / http://gomo.se/
  4181. * @author alteredq / http://alteredqualia.com/
  4182. * @author WestLangley / http://github.com/WestLangley
  4183. */
  4184. THREE.Object3D = function () {
  4185. this.id = THREE.Object3DIdCount ++;
  4186. this.uuid = THREE.Math.generateUUID();
  4187. this.name = '';
  4188. this.parent = undefined;
  4189. this.children = [];
  4190. this.up = THREE.Object3D.DefaultUp.clone();
  4191. var scope = this;
  4192. var position = new THREE.Vector3();
  4193. var rotation = new THREE.Euler();
  4194. var quaternion = new THREE.Quaternion();
  4195. var scale = new THREE.Vector3( 1, 1, 1 );
  4196. rotation.onChange( function () {
  4197. quaternion.setFromEuler( rotation, false );
  4198. } );
  4199. quaternion.onChange( function () {
  4200. rotation.setFromQuaternion( quaternion, undefined, false );
  4201. } );
  4202. Object.defineProperties( this, {
  4203. position: {
  4204. enumerable: true,
  4205. value: position
  4206. },
  4207. rotation: {
  4208. enumerable: true,
  4209. value: rotation
  4210. },
  4211. quaternion: {
  4212. enumerable: true,
  4213. value: quaternion
  4214. },
  4215. scale: {
  4216. enumerable: true,
  4217. value: scale
  4218. },
  4219. } );
  4220. this.renderDepth = null;
  4221. this.rotationAutoUpdate = true;
  4222. this.matrix = new THREE.Matrix4();
  4223. this.matrixWorld = new THREE.Matrix4();
  4224. this.matrixAutoUpdate = true;
  4225. this.matrixWorldNeedsUpdate = false;
  4226. this.visible = true;
  4227. this.castShadow = false;
  4228. this.receiveShadow = false;
  4229. this.frustumCulled = true;
  4230. this.userData = {};
  4231. };
  4232. THREE.Object3D.DefaultUp = new THREE.Vector3( 0, 1, 0 );
  4233. THREE.Object3D.prototype = {
  4234. constructor: THREE.Object3D,
  4235. get eulerOrder () {
  4236. console.warn( 'THREE.Object3D: .eulerOrder has been moved to .rotation.order.' );
  4237. return this.rotation.order;
  4238. },
  4239. set eulerOrder ( value ) {
  4240. console.warn( 'THREE.Object3D: .eulerOrder has been moved to .rotation.order.' );
  4241. this.rotation.order = value;
  4242. },
  4243. get useQuaternion () {
  4244. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  4245. },
  4246. set useQuaternion ( value ) {
  4247. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  4248. },
  4249. applyMatrix: function ( matrix ) {
  4250. this.matrix.multiplyMatrices( matrix, this.matrix );
  4251. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4252. },
  4253. setRotationFromAxisAngle: function ( axis, angle ) {
  4254. // assumes axis is normalized
  4255. this.quaternion.setFromAxisAngle( axis, angle );
  4256. },
  4257. setRotationFromEuler: function ( euler ) {
  4258. this.quaternion.setFromEuler( euler, true );
  4259. },
  4260. setRotationFromMatrix: function ( m ) {
  4261. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4262. this.quaternion.setFromRotationMatrix( m );
  4263. },
  4264. setRotationFromQuaternion: function ( q ) {
  4265. // assumes q is normalized
  4266. this.quaternion.copy( q );
  4267. },
  4268. rotateOnAxis: function () {
  4269. // rotate object on axis in object space
  4270. // axis is assumed to be normalized
  4271. var q1 = new THREE.Quaternion();
  4272. return function ( axis, angle ) {
  4273. q1.setFromAxisAngle( axis, angle );
  4274. this.quaternion.multiply( q1 );
  4275. return this;
  4276. }
  4277. }(),
  4278. rotateX: function () {
  4279. var v1 = new THREE.Vector3( 1, 0, 0 );
  4280. return function ( angle ) {
  4281. return this.rotateOnAxis( v1, angle );
  4282. };
  4283. }(),
  4284. rotateY: function () {
  4285. var v1 = new THREE.Vector3( 0, 1, 0 );
  4286. return function ( angle ) {
  4287. return this.rotateOnAxis( v1, angle );
  4288. };
  4289. }(),
  4290. rotateZ: function () {
  4291. var v1 = new THREE.Vector3( 0, 0, 1 );
  4292. return function ( angle ) {
  4293. return this.rotateOnAxis( v1, angle );
  4294. };
  4295. }(),
  4296. translateOnAxis: function () {
  4297. // translate object by distance along axis in object space
  4298. // axis is assumed to be normalized
  4299. var v1 = new THREE.Vector3();
  4300. return function ( axis, distance ) {
  4301. v1.copy( axis ).applyQuaternion( this.quaternion );
  4302. this.position.add( v1.multiplyScalar( distance ) );
  4303. return this;
  4304. }
  4305. }(),
  4306. translate: function ( distance, axis ) {
  4307. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  4308. return this.translateOnAxis( axis, distance );
  4309. },
  4310. translateX: function () {
  4311. var v1 = new THREE.Vector3( 1, 0, 0 );
  4312. return function ( distance ) {
  4313. return this.translateOnAxis( v1, distance );
  4314. };
  4315. }(),
  4316. translateY: function () {
  4317. var v1 = new THREE.Vector3( 0, 1, 0 );
  4318. return function ( distance ) {
  4319. return this.translateOnAxis( v1, distance );
  4320. };
  4321. }(),
  4322. translateZ: function () {
  4323. var v1 = new THREE.Vector3( 0, 0, 1 );
  4324. return function ( distance ) {
  4325. return this.translateOnAxis( v1, distance );
  4326. };
  4327. }(),
  4328. localToWorld: function ( vector ) {
  4329. return vector.applyMatrix4( this.matrixWorld );
  4330. },
  4331. worldToLocal: function () {
  4332. var m1 = new THREE.Matrix4();
  4333. return function ( vector ) {
  4334. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4335. };
  4336. }(),
  4337. lookAt: function () {
  4338. // This routine does not support objects with rotated and/or translated parent(s)
  4339. var m1 = new THREE.Matrix4();
  4340. return function ( vector ) {
  4341. m1.lookAt( vector, this.position, this.up );
  4342. this.quaternion.setFromRotationMatrix( m1 );
  4343. };
  4344. }(),
  4345. add: function ( object ) {
  4346. if ( arguments.length > 1 ) {
  4347. for ( var i = 0; i < arguments.length; i++ ) {
  4348. this.add( arguments[ i ] );
  4349. }
  4350. return this;
  4351. };
  4352. if ( object === this ) {
  4353. console.warn( "THREE.Object3D.add: An object can't be added as a child of itself." );
  4354. return this;
  4355. }
  4356. if ( object instanceof THREE.Object3D ) {
  4357. if ( object.parent !== undefined ) {
  4358. object.parent.remove( object );
  4359. }
  4360. object.parent = this;
  4361. object.dispatchEvent( { type: 'added' } );
  4362. this.children.push( object );
  4363. // add to scene
  4364. var scene = this;
  4365. while ( scene.parent !== undefined ) {
  4366. scene = scene.parent;
  4367. }
  4368. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4369. scene.__addObject( object );
  4370. }
  4371. }
  4372. return this;
  4373. },
  4374. remove: function ( object ) {
  4375. if ( arguments.length > 1 ) {
  4376. for ( var i = 0; i < arguments.length; i++ ) {
  4377. this.remove( arguments[ i ] );
  4378. }
  4379. };
  4380. var index = this.children.indexOf( object );
  4381. if ( index !== - 1 ) {
  4382. object.parent = undefined;
  4383. object.dispatchEvent( { type: 'removed' } );
  4384. this.children.splice( index, 1 );
  4385. // remove from scene
  4386. var scene = this;
  4387. while ( scene.parent !== undefined ) {
  4388. scene = scene.parent;
  4389. }
  4390. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4391. scene.__removeObject( object );
  4392. }
  4393. }
  4394. },
  4395. raycast: function () {},
  4396. traverse: function ( callback ) {
  4397. callback( this );
  4398. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4399. this.children[ i ].traverse( callback );
  4400. }
  4401. },
  4402. getObjectById: function ( id, recursive ) {
  4403. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4404. var child = this.children[ i ];
  4405. if ( child.id === id ) {
  4406. return child;
  4407. }
  4408. if ( recursive === true ) {
  4409. child = child.getObjectById( id, recursive );
  4410. if ( child !== undefined ) {
  4411. return child;
  4412. }
  4413. }
  4414. }
  4415. return undefined;
  4416. },
  4417. getObjectByName: function ( name, recursive ) {
  4418. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4419. var child = this.children[ i ];
  4420. if ( child.name === name ) {
  4421. return child;
  4422. }
  4423. if ( recursive === true ) {
  4424. child = child.getObjectByName( name, recursive );
  4425. if ( child !== undefined ) {
  4426. return child;
  4427. }
  4428. }
  4429. }
  4430. return undefined;
  4431. },
  4432. getChildByName: function ( name, recursive ) {
  4433. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  4434. return this.getObjectByName( name, recursive );
  4435. },
  4436. updateMatrix: function () {
  4437. this.matrix.compose( this.position, this.quaternion, this.scale );
  4438. this.matrixWorldNeedsUpdate = true;
  4439. },
  4440. updateMatrixWorld: function ( force ) {
  4441. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4442. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4443. if ( this.parent === undefined ) {
  4444. this.matrixWorld.copy( this.matrix );
  4445. } else {
  4446. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4447. }
  4448. this.matrixWorldNeedsUpdate = false;
  4449. force = true;
  4450. }
  4451. // update children
  4452. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4453. this.children[ i ].updateMatrixWorld( force );
  4454. }
  4455. },
  4456. clone: function ( object, recursive ) {
  4457. if ( object === undefined ) object = new THREE.Object3D();
  4458. if ( recursive === undefined ) recursive = true;
  4459. object.name = this.name;
  4460. object.up.copy( this.up );
  4461. object.position.copy( this.position );
  4462. object.quaternion.copy( this.quaternion );
  4463. object.scale.copy( this.scale );
  4464. object.renderDepth = this.renderDepth;
  4465. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4466. object.matrix.copy( this.matrix );
  4467. object.matrixWorld.copy( this.matrixWorld );
  4468. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4469. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4470. object.visible = this.visible;
  4471. object.castShadow = this.castShadow;
  4472. object.receiveShadow = this.receiveShadow;
  4473. object.frustumCulled = this.frustumCulled;
  4474. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4475. if ( recursive === true ) {
  4476. for ( var i = 0; i < this.children.length; i ++ ) {
  4477. var child = this.children[ i ];
  4478. object.add( child.clone() );
  4479. }
  4480. }
  4481. return object;
  4482. }
  4483. };
  4484. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  4485. THREE.Object3DIdCount = 0;
  4486. // File:src/core/Projector.js
  4487. /**
  4488. * @author mrdoob / http://mrdoob.com/
  4489. * @author supereggbert / http://www.paulbrunt.co.uk/
  4490. * @author julianwa / https://github.com/julianwa
  4491. */
  4492. THREE.Projector = function () {
  4493. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  4494. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  4495. _face, _faceCount, _facePool = [], _facePoolLength = 0,
  4496. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  4497. _sprite, _spriteCount, _spritePool = [], _spritePoolLength = 0,
  4498. _renderData = { objects: [], lights: [], elements: [] },
  4499. _vA = new THREE.Vector3(),
  4500. _vB = new THREE.Vector3(),
  4501. _vC = new THREE.Vector3(),
  4502. _vector3 = new THREE.Vector3(),
  4503. _vector4 = new THREE.Vector4(),
  4504. _clipBox = new THREE.Box3( new THREE.Vector3( - 1, - 1, - 1 ), new THREE.Vector3( 1, 1, 1 ) ),
  4505. _boundingBox = new THREE.Box3(),
  4506. _points3 = new Array( 3 ),
  4507. _points4 = new Array( 4 ),
  4508. _viewMatrix = new THREE.Matrix4(),
  4509. _viewProjectionMatrix = new THREE.Matrix4(),
  4510. _modelMatrix,
  4511. _modelViewProjectionMatrix = new THREE.Matrix4(),
  4512. _normalMatrix = new THREE.Matrix3(),
  4513. _frustum = new THREE.Frustum(),
  4514. _clippedVertex1PositionScreen = new THREE.Vector4(),
  4515. _clippedVertex2PositionScreen = new THREE.Vector4();
  4516. this.projectVector = function ( vector, camera ) {
  4517. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4518. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  4519. return vector.applyProjection( _viewProjectionMatrix );
  4520. };
  4521. this.unprojectVector = function () {
  4522. var projectionMatrixInverse = new THREE.Matrix4();
  4523. return function ( vector, camera ) {
  4524. projectionMatrixInverse.getInverse( camera.projectionMatrix );
  4525. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, projectionMatrixInverse );
  4526. return vector.applyProjection( _viewProjectionMatrix );
  4527. };
  4528. }();
  4529. this.pickingRay = function ( vector, camera ) {
  4530. // set two vectors with opposing z values
  4531. vector.z = - 1.0;
  4532. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4533. this.unprojectVector( vector, camera );
  4534. this.unprojectVector( end, camera );
  4535. // find direction from vector to end
  4536. end.sub( vector ).normalize();
  4537. return new THREE.Raycaster( vector, end );
  4538. };
  4539. var projectObject = function ( object ) {
  4540. if ( object.visible === false ) return;
  4541. if ( object instanceof THREE.Light ) {
  4542. _renderData.lights.push( object );
  4543. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Sprite ) {
  4544. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4545. _object = getNextObjectInPool();
  4546. _object.id = object.id;
  4547. _object.object = object;
  4548. if ( object.renderDepth !== null ) {
  4549. _object.z = object.renderDepth;
  4550. } else {
  4551. _vector3.setFromMatrixPosition( object.matrixWorld );
  4552. _vector3.applyProjection( _viewProjectionMatrix );
  4553. _object.z = _vector3.z;
  4554. }
  4555. _renderData.objects.push( _object );
  4556. }
  4557. }
  4558. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  4559. projectObject( object.children[ i ] );
  4560. }
  4561. };
  4562. var projectGraph = function ( root, sortObjects ) {
  4563. _objectCount = 0;
  4564. _renderData.objects.length = 0;
  4565. _renderData.lights.length = 0;
  4566. projectObject( root );
  4567. if ( sortObjects === true ) {
  4568. _renderData.objects.sort( painterSort );
  4569. }
  4570. };
  4571. var RenderList = function () {
  4572. var normals = [];
  4573. var uvs = [];
  4574. var object = null;
  4575. var material = null;
  4576. var normalMatrix = new THREE.Matrix3();
  4577. var setObject = function ( value ) {
  4578. object = value;
  4579. material = object.material;
  4580. normalMatrix.getNormalMatrix( object.matrixWorld );
  4581. normals.length = 0;
  4582. uvs.length = 0;
  4583. };
  4584. var projectVertex = function ( vertex ) {
  4585. var position = vertex.position;
  4586. var positionWorld = vertex.positionWorld;
  4587. var positionScreen = vertex.positionScreen;
  4588. positionWorld.copy( position ).applyMatrix4( _modelMatrix );
  4589. positionScreen.copy( positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4590. var invW = 1 / positionScreen.w;
  4591. positionScreen.x *= invW;
  4592. positionScreen.y *= invW;
  4593. positionScreen.z *= invW;
  4594. vertex.visible = positionScreen.x >= - 1 && positionScreen.x <= 1 &&
  4595. positionScreen.y >= - 1 && positionScreen.y <= 1 &&
  4596. positionScreen.z >= - 1 && positionScreen.z <= 1;
  4597. };
  4598. var pushVertex = function ( x, y, z ) {
  4599. _vertex = getNextVertexInPool();
  4600. _vertex.position.set( x, y, z );
  4601. projectVertex( _vertex );
  4602. };
  4603. var pushNormal = function ( x, y, z ) {
  4604. normals.push( x, y, z );
  4605. };
  4606. var pushUv = function ( x, y ) {
  4607. uvs.push( x, y );
  4608. };
  4609. var checkTriangleVisibility = function ( v1, v2, v3 ) {
  4610. if ( v1.visible === true || v2.visible === true || v3.visible === true ) return true;
  4611. _points3[ 0 ] = v1.positionScreen;
  4612. _points3[ 1 ] = v2.positionScreen;
  4613. _points3[ 2 ] = v3.positionScreen;
  4614. return _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) );
  4615. };
  4616. var checkBackfaceCulling = function ( v1, v2, v3 ) {
  4617. return ( ( v3.positionScreen.x - v1.positionScreen.x ) *
  4618. ( v2.positionScreen.y - v1.positionScreen.y ) -
  4619. ( v3.positionScreen.y - v1.positionScreen.y ) *
  4620. ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4621. };
  4622. var pushLine = function ( a, b ) {
  4623. var v1 = _vertexPool[ a ];
  4624. var v2 = _vertexPool[ b ];
  4625. _line = getNextLineInPool();
  4626. _line.id = object.id;
  4627. _line.v1.copy( v1 );
  4628. _line.v2.copy( v2 );
  4629. _line.z = ( v1.positionScreen.z + v2.positionScreen.z ) / 2;
  4630. _line.material = object.material;
  4631. _renderData.elements.push( _line );
  4632. };
  4633. var pushTriangle = function ( a, b, c ) {
  4634. var v1 = _vertexPool[ a ];
  4635. var v2 = _vertexPool[ b ];
  4636. var v3 = _vertexPool[ c ];
  4637. if ( checkTriangleVisibility( v1, v2, v3 ) === false ) return;
  4638. if ( material.side === THREE.DoubleSide || checkBackfaceCulling( v1, v2, v3 ) === true ) {
  4639. _face = getNextFaceInPool();
  4640. _face.id = object.id;
  4641. _face.v1.copy( v1 );
  4642. _face.v2.copy( v2 );
  4643. _face.v3.copy( v3 );
  4644. _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
  4645. for ( var i = 0; i < 3; i ++ ) {
  4646. var offset = arguments[ i ] * 3;
  4647. var normal = _face.vertexNormalsModel[ i ];
  4648. normal.set( normals[ offset ], normals[ offset + 1 ], normals[ offset + 2 ] );
  4649. normal.applyMatrix3( normalMatrix ).normalize();
  4650. var offset2 = arguments[ i ] * 2;
  4651. var uv = _face.uvs[ i ];
  4652. uv.set( uvs[ offset2 ], uvs[ offset2 + 1 ] );
  4653. }
  4654. _face.vertexNormalsLength = 3;
  4655. _face.material = object.material;
  4656. _renderData.elements.push( _face );
  4657. }
  4658. };
  4659. return {
  4660. setObject: setObject,
  4661. projectVertex: projectVertex,
  4662. checkTriangleVisibility: checkTriangleVisibility,
  4663. checkBackfaceCulling: checkBackfaceCulling,
  4664. pushVertex: pushVertex,
  4665. pushNormal: pushNormal,
  4666. pushUv: pushUv,
  4667. pushLine: pushLine,
  4668. pushTriangle: pushTriangle
  4669. }
  4670. };
  4671. var renderList = new RenderList();
  4672. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4673. var object, geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs,
  4674. isFaceMaterial, objectMaterials;
  4675. _faceCount = 0;
  4676. _lineCount = 0;
  4677. _spriteCount = 0;
  4678. _renderData.elements.length = 0;
  4679. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4680. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4681. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4682. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4683. _frustum.setFromMatrix( _viewProjectionMatrix );
  4684. projectGraph( scene, sortObjects );
  4685. for ( var o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4686. object = _renderData.objects[ o ].object;
  4687. geometry = object.geometry;
  4688. renderList.setObject( object );
  4689. _modelMatrix = object.matrixWorld;
  4690. _vertexCount = 0;
  4691. if ( object instanceof THREE.Mesh ) {
  4692. if ( geometry instanceof THREE.BufferGeometry ) {
  4693. var attributes = geometry.attributes;
  4694. var offsets = geometry.offsets;
  4695. if ( attributes.position === undefined ) continue;
  4696. var positions = attributes.position.array;
  4697. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  4698. renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  4699. }
  4700. if ( attributes.normal !== undefined ) {
  4701. var normals = attributes.normal.array;
  4702. for ( var i = 0, l = normals.length; i < l; i += 3 ) {
  4703. renderList.pushNormal( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] );
  4704. }
  4705. }
  4706. if ( attributes.uv !== undefined ) {
  4707. var uvs = attributes.uv.array;
  4708. for ( var i = 0, l = uvs.length; i < l; i += 2 ) {
  4709. renderList.pushUv( uvs[ i ], uvs[ i + 1 ] );
  4710. }
  4711. }
  4712. if ( attributes.index !== undefined ) {
  4713. var indices = attributes.index.array;
  4714. if ( offsets.length > 0 ) {
  4715. for ( var o = 0; o < offsets.length; o ++ ) {
  4716. var offset = offsets[ o ];
  4717. var index = offset.index;
  4718. for ( var i = offset.start, l = offset.start + offset.count; i < l; i += 3 ) {
  4719. renderList.pushTriangle( indices[ i ] + index, indices[ i + 1 ] + index, indices[ i + 2 ] + index );
  4720. }
  4721. }
  4722. } else {
  4723. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  4724. renderList.pushTriangle( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  4725. }
  4726. }
  4727. } else {
  4728. for ( var i = 0, l = positions.length / 3; i < l; i += 3 ) {
  4729. renderList.pushTriangle( i, i + 1, i + 2 );
  4730. }
  4731. }
  4732. } else if ( geometry instanceof THREE.Geometry ) {
  4733. vertices = geometry.vertices;
  4734. faces = geometry.faces;
  4735. faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  4736. _normalMatrix.getNormalMatrix( _modelMatrix );
  4737. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4738. objectMaterials = isFaceMaterial === true ? object.material : null;
  4739. for ( var v = 0, vl = vertices.length; v < vl; v ++ ) {
  4740. var vertex = vertices[ v ];
  4741. renderList.pushVertex( vertex.x, vertex.y, vertex.z );
  4742. }
  4743. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  4744. face = faces[ f ];
  4745. var material = isFaceMaterial === true
  4746. ? objectMaterials.materials[ face.materialIndex ]
  4747. : object.material;
  4748. if ( material === undefined ) continue;
  4749. var side = material.side;
  4750. var v1 = _vertexPool[ face.a ];
  4751. var v2 = _vertexPool[ face.b ];
  4752. var v3 = _vertexPool[ face.c ];
  4753. if ( material.morphTargets === true ) {
  4754. var morphTargets = geometry.morphTargets;
  4755. var morphInfluences = object.morphTargetInfluences;
  4756. var v1p = v1.position;
  4757. var v2p = v2.position;
  4758. var v3p = v3.position;
  4759. _vA.set( 0, 0, 0 );
  4760. _vB.set( 0, 0, 0 );
  4761. _vC.set( 0, 0, 0 );
  4762. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  4763. var influence = morphInfluences[ t ];
  4764. if ( influence === 0 ) continue;
  4765. var targets = morphTargets[ t ].vertices;
  4766. _vA.x += ( targets[ face.a ].x - v1p.x ) * influence;
  4767. _vA.y += ( targets[ face.a ].y - v1p.y ) * influence;
  4768. _vA.z += ( targets[ face.a ].z - v1p.z ) * influence;
  4769. _vB.x += ( targets[ face.b ].x - v2p.x ) * influence;
  4770. _vB.y += ( targets[ face.b ].y - v2p.y ) * influence;
  4771. _vB.z += ( targets[ face.b ].z - v2p.z ) * influence;
  4772. _vC.x += ( targets[ face.c ].x - v3p.x ) * influence;
  4773. _vC.y += ( targets[ face.c ].y - v3p.y ) * influence;
  4774. _vC.z += ( targets[ face.c ].z - v3p.z ) * influence;
  4775. }
  4776. v1.position.add( _vA );
  4777. v2.position.add( _vB );
  4778. v3.position.add( _vC );
  4779. renderList.projectVertex( v1 );
  4780. renderList.projectVertex( v2 );
  4781. renderList.projectVertex( v3 );
  4782. }
  4783. if ( renderList.checkTriangleVisibility( v1, v2, v3 ) === false ) continue;
  4784. var visible = renderList.checkBackfaceCulling( v1, v2, v3 );
  4785. if ( side !== THREE.DoubleSide ) {
  4786. if ( side === THREE.FrontSide && visible === false ) continue;
  4787. if ( side === THREE.BackSide && visible === true ) continue;
  4788. }
  4789. _face = getNextFaceInPool();
  4790. _face.id = object.id;
  4791. _face.v1.copy( v1 );
  4792. _face.v2.copy( v2 );
  4793. _face.v3.copy( v3 );
  4794. _face.normalModel.copy( face.normal );
  4795. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4796. _face.normalModel.negate();
  4797. }
  4798. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4799. faceVertexNormals = face.vertexNormals;
  4800. for ( var n = 0, nl = Math.min( faceVertexNormals.length, 3 ); n < nl; n ++ ) {
  4801. var normalModel = _face.vertexNormalsModel[ n ];
  4802. normalModel.copy( faceVertexNormals[ n ] );
  4803. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4804. normalModel.negate();
  4805. }
  4806. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4807. }
  4808. _face.vertexNormalsLength = faceVertexNormals.length;
  4809. var vertexUvs = faceVertexUvs[ f ];
  4810. if ( vertexUvs !== undefined ) {
  4811. for ( var u = 0; u < 3; u ++ ) {
  4812. _face.uvs[ u ].copy( vertexUvs[ u ] );
  4813. }
  4814. }
  4815. _face.color = face.color;
  4816. _face.material = material;
  4817. _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
  4818. _renderData.elements.push( _face );
  4819. }
  4820. }
  4821. } else if ( object instanceof THREE.Line ) {
  4822. if ( geometry instanceof THREE.BufferGeometry ) {
  4823. var attributes = geometry.attributes;
  4824. if ( attributes.position !== undefined ) {
  4825. var positions = attributes.position.array;
  4826. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  4827. renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  4828. }
  4829. if ( attributes.index !== undefined ) {
  4830. var indices = attributes.index.array;
  4831. for ( var i = 0, l = indices.length; i < l; i += 2 ) {
  4832. renderList.pushLine( indices[ i ], indices[ i + 1 ] );
  4833. }
  4834. } else {
  4835. var step = object.type === THREE.LinePieces ? 2 : 1;
  4836. for ( var i = 0, l = ( positions.length / 3 ) - 1; i < l; i += step ) {
  4837. renderList.pushLine( i, i + 1 );
  4838. }
  4839. }
  4840. }
  4841. } else if ( geometry instanceof THREE.Geometry ) {
  4842. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  4843. vertices = object.geometry.vertices;
  4844. if ( vertices.length === 0 ) continue;
  4845. v1 = getNextVertexInPool();
  4846. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  4847. // Handle LineStrip and LinePieces
  4848. var step = object.type === THREE.LinePieces ? 2 : 1;
  4849. for ( var v = 1, vl = vertices.length; v < vl; v ++ ) {
  4850. v1 = getNextVertexInPool();
  4851. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  4852. if ( ( v + 1 ) % step > 0 ) continue;
  4853. v2 = _vertexPool[ _vertexCount - 2 ];
  4854. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  4855. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  4856. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  4857. // Perform the perspective divide
  4858. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  4859. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  4860. _line = getNextLineInPool();
  4861. _line.id = object.id;
  4862. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  4863. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  4864. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  4865. _line.material = object.material;
  4866. if ( object.material.vertexColors === THREE.VertexColors ) {
  4867. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  4868. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  4869. }
  4870. _renderData.elements.push( _line );
  4871. }
  4872. }
  4873. }
  4874. } else if ( object instanceof THREE.Sprite ) {
  4875. _vector4.set( _modelMatrix.elements[ 12 ], _modelMatrix.elements[ 13 ], _modelMatrix.elements[ 14 ], 1 );
  4876. _vector4.applyMatrix4( _viewProjectionMatrix );
  4877. var invW = 1 / _vector4.w;
  4878. _vector4.z *= invW;
  4879. if ( _vector4.z >= - 1 && _vector4.z <= 1 ) {
  4880. _sprite = getNextSpriteInPool();
  4881. _sprite.id = object.id;
  4882. _sprite.x = _vector4.x * invW;
  4883. _sprite.y = _vector4.y * invW;
  4884. _sprite.z = _vector4.z;
  4885. _sprite.object = object;
  4886. _sprite.rotation = object.rotation;
  4887. _sprite.scale.x = object.scale.x * Math.abs( _sprite.x - ( _vector4.x + camera.projectionMatrix.elements[ 0 ] ) / ( _vector4.w + camera.projectionMatrix.elements[ 12 ] ) );
  4888. _sprite.scale.y = object.scale.y * Math.abs( _sprite.y - ( _vector4.y + camera.projectionMatrix.elements[ 5 ] ) / ( _vector4.w + camera.projectionMatrix.elements[ 13 ] ) );
  4889. _sprite.material = object.material;
  4890. _renderData.elements.push( _sprite );
  4891. }
  4892. }
  4893. }
  4894. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4895. return _renderData;
  4896. };
  4897. // Pools
  4898. function getNextObjectInPool() {
  4899. if ( _objectCount === _objectPoolLength ) {
  4900. var object = new THREE.RenderableObject();
  4901. _objectPool.push( object );
  4902. _objectPoolLength ++;
  4903. _objectCount ++;
  4904. return object;
  4905. }
  4906. return _objectPool[ _objectCount ++ ];
  4907. }
  4908. function getNextVertexInPool() {
  4909. if ( _vertexCount === _vertexPoolLength ) {
  4910. var vertex = new THREE.RenderableVertex();
  4911. _vertexPool.push( vertex );
  4912. _vertexPoolLength ++;
  4913. _vertexCount ++;
  4914. return vertex;
  4915. }
  4916. return _vertexPool[ _vertexCount ++ ];
  4917. }
  4918. function getNextFaceInPool() {
  4919. if ( _faceCount === _facePoolLength ) {
  4920. var face = new THREE.RenderableFace();
  4921. _facePool.push( face );
  4922. _facePoolLength ++;
  4923. _faceCount ++;
  4924. return face;
  4925. }
  4926. return _facePool[ _faceCount ++ ];
  4927. }
  4928. function getNextLineInPool() {
  4929. if ( _lineCount === _linePoolLength ) {
  4930. var line = new THREE.RenderableLine();
  4931. _linePool.push( line );
  4932. _linePoolLength ++;
  4933. _lineCount ++
  4934. return line;
  4935. }
  4936. return _linePool[ _lineCount ++ ];
  4937. }
  4938. function getNextSpriteInPool() {
  4939. if ( _spriteCount === _spritePoolLength ) {
  4940. var sprite = new THREE.RenderableSprite();
  4941. _spritePool.push( sprite );
  4942. _spritePoolLength ++;
  4943. _spriteCount ++
  4944. return sprite;
  4945. }
  4946. return _spritePool[ _spriteCount ++ ];
  4947. }
  4948. //
  4949. function painterSort( a, b ) {
  4950. if ( a.z !== b.z ) {
  4951. return b.z - a.z;
  4952. } else if ( a.id !== b.id ) {
  4953. return a.id - b.id;
  4954. } else {
  4955. return 0;
  4956. }
  4957. }
  4958. function clipLine( s1, s2 ) {
  4959. var alpha1 = 0, alpha2 = 1,
  4960. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4961. // Z = -1 and Z = +1, respectively.
  4962. bc1near = s1.z + s1.w,
  4963. bc2near = s2.z + s2.w,
  4964. bc1far = - s1.z + s1.w,
  4965. bc2far = - s2.z + s2.w;
  4966. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4967. // Both vertices lie entirely within all clip planes.
  4968. return true;
  4969. } else if ( ( bc1near < 0 && bc2near < 0 ) || ( bc1far < 0 && bc2far < 0 ) ) {
  4970. // Both vertices lie entirely outside one of the clip planes.
  4971. return false;
  4972. } else {
  4973. // The line segment spans at least one clip plane.
  4974. if ( bc1near < 0 ) {
  4975. // v1 lies outside the near plane, v2 inside
  4976. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4977. } else if ( bc2near < 0 ) {
  4978. // v2 lies outside the near plane, v1 inside
  4979. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4980. }
  4981. if ( bc1far < 0 ) {
  4982. // v1 lies outside the far plane, v2 inside
  4983. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4984. } else if ( bc2far < 0 ) {
  4985. // v2 lies outside the far plane, v2 inside
  4986. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4987. }
  4988. if ( alpha2 < alpha1 ) {
  4989. // The line segment spans two boundaries, but is outside both of them.
  4990. // (This can't happen when we're only clipping against just near/far but good
  4991. // to leave the check here for future usage if other clip planes are added.)
  4992. return false;
  4993. } else {
  4994. // Update the s1 and s2 vertices to match the clipped line segment.
  4995. s1.lerp( s2, alpha1 );
  4996. s2.lerp( s1, 1 - alpha2 );
  4997. return true;
  4998. }
  4999. }
  5000. }
  5001. };
  5002. // File:src/core/Face3.js
  5003. /**
  5004. * @author mrdoob / http://mrdoob.com/
  5005. * @author alteredq / http://alteredqualia.com/
  5006. */
  5007. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  5008. this.a = a;
  5009. this.b = b;
  5010. this.c = c;
  5011. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  5012. this.vertexNormals = normal instanceof Array ? normal : [];
  5013. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  5014. this.vertexColors = color instanceof Array ? color : [];
  5015. this.vertexTangents = [];
  5016. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  5017. };
  5018. THREE.Face3.prototype = {
  5019. constructor: THREE.Face3,
  5020. clone: function () {
  5021. var face = new THREE.Face3( this.a, this.b, this.c );
  5022. face.normal.copy( this.normal );
  5023. face.color.copy( this.color );
  5024. face.materialIndex = this.materialIndex;
  5025. for ( var i = 0, il = this.vertexNormals.length; i < il; i ++ ) {
  5026. face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  5027. }
  5028. for ( var i = 0, il = this.vertexColors.length; i < il; i ++ ) {
  5029. face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  5030. }
  5031. for ( var i = 0, il = this.vertexTangents.length; i < il; i ++ ) {
  5032. face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  5033. }
  5034. return face;
  5035. }
  5036. };
  5037. // File:src/core/Face4.js
  5038. /**
  5039. * @author mrdoob / http://mrdoob.com/
  5040. */
  5041. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  5042. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' )
  5043. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  5044. };
  5045. // File:src/core/BufferAttribute.js
  5046. /**
  5047. * @author mrdoob / http://mrdoob.com/
  5048. */
  5049. THREE.BufferAttribute = function ( array, itemSize ) {
  5050. this.array = array;
  5051. this.itemSize = itemSize;
  5052. };
  5053. THREE.BufferAttribute.prototype = {
  5054. constructor: THREE.BufferAttribute,
  5055. get length () {
  5056. return this.array.length;
  5057. },
  5058. set: function ( value ) {
  5059. this.array.set( value );
  5060. return this;
  5061. },
  5062. setX: function ( index, x ) {
  5063. this.array[ index * this.itemSize ] = x;
  5064. return this;
  5065. },
  5066. setY: function ( index, y ) {
  5067. this.array[ index * this.itemSize + 1 ] = y;
  5068. return this;
  5069. },
  5070. setZ: function ( index, z ) {
  5071. this.array[ index * this.itemSize + 2 ] = z;
  5072. return this;
  5073. },
  5074. setXY: function ( index, x, y ) {
  5075. index *= this.itemSize;
  5076. this.array[ index ] = x;
  5077. this.array[ index + 1 ] = y;
  5078. return this;
  5079. },
  5080. setXYZ: function ( index, x, y, z ) {
  5081. index *= this.itemSize;
  5082. this.array[ index ] = x;
  5083. this.array[ index + 1 ] = y;
  5084. this.array[ index + 2 ] = z;
  5085. return this;
  5086. },
  5087. setXYZW: function ( index, x, y, z, w ) {
  5088. index *= this.itemSize;
  5089. this.array[ index ] = x;
  5090. this.array[ index + 1 ] = y;
  5091. this.array[ index + 2 ] = z;
  5092. this.array[ index + 3 ] = w;
  5093. return this;
  5094. }
  5095. };
  5096. //
  5097. THREE.Int8Attribute = function ( data, itemSize ) {
  5098. console.warn( 'THREE.Int8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  5099. return new THREE.BufferAttribute( data, itemSize );
  5100. };
  5101. THREE.Uint8Attribute = function ( data, itemSize ) {
  5102. console.warn( 'THREE.Uint8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  5103. return new THREE.BufferAttribute( data, itemSize );
  5104. };
  5105. THREE.Uint8ClampedAttribute = function ( data, itemSize ) {
  5106. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  5107. return new THREE.BufferAttribute( data, itemSize );
  5108. };
  5109. THREE.Int16Attribute = function ( data, itemSize ) {
  5110. console.warn( 'THREE.Int16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  5111. return new THREE.BufferAttribute( data, itemSize );
  5112. };
  5113. THREE.Uint16Attribute = function ( data, itemSize ) {
  5114. console.warn( 'THREE.Uint16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  5115. return new THREE.BufferAttribute( data, itemSize );
  5116. };
  5117. THREE.Int32Attribute = function ( data, itemSize ) {
  5118. console.warn( 'THREE.Int32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  5119. return new THREE.BufferAttribute( data, itemSize );
  5120. };
  5121. THREE.Uint32Attribute = function ( data, itemSize ) {
  5122. console.warn( 'THREE.Uint32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  5123. return new THREE.BufferAttribute( data, itemSize );
  5124. };
  5125. THREE.Float32Attribute = function ( data, itemSize ) {
  5126. console.warn( 'THREE.Float32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  5127. return new THREE.BufferAttribute( data, itemSize );
  5128. };
  5129. THREE.Float64Attribute = function ( data, itemSize ) {
  5130. console.warn( 'THREE.Float64Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  5131. return new THREE.BufferAttribute( data, itemSize );
  5132. };
  5133. // File:src/core/BufferGeometry.js
  5134. /**
  5135. * @author alteredq / http://alteredqualia.com/
  5136. */
  5137. THREE.BufferGeometry = function () {
  5138. this.id = THREE.GeometryIdCount ++;
  5139. this.uuid = THREE.Math.generateUUID();
  5140. this.name = '';
  5141. this.attributes = {};
  5142. this.drawcalls = [];
  5143. this.offsets = this.drawcalls; // backwards compatibility
  5144. this.boundingBox = null;
  5145. this.boundingSphere = null;
  5146. };
  5147. THREE.BufferGeometry.prototype = {
  5148. constructor: THREE.BufferGeometry,
  5149. addAttribute: function ( name, attribute ) {
  5150. if ( attribute instanceof THREE.BufferAttribute === false ) {
  5151. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  5152. this.attributes[ name ] = { array: arguments[ 1 ], itemSize: arguments[ 2 ] };
  5153. return;
  5154. }
  5155. this.attributes[ name ] = attribute;
  5156. },
  5157. getAttribute: function ( name ) {
  5158. return this.attributes[ name ];
  5159. },
  5160. addDrawCall: function ( start, count, indexOffset ) {
  5161. this.drawcalls.push( {
  5162. start: start,
  5163. count: count,
  5164. index: indexOffset !== undefined ? indexOffset : 0
  5165. } );
  5166. },
  5167. applyMatrix: function ( matrix ) {
  5168. var position = this.attributes.position;
  5169. if ( position !== undefined ) {
  5170. matrix.applyToVector3Array( position.array );
  5171. position.needsUpdate = true;
  5172. }
  5173. var normal = this.attributes.normal;
  5174. if ( normal !== undefined ) {
  5175. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5176. normalMatrix.applyToVector3Array( normal.array );
  5177. normal.needsUpdate = true;
  5178. }
  5179. },
  5180. fromGeometry: function ( geometry, settings ) {
  5181. settings = settings || { 'vertexColors': THREE.NoColors };
  5182. var vertices = geometry.vertices;
  5183. var faces = geometry.faces;
  5184. var faceVertexUvs = geometry.faceVertexUvs;
  5185. var vertexColors = settings.vertexColors;
  5186. var hasFaceVertexUv = faceVertexUvs[ 0 ].length > 0;
  5187. var hasFaceVertexNormals = faces[ 0 ].vertexNormals.length == 3;
  5188. var positions = new Float32Array( faces.length * 3 * 3 );
  5189. this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  5190. var normals = new Float32Array( faces.length * 3 * 3 );
  5191. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  5192. if ( vertexColors !== THREE.NoColors ) {
  5193. var colors = new Float32Array( faces.length * 3 * 3 );
  5194. this.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
  5195. }
  5196. if ( hasFaceVertexUv === true ) {
  5197. var uvs = new Float32Array( faces.length * 3 * 2 );
  5198. this.addAttribute( 'uvs', new THREE.BufferAttribute( uvs, 2 ) );
  5199. }
  5200. for ( var i = 0, i2 = 0, i3 = 0; i < faces.length; i ++, i2 += 6, i3 += 9 ) {
  5201. var face = faces[ i ];
  5202. var a = vertices[ face.a ];
  5203. var b = vertices[ face.b ];
  5204. var c = vertices[ face.c ];
  5205. positions[ i3 ] = a.x;
  5206. positions[ i3 + 1 ] = a.y;
  5207. positions[ i3 + 2 ] = a.z;
  5208. positions[ i3 + 3 ] = b.x;
  5209. positions[ i3 + 4 ] = b.y;
  5210. positions[ i3 + 5 ] = b.z;
  5211. positions[ i3 + 6 ] = c.x;
  5212. positions[ i3 + 7 ] = c.y;
  5213. positions[ i3 + 8 ] = c.z;
  5214. if ( hasFaceVertexNormals === true ) {
  5215. var na = face.vertexNormals[ 0 ];
  5216. var nb = face.vertexNormals[ 1 ];
  5217. var nc = face.vertexNormals[ 2 ];
  5218. normals[ i3 ] = na.x;
  5219. normals[ i3 + 1 ] = na.y;
  5220. normals[ i3 + 2 ] = na.z;
  5221. normals[ i3 + 3 ] = nb.x;
  5222. normals[ i3 + 4 ] = nb.y;
  5223. normals[ i3 + 5 ] = nb.z;
  5224. normals[ i3 + 6 ] = nc.x;
  5225. normals[ i3 + 7 ] = nc.y;
  5226. normals[ i3 + 8 ] = nc.z;
  5227. } else {
  5228. var n = face.normal;
  5229. normals[ i3 ] = n.x;
  5230. normals[ i3 + 1 ] = n.y;
  5231. normals[ i3 + 2 ] = n.z;
  5232. normals[ i3 + 3 ] = n.x;
  5233. normals[ i3 + 4 ] = n.y;
  5234. normals[ i3 + 5 ] = n.z;
  5235. normals[ i3 + 6 ] = n.x;
  5236. normals[ i3 + 7 ] = n.y;
  5237. normals[ i3 + 8 ] = n.z;
  5238. }
  5239. if ( vertexColors === THREE.FaceColors ) {
  5240. var fc = face.color;
  5241. colors[ i3 ] = fc.r;
  5242. colors[ i3 + 1 ] = fc.g;
  5243. colors[ i3 + 2 ] = fc.b;
  5244. colors[ i3 + 3 ] = fc.r;
  5245. colors[ i3 + 4 ] = fc.g;
  5246. colors[ i3 + 5 ] = fc.b;
  5247. colors[ i3 + 6 ] = fc.r;
  5248. colors[ i3 + 7 ] = fc.g;
  5249. colors[ i3 + 8 ] = fc.b;
  5250. } else if ( vertexColors === THREE.VertexColors ) {
  5251. var vca = face.vertexColors[ 0 ];
  5252. var vcb = face.vertexColors[ 1 ];
  5253. var vcc = face.vertexColors[ 2 ];
  5254. colors[ i3 ] = vca.r;
  5255. colors[ i3 + 1 ] = vca.g;
  5256. colors[ i3 + 2 ] = vca.b;
  5257. colors[ i3 + 3 ] = vcb.r;
  5258. colors[ i3 + 4 ] = vcb.g;
  5259. colors[ i3 + 5 ] = vcb.b;
  5260. colors[ i3 + 6 ] = vcc.r;
  5261. colors[ i3 + 7 ] = vcc.g;
  5262. colors[ i3 + 8 ] = vcc.b;
  5263. }
  5264. if ( hasFaceVertexUv === true ) {
  5265. var uva = faceVertexUvs[ 0 ][ i ][ 0 ];
  5266. var uvb = faceVertexUvs[ 0 ][ i ][ 1 ];
  5267. var uvc = faceVertexUvs[ 0 ][ i ][ 2 ];
  5268. uvs[ i2 ] = uva.x;
  5269. uvs[ i2 + 1 ] = uva.y;
  5270. uvs[ i2 + 2 ] = uvb.x;
  5271. uvs[ i2 + 3 ] = uvb.y;
  5272. uvs[ i2 + 4 ] = uvc.x;
  5273. uvs[ i2 + 5 ] = uvc.y;
  5274. }
  5275. }
  5276. this.computeBoundingSphere()
  5277. return this;
  5278. },
  5279. computeBoundingBox: function () {
  5280. if ( this.boundingBox === null ) {
  5281. this.boundingBox = new THREE.Box3();
  5282. }
  5283. var positions = this.attributes[ 'position' ].array;
  5284. if ( positions ) {
  5285. var bb = this.boundingBox;
  5286. if ( positions.length >= 3 ) {
  5287. bb.min.x = bb.max.x = positions[ 0 ];
  5288. bb.min.y = bb.max.y = positions[ 1 ];
  5289. bb.min.z = bb.max.z = positions[ 2 ];
  5290. }
  5291. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  5292. var x = positions[ i ];
  5293. var y = positions[ i + 1 ];
  5294. var z = positions[ i + 2 ];
  5295. // bounding box
  5296. if ( x < bb.min.x ) {
  5297. bb.min.x = x;
  5298. } else if ( x > bb.max.x ) {
  5299. bb.max.x = x;
  5300. }
  5301. if ( y < bb.min.y ) {
  5302. bb.min.y = y;
  5303. } else if ( y > bb.max.y ) {
  5304. bb.max.y = y;
  5305. }
  5306. if ( z < bb.min.z ) {
  5307. bb.min.z = z;
  5308. } else if ( z > bb.max.z ) {
  5309. bb.max.z = z;
  5310. }
  5311. }
  5312. }
  5313. if ( positions === undefined || positions.length === 0 ) {
  5314. this.boundingBox.min.set( 0, 0, 0 );
  5315. this.boundingBox.max.set( 0, 0, 0 );
  5316. }
  5317. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  5318. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.' );
  5319. }
  5320. },
  5321. computeBoundingSphere: function () {
  5322. var box = new THREE.Box3();
  5323. var vector = new THREE.Vector3();
  5324. return function () {
  5325. if ( this.boundingSphere === null ) {
  5326. this.boundingSphere = new THREE.Sphere();
  5327. }
  5328. var positions = this.attributes[ 'position' ].array;
  5329. if ( positions ) {
  5330. box.makeEmpty();
  5331. var center = this.boundingSphere.center;
  5332. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5333. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5334. box.expandByPoint( vector );
  5335. }
  5336. box.center( center );
  5337. // hoping to find a boundingSphere with a radius smaller than the
  5338. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  5339. var maxRadiusSq = 0;
  5340. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5341. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5342. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  5343. }
  5344. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5345. if ( isNaN( this.boundingSphere.radius ) ) {
  5346. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.' );
  5347. }
  5348. }
  5349. }
  5350. }(),
  5351. computeFaceNormals: function () {
  5352. // backwards compatibility
  5353. },
  5354. computeVertexNormals: function () {
  5355. if ( this.attributes[ 'position' ] ) {
  5356. var i, il;
  5357. var j, jl;
  5358. var nVertexElements = this.attributes[ 'position' ].array.length;
  5359. if ( this.attributes[ 'normal' ] === undefined ) {
  5360. this.attributes[ 'normal' ] = {
  5361. itemSize: 3,
  5362. array: new Float32Array( nVertexElements )
  5363. };
  5364. } else {
  5365. // reset existing normals to zero
  5366. for ( i = 0, il = this.attributes[ 'normal' ].array.length; i < il; i ++ ) {
  5367. this.attributes[ 'normal' ].array[ i ] = 0;
  5368. }
  5369. }
  5370. var positions = this.attributes[ 'position' ].array;
  5371. var normals = this.attributes[ 'normal' ].array;
  5372. var vA, vB, vC, x, y, z,
  5373. pA = new THREE.Vector3(),
  5374. pB = new THREE.Vector3(),
  5375. pC = new THREE.Vector3(),
  5376. cb = new THREE.Vector3(),
  5377. ab = new THREE.Vector3();
  5378. // indexed elements
  5379. if ( this.attributes[ 'index' ] ) {
  5380. var indices = this.attributes[ 'index' ].array;
  5381. var offsets = ( this.offsets.length > 0 ? this.offsets : [ { start: 0, count: indices.length, index: 0 } ] );
  5382. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5383. var start = offsets[ j ].start;
  5384. var count = offsets[ j ].count;
  5385. var index = offsets[ j ].index;
  5386. for ( i = start, il = start + count; i < il; i += 3 ) {
  5387. vA = index + indices[ i ];
  5388. vB = index + indices[ i + 1 ];
  5389. vC = index + indices[ i + 2 ];
  5390. x = positions[ vA * 3 ];
  5391. y = positions[ vA * 3 + 1 ];
  5392. z = positions[ vA * 3 + 2 ];
  5393. pA.set( x, y, z );
  5394. x = positions[ vB * 3 ];
  5395. y = positions[ vB * 3 + 1 ];
  5396. z = positions[ vB * 3 + 2 ];
  5397. pB.set( x, y, z );
  5398. x = positions[ vC * 3 ];
  5399. y = positions[ vC * 3 + 1 ];
  5400. z = positions[ vC * 3 + 2 ];
  5401. pC.set( x, y, z );
  5402. cb.subVectors( pC, pB );
  5403. ab.subVectors( pA, pB );
  5404. cb.cross( ab );
  5405. normals[ vA * 3 ] += cb.x;
  5406. normals[ vA * 3 + 1 ] += cb.y;
  5407. normals[ vA * 3 + 2 ] += cb.z;
  5408. normals[ vB * 3 ] += cb.x;
  5409. normals[ vB * 3 + 1 ] += cb.y;
  5410. normals[ vB * 3 + 2 ] += cb.z;
  5411. normals[ vC * 3 ] += cb.x;
  5412. normals[ vC * 3 + 1 ] += cb.y;
  5413. normals[ vC * 3 + 2 ] += cb.z;
  5414. }
  5415. }
  5416. // non-indexed elements (unconnected triangle soup)
  5417. } else {
  5418. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5419. x = positions[ i ];
  5420. y = positions[ i + 1 ];
  5421. z = positions[ i + 2 ];
  5422. pA.set( x, y, z );
  5423. x = positions[ i + 3 ];
  5424. y = positions[ i + 4 ];
  5425. z = positions[ i + 5 ];
  5426. pB.set( x, y, z );
  5427. x = positions[ i + 6 ];
  5428. y = positions[ i + 7 ];
  5429. z = positions[ i + 8 ];
  5430. pC.set( x, y, z );
  5431. cb.subVectors( pC, pB );
  5432. ab.subVectors( pA, pB );
  5433. cb.cross( ab );
  5434. normals[ i ] = cb.x;
  5435. normals[ i + 1 ] = cb.y;
  5436. normals[ i + 2 ] = cb.z;
  5437. normals[ i + 3 ] = cb.x;
  5438. normals[ i + 4 ] = cb.y;
  5439. normals[ i + 5 ] = cb.z;
  5440. normals[ i + 6 ] = cb.x;
  5441. normals[ i + 7 ] = cb.y;
  5442. normals[ i + 8 ] = cb.z;
  5443. }
  5444. }
  5445. this.normalizeNormals();
  5446. this.normalsNeedUpdate = true;
  5447. }
  5448. },
  5449. computeTangents: function () {
  5450. // based on http://www.terathon.com/code/tangent.html
  5451. // (per vertex tangents)
  5452. if ( this.attributes[ 'index' ] === undefined ||
  5453. this.attributes[ 'position' ] === undefined ||
  5454. this.attributes[ 'normal' ] === undefined ||
  5455. this.attributes[ 'uv' ] === undefined ) {
  5456. console.warn( 'Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()' );
  5457. return;
  5458. }
  5459. var indices = this.attributes[ 'index' ].array;
  5460. var positions = this.attributes[ 'position' ].array;
  5461. var normals = this.attributes[ 'normal' ].array;
  5462. var uvs = this.attributes[ 'uv' ].array;
  5463. var nVertices = positions.length / 3;
  5464. if ( this.attributes[ 'tangent' ] === undefined ) {
  5465. var nTangentElements = 4 * nVertices;
  5466. this.attributes[ 'tangent' ] = {
  5467. itemSize: 4,
  5468. array: new Float32Array( nTangentElements )
  5469. };
  5470. }
  5471. var tangents = this.attributes[ 'tangent' ].array;
  5472. var tan1 = [], tan2 = [];
  5473. for ( var k = 0; k < nVertices; k ++ ) {
  5474. tan1[ k ] = new THREE.Vector3();
  5475. tan2[ k ] = new THREE.Vector3();
  5476. }
  5477. var xA, yA, zA,
  5478. xB, yB, zB,
  5479. xC, yC, zC,
  5480. uA, vA,
  5481. uB, vB,
  5482. uC, vC,
  5483. x1, x2, y1, y2, z1, z2,
  5484. s1, s2, t1, t2, r;
  5485. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5486. function handleTriangle( a, b, c ) {
  5487. xA = positions[ a * 3 ];
  5488. yA = positions[ a * 3 + 1 ];
  5489. zA = positions[ a * 3 + 2 ];
  5490. xB = positions[ b * 3 ];
  5491. yB = positions[ b * 3 + 1 ];
  5492. zB = positions[ b * 3 + 2 ];
  5493. xC = positions[ c * 3 ];
  5494. yC = positions[ c * 3 + 1 ];
  5495. zC = positions[ c * 3 + 2 ];
  5496. uA = uvs[ a * 2 ];
  5497. vA = uvs[ a * 2 + 1 ];
  5498. uB = uvs[ b * 2 ];
  5499. vB = uvs[ b * 2 + 1 ];
  5500. uC = uvs[ c * 2 ];
  5501. vC = uvs[ c * 2 + 1 ];
  5502. x1 = xB - xA;
  5503. x2 = xC - xA;
  5504. y1 = yB - yA;
  5505. y2 = yC - yA;
  5506. z1 = zB - zA;
  5507. z2 = zC - zA;
  5508. s1 = uB - uA;
  5509. s2 = uC - uA;
  5510. t1 = vB - vA;
  5511. t2 = vC - vA;
  5512. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5513. sdir.set(
  5514. ( t2 * x1 - t1 * x2 ) * r,
  5515. ( t2 * y1 - t1 * y2 ) * r,
  5516. ( t2 * z1 - t1 * z2 ) * r
  5517. );
  5518. tdir.set(
  5519. ( s1 * x2 - s2 * x1 ) * r,
  5520. ( s1 * y2 - s2 * y1 ) * r,
  5521. ( s1 * z2 - s2 * z1 ) * r
  5522. );
  5523. tan1[ a ].add( sdir );
  5524. tan1[ b ].add( sdir );
  5525. tan1[ c ].add( sdir );
  5526. tan2[ a ].add( tdir );
  5527. tan2[ b ].add( tdir );
  5528. tan2[ c ].add( tdir );
  5529. }
  5530. var i, il;
  5531. var j, jl;
  5532. var iA, iB, iC;
  5533. var offsets = this.offsets;
  5534. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5535. var start = offsets[ j ].start;
  5536. var count = offsets[ j ].count;
  5537. var index = offsets[ j ].index;
  5538. for ( i = start, il = start + count; i < il; i += 3 ) {
  5539. iA = index + indices[ i ];
  5540. iB = index + indices[ i + 1 ];
  5541. iC = index + indices[ i + 2 ];
  5542. handleTriangle( iA, iB, iC );
  5543. }
  5544. }
  5545. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5546. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5547. var w, t, test;
  5548. function handleVertex( v ) {
  5549. n.x = normals[ v * 3 ];
  5550. n.y = normals[ v * 3 + 1 ];
  5551. n.z = normals[ v * 3 + 2 ];
  5552. n2.copy( n );
  5553. t = tan1[ v ];
  5554. // Gram-Schmidt orthogonalize
  5555. tmp.copy( t );
  5556. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5557. // Calculate handedness
  5558. tmp2.crossVectors( n2, t );
  5559. test = tmp2.dot( tan2[ v ] );
  5560. w = ( test < 0.0 ) ? - 1.0 : 1.0;
  5561. tangents[ v * 4 ] = tmp.x;
  5562. tangents[ v * 4 + 1 ] = tmp.y;
  5563. tangents[ v * 4 + 2 ] = tmp.z;
  5564. tangents[ v * 4 + 3 ] = w;
  5565. }
  5566. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5567. var start = offsets[ j ].start;
  5568. var count = offsets[ j ].count;
  5569. var index = offsets[ j ].index;
  5570. for ( i = start, il = start + count; i < il; i += 3 ) {
  5571. iA = index + indices[ i ];
  5572. iB = index + indices[ i + 1 ];
  5573. iC = index + indices[ i + 2 ];
  5574. handleVertex( iA );
  5575. handleVertex( iB );
  5576. handleVertex( iC );
  5577. }
  5578. }
  5579. },
  5580. /*
  5581. computeOffsets
  5582. Compute the draw offset for large models by chunking the index buffer into chunks of 65k addressable vertices.
  5583. This method will effectively rewrite the index buffer and remap all attributes to match the new indices.
  5584. WARNING: This method will also expand the vertex count to prevent sprawled triangles across draw offsets.
  5585. indexBufferSize - Defaults to 65535, but allows for larger or smaller chunks.
  5586. */
  5587. computeOffsets: function ( indexBufferSize ) {
  5588. var size = indexBufferSize;
  5589. if ( indexBufferSize === undefined )
  5590. size = 65535; //WebGL limits type of index buffer values to 16-bit.
  5591. var s = Date.now();
  5592. var indices = this.attributes[ 'index' ].array;
  5593. var vertices = this.attributes[ 'position' ].array;
  5594. var verticesCount = ( vertices.length / 3 );
  5595. var facesCount = ( indices.length / 3 );
  5596. /*
  5597. console.log("Computing buffers in offsets of "+size+" -> indices:"+indices.length+" vertices:"+vertices.length);
  5598. console.log("Faces to process: "+(indices.length/3));
  5599. console.log("Reordering "+verticesCount+" vertices.");
  5600. */
  5601. var sortedIndices = new Uint16Array( indices.length ); //16-bit buffers
  5602. var indexPtr = 0;
  5603. var vertexPtr = 0;
  5604. var offsets = [ { start:0, count:0, index:0 } ];
  5605. var offset = offsets[ 0 ];
  5606. var duplicatedVertices = 0;
  5607. var newVerticeMaps = 0;
  5608. var faceVertices = new Int32Array( 6 );
  5609. var vertexMap = new Int32Array( vertices.length );
  5610. var revVertexMap = new Int32Array( vertices.length );
  5611. for ( var j = 0; j < vertices.length; j ++ ) { vertexMap[ j ] = - 1; revVertexMap[ j ] = - 1; }
  5612. /*
  5613. Traverse every face and reorder vertices in the proper offsets of 65k.
  5614. We can have more than 65k entries in the index buffer per offset, but only reference 65k values.
  5615. */
  5616. for ( var findex = 0; findex < facesCount; findex ++ ) {
  5617. newVerticeMaps = 0;
  5618. for ( var vo = 0; vo < 3; vo ++ ) {
  5619. var vid = indices[ findex * 3 + vo ];
  5620. if ( vertexMap[ vid ] == - 1 ) {
  5621. //Unmapped vertice
  5622. faceVertices[ vo * 2 ] = vid;
  5623. faceVertices[ vo * 2 + 1 ] = - 1;
  5624. newVerticeMaps ++;
  5625. } else if ( vertexMap[ vid ] < offset.index ) {
  5626. //Reused vertices from previous block (duplicate)
  5627. faceVertices[ vo * 2 ] = vid;
  5628. faceVertices[ vo * 2 + 1 ] = - 1;
  5629. duplicatedVertices ++;
  5630. } else {
  5631. //Reused vertice in the current block
  5632. faceVertices[ vo * 2 ] = vid;
  5633. faceVertices[ vo * 2 + 1 ] = vertexMap[ vid ];
  5634. }
  5635. }
  5636. var faceMax = vertexPtr + newVerticeMaps;
  5637. if ( faceMax > ( offset.index + size ) ) {
  5638. var new_offset = { start:indexPtr, count:0, index:vertexPtr };
  5639. offsets.push( new_offset );
  5640. offset = new_offset;
  5641. //Re-evaluate reused vertices in light of new offset.
  5642. for ( var v = 0; v < 6; v += 2 ) {
  5643. var new_vid = faceVertices[ v + 1 ];
  5644. if ( new_vid > - 1 && new_vid < offset.index )
  5645. faceVertices[ v + 1 ] = - 1;
  5646. }
  5647. }
  5648. //Reindex the face.
  5649. for ( var v = 0; v < 6; v += 2 ) {
  5650. var vid = faceVertices[ v ];
  5651. var new_vid = faceVertices[ v + 1 ];
  5652. if ( new_vid === - 1 )
  5653. new_vid = vertexPtr ++;
  5654. vertexMap[ vid ] = new_vid;
  5655. revVertexMap[ new_vid ] = vid;
  5656. sortedIndices[ indexPtr ++ ] = new_vid - offset.index; //XXX overflows at 16bit
  5657. offset.count ++;
  5658. }
  5659. }
  5660. /* Move all attribute values to map to the new computed indices , also expand the vertice stack to match our new vertexPtr. */
  5661. this.reorderBuffers( sortedIndices, revVertexMap, vertexPtr );
  5662. this.offsets = offsets;
  5663. /*
  5664. var orderTime = Date.now();
  5665. console.log("Reorder time: "+(orderTime-s)+"ms");
  5666. console.log("Duplicated "+duplicatedVertices+" vertices.");
  5667. console.log("Compute Buffers time: "+(Date.now()-s)+"ms");
  5668. console.log("Draw offsets: "+offsets.length);
  5669. */
  5670. return offsets;
  5671. },
  5672. merge: function () {
  5673. console.log( 'BufferGeometry.merge(): TODO' );
  5674. },
  5675. normalizeNormals: function () {
  5676. var normals = this.attributes[ 'normal' ].array;
  5677. var x, y, z, n;
  5678. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5679. x = normals[ i ];
  5680. y = normals[ i + 1 ];
  5681. z = normals[ i + 2 ];
  5682. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5683. normals[ i ] *= n;
  5684. normals[ i + 1 ] *= n;
  5685. normals[ i + 2 ] *= n;
  5686. }
  5687. },
  5688. /*
  5689. reoderBuffers:
  5690. Reorder attributes based on a new indexBuffer and indexMap.
  5691. indexBuffer - Uint16Array of the new ordered indices.
  5692. indexMap - Int32Array where the position is the new vertex ID and the value the old vertex ID for each vertex.
  5693. vertexCount - Amount of total vertices considered in this reordering (in case you want to grow the vertice stack).
  5694. */
  5695. reorderBuffers: function ( indexBuffer, indexMap, vertexCount ) {
  5696. /* Create a copy of all attributes for reordering. */
  5697. var sortedAttributes = {};
  5698. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  5699. for ( var attr in this.attributes ) {
  5700. if ( attr == 'index' )
  5701. continue;
  5702. var sourceArray = this.attributes[ attr ].array;
  5703. for ( var i = 0, il = types.length; i < il; i ++ ) {
  5704. var type = types[ i ];
  5705. if ( sourceArray instanceof type ) {
  5706. sortedAttributes[ attr ] = new type( this.attributes[ attr ].itemSize * vertexCount );
  5707. break;
  5708. }
  5709. }
  5710. }
  5711. /* Move attribute positions based on the new index map */
  5712. for ( var new_vid = 0; new_vid < vertexCount; new_vid ++ ) {
  5713. var vid = indexMap[ new_vid ];
  5714. for ( var attr in this.attributes ) {
  5715. if ( attr == 'index' )
  5716. continue;
  5717. var attrArray = this.attributes[ attr ].array;
  5718. var attrSize = this.attributes[ attr ].itemSize;
  5719. var sortedAttr = sortedAttributes[ attr ];
  5720. for ( var k = 0; k < attrSize; k ++ )
  5721. sortedAttr[ new_vid * attrSize + k ] = attrArray[ vid * attrSize + k ];
  5722. }
  5723. }
  5724. /* Carry the new sorted buffers locally */
  5725. this.attributes[ 'index' ].array = indexBuffer;
  5726. for ( var attr in this.attributes ) {
  5727. if ( attr == 'index' )
  5728. continue;
  5729. this.attributes[ attr ].array = sortedAttributes[ attr ];
  5730. this.attributes[ attr ].numItems = this.attributes[ attr ].itemSize * vertexCount;
  5731. }
  5732. },
  5733. clone: function () {
  5734. var geometry = new THREE.BufferGeometry();
  5735. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  5736. for ( var attr in this.attributes ) {
  5737. var sourceAttr = this.attributes[ attr ];
  5738. var sourceArray = sourceAttr.array;
  5739. var attribute = {
  5740. itemSize: sourceAttr.itemSize,
  5741. array: null
  5742. };
  5743. for ( var i = 0, il = types.length; i < il; i ++ ) {
  5744. var type = types[ i ];
  5745. if ( sourceArray instanceof type ) {
  5746. attribute.array = new type( sourceArray );
  5747. break;
  5748. }
  5749. }
  5750. geometry.attributes[ attr ] = attribute;
  5751. }
  5752. for ( var i = 0, il = this.offsets.length; i < il; i ++ ) {
  5753. var offset = this.offsets[ i ];
  5754. geometry.offsets.push( {
  5755. start: offset.start,
  5756. index: offset.index,
  5757. count: offset.count
  5758. } );
  5759. }
  5760. return geometry;
  5761. },
  5762. dispose: function () {
  5763. this.dispatchEvent( { type: 'dispose' } );
  5764. }
  5765. };
  5766. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  5767. // File:src/core/Geometry.js
  5768. /**
  5769. * @author mrdoob / http://mrdoob.com/
  5770. * @author kile / http://kile.stravaganza.org/
  5771. * @author alteredq / http://alteredqualia.com/
  5772. * @author mikael emtinger / http://gomo.se/
  5773. * @author zz85 / http://www.lab4games.net/zz85/blog
  5774. * @author bhouston / http://exocortex.com
  5775. */
  5776. THREE.Geometry = function () {
  5777. this.id = THREE.GeometryIdCount ++;
  5778. this.uuid = THREE.Math.generateUUID();
  5779. this.name = '';
  5780. this.vertices = [];
  5781. this.colors = []; // one-to-one vertex colors, used in Points and Line
  5782. this.faces = [];
  5783. this.faceVertexUvs = [ [] ];
  5784. this.morphTargets = [];
  5785. this.morphColors = [];
  5786. this.morphNormals = [];
  5787. this.skinWeights = [];
  5788. this.skinIndices = [];
  5789. this.lineDistances = [];
  5790. this.boundingBox = null;
  5791. this.boundingSphere = null;
  5792. this.hasTangents = false;
  5793. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  5794. // update flags
  5795. this.verticesNeedUpdate = false;
  5796. this.elementsNeedUpdate = false;
  5797. this.uvsNeedUpdate = false;
  5798. this.normalsNeedUpdate = false;
  5799. this.tangentsNeedUpdate = false;
  5800. this.colorsNeedUpdate = false;
  5801. this.lineDistancesNeedUpdate = false;
  5802. this.buffersNeedUpdate = false;
  5803. };
  5804. THREE.Geometry.prototype = {
  5805. constructor: THREE.Geometry,
  5806. applyMatrix: function ( matrix ) {
  5807. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5808. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  5809. var vertex = this.vertices[ i ];
  5810. vertex.applyMatrix4( matrix );
  5811. }
  5812. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  5813. var face = this.faces[ i ];
  5814. face.normal.applyMatrix3( normalMatrix ).normalize();
  5815. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  5816. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  5817. }
  5818. }
  5819. if ( this.boundingBox instanceof THREE.Box3 ) {
  5820. this.computeBoundingBox();
  5821. }
  5822. if ( this.boundingSphere instanceof THREE.Sphere ) {
  5823. this.computeBoundingSphere();
  5824. }
  5825. },
  5826. center: function () {
  5827. this.computeBoundingBox();
  5828. var offset = new THREE.Vector3();
  5829. offset.addVectors( this.boundingBox.min, this.boundingBox.max );
  5830. offset.multiplyScalar( - 0.5 );
  5831. this.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  5832. this.computeBoundingBox();
  5833. return offset;
  5834. },
  5835. computeFaceNormals: function () {
  5836. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5837. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5838. var face = this.faces[ f ];
  5839. var vA = this.vertices[ face.a ];
  5840. var vB = this.vertices[ face.b ];
  5841. var vC = this.vertices[ face.c ];
  5842. cb.subVectors( vC, vB );
  5843. ab.subVectors( vA, vB );
  5844. cb.cross( ab );
  5845. cb.normalize();
  5846. face.normal.copy( cb );
  5847. }
  5848. },
  5849. computeVertexNormals: function ( areaWeighted ) {
  5850. var v, vl, f, fl, face, vertices;
  5851. vertices = new Array( this.vertices.length );
  5852. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5853. vertices[ v ] = new THREE.Vector3();
  5854. }
  5855. if ( areaWeighted ) {
  5856. // vertex normals weighted by triangle areas
  5857. // http://www.iquilezles.org/www/articles/normals/normals.htm
  5858. var vA, vB, vC, vD;
  5859. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  5860. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  5861. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5862. face = this.faces[ f ];
  5863. vA = this.vertices[ face.a ];
  5864. vB = this.vertices[ face.b ];
  5865. vC = this.vertices[ face.c ];
  5866. cb.subVectors( vC, vB );
  5867. ab.subVectors( vA, vB );
  5868. cb.cross( ab );
  5869. vertices[ face.a ].add( cb );
  5870. vertices[ face.b ].add( cb );
  5871. vertices[ face.c ].add( cb );
  5872. }
  5873. } else {
  5874. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5875. face = this.faces[ f ];
  5876. vertices[ face.a ].add( face.normal );
  5877. vertices[ face.b ].add( face.normal );
  5878. vertices[ face.c ].add( face.normal );
  5879. }
  5880. }
  5881. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5882. vertices[ v ].normalize();
  5883. }
  5884. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5885. face = this.faces[ f ];
  5886. face.vertexNormals[ 0 ] = vertices[ face.a ].clone();
  5887. face.vertexNormals[ 1 ] = vertices[ face.b ].clone();
  5888. face.vertexNormals[ 2 ] = vertices[ face.c ].clone();
  5889. }
  5890. },
  5891. computeMorphNormals: function () {
  5892. var i, il, f, fl, face;
  5893. // save original normals
  5894. // - create temp variables on first access
  5895. // otherwise just copy (for faster repeated calls)
  5896. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5897. face = this.faces[ f ];
  5898. if ( ! face.__originalFaceNormal ) {
  5899. face.__originalFaceNormal = face.normal.clone();
  5900. } else {
  5901. face.__originalFaceNormal.copy( face.normal );
  5902. }
  5903. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  5904. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  5905. if ( ! face.__originalVertexNormals[ i ] ) {
  5906. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  5907. } else {
  5908. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  5909. }
  5910. }
  5911. }
  5912. // use temp geometry to compute face and vertex normals for each morph
  5913. var tmpGeo = new THREE.Geometry();
  5914. tmpGeo.faces = this.faces;
  5915. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  5916. // create on first access
  5917. if ( ! this.morphNormals[ i ] ) {
  5918. this.morphNormals[ i ] = {};
  5919. this.morphNormals[ i ].faceNormals = [];
  5920. this.morphNormals[ i ].vertexNormals = [];
  5921. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  5922. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  5923. var faceNormal, vertexNormals;
  5924. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5925. faceNormal = new THREE.Vector3();
  5926. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  5927. dstNormalsFace.push( faceNormal );
  5928. dstNormalsVertex.push( vertexNormals );
  5929. }
  5930. }
  5931. var morphNormals = this.morphNormals[ i ];
  5932. // set vertices to morph target
  5933. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  5934. // compute morph normals
  5935. tmpGeo.computeFaceNormals();
  5936. tmpGeo.computeVertexNormals();
  5937. // store morph normals
  5938. var faceNormal, vertexNormals;
  5939. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5940. face = this.faces[ f ];
  5941. faceNormal = morphNormals.faceNormals[ f ];
  5942. vertexNormals = morphNormals.vertexNormals[ f ];
  5943. faceNormal.copy( face.normal );
  5944. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  5945. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  5946. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  5947. }
  5948. }
  5949. // restore original normals
  5950. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5951. face = this.faces[ f ];
  5952. face.normal = face.__originalFaceNormal;
  5953. face.vertexNormals = face.__originalVertexNormals;
  5954. }
  5955. },
  5956. computeTangents: function () {
  5957. // based on http://www.terathon.com/code/tangent.html
  5958. // tangents go to vertices
  5959. var f, fl, v, vl, i, il, vertexIndex,
  5960. face, uv, vA, vB, vC, uvA, uvB, uvC,
  5961. x1, x2, y1, y2, z1, z2,
  5962. s1, s2, t1, t2, r, t, test,
  5963. tan1 = [], tan2 = [],
  5964. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  5965. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  5966. n = new THREE.Vector3(), w;
  5967. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5968. tan1[ v ] = new THREE.Vector3();
  5969. tan2[ v ] = new THREE.Vector3();
  5970. }
  5971. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  5972. vA = context.vertices[ a ];
  5973. vB = context.vertices[ b ];
  5974. vC = context.vertices[ c ];
  5975. uvA = uv[ ua ];
  5976. uvB = uv[ ub ];
  5977. uvC = uv[ uc ];
  5978. x1 = vB.x - vA.x;
  5979. x2 = vC.x - vA.x;
  5980. y1 = vB.y - vA.y;
  5981. y2 = vC.y - vA.y;
  5982. z1 = vB.z - vA.z;
  5983. z2 = vC.z - vA.z;
  5984. s1 = uvB.x - uvA.x;
  5985. s2 = uvC.x - uvA.x;
  5986. t1 = uvB.y - uvA.y;
  5987. t2 = uvC.y - uvA.y;
  5988. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5989. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  5990. ( t2 * y1 - t1 * y2 ) * r,
  5991. ( t2 * z1 - t1 * z2 ) * r );
  5992. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  5993. ( s1 * y2 - s2 * y1 ) * r,
  5994. ( s1 * z2 - s2 * z1 ) * r );
  5995. tan1[ a ].add( sdir );
  5996. tan1[ b ].add( sdir );
  5997. tan1[ c ].add( sdir );
  5998. tan2[ a ].add( tdir );
  5999. tan2[ b ].add( tdir );
  6000. tan2[ c ].add( tdir );
  6001. }
  6002. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6003. face = this.faces[ f ];
  6004. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  6005. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  6006. }
  6007. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  6008. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6009. face = this.faces[ f ];
  6010. for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i ++ ) {
  6011. n.copy( face.vertexNormals[ i ] );
  6012. vertexIndex = face[ faceIndex[ i ] ];
  6013. t = tan1[ vertexIndex ];
  6014. // Gram-Schmidt orthogonalize
  6015. tmp.copy( t );
  6016. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6017. // Calculate handedness
  6018. tmp2.crossVectors( face.vertexNormals[ i ], t );
  6019. test = tmp2.dot( tan2[ vertexIndex ] );
  6020. w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6021. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  6022. }
  6023. }
  6024. this.hasTangents = true;
  6025. },
  6026. computeLineDistances: function () {
  6027. var d = 0;
  6028. var vertices = this.vertices;
  6029. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6030. if ( i > 0 ) {
  6031. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  6032. }
  6033. this.lineDistances[ i ] = d;
  6034. }
  6035. },
  6036. computeBoundingBox: function () {
  6037. if ( this.boundingBox === null ) {
  6038. this.boundingBox = new THREE.Box3();
  6039. }
  6040. this.boundingBox.setFromPoints( this.vertices );
  6041. },
  6042. computeBoundingSphere: function () {
  6043. if ( this.boundingSphere === null ) {
  6044. this.boundingSphere = new THREE.Sphere();
  6045. }
  6046. this.boundingSphere.setFromPoints( this.vertices );
  6047. },
  6048. merge: function ( geometry, matrix, materialIndexOffset ) {
  6049. if ( geometry instanceof THREE.Geometry === false ) {
  6050. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  6051. return;
  6052. }
  6053. var normalMatrix,
  6054. vertexOffset = this.vertices.length,
  6055. uvPosition = this.faceVertexUvs[ 0 ].length,
  6056. vertices1 = this.vertices,
  6057. vertices2 = geometry.vertices,
  6058. faces1 = this.faces,
  6059. faces2 = geometry.faces,
  6060. uvs1 = this.faceVertexUvs[ 0 ],
  6061. uvs2 = geometry.faceVertexUvs[ 0 ];
  6062. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  6063. if ( matrix !== undefined ) {
  6064. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  6065. }
  6066. // vertices
  6067. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  6068. var vertex = vertices2[ i ];
  6069. var vertexCopy = vertex.clone();
  6070. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  6071. vertices1.push( vertexCopy );
  6072. }
  6073. // faces
  6074. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  6075. var face = faces2[ i ], faceCopy, normal, color,
  6076. faceVertexNormals = face.vertexNormals,
  6077. faceVertexColors = face.vertexColors;
  6078. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  6079. faceCopy.normal.copy( face.normal );
  6080. if ( normalMatrix !== undefined ) {
  6081. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  6082. }
  6083. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  6084. normal = faceVertexNormals[ j ].clone();
  6085. if ( normalMatrix !== undefined ) {
  6086. normal.applyMatrix3( normalMatrix ).normalize();
  6087. }
  6088. faceCopy.vertexNormals.push( normal );
  6089. }
  6090. faceCopy.color.copy( face.color );
  6091. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  6092. color = faceVertexColors[ j ];
  6093. faceCopy.vertexColors.push( color.clone() );
  6094. }
  6095. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  6096. faces1.push( faceCopy );
  6097. }
  6098. // uvs
  6099. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  6100. var uv = uvs2[ i ], uvCopy = [];
  6101. if ( uv === undefined ) {
  6102. continue;
  6103. }
  6104. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  6105. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  6106. }
  6107. uvs1.push( uvCopy );
  6108. }
  6109. },
  6110. /*
  6111. * Checks for duplicate vertices with hashmap.
  6112. * Duplicated vertices are removed
  6113. * and faces' vertices are updated.
  6114. */
  6115. mergeVertices: function () {
  6116. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  6117. var unique = [], changes = [];
  6118. var v, key;
  6119. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  6120. var precision = Math.pow( 10, precisionPoints );
  6121. var i,il, face;
  6122. var indices, k, j, jl, u;
  6123. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  6124. v = this.vertices[ i ];
  6125. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  6126. if ( verticesMap[ key ] === undefined ) {
  6127. verticesMap[ key ] = i;
  6128. unique.push( this.vertices[ i ] );
  6129. changes[ i ] = unique.length - 1;
  6130. } else {
  6131. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  6132. changes[ i ] = changes[ verticesMap[ key ] ];
  6133. }
  6134. };
  6135. // if faces are completely degenerate after merging vertices, we
  6136. // have to remove them from the geometry.
  6137. var faceIndicesToRemove = [];
  6138. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  6139. face = this.faces[ i ];
  6140. face.a = changes[ face.a ];
  6141. face.b = changes[ face.b ];
  6142. face.c = changes[ face.c ];
  6143. indices = [ face.a, face.b, face.c ];
  6144. var dupIndex = - 1;
  6145. // if any duplicate vertices are found in a Face3
  6146. // we have to remove the face as nothing can be saved
  6147. for ( var n = 0; n < 3; n ++ ) {
  6148. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  6149. dupIndex = n;
  6150. faceIndicesToRemove.push( i );
  6151. break;
  6152. }
  6153. }
  6154. }
  6155. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  6156. var idx = faceIndicesToRemove[ i ];
  6157. this.faces.splice( idx, 1 );
  6158. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  6159. this.faceVertexUvs[ j ].splice( idx, 1 );
  6160. }
  6161. }
  6162. // Use unique set of vertices
  6163. var diff = this.vertices.length - unique.length;
  6164. this.vertices = unique;
  6165. return diff;
  6166. },
  6167. // Geometry splitting
  6168. makeGroups: ( function () {
  6169. var geometryGroupCounter = 0;
  6170. return function ( usesFaceMaterial, maxVerticesInGroup ) {
  6171. var f, fl, face, materialIndex,
  6172. groupHash, hash_map = {},geometryGroup;
  6173. var numMorphTargets = this.morphTargets.length;
  6174. var numMorphNormals = this.morphNormals.length;
  6175. this.geometryGroups = {};
  6176. this.geometryGroupsList = [];
  6177. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6178. face = this.faces[ f ];
  6179. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  6180. if ( ! ( materialIndex in hash_map ) ) {
  6181. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  6182. }
  6183. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  6184. if ( ! ( groupHash in this.geometryGroups ) ) {
  6185. geometryGroup = { 'id': geometryGroupCounter++, 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  6186. this.geometryGroups[ groupHash ] = geometryGroup;
  6187. this.geometryGroupsList.push(geometryGroup);
  6188. }
  6189. if ( this.geometryGroups[ groupHash ].vertices + 3 > maxVerticesInGroup ) {
  6190. hash_map[ materialIndex ].counter += 1;
  6191. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  6192. if ( ! ( groupHash in this.geometryGroups ) ) {
  6193. geometryGroup = { 'id': geometryGroupCounter++, 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  6194. this.geometryGroups[ groupHash ] = geometryGroup;
  6195. this.geometryGroupsList.push(geometryGroup);
  6196. }
  6197. }
  6198. this.geometryGroups[ groupHash ].faces3.push( f );
  6199. this.geometryGroups[ groupHash ].vertices += 3;
  6200. }
  6201. };
  6202. } )(),
  6203. clone: function () {
  6204. var geometry = new THREE.Geometry();
  6205. var vertices = this.vertices;
  6206. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6207. geometry.vertices.push( vertices[ i ].clone() );
  6208. }
  6209. var faces = this.faces;
  6210. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  6211. geometry.faces.push( faces[ i ].clone() );
  6212. }
  6213. var uvs = this.faceVertexUvs[ 0 ];
  6214. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  6215. var uv = uvs[ i ], uvCopy = [];
  6216. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  6217. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  6218. }
  6219. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  6220. }
  6221. return geometry;
  6222. },
  6223. dispose: function () {
  6224. this.dispatchEvent( { type: 'dispose' } );
  6225. }
  6226. };
  6227. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  6228. THREE.GeometryIdCount = 0;
  6229. // File:src/cameras/Camera.js
  6230. /**
  6231. * @author mrdoob / http://mrdoob.com/
  6232. * @author mikael emtinger / http://gomo.se/
  6233. * @author WestLangley / http://github.com/WestLangley
  6234. */
  6235. THREE.Camera = function () {
  6236. THREE.Object3D.call( this );
  6237. this.matrixWorldInverse = new THREE.Matrix4();
  6238. this.projectionMatrix = new THREE.Matrix4();
  6239. };
  6240. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  6241. THREE.Camera.prototype.lookAt = function () {
  6242. // This routine does not support cameras with rotated and/or translated parent(s)
  6243. var m1 = new THREE.Matrix4();
  6244. return function ( vector ) {
  6245. m1.lookAt( this.position, vector, this.up );
  6246. this.quaternion.setFromRotationMatrix( m1 );
  6247. };
  6248. }();
  6249. THREE.Camera.prototype.clone = function ( camera ) {
  6250. if ( camera === undefined ) camera = new THREE.Camera();
  6251. THREE.Object3D.prototype.clone.call( this, camera );
  6252. camera.matrixWorldInverse.copy( this.matrixWorldInverse );
  6253. camera.projectionMatrix.copy( this.projectionMatrix );
  6254. return camera;
  6255. };
  6256. // File:src/cameras/CubeCamera.js
  6257. /**
  6258. * Camera for rendering cube maps
  6259. * - renders scene into axis-aligned cube
  6260. *
  6261. * @author alteredq / http://alteredqualia.com/
  6262. */
  6263. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  6264. THREE.Object3D.call( this );
  6265. var fov = 90, aspect = 1;
  6266. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6267. cameraPX.up.set( 0, - 1, 0 );
  6268. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  6269. this.add( cameraPX );
  6270. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6271. cameraNX.up.set( 0, - 1, 0 );
  6272. cameraNX.lookAt( new THREE.Vector3( - 1, 0, 0 ) );
  6273. this.add( cameraNX );
  6274. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6275. cameraPY.up.set( 0, 0, 1 );
  6276. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  6277. this.add( cameraPY );
  6278. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6279. cameraNY.up.set( 0, 0, - 1 );
  6280. cameraNY.lookAt( new THREE.Vector3( 0, - 1, 0 ) );
  6281. this.add( cameraNY );
  6282. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6283. cameraPZ.up.set( 0, - 1, 0 );
  6284. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  6285. this.add( cameraPZ );
  6286. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6287. cameraNZ.up.set( 0, - 1, 0 );
  6288. cameraNZ.lookAt( new THREE.Vector3( 0, 0, - 1 ) );
  6289. this.add( cameraNZ );
  6290. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  6291. this.updateCubeMap = function ( renderer, scene ) {
  6292. var renderTarget = this.renderTarget;
  6293. var generateMipmaps = renderTarget.generateMipmaps;
  6294. renderTarget.generateMipmaps = false;
  6295. renderTarget.activeCubeFace = 0;
  6296. renderer.render( scene, cameraPX, renderTarget );
  6297. renderTarget.activeCubeFace = 1;
  6298. renderer.render( scene, cameraNX, renderTarget );
  6299. renderTarget.activeCubeFace = 2;
  6300. renderer.render( scene, cameraPY, renderTarget );
  6301. renderTarget.activeCubeFace = 3;
  6302. renderer.render( scene, cameraNY, renderTarget );
  6303. renderTarget.activeCubeFace = 4;
  6304. renderer.render( scene, cameraPZ, renderTarget );
  6305. renderTarget.generateMipmaps = generateMipmaps;
  6306. renderTarget.activeCubeFace = 5;
  6307. renderer.render( scene, cameraNZ, renderTarget );
  6308. };
  6309. };
  6310. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  6311. // File:src/cameras/OrthographicCamera.js
  6312. /**
  6313. * @author alteredq / http://alteredqualia.com/
  6314. */
  6315. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  6316. THREE.Camera.call( this );
  6317. this.left = left;
  6318. this.right = right;
  6319. this.top = top;
  6320. this.bottom = bottom;
  6321. this.near = ( near !== undefined ) ? near : 0.1;
  6322. this.far = ( far !== undefined ) ? far : 2000;
  6323. this.updateProjectionMatrix();
  6324. };
  6325. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  6326. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  6327. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  6328. };
  6329. THREE.OrthographicCamera.prototype.clone = function () {
  6330. var camera = new THREE.OrthographicCamera();
  6331. THREE.Camera.prototype.clone.call( this, camera );
  6332. camera.left = this.left;
  6333. camera.right = this.right;
  6334. camera.top = this.top;
  6335. camera.bottom = this.bottom;
  6336. camera.near = this.near;
  6337. camera.far = this.far;
  6338. return camera;
  6339. };
  6340. // File:src/cameras/PerspectiveCamera.js
  6341. /**
  6342. * @author mrdoob / http://mrdoob.com/
  6343. * @author greggman / http://games.greggman.com/
  6344. * @author zz85 / http://www.lab4games.net/zz85/blog
  6345. */
  6346. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  6347. THREE.Camera.call( this );
  6348. this.fov = fov !== undefined ? fov : 50;
  6349. this.aspect = aspect !== undefined ? aspect : 1;
  6350. this.near = near !== undefined ? near : 0.1;
  6351. this.far = far !== undefined ? far : 2000;
  6352. this.updateProjectionMatrix();
  6353. };
  6354. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  6355. /**
  6356. * Uses Focal Length (in mm) to estimate and set FOV
  6357. * 35mm (fullframe) camera is used if frame size is not specified;
  6358. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  6359. */
  6360. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  6361. if ( frameHeight === undefined ) frameHeight = 24;
  6362. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  6363. this.updateProjectionMatrix();
  6364. }
  6365. /**
  6366. * Sets an offset in a larger frustum. This is useful for multi-window or
  6367. * multi-monitor/multi-machine setups.
  6368. *
  6369. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6370. * the monitors are in grid like this
  6371. *
  6372. * +---+---+---+
  6373. * | A | B | C |
  6374. * +---+---+---+
  6375. * | D | E | F |
  6376. * +---+---+---+
  6377. *
  6378. * then for each monitor you would call it like this
  6379. *
  6380. * var w = 1920;
  6381. * var h = 1080;
  6382. * var fullWidth = w * 3;
  6383. * var fullHeight = h * 2;
  6384. *
  6385. * --A--
  6386. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6387. * --B--
  6388. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6389. * --C--
  6390. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6391. * --D--
  6392. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6393. * --E--
  6394. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  6395. * --F--
  6396. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  6397. *
  6398. * Note there is no reason monitors have to be the same size or in a grid.
  6399. */
  6400. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  6401. this.fullWidth = fullWidth;
  6402. this.fullHeight = fullHeight;
  6403. this.x = x;
  6404. this.y = y;
  6405. this.width = width;
  6406. this.height = height;
  6407. this.updateProjectionMatrix();
  6408. };
  6409. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  6410. if ( this.fullWidth ) {
  6411. var aspect = this.fullWidth / this.fullHeight;
  6412. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  6413. var bottom = - top;
  6414. var left = aspect * bottom;
  6415. var right = aspect * top;
  6416. var width = Math.abs( right - left );
  6417. var height = Math.abs( top - bottom );
  6418. this.projectionMatrix.makeFrustum(
  6419. left + this.x * width / this.fullWidth,
  6420. left + ( this.x + this.width ) * width / this.fullWidth,
  6421. top - ( this.y + this.height ) * height / this.fullHeight,
  6422. top - this.y * height / this.fullHeight,
  6423. this.near,
  6424. this.far
  6425. );
  6426. } else {
  6427. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  6428. }
  6429. };
  6430. THREE.PerspectiveCamera.prototype.clone = function () {
  6431. var camera = new THREE.PerspectiveCamera();
  6432. THREE.Camera.prototype.clone.call( this, camera );
  6433. camera.fov = this.fov;
  6434. camera.aspect = this.aspect;
  6435. camera.near = this.near;
  6436. camera.far = this.far;
  6437. return camera;
  6438. };
  6439. // File:src/lights/Light.js
  6440. /**
  6441. * @author mrdoob / http://mrdoob.com/
  6442. * @author alteredq / http://alteredqualia.com/
  6443. */
  6444. THREE.Light = function ( color ) {
  6445. THREE.Object3D.call( this );
  6446. this.color = new THREE.Color( color );
  6447. };
  6448. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  6449. THREE.Light.prototype.clone = function ( light ) {
  6450. if ( light === undefined ) light = new THREE.Light();
  6451. THREE.Object3D.prototype.clone.call( this, light );
  6452. light.color.copy( this.color );
  6453. return light;
  6454. };
  6455. // File:src/lights/AmbientLight.js
  6456. /**
  6457. * @author mrdoob / http://mrdoob.com/
  6458. */
  6459. THREE.AmbientLight = function ( color ) {
  6460. THREE.Light.call( this, color );
  6461. };
  6462. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  6463. THREE.AmbientLight.prototype.clone = function () {
  6464. var light = new THREE.AmbientLight();
  6465. THREE.Light.prototype.clone.call( this, light );
  6466. return light;
  6467. };
  6468. // File:src/lights/AreaLight.js
  6469. /**
  6470. * @author MPanknin / http://www.redplant.de/
  6471. * @author alteredq / http://alteredqualia.com/
  6472. */
  6473. THREE.AreaLight = function ( color, intensity ) {
  6474. THREE.Light.call( this, color );
  6475. this.normal = new THREE.Vector3( 0, - 1, 0 );
  6476. this.right = new THREE.Vector3( 1, 0, 0 );
  6477. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6478. this.width = 1.0;
  6479. this.height = 1.0;
  6480. this.constantAttenuation = 1.5;
  6481. this.linearAttenuation = 0.5;
  6482. this.quadraticAttenuation = 0.1;
  6483. };
  6484. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  6485. // File:src/lights/DirectionalLight.js
  6486. /**
  6487. * @author mrdoob / http://mrdoob.com/
  6488. * @author alteredq / http://alteredqualia.com/
  6489. */
  6490. THREE.DirectionalLight = function ( color, intensity ) {
  6491. THREE.Light.call( this, color );
  6492. this.position.set( 0, 1, 0 );
  6493. this.target = new THREE.Object3D();
  6494. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6495. this.castShadow = false;
  6496. this.onlyShadow = false;
  6497. //
  6498. this.shadowCameraNear = 50;
  6499. this.shadowCameraFar = 5000;
  6500. this.shadowCameraLeft = - 500;
  6501. this.shadowCameraRight = 500;
  6502. this.shadowCameraTop = 500;
  6503. this.shadowCameraBottom = - 500;
  6504. this.shadowCameraVisible = false;
  6505. this.shadowBias = 0;
  6506. this.shadowDarkness = 0.5;
  6507. this.shadowMapWidth = 512;
  6508. this.shadowMapHeight = 512;
  6509. //
  6510. this.shadowCascade = false;
  6511. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, - 1000 );
  6512. this.shadowCascadeCount = 2;
  6513. this.shadowCascadeBias = [ 0, 0, 0 ];
  6514. this.shadowCascadeWidth = [ 512, 512, 512 ];
  6515. this.shadowCascadeHeight = [ 512, 512, 512 ];
  6516. this.shadowCascadeNearZ = [ - 1.000, 0.990, 0.998 ];
  6517. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  6518. this.shadowCascadeArray = [];
  6519. //
  6520. this.shadowMap = null;
  6521. this.shadowMapSize = null;
  6522. this.shadowCamera = null;
  6523. this.shadowMatrix = null;
  6524. };
  6525. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  6526. THREE.DirectionalLight.prototype.clone = function () {
  6527. var light = new THREE.DirectionalLight();
  6528. THREE.Light.prototype.clone.call( this, light );
  6529. light.target = this.target.clone();
  6530. light.intensity = this.intensity;
  6531. light.castShadow = this.castShadow;
  6532. light.onlyShadow = this.onlyShadow;
  6533. //
  6534. light.shadowCameraNear = this.shadowCameraNear;
  6535. light.shadowCameraFar = this.shadowCameraFar;
  6536. light.shadowCameraLeft = this.shadowCameraLeft;
  6537. light.shadowCameraRight = this.shadowCameraRight;
  6538. light.shadowCameraTop = this.shadowCameraTop;
  6539. light.shadowCameraBottom = this.shadowCameraBottom;
  6540. light.shadowCameraVisible = this.shadowCameraVisible;
  6541. light.shadowBias = this.shadowBias;
  6542. light.shadowDarkness = this.shadowDarkness;
  6543. light.shadowMapWidth = this.shadowMapWidth;
  6544. light.shadowMapHeight = this.shadowMapHeight;
  6545. //
  6546. light.shadowCascade = this.shadowCascade;
  6547. light.shadowCascadeOffset.copy( this.shadowCascadeOffset );
  6548. light.shadowCascadeCount = this.shadowCascadeCount;
  6549. light.shadowCascadeBias = this.shadowCascadeBias.slice( 0 );
  6550. light.shadowCascadeWidth = this.shadowCascadeWidth.slice( 0 );
  6551. light.shadowCascadeHeight = this.shadowCascadeHeight.slice( 0 );
  6552. light.shadowCascadeNearZ = this.shadowCascadeNearZ.slice( 0 );
  6553. light.shadowCascadeFarZ = this.shadowCascadeFarZ.slice( 0 );
  6554. return light;
  6555. };
  6556. // File:src/lights/HemisphereLight.js
  6557. /**
  6558. * @author alteredq / http://alteredqualia.com/
  6559. */
  6560. THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
  6561. THREE.Light.call( this, skyColor );
  6562. this.position.set( 0, 100, 0 );
  6563. this.groundColor = new THREE.Color( groundColor );
  6564. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6565. };
  6566. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  6567. THREE.HemisphereLight.prototype.clone = function () {
  6568. var light = new THREE.HemisphereLight();
  6569. THREE.Light.prototype.clone.call( this, light );
  6570. light.groundColor.copy( this.groundColor );
  6571. light.intensity = this.intensity;
  6572. return light;
  6573. };
  6574. // File:src/lights/PointLight.js
  6575. /**
  6576. * @author mrdoob / http://mrdoob.com/
  6577. */
  6578. THREE.PointLight = function ( color, intensity, distance ) {
  6579. THREE.Light.call( this, color );
  6580. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6581. this.distance = ( distance !== undefined ) ? distance : 0;
  6582. };
  6583. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  6584. THREE.PointLight.prototype.clone = function () {
  6585. var light = new THREE.PointLight();
  6586. THREE.Light.prototype.clone.call( this, light );
  6587. light.intensity = this.intensity;
  6588. light.distance = this.distance;
  6589. return light;
  6590. };
  6591. // File:src/lights/SpotLight.js
  6592. /**
  6593. * @author alteredq / http://alteredqualia.com/
  6594. */
  6595. THREE.SpotLight = function ( color, intensity, distance, angle, exponent ) {
  6596. THREE.Light.call( this, color );
  6597. this.position.set( 0, 1, 0 );
  6598. this.target = new THREE.Object3D();
  6599. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6600. this.distance = ( distance !== undefined ) ? distance : 0;
  6601. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  6602. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  6603. this.castShadow = false;
  6604. this.onlyShadow = false;
  6605. //
  6606. this.shadowCameraNear = 50;
  6607. this.shadowCameraFar = 5000;
  6608. this.shadowCameraFov = 50;
  6609. this.shadowCameraVisible = false;
  6610. this.shadowBias = 0;
  6611. this.shadowDarkness = 0.5;
  6612. this.shadowMapWidth = 512;
  6613. this.shadowMapHeight = 512;
  6614. //
  6615. this.shadowMap = null;
  6616. this.shadowMapSize = null;
  6617. this.shadowCamera = null;
  6618. this.shadowMatrix = null;
  6619. };
  6620. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  6621. THREE.SpotLight.prototype.clone = function () {
  6622. var light = new THREE.SpotLight();
  6623. THREE.Light.prototype.clone.call( this, light );
  6624. light.target = this.target.clone();
  6625. light.intensity = this.intensity;
  6626. light.distance = this.distance;
  6627. light.angle = this.angle;
  6628. light.exponent = this.exponent;
  6629. light.castShadow = this.castShadow;
  6630. light.onlyShadow = this.onlyShadow;
  6631. //
  6632. light.shadowCameraNear = this.shadowCameraNear;
  6633. light.shadowCameraFar = this.shadowCameraFar;
  6634. light.shadowCameraFov = this.shadowCameraFov;
  6635. light.shadowCameraVisible = this.shadowCameraVisible;
  6636. light.shadowBias = this.shadowBias;
  6637. light.shadowDarkness = this.shadowDarkness;
  6638. light.shadowMapWidth = this.shadowMapWidth;
  6639. light.shadowMapHeight = this.shadowMapHeight;
  6640. return light;
  6641. };
  6642. // File:src/loaders/Cache.js
  6643. /**
  6644. * @author mrdoob / http://mrdoob.com/
  6645. */
  6646. THREE.Cache = function () {
  6647. this.files = {};
  6648. };
  6649. THREE.Cache.prototype = {
  6650. constructor: THREE.Cache,
  6651. add: function ( key, file ) {
  6652. // console.log( 'THREE.Cache', 'Adding key:', key );
  6653. this.files[ key ] = file;
  6654. },
  6655. get: function ( key ) {
  6656. // console.log( 'THREE.Cache', 'Checking key:', key );
  6657. return this.files[ key ];
  6658. },
  6659. remove: function ( key ) {
  6660. delete this.files[ key ];
  6661. },
  6662. clear: function () {
  6663. this.files = {}
  6664. }
  6665. };
  6666. // File:src/loaders/Loader.js
  6667. /**
  6668. * @author alteredq / http://alteredqualia.com/
  6669. */
  6670. THREE.Loader = function ( showStatus ) {
  6671. this.showStatus = showStatus;
  6672. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  6673. this.imageLoader = new THREE.ImageLoader();
  6674. this.onLoadStart = function () {};
  6675. this.onLoadProgress = function () {};
  6676. this.onLoadComplete = function () {};
  6677. };
  6678. THREE.Loader.prototype = {
  6679. constructor: THREE.Loader,
  6680. crossOrigin: undefined,
  6681. addStatusElement: function () {
  6682. var e = document.createElement( 'div' );
  6683. e.style.position = 'absolute';
  6684. e.style.right = '0px';
  6685. e.style.top = '0px';
  6686. e.style.fontSize = '0.8em';
  6687. e.style.textAlign = 'left';
  6688. e.style.background = 'rgba(0,0,0,0.25)';
  6689. e.style.color = '#fff';
  6690. e.style.width = '120px';
  6691. e.style.padding = '0.5em 0.5em 0.5em 0.5em';
  6692. e.style.zIndex = 1000;
  6693. e.innerHTML = 'Loading ...';
  6694. return e;
  6695. },
  6696. updateProgress: function ( progress ) {
  6697. var message = 'Loaded ';
  6698. if ( progress.total ) {
  6699. message += ( 100 * progress.loaded / progress.total ).toFixed( 0 ) + '%';
  6700. } else {
  6701. message += ( progress.loaded / 1024 ).toFixed( 2 ) + ' KB';
  6702. }
  6703. this.statusDomElement.innerHTML = message;
  6704. },
  6705. extractUrlBase: function ( url ) {
  6706. var parts = url.split( '/' );
  6707. if ( parts.length === 1 ) return './';
  6708. parts.pop();
  6709. return parts.join( '/' ) + '/';
  6710. },
  6711. initMaterials: function ( materials, texturePath ) {
  6712. var array = [];
  6713. for ( var i = 0; i < materials.length; ++ i ) {
  6714. array[ i ] = this.createMaterial( materials[ i ], texturePath );
  6715. }
  6716. return array;
  6717. },
  6718. needsTangents: function ( materials ) {
  6719. for ( var i = 0, il = materials.length; i < il; i ++ ) {
  6720. var m = materials[ i ];
  6721. if ( m instanceof THREE.ShaderMaterial ) return true;
  6722. }
  6723. return false;
  6724. },
  6725. createMaterial: function ( m, texturePath ) {
  6726. var scope = this;
  6727. function nearest_pow2( n ) {
  6728. var l = Math.log( n ) / Math.LN2;
  6729. return Math.pow( 2, Math.round( l ) );
  6730. }
  6731. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  6732. var fullPath = texturePath + sourceFile;
  6733. var texture;
  6734. var loader = THREE.Loader.Handlers.get( fullPath );
  6735. if ( loader !== null ) {
  6736. texture = loader.load( fullPath );
  6737. } else {
  6738. texture = new THREE.Texture();
  6739. loader = scope.imageLoader;
  6740. loader.crossOrigin = scope.crossOrigin;
  6741. loader.load( fullPath, function ( image ) {
  6742. if ( THREE.Math.isPowerOfTwo( image.width ) === false ||
  6743. THREE.Math.isPowerOfTwo( image.height ) === false ) {
  6744. var width = nearest_pow2( image.width );
  6745. var height = nearest_pow2( image.height );
  6746. var canvas = document.createElement( 'canvas' );
  6747. canvas.width = width;
  6748. canvas.height = height;
  6749. var context = canvas.getContext( '2d' );
  6750. context.drawImage( image, 0, 0, width, height );
  6751. texture.image = canvas;
  6752. } else {
  6753. texture.image = image;
  6754. }
  6755. texture.needsUpdate = true;
  6756. } );
  6757. }
  6758. texture.sourceFile = sourceFile;
  6759. if ( repeat ) {
  6760. texture.repeat.set( repeat[ 0 ], repeat[ 1 ] );
  6761. if ( repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  6762. if ( repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  6763. }
  6764. if ( offset ) {
  6765. texture.offset.set( offset[ 0 ], offset[ 1 ] );
  6766. }
  6767. if ( wrap ) {
  6768. var wrapMap = {
  6769. 'repeat': THREE.RepeatWrapping,
  6770. 'mirror': THREE.MirroredRepeatWrapping
  6771. }
  6772. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ wrap[ 0 ] ];
  6773. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ wrap[ 1 ] ];
  6774. }
  6775. if ( anisotropy ) {
  6776. texture.anisotropy = anisotropy;
  6777. }
  6778. where[ name ] = texture;
  6779. }
  6780. function rgb2hex( rgb ) {
  6781. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  6782. }
  6783. // defaults
  6784. var mtype = 'MeshLambertMaterial';
  6785. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  6786. // parameters from model file
  6787. if ( m.shading ) {
  6788. var shading = m.shading.toLowerCase();
  6789. if ( shading === 'phong' ) mtype = 'MeshPhongMaterial';
  6790. else if ( shading === 'basic' ) mtype = 'MeshBasicMaterial';
  6791. }
  6792. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  6793. mpars.blending = THREE[ m.blending ];
  6794. }
  6795. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  6796. mpars.transparent = m.transparent;
  6797. }
  6798. if ( m.depthTest !== undefined ) {
  6799. mpars.depthTest = m.depthTest;
  6800. }
  6801. if ( m.depthWrite !== undefined ) {
  6802. mpars.depthWrite = m.depthWrite;
  6803. }
  6804. if ( m.visible !== undefined ) {
  6805. mpars.visible = m.visible;
  6806. }
  6807. if ( m.flipSided !== undefined ) {
  6808. mpars.side = THREE.BackSide;
  6809. }
  6810. if ( m.doubleSided !== undefined ) {
  6811. mpars.side = THREE.DoubleSide;
  6812. }
  6813. if ( m.wireframe !== undefined ) {
  6814. mpars.wireframe = m.wireframe;
  6815. }
  6816. if ( m.vertexColors !== undefined ) {
  6817. if ( m.vertexColors === 'face' ) {
  6818. mpars.vertexColors = THREE.FaceColors;
  6819. } else if ( m.vertexColors ) {
  6820. mpars.vertexColors = THREE.VertexColors;
  6821. }
  6822. }
  6823. // colors
  6824. if ( m.colorDiffuse ) {
  6825. mpars.color = rgb2hex( m.colorDiffuse );
  6826. } else if ( m.DbgColor ) {
  6827. mpars.color = m.DbgColor;
  6828. }
  6829. if ( m.colorSpecular ) {
  6830. mpars.specular = rgb2hex( m.colorSpecular );
  6831. }
  6832. if ( m.colorAmbient ) {
  6833. mpars.ambient = rgb2hex( m.colorAmbient );
  6834. }
  6835. if ( m.colorEmissive ) {
  6836. mpars.emissive = rgb2hex( m.colorEmissive );
  6837. }
  6838. // modifiers
  6839. if ( m.transparency ) {
  6840. mpars.opacity = m.transparency;
  6841. }
  6842. if ( m.specularCoef ) {
  6843. mpars.shininess = m.specularCoef;
  6844. }
  6845. // textures
  6846. if ( m.mapDiffuse && texturePath ) {
  6847. create_texture( mpars, 'map', m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  6848. }
  6849. if ( m.mapLight && texturePath ) {
  6850. create_texture( mpars, 'lightMap', m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  6851. }
  6852. if ( m.mapBump && texturePath ) {
  6853. create_texture( mpars, 'bumpMap', m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  6854. }
  6855. if ( m.mapNormal && texturePath ) {
  6856. create_texture( mpars, 'normalMap', m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  6857. }
  6858. if ( m.mapSpecular && texturePath ) {
  6859. create_texture( mpars, 'specularMap', m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  6860. }
  6861. //
  6862. if ( m.mapBumpScale ) {
  6863. mpars.bumpScale = m.mapBumpScale;
  6864. }
  6865. // special case for normal mapped material
  6866. if ( m.mapNormal ) {
  6867. var shader = THREE.ShaderLib[ 'normalmap' ];
  6868. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6869. uniforms[ 'tNormal' ].value = mpars.normalMap;
  6870. if ( m.mapNormalFactor ) {
  6871. uniforms[ 'uNormalScale' ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  6872. }
  6873. if ( mpars.map ) {
  6874. uniforms[ 'tDiffuse' ].value = mpars.map;
  6875. uniforms[ 'enableDiffuse' ].value = true;
  6876. }
  6877. if ( mpars.specularMap ) {
  6878. uniforms[ 'tSpecular' ].value = mpars.specularMap;
  6879. uniforms[ 'enableSpecular' ].value = true;
  6880. }
  6881. if ( mpars.lightMap ) {
  6882. uniforms[ 'tAO' ].value = mpars.lightMap;
  6883. uniforms[ 'enableAO' ].value = true;
  6884. }
  6885. // for the moment don't handle displacement texture
  6886. uniforms[ 'diffuse' ].value.setHex( mpars.color );
  6887. uniforms[ 'specular' ].value.setHex( mpars.specular );
  6888. uniforms[ 'ambient' ].value.setHex( mpars.ambient );
  6889. uniforms[ 'shininess' ].value = mpars.shininess;
  6890. if ( mpars.opacity !== undefined ) {
  6891. uniforms[ 'opacity' ].value = mpars.opacity;
  6892. }
  6893. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6894. var material = new THREE.ShaderMaterial( parameters );
  6895. if ( mpars.transparent ) {
  6896. material.transparent = true;
  6897. }
  6898. } else {
  6899. var material = new THREE[ mtype ]( mpars );
  6900. }
  6901. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6902. return material;
  6903. }
  6904. };
  6905. THREE.Loader.Handlers = {
  6906. handlers: [],
  6907. add: function ( regex, loader ) {
  6908. this.handlers.push( regex, loader );
  6909. },
  6910. get: function ( file ) {
  6911. for ( var i = 0, l = this.handlers.length; i < l; i += 2 ) {
  6912. var regex = this.handlers[ i ];
  6913. var loader = this.handlers[ i + 1 ];
  6914. if ( regex.test( file ) ) {
  6915. return loader;
  6916. }
  6917. }
  6918. return null;
  6919. }
  6920. };
  6921. // File:src/loaders/XHRLoader.js
  6922. /**
  6923. * @author mrdoob / http://mrdoob.com/
  6924. */
  6925. THREE.XHRLoader = function ( manager ) {
  6926. this.cache = new THREE.Cache();
  6927. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6928. };
  6929. THREE.XHRLoader.prototype = {
  6930. constructor: THREE.XHRLoader,
  6931. load: function ( url, onLoad, onProgress, onError ) {
  6932. var scope = this;
  6933. var cached = scope.cache.get( url );
  6934. if ( cached !== undefined ) {
  6935. if ( onLoad ) onLoad( cached );
  6936. return;
  6937. }
  6938. var request = new XMLHttpRequest();
  6939. request.open( 'GET', url, true );
  6940. request.addEventListener( 'load', function ( event ) {
  6941. scope.cache.add( url, this.response );
  6942. if ( onLoad ) onLoad( this.response );
  6943. scope.manager.itemEnd( url );
  6944. }, false );
  6945. if ( onProgress !== undefined ) {
  6946. request.addEventListener( 'progress', function ( event ) {
  6947. onProgress( event );
  6948. }, false );
  6949. }
  6950. if ( onError !== undefined ) {
  6951. request.addEventListener( 'error', function ( event ) {
  6952. onError( event );
  6953. }, false );
  6954. }
  6955. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  6956. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  6957. request.send( null );
  6958. scope.manager.itemStart( url );
  6959. },
  6960. setResponseType: function ( value ) {
  6961. this.responseType = value;
  6962. },
  6963. setCrossOrigin: function ( value ) {
  6964. this.crossOrigin = value;
  6965. }
  6966. };
  6967. // File:src/loaders/ImageLoader.js
  6968. /**
  6969. * @author mrdoob / http://mrdoob.com/
  6970. */
  6971. THREE.ImageLoader = function ( manager ) {
  6972. this.cache = new THREE.Cache();
  6973. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6974. };
  6975. THREE.ImageLoader.prototype = {
  6976. constructor: THREE.ImageLoader,
  6977. load: function ( url, onLoad, onProgress, onError ) {
  6978. var scope = this;
  6979. var cached = scope.cache.get( url );
  6980. if ( cached !== undefined ) {
  6981. onLoad( cached );
  6982. return;
  6983. }
  6984. var image = document.createElement( 'img' );
  6985. if ( onLoad !== undefined ) {
  6986. image.addEventListener( 'load', function ( event ) {
  6987. scope.cache.add( url, this );
  6988. onLoad( this );
  6989. scope.manager.itemEnd( url );
  6990. }, false );
  6991. }
  6992. if ( onProgress !== undefined ) {
  6993. image.addEventListener( 'progress', function ( event ) {
  6994. onProgress( event );
  6995. }, false );
  6996. }
  6997. if ( onError !== undefined ) {
  6998. image.addEventListener( 'error', function ( event ) {
  6999. onError( event );
  7000. }, false );
  7001. }
  7002. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  7003. image.src = url;
  7004. scope.manager.itemStart( url );
  7005. return image;
  7006. },
  7007. setCrossOrigin: function ( value ) {
  7008. this.crossOrigin = value;
  7009. }
  7010. }
  7011. // File:src/loaders/JSONLoader.js
  7012. /**
  7013. * @author mrdoob / http://mrdoob.com/
  7014. * @author alteredq / http://alteredqualia.com/
  7015. */
  7016. THREE.JSONLoader = function ( showStatus ) {
  7017. THREE.Loader.call( this, showStatus );
  7018. this.withCredentials = false;
  7019. };
  7020. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  7021. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  7022. var scope = this;
  7023. // todo: unify load API to for easier SceneLoader use
  7024. texturePath = texturePath && ( typeof texturePath === 'string' ) ? texturePath : this.extractUrlBase( url );
  7025. this.onLoadStart();
  7026. this.loadAjaxJSON( this, url, callback, texturePath );
  7027. };
  7028. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  7029. var xhr = new XMLHttpRequest();
  7030. var length = 0;
  7031. xhr.onreadystatechange = function () {
  7032. if ( xhr.readyState === xhr.DONE ) {
  7033. if ( xhr.status === 200 || xhr.status === 0 ) {
  7034. if ( xhr.responseText ) {
  7035. var json = JSON.parse( xhr.responseText );
  7036. if ( json.metadata !== undefined && json.metadata.type === 'scene' ) {
  7037. console.error( 'THREE.JSONLoader: "' + url + '" seems to be a Scene. Use THREE.SceneLoader instead.' );
  7038. return;
  7039. }
  7040. var result = context.parse( json, texturePath );
  7041. callback( result.geometry, result.materials );
  7042. } else {
  7043. console.error( 'THREE.JSONLoader: "' + url + '" seems to be unreachable or the file is empty.' );
  7044. }
  7045. // in context of more complex asset initialization
  7046. // do not block on single failed file
  7047. // maybe should go even one more level up
  7048. context.onLoadComplete();
  7049. } else {
  7050. console.error( 'THREE.JSONLoader: Couldn\'t load "' + url + '" (' + xhr.status + ')' );
  7051. }
  7052. } else if ( xhr.readyState === xhr.LOADING ) {
  7053. if ( callbackProgress ) {
  7054. if ( length === 0 ) {
  7055. length = xhr.getResponseHeader( 'Content-Length' );
  7056. }
  7057. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  7058. }
  7059. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  7060. if ( callbackProgress !== undefined ) {
  7061. length = xhr.getResponseHeader( 'Content-Length' );
  7062. }
  7063. }
  7064. };
  7065. xhr.open( 'GET', url, true );
  7066. xhr.withCredentials = this.withCredentials;
  7067. xhr.send( null );
  7068. };
  7069. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  7070. var scope = this,
  7071. geometry = new THREE.Geometry(),
  7072. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  7073. parseModel( scale );
  7074. parseSkin();
  7075. parseMorphing( scale );
  7076. geometry.computeFaceNormals();
  7077. geometry.computeBoundingSphere();
  7078. function parseModel( scale ) {
  7079. function isBitSet( value, position ) {
  7080. return value & ( 1 << position );
  7081. }
  7082. var i, j, fi,
  7083. offset, zLength,
  7084. colorIndex, normalIndex, uvIndex, materialIndex,
  7085. type,
  7086. isQuad,
  7087. hasMaterial,
  7088. hasFaceVertexUv,
  7089. hasFaceNormal, hasFaceVertexNormal,
  7090. hasFaceColor, hasFaceVertexColor,
  7091. vertex, face, faceA, faceB, color, hex, normal,
  7092. uvLayer, uv, u, v,
  7093. faces = json.faces,
  7094. vertices = json.vertices,
  7095. normals = json.normals,
  7096. colors = json.colors,
  7097. nUvLayers = 0;
  7098. if ( json.uvs !== undefined ) {
  7099. // disregard empty arrays
  7100. for ( i = 0; i < json.uvs.length; i ++ ) {
  7101. if ( json.uvs[ i ].length ) nUvLayers ++;
  7102. }
  7103. for ( i = 0; i < nUvLayers; i ++ ) {
  7104. geometry.faceVertexUvs[ i ] = [];
  7105. }
  7106. }
  7107. offset = 0;
  7108. zLength = vertices.length;
  7109. while ( offset < zLength ) {
  7110. vertex = new THREE.Vector3();
  7111. vertex.x = vertices[ offset ++ ] * scale;
  7112. vertex.y = vertices[ offset ++ ] * scale;
  7113. vertex.z = vertices[ offset ++ ] * scale;
  7114. geometry.vertices.push( vertex );
  7115. }
  7116. offset = 0;
  7117. zLength = faces.length;
  7118. while ( offset < zLength ) {
  7119. type = faces[ offset ++ ];
  7120. isQuad = isBitSet( type, 0 );
  7121. hasMaterial = isBitSet( type, 1 );
  7122. hasFaceVertexUv = isBitSet( type, 3 );
  7123. hasFaceNormal = isBitSet( type, 4 );
  7124. hasFaceVertexNormal = isBitSet( type, 5 );
  7125. hasFaceColor = isBitSet( type, 6 );
  7126. hasFaceVertexColor = isBitSet( type, 7 );
  7127. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  7128. if ( isQuad ) {
  7129. faceA = new THREE.Face3();
  7130. faceA.a = faces[ offset ];
  7131. faceA.b = faces[ offset + 1 ];
  7132. faceA.c = faces[ offset + 3 ];
  7133. faceB = new THREE.Face3();
  7134. faceB.a = faces[ offset + 1 ];
  7135. faceB.b = faces[ offset + 2 ];
  7136. faceB.c = faces[ offset + 3 ];
  7137. offset += 4;
  7138. if ( hasMaterial ) {
  7139. materialIndex = faces[ offset ++ ];
  7140. faceA.materialIndex = materialIndex;
  7141. faceB.materialIndex = materialIndex;
  7142. }
  7143. // to get face <=> uv index correspondence
  7144. fi = geometry.faces.length;
  7145. if ( hasFaceVertexUv ) {
  7146. for ( i = 0; i < nUvLayers; i ++ ) {
  7147. uvLayer = json.uvs[ i ];
  7148. geometry.faceVertexUvs[ i ][ fi ] = [];
  7149. geometry.faceVertexUvs[ i ][ fi + 1 ] = []
  7150. for ( j = 0; j < 4; j ++ ) {
  7151. uvIndex = faces[ offset ++ ];
  7152. u = uvLayer[ uvIndex * 2 ];
  7153. v = uvLayer[ uvIndex * 2 + 1 ];
  7154. uv = new THREE.Vector2( u, v );
  7155. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7156. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  7157. }
  7158. }
  7159. }
  7160. if ( hasFaceNormal ) {
  7161. normalIndex = faces[ offset ++ ] * 3;
  7162. faceA.normal.set(
  7163. normals[ normalIndex ++ ],
  7164. normals[ normalIndex ++ ],
  7165. normals[ normalIndex ]
  7166. );
  7167. faceB.normal.copy( faceA.normal );
  7168. }
  7169. if ( hasFaceVertexNormal ) {
  7170. for ( i = 0; i < 4; i ++ ) {
  7171. normalIndex = faces[ offset ++ ] * 3;
  7172. normal = new THREE.Vector3(
  7173. normals[ normalIndex ++ ],
  7174. normals[ normalIndex ++ ],
  7175. normals[ normalIndex ]
  7176. );
  7177. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  7178. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  7179. }
  7180. }
  7181. if ( hasFaceColor ) {
  7182. colorIndex = faces[ offset ++ ];
  7183. hex = colors[ colorIndex ];
  7184. faceA.color.setHex( hex );
  7185. faceB.color.setHex( hex );
  7186. }
  7187. if ( hasFaceVertexColor ) {
  7188. for ( i = 0; i < 4; i ++ ) {
  7189. colorIndex = faces[ offset ++ ];
  7190. hex = colors[ colorIndex ];
  7191. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  7192. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  7193. }
  7194. }
  7195. geometry.faces.push( faceA );
  7196. geometry.faces.push( faceB );
  7197. } else {
  7198. face = new THREE.Face3();
  7199. face.a = faces[ offset ++ ];
  7200. face.b = faces[ offset ++ ];
  7201. face.c = faces[ offset ++ ];
  7202. if ( hasMaterial ) {
  7203. materialIndex = faces[ offset ++ ];
  7204. face.materialIndex = materialIndex;
  7205. }
  7206. // to get face <=> uv index correspondence
  7207. fi = geometry.faces.length;
  7208. if ( hasFaceVertexUv ) {
  7209. for ( i = 0; i < nUvLayers; i ++ ) {
  7210. uvLayer = json.uvs[ i ];
  7211. geometry.faceVertexUvs[ i ][ fi ] = [];
  7212. for ( j = 0; j < 3; j ++ ) {
  7213. uvIndex = faces[ offset ++ ];
  7214. u = uvLayer[ uvIndex * 2 ];
  7215. v = uvLayer[ uvIndex * 2 + 1 ];
  7216. uv = new THREE.Vector2( u, v );
  7217. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7218. }
  7219. }
  7220. }
  7221. if ( hasFaceNormal ) {
  7222. normalIndex = faces[ offset ++ ] * 3;
  7223. face.normal.set(
  7224. normals[ normalIndex ++ ],
  7225. normals[ normalIndex ++ ],
  7226. normals[ normalIndex ]
  7227. );
  7228. }
  7229. if ( hasFaceVertexNormal ) {
  7230. for ( i = 0; i < 3; i ++ ) {
  7231. normalIndex = faces[ offset ++ ] * 3;
  7232. normal = new THREE.Vector3(
  7233. normals[ normalIndex ++ ],
  7234. normals[ normalIndex ++ ],
  7235. normals[ normalIndex ]
  7236. );
  7237. face.vertexNormals.push( normal );
  7238. }
  7239. }
  7240. if ( hasFaceColor ) {
  7241. colorIndex = faces[ offset ++ ];
  7242. face.color.setHex( colors[ colorIndex ] );
  7243. }
  7244. if ( hasFaceVertexColor ) {
  7245. for ( i = 0; i < 3; i ++ ) {
  7246. colorIndex = faces[ offset ++ ];
  7247. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  7248. }
  7249. }
  7250. geometry.faces.push( face );
  7251. }
  7252. }
  7253. };
  7254. function parseSkin() {
  7255. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  7256. if ( json.skinWeights ) {
  7257. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  7258. var x = json.skinWeights[ i ];
  7259. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  7260. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  7261. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  7262. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  7263. }
  7264. }
  7265. if ( json.skinIndices ) {
  7266. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  7267. var a = json.skinIndices[ i ];
  7268. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  7269. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  7270. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  7271. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  7272. }
  7273. }
  7274. geometry.bones = json.bones;
  7275. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  7276. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  7277. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  7278. }
  7279. // could change this to json.animations[0] or remove completely
  7280. geometry.animation = json.animation;
  7281. geometry.animations = json.animations;
  7282. };
  7283. function parseMorphing( scale ) {
  7284. if ( json.morphTargets !== undefined ) {
  7285. var i, l, v, vl, dstVertices, srcVertices;
  7286. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  7287. geometry.morphTargets[ i ] = {};
  7288. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  7289. geometry.morphTargets[ i ].vertices = [];
  7290. dstVertices = geometry.morphTargets[ i ].vertices;
  7291. srcVertices = json.morphTargets [ i ].vertices;
  7292. for ( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  7293. var vertex = new THREE.Vector3();
  7294. vertex.x = srcVertices[ v ] * scale;
  7295. vertex.y = srcVertices[ v + 1 ] * scale;
  7296. vertex.z = srcVertices[ v + 2 ] * scale;
  7297. dstVertices.push( vertex );
  7298. }
  7299. }
  7300. }
  7301. if ( json.morphColors !== undefined ) {
  7302. var i, l, c, cl, dstColors, srcColors, color;
  7303. for ( i = 0, l = json.morphColors.length; i < l; i ++ ) {
  7304. geometry.morphColors[ i ] = {};
  7305. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  7306. geometry.morphColors[ i ].colors = [];
  7307. dstColors = geometry.morphColors[ i ].colors;
  7308. srcColors = json.morphColors [ i ].colors;
  7309. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  7310. color = new THREE.Color( 0xffaa00 );
  7311. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  7312. dstColors.push( color );
  7313. }
  7314. }
  7315. }
  7316. };
  7317. if ( json.materials === undefined || json.materials.length === 0 ) {
  7318. return { geometry: geometry };
  7319. } else {
  7320. var materials = this.initMaterials( json.materials, texturePath );
  7321. if ( this.needsTangents( materials ) ) {
  7322. geometry.computeTangents();
  7323. }
  7324. return { geometry: geometry, materials: materials };
  7325. }
  7326. };
  7327. // File:src/loaders/LoadingManager.js
  7328. /**
  7329. * @author mrdoob / http://mrdoob.com/
  7330. */
  7331. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  7332. var scope = this;
  7333. var loaded = 0, total = 0;
  7334. this.onLoad = onLoad;
  7335. this.onProgress = onProgress;
  7336. this.onError = onError;
  7337. this.itemStart = function ( url ) {
  7338. total ++;
  7339. };
  7340. this.itemEnd = function ( url ) {
  7341. loaded ++;
  7342. if ( scope.onProgress !== undefined ) {
  7343. scope.onProgress( url, loaded, total );
  7344. }
  7345. if ( loaded === total && scope.onLoad !== undefined ) {
  7346. scope.onLoad();
  7347. }
  7348. };
  7349. };
  7350. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  7351. // File:src/loaders/BufferGeometryLoader.js
  7352. /**
  7353. * @author mrdoob / http://mrdoob.com/
  7354. */
  7355. THREE.BufferGeometryLoader = function ( manager ) {
  7356. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7357. };
  7358. THREE.BufferGeometryLoader.prototype = {
  7359. constructor: THREE.BufferGeometryLoader,
  7360. load: function ( url, onLoad, onProgress, onError ) {
  7361. var scope = this;
  7362. var loader = new THREE.XHRLoader();
  7363. loader.setCrossOrigin( this.crossOrigin );
  7364. loader.load( url, function ( text ) {
  7365. onLoad( scope.parse( JSON.parse( text ) ) );
  7366. }, onProgress, onError );
  7367. },
  7368. setCrossOrigin: function ( value ) {
  7369. this.crossOrigin = value;
  7370. },
  7371. parse: function ( json ) {
  7372. var geometry = new THREE.BufferGeometry();
  7373. var attributes = json.attributes;
  7374. for ( var key in attributes ) {
  7375. var attribute = attributes[ key ];
  7376. geometry.attributes[ key ] = {
  7377. itemSize: attribute.itemSize,
  7378. array: new self[ attribute.type ]( attribute.array )
  7379. }
  7380. }
  7381. var offsets = json.offsets;
  7382. if ( offsets !== undefined ) {
  7383. geometry.offsets = JSON.parse( JSON.stringify( offsets ) );
  7384. }
  7385. var boundingSphere = json.boundingSphere;
  7386. if ( boundingSphere !== undefined ) {
  7387. geometry.boundingSphere = new THREE.Sphere(
  7388. new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ),
  7389. boundingSphere.radius
  7390. );
  7391. }
  7392. return geometry;
  7393. }
  7394. };
  7395. // File:src/loaders/MaterialLoader.js
  7396. /**
  7397. * @author mrdoob / http://mrdoob.com/
  7398. */
  7399. THREE.MaterialLoader = function ( manager ) {
  7400. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7401. };
  7402. THREE.MaterialLoader.prototype = {
  7403. constructor: THREE.MaterialLoader,
  7404. load: function ( url, onLoad, onProgress, onError ) {
  7405. var scope = this;
  7406. var loader = new THREE.XHRLoader();
  7407. loader.setCrossOrigin( this.crossOrigin );
  7408. loader.load( url, function ( text ) {
  7409. onLoad( scope.parse( JSON.parse( text ) ) );
  7410. }, onProgress, onError );
  7411. },
  7412. setCrossOrigin: function ( value ) {
  7413. this.crossOrigin = value;
  7414. },
  7415. parse: function ( json ) {
  7416. var material = new THREE[ json.type ];
  7417. if ( json.color !== undefined ) material.color.setHex( json.color );
  7418. if ( json.ambient !== undefined ) material.ambient.setHex( json.ambient );
  7419. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  7420. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  7421. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  7422. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  7423. if ( json.blending !== undefined ) material.blending = json.blending;
  7424. if ( json.side !== undefined ) material.side = json.side;
  7425. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  7426. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  7427. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  7428. if ( json.materials !== undefined ) {
  7429. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  7430. material.materials.push( this.parse( json.materials[ i ] ) );
  7431. }
  7432. }
  7433. return material;
  7434. }
  7435. };
  7436. // File:src/loaders/ObjectLoader.js
  7437. /**
  7438. * @author mrdoob / http://mrdoob.com/
  7439. */
  7440. THREE.ObjectLoader = function ( manager ) {
  7441. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7442. };
  7443. THREE.ObjectLoader.prototype = {
  7444. constructor: THREE.ObjectLoader,
  7445. load: function ( url, onLoad, onProgress, onError ) {
  7446. var scope = this;
  7447. var loader = new THREE.XHRLoader( scope.manager );
  7448. loader.setCrossOrigin( this.crossOrigin );
  7449. loader.load( url, function ( text ) {
  7450. onLoad( scope.parse( JSON.parse( text ) ) );
  7451. }, onProgress, onError );
  7452. },
  7453. setCrossOrigin: function ( value ) {
  7454. this.crossOrigin = value;
  7455. },
  7456. parse: function ( json ) {
  7457. var geometries = this.parseGeometries( json.geometries );
  7458. var materials = this.parseMaterials( json.materials );
  7459. var object = this.parseObject( json.object, geometries, materials );
  7460. return object;
  7461. },
  7462. parseGeometries: function ( json ) {
  7463. var geometries = {};
  7464. if ( json !== undefined ) {
  7465. var geometryLoader = new THREE.JSONLoader();
  7466. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  7467. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7468. var geometry;
  7469. var data = json[ i ];
  7470. switch ( data.type ) {
  7471. case 'PlaneGeometry':
  7472. geometry = new THREE.PlaneGeometry(
  7473. data.width,
  7474. data.height,
  7475. data.widthSegments,
  7476. data.heightSegments
  7477. );
  7478. break;
  7479. case 'BoxGeometry':
  7480. case 'CubeGeometry': // backwards compatible
  7481. geometry = new THREE.BoxGeometry(
  7482. data.width,
  7483. data.height,
  7484. data.depth,
  7485. data.widthSegments,
  7486. data.heightSegments,
  7487. data.depthSegments
  7488. );
  7489. break;
  7490. case 'CircleGeometry':
  7491. geometry = new THREE.CircleGeometry(
  7492. data.radius,
  7493. data.segments
  7494. );
  7495. break;
  7496. case 'CylinderGeometry':
  7497. geometry = new THREE.CylinderGeometry(
  7498. data.radiusTop,
  7499. data.radiusBottom,
  7500. data.height,
  7501. data.radialSegments,
  7502. data.heightSegments,
  7503. data.openEnded
  7504. );
  7505. break;
  7506. case 'SphereGeometry':
  7507. geometry = new THREE.SphereGeometry(
  7508. data.radius,
  7509. data.widthSegments,
  7510. data.heightSegments,
  7511. data.phiStart,
  7512. data.phiLength,
  7513. data.thetaStart,
  7514. data.thetaLength
  7515. );
  7516. break;
  7517. case 'IcosahedronGeometry':
  7518. geometry = new THREE.IcosahedronGeometry(
  7519. data.radius,
  7520. data.detail
  7521. );
  7522. break;
  7523. case 'TorusGeometry':
  7524. geometry = new THREE.TorusGeometry(
  7525. data.radius,
  7526. data.tube,
  7527. data.radialSegments,
  7528. data.tubularSegments,
  7529. data.arc
  7530. );
  7531. break;
  7532. case 'TorusKnotGeometry':
  7533. geometry = new THREE.TorusKnotGeometry(
  7534. data.radius,
  7535. data.tube,
  7536. data.radialSegments,
  7537. data.tubularSegments,
  7538. data.p,
  7539. data.q,
  7540. data.heightScale
  7541. );
  7542. break;
  7543. case 'BufferGeometry':
  7544. geometry = bufferGeometryLoader.parse( data.data );
  7545. break;
  7546. case 'Geometry':
  7547. geometry = geometryLoader.parse( data.data ).geometry;
  7548. break;
  7549. }
  7550. geometry.uuid = data.uuid;
  7551. if ( data.name !== undefined ) geometry.name = data.name;
  7552. geometries[ data.uuid ] = geometry;
  7553. }
  7554. }
  7555. return geometries;
  7556. },
  7557. parseMaterials: function ( json ) {
  7558. var materials = {};
  7559. if ( json !== undefined ) {
  7560. var loader = new THREE.MaterialLoader();
  7561. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7562. var data = json[ i ];
  7563. var material = loader.parse( data );
  7564. material.uuid = data.uuid;
  7565. if ( data.name !== undefined ) material.name = data.name;
  7566. materials[ data.uuid ] = material;
  7567. }
  7568. }
  7569. return materials;
  7570. },
  7571. parseObject: function () {
  7572. var matrix = new THREE.Matrix4();
  7573. return function ( data, geometries, materials ) {
  7574. var object;
  7575. switch ( data.type ) {
  7576. case 'Scene':
  7577. object = new THREE.Scene();
  7578. break;
  7579. case 'PerspectiveCamera':
  7580. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  7581. break;
  7582. case 'OrthographicCamera':
  7583. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  7584. break;
  7585. case 'AmbientLight':
  7586. object = new THREE.AmbientLight( data.color );
  7587. break;
  7588. case 'DirectionalLight':
  7589. object = new THREE.DirectionalLight( data.color, data.intensity );
  7590. break;
  7591. case 'PointLight':
  7592. object = new THREE.PointLight( data.color, data.intensity, data.distance );
  7593. break;
  7594. case 'SpotLight':
  7595. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent );
  7596. break;
  7597. case 'HemisphereLight':
  7598. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  7599. break;
  7600. case 'Mesh':
  7601. var geometry = geometries[ data.geometry ];
  7602. var material = materials[ data.material ];
  7603. if ( geometry === undefined ) {
  7604. console.error( 'THREE.ObjectLoader: Undefined geometry ' + data.geometry );
  7605. }
  7606. if ( material === undefined ) {
  7607. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  7608. }
  7609. object = new THREE.Mesh( geometry, material );
  7610. break;
  7611. case 'Sprite':
  7612. var material = materials[ data.material ];
  7613. if ( material === undefined ) {
  7614. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  7615. }
  7616. object = new THREE.Sprite( material );
  7617. break;
  7618. default:
  7619. object = new THREE.Object3D();
  7620. }
  7621. object.uuid = data.uuid;
  7622. if ( data.name !== undefined ) object.name = data.name;
  7623. if ( data.matrix !== undefined ) {
  7624. matrix.fromArray( data.matrix );
  7625. matrix.decompose( object.position, object.quaternion, object.scale );
  7626. } else {
  7627. if ( data.position !== undefined ) object.position.fromArray( data.position );
  7628. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  7629. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  7630. }
  7631. if ( data.visible !== undefined ) object.visible = data.visible;
  7632. if ( data.userData !== undefined ) object.userData = data.userData;
  7633. if ( data.children !== undefined ) {
  7634. for ( var child in data.children ) {
  7635. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  7636. }
  7637. }
  7638. return object;
  7639. }
  7640. }()
  7641. };
  7642. // File:src/loaders/TextureLoader.js
  7643. /**
  7644. * @author mrdoob / http://mrdoob.com/
  7645. */
  7646. THREE.TextureLoader = function ( manager ) {
  7647. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7648. };
  7649. THREE.TextureLoader.prototype = {
  7650. constructor: THREE.TextureLoader,
  7651. load: function ( url, onLoad, onProgress, onError ) {
  7652. var scope = this;
  7653. var loader = new THREE.ImageLoader( scope.manager );
  7654. loader.setCrossOrigin( this.crossOrigin );
  7655. loader.load( url, function ( image ) {
  7656. var texture = new THREE.Texture( image );
  7657. texture.needsUpdate = true;
  7658. if ( onLoad !== undefined ) {
  7659. onLoad( texture );
  7660. }
  7661. }, onProgress, onError );
  7662. },
  7663. setCrossOrigin: function ( value ) {
  7664. this.crossOrigin = value;
  7665. }
  7666. };
  7667. // File:src/materials/Material.js
  7668. /**
  7669. * @author mrdoob / http://mrdoob.com/
  7670. * @author alteredq / http://alteredqualia.com/
  7671. */
  7672. THREE.Material = function () {
  7673. this.id = THREE.MaterialIdCount ++;
  7674. this.uuid = THREE.Math.generateUUID();
  7675. this.name = '';
  7676. this.side = THREE.FrontSide;
  7677. this.opacity = 1;
  7678. this.transparent = false;
  7679. this.blending = THREE.NormalBlending;
  7680. this.blendSrc = THREE.SrcAlphaFactor;
  7681. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  7682. this.blendEquation = THREE.AddEquation;
  7683. this.depthTest = true;
  7684. this.depthWrite = true;
  7685. this.polygonOffset = false;
  7686. this.polygonOffsetFactor = 0;
  7687. this.polygonOffsetUnits = 0;
  7688. this.alphaTest = 0;
  7689. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  7690. this.visible = true;
  7691. this.needsUpdate = true;
  7692. };
  7693. THREE.Material.prototype = {
  7694. constructor: THREE.Material,
  7695. setValues: function ( values ) {
  7696. if ( values === undefined ) return;
  7697. for ( var key in values ) {
  7698. var newValue = values[ key ];
  7699. if ( newValue === undefined ) {
  7700. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  7701. continue;
  7702. }
  7703. if ( key in this ) {
  7704. var currentValue = this[ key ];
  7705. if ( currentValue instanceof THREE.Color ) {
  7706. currentValue.set( newValue );
  7707. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  7708. currentValue.copy( newValue );
  7709. } else if ( key == 'overdraw' ) {
  7710. // ensure overdraw is backwards-compatable with legacy boolean type
  7711. this[ key ] = Number( newValue );
  7712. } else {
  7713. this[ key ] = newValue;
  7714. }
  7715. }
  7716. }
  7717. },
  7718. clone: function ( material ) {
  7719. if ( material === undefined ) material = new THREE.Material();
  7720. material.name = this.name;
  7721. material.side = this.side;
  7722. material.opacity = this.opacity;
  7723. material.transparent = this.transparent;
  7724. material.blending = this.blending;
  7725. material.blendSrc = this.blendSrc;
  7726. material.blendDst = this.blendDst;
  7727. material.blendEquation = this.blendEquation;
  7728. material.depthTest = this.depthTest;
  7729. material.depthWrite = this.depthWrite;
  7730. material.polygonOffset = this.polygonOffset;
  7731. material.polygonOffsetFactor = this.polygonOffsetFactor;
  7732. material.polygonOffsetUnits = this.polygonOffsetUnits;
  7733. material.alphaTest = this.alphaTest;
  7734. material.overdraw = this.overdraw;
  7735. material.visible = this.visible;
  7736. return material;
  7737. },
  7738. dispose: function () {
  7739. this.dispatchEvent( { type: 'dispose' } );
  7740. }
  7741. };
  7742. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  7743. THREE.MaterialIdCount = 0;
  7744. // File:src/materials/LineBasicMaterial.js
  7745. /**
  7746. * @author mrdoob / http://mrdoob.com/
  7747. * @author alteredq / http://alteredqualia.com/
  7748. *
  7749. * parameters = {
  7750. * color: <hex>,
  7751. * opacity: <float>,
  7752. *
  7753. * blending: THREE.NormalBlending,
  7754. * depthTest: <bool>,
  7755. * depthWrite: <bool>,
  7756. *
  7757. * linewidth: <float>,
  7758. * linecap: "round",
  7759. * linejoin: "round",
  7760. *
  7761. * vertexColors: <bool>
  7762. *
  7763. * fog: <bool>
  7764. * }
  7765. */
  7766. THREE.LineBasicMaterial = function ( parameters ) {
  7767. THREE.Material.call( this );
  7768. this.color = new THREE.Color( 0xffffff );
  7769. this.linewidth = 1;
  7770. this.linecap = 'round';
  7771. this.linejoin = 'round';
  7772. this.vertexColors = THREE.NoColors;
  7773. this.fog = true;
  7774. this.setValues( parameters );
  7775. };
  7776. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7777. THREE.LineBasicMaterial.prototype.clone = function () {
  7778. var material = new THREE.LineBasicMaterial();
  7779. THREE.Material.prototype.clone.call( this, material );
  7780. material.color.copy( this.color );
  7781. material.linewidth = this.linewidth;
  7782. material.linecap = this.linecap;
  7783. material.linejoin = this.linejoin;
  7784. material.vertexColors = this.vertexColors;
  7785. material.fog = this.fog;
  7786. return material;
  7787. };
  7788. // File:src/materials/LineDashedMaterial.js
  7789. /**
  7790. * @author alteredq / http://alteredqualia.com/
  7791. *
  7792. * parameters = {
  7793. * color: <hex>,
  7794. * opacity: <float>,
  7795. *
  7796. * blending: THREE.NormalBlending,
  7797. * depthTest: <bool>,
  7798. * depthWrite: <bool>,
  7799. *
  7800. * linewidth: <float>,
  7801. *
  7802. * scale: <float>,
  7803. * dashSize: <float>,
  7804. * gapSize: <float>,
  7805. *
  7806. * vertexColors: <bool>
  7807. *
  7808. * fog: <bool>
  7809. * }
  7810. */
  7811. THREE.LineDashedMaterial = function ( parameters ) {
  7812. THREE.Material.call( this );
  7813. this.color = new THREE.Color( 0xffffff );
  7814. this.linewidth = 1;
  7815. this.scale = 1;
  7816. this.dashSize = 3;
  7817. this.gapSize = 1;
  7818. this.vertexColors = false;
  7819. this.fog = true;
  7820. this.setValues( parameters );
  7821. };
  7822. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  7823. THREE.LineDashedMaterial.prototype.clone = function () {
  7824. var material = new THREE.LineDashedMaterial();
  7825. THREE.Material.prototype.clone.call( this, material );
  7826. material.color.copy( this.color );
  7827. material.linewidth = this.linewidth;
  7828. material.scale = this.scale;
  7829. material.dashSize = this.dashSize;
  7830. material.gapSize = this.gapSize;
  7831. material.vertexColors = this.vertexColors;
  7832. material.fog = this.fog;
  7833. return material;
  7834. };
  7835. // File:src/materials/MeshBasicMaterial.js
  7836. /**
  7837. * @author mrdoob / http://mrdoob.com/
  7838. * @author alteredq / http://alteredqualia.com/
  7839. *
  7840. * parameters = {
  7841. * color: <hex>,
  7842. * opacity: <float>,
  7843. * map: new THREE.Texture( <Image> ),
  7844. *
  7845. * lightMap: new THREE.Texture( <Image> ),
  7846. *
  7847. * specularMap: new THREE.Texture( <Image> ),
  7848. *
  7849. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7850. * combine: THREE.Multiply,
  7851. * reflectivity: <float>,
  7852. * refractionRatio: <float>,
  7853. *
  7854. * shading: THREE.SmoothShading,
  7855. * blending: THREE.NormalBlending,
  7856. * depthTest: <bool>,
  7857. * depthWrite: <bool>,
  7858. *
  7859. * wireframe: <boolean>,
  7860. * wireframeLinewidth: <float>,
  7861. *
  7862. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7863. *
  7864. * skinning: <bool>,
  7865. * morphTargets: <bool>,
  7866. *
  7867. * fog: <bool>
  7868. * }
  7869. */
  7870. THREE.MeshBasicMaterial = function ( parameters ) {
  7871. THREE.Material.call( this );
  7872. this.color = new THREE.Color( 0xffffff ); // emissive
  7873. this.map = null;
  7874. this.lightMap = null;
  7875. this.specularMap = null;
  7876. this.envMap = null;
  7877. this.combine = THREE.MultiplyOperation;
  7878. this.reflectivity = 1;
  7879. this.refractionRatio = 0.98;
  7880. this.fog = true;
  7881. this.shading = THREE.SmoothShading;
  7882. this.wireframe = false;
  7883. this.wireframeLinewidth = 1;
  7884. this.wireframeLinecap = 'round';
  7885. this.wireframeLinejoin = 'round';
  7886. this.vertexColors = THREE.NoColors;
  7887. this.skinning = false;
  7888. this.morphTargets = false;
  7889. this.setValues( parameters );
  7890. };
  7891. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7892. THREE.MeshBasicMaterial.prototype.clone = function () {
  7893. var material = new THREE.MeshBasicMaterial();
  7894. THREE.Material.prototype.clone.call( this, material );
  7895. material.color.copy( this.color );
  7896. material.map = this.map;
  7897. material.lightMap = this.lightMap;
  7898. material.specularMap = this.specularMap;
  7899. material.envMap = this.envMap;
  7900. material.combine = this.combine;
  7901. material.reflectivity = this.reflectivity;
  7902. material.refractionRatio = this.refractionRatio;
  7903. material.fog = this.fog;
  7904. material.shading = this.shading;
  7905. material.wireframe = this.wireframe;
  7906. material.wireframeLinewidth = this.wireframeLinewidth;
  7907. material.wireframeLinecap = this.wireframeLinecap;
  7908. material.wireframeLinejoin = this.wireframeLinejoin;
  7909. material.vertexColors = this.vertexColors;
  7910. material.skinning = this.skinning;
  7911. material.morphTargets = this.morphTargets;
  7912. return material;
  7913. };
  7914. // File:src/materials/MeshLambertMaterial.js
  7915. /**
  7916. * @author mrdoob / http://mrdoob.com/
  7917. * @author alteredq / http://alteredqualia.com/
  7918. *
  7919. * parameters = {
  7920. * color: <hex>,
  7921. * ambient: <hex>,
  7922. * emissive: <hex>,
  7923. * opacity: <float>,
  7924. *
  7925. * map: new THREE.Texture( <Image> ),
  7926. *
  7927. * lightMap: new THREE.Texture( <Image> ),
  7928. *
  7929. * specularMap: new THREE.Texture( <Image> ),
  7930. *
  7931. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7932. * combine: THREE.Multiply,
  7933. * reflectivity: <float>,
  7934. * refractionRatio: <float>,
  7935. *
  7936. * shading: THREE.SmoothShading,
  7937. * blending: THREE.NormalBlending,
  7938. * depthTest: <bool>,
  7939. * depthWrite: <bool>,
  7940. *
  7941. * wireframe: <boolean>,
  7942. * wireframeLinewidth: <float>,
  7943. *
  7944. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7945. *
  7946. * skinning: <bool>,
  7947. * morphTargets: <bool>,
  7948. * morphNormals: <bool>,
  7949. *
  7950. * fog: <bool>
  7951. * }
  7952. */
  7953. THREE.MeshLambertMaterial = function ( parameters ) {
  7954. THREE.Material.call( this );
  7955. this.color = new THREE.Color( 0xffffff ); // diffuse
  7956. this.ambient = new THREE.Color( 0xffffff );
  7957. this.emissive = new THREE.Color( 0x000000 );
  7958. this.wrapAround = false;
  7959. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7960. this.map = null;
  7961. this.lightMap = null;
  7962. this.specularMap = null;
  7963. this.envMap = null;
  7964. this.combine = THREE.MultiplyOperation;
  7965. this.reflectivity = 1;
  7966. this.refractionRatio = 0.98;
  7967. this.fog = true;
  7968. this.shading = THREE.SmoothShading;
  7969. this.wireframe = false;
  7970. this.wireframeLinewidth = 1;
  7971. this.wireframeLinecap = 'round';
  7972. this.wireframeLinejoin = 'round';
  7973. this.vertexColors = THREE.NoColors;
  7974. this.skinning = false;
  7975. this.morphTargets = false;
  7976. this.morphNormals = false;
  7977. this.setValues( parameters );
  7978. };
  7979. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  7980. THREE.MeshLambertMaterial.prototype.clone = function () {
  7981. var material = new THREE.MeshLambertMaterial();
  7982. THREE.Material.prototype.clone.call( this, material );
  7983. material.color.copy( this.color );
  7984. material.ambient.copy( this.ambient );
  7985. material.emissive.copy( this.emissive );
  7986. material.wrapAround = this.wrapAround;
  7987. material.wrapRGB.copy( this.wrapRGB );
  7988. material.map = this.map;
  7989. material.lightMap = this.lightMap;
  7990. material.specularMap = this.specularMap;
  7991. material.envMap = this.envMap;
  7992. material.combine = this.combine;
  7993. material.reflectivity = this.reflectivity;
  7994. material.refractionRatio = this.refractionRatio;
  7995. material.fog = this.fog;
  7996. material.shading = this.shading;
  7997. material.wireframe = this.wireframe;
  7998. material.wireframeLinewidth = this.wireframeLinewidth;
  7999. material.wireframeLinecap = this.wireframeLinecap;
  8000. material.wireframeLinejoin = this.wireframeLinejoin;
  8001. material.vertexColors = this.vertexColors;
  8002. material.skinning = this.skinning;
  8003. material.morphTargets = this.morphTargets;
  8004. material.morphNormals = this.morphNormals;
  8005. return material;
  8006. };
  8007. // File:src/materials/MeshPhongMaterial.js
  8008. /**
  8009. * @author mrdoob / http://mrdoob.com/
  8010. * @author alteredq / http://alteredqualia.com/
  8011. *
  8012. * parameters = {
  8013. * color: <hex>,
  8014. * ambient: <hex>,
  8015. * emissive: <hex>,
  8016. * specular: <hex>,
  8017. * shininess: <float>,
  8018. * opacity: <float>,
  8019. *
  8020. * map: new THREE.Texture( <Image> ),
  8021. *
  8022. * lightMap: new THREE.Texture( <Image> ),
  8023. *
  8024. * bumpMap: new THREE.Texture( <Image> ),
  8025. * bumpScale: <float>,
  8026. *
  8027. * normalMap: new THREE.Texture( <Image> ),
  8028. * normalScale: <Vector2>,
  8029. *
  8030. * specularMap: new THREE.Texture( <Image> ),
  8031. *
  8032. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8033. * combine: THREE.Multiply,
  8034. * reflectivity: <float>,
  8035. * refractionRatio: <float>,
  8036. *
  8037. * shading: THREE.SmoothShading,
  8038. * blending: THREE.NormalBlending,
  8039. * depthTest: <bool>,
  8040. * depthWrite: <bool>,
  8041. *
  8042. * wireframe: <boolean>,
  8043. * wireframeLinewidth: <float>,
  8044. *
  8045. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8046. *
  8047. * skinning: <bool>,
  8048. * morphTargets: <bool>,
  8049. * morphNormals: <bool>,
  8050. *
  8051. * fog: <bool>
  8052. * }
  8053. */
  8054. THREE.MeshPhongMaterial = function ( parameters ) {
  8055. THREE.Material.call( this );
  8056. this.color = new THREE.Color( 0xffffff ); // diffuse
  8057. this.ambient = new THREE.Color( 0xffffff );
  8058. this.emissive = new THREE.Color( 0x000000 );
  8059. this.specular = new THREE.Color( 0x111111 );
  8060. this.shininess = 30;
  8061. this.metal = false;
  8062. this.wrapAround = false;
  8063. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8064. this.map = null;
  8065. this.lightMap = null;
  8066. this.bumpMap = null;
  8067. this.bumpScale = 1;
  8068. this.normalMap = null;
  8069. this.normalScale = new THREE.Vector2( 1, 1 );
  8070. this.specularMap = null;
  8071. this.envMap = null;
  8072. this.combine = THREE.MultiplyOperation;
  8073. this.reflectivity = 1;
  8074. this.refractionRatio = 0.98;
  8075. this.fog = true;
  8076. this.shading = THREE.SmoothShading;
  8077. this.wireframe = false;
  8078. this.wireframeLinewidth = 1;
  8079. this.wireframeLinecap = 'round';
  8080. this.wireframeLinejoin = 'round';
  8081. this.vertexColors = THREE.NoColors;
  8082. this.skinning = false;
  8083. this.morphTargets = false;
  8084. this.morphNormals = false;
  8085. this.setValues( parameters );
  8086. };
  8087. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  8088. THREE.MeshPhongMaterial.prototype.clone = function () {
  8089. var material = new THREE.MeshPhongMaterial();
  8090. THREE.Material.prototype.clone.call( this, material );
  8091. material.color.copy( this.color );
  8092. material.ambient.copy( this.ambient );
  8093. material.emissive.copy( this.emissive );
  8094. material.specular.copy( this.specular );
  8095. material.shininess = this.shininess;
  8096. material.metal = this.metal;
  8097. material.wrapAround = this.wrapAround;
  8098. material.wrapRGB.copy( this.wrapRGB );
  8099. material.map = this.map;
  8100. material.lightMap = this.lightMap;
  8101. material.bumpMap = this.bumpMap;
  8102. material.bumpScale = this.bumpScale;
  8103. material.normalMap = this.normalMap;
  8104. material.normalScale.copy( this.normalScale );
  8105. material.specularMap = this.specularMap;
  8106. material.envMap = this.envMap;
  8107. material.combine = this.combine;
  8108. material.reflectivity = this.reflectivity;
  8109. material.refractionRatio = this.refractionRatio;
  8110. material.fog = this.fog;
  8111. material.shading = this.shading;
  8112. material.wireframe = this.wireframe;
  8113. material.wireframeLinewidth = this.wireframeLinewidth;
  8114. material.wireframeLinecap = this.wireframeLinecap;
  8115. material.wireframeLinejoin = this.wireframeLinejoin;
  8116. material.vertexColors = this.vertexColors;
  8117. material.skinning = this.skinning;
  8118. material.morphTargets = this.morphTargets;
  8119. material.morphNormals = this.morphNormals;
  8120. return material;
  8121. };
  8122. // File:src/materials/MeshDepthMaterial.js
  8123. /**
  8124. * @author mrdoob / http://mrdoob.com/
  8125. * @author alteredq / http://alteredqualia.com/
  8126. *
  8127. * parameters = {
  8128. * opacity: <float>,
  8129. *
  8130. * blending: THREE.NormalBlending,
  8131. * depthTest: <bool>,
  8132. * depthWrite: <bool>,
  8133. *
  8134. * wireframe: <boolean>,
  8135. * wireframeLinewidth: <float>
  8136. * }
  8137. */
  8138. THREE.MeshDepthMaterial = function ( parameters ) {
  8139. THREE.Material.call( this );
  8140. this.morphTargets = false;
  8141. this.wireframe = false;
  8142. this.wireframeLinewidth = 1;
  8143. this.setValues( parameters );
  8144. };
  8145. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  8146. THREE.MeshDepthMaterial.prototype.clone = function () {
  8147. var material = new THREE.MeshDepthMaterial();
  8148. THREE.Material.prototype.clone.call( this, material );
  8149. material.wireframe = this.wireframe;
  8150. material.wireframeLinewidth = this.wireframeLinewidth;
  8151. return material;
  8152. };
  8153. // File:src/materials/MeshNormalMaterial.js
  8154. /**
  8155. * @author mrdoob / http://mrdoob.com/
  8156. *
  8157. * parameters = {
  8158. * opacity: <float>,
  8159. *
  8160. * shading: THREE.FlatShading,
  8161. * blending: THREE.NormalBlending,
  8162. * depthTest: <bool>,
  8163. * depthWrite: <bool>,
  8164. *
  8165. * wireframe: <boolean>,
  8166. * wireframeLinewidth: <float>
  8167. * }
  8168. */
  8169. THREE.MeshNormalMaterial = function ( parameters ) {
  8170. THREE.Material.call( this, parameters );
  8171. this.shading = THREE.FlatShading;
  8172. this.wireframe = false;
  8173. this.wireframeLinewidth = 1;
  8174. this.morphTargets = false;
  8175. this.setValues( parameters );
  8176. };
  8177. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  8178. THREE.MeshNormalMaterial.prototype.clone = function () {
  8179. var material = new THREE.MeshNormalMaterial();
  8180. THREE.Material.prototype.clone.call( this, material );
  8181. material.shading = this.shading;
  8182. material.wireframe = this.wireframe;
  8183. material.wireframeLinewidth = this.wireframeLinewidth;
  8184. return material;
  8185. };
  8186. // File:src/materials/MeshFaceMaterial.js
  8187. /**
  8188. * @author mrdoob / http://mrdoob.com/
  8189. */
  8190. THREE.MeshFaceMaterial = function ( materials ) {
  8191. this.materials = materials instanceof Array ? materials : [];
  8192. };
  8193. THREE.MeshFaceMaterial.prototype.clone = function () {
  8194. var material = new THREE.MeshFaceMaterial();
  8195. for ( var i = 0; i < this.materials.length; i ++ ) {
  8196. material.materials.push( this.materials[ i ].clone() );
  8197. }
  8198. return material;
  8199. };
  8200. // File:src/materials/PointCloudMaterial.js
  8201. /**
  8202. * @author mrdoob / http://mrdoob.com/
  8203. * @author alteredq / http://alteredqualia.com/
  8204. *
  8205. * parameters = {
  8206. * color: <hex>,
  8207. * opacity: <float>,
  8208. * map: new THREE.Texture( <Image> ),
  8209. *
  8210. * size: <float>,
  8211. *
  8212. * blending: THREE.NormalBlending,
  8213. * depthTest: <bool>,
  8214. * depthWrite: <bool>,
  8215. *
  8216. * vertexColors: <bool>,
  8217. *
  8218. * fog: <bool>
  8219. * }
  8220. */
  8221. THREE.PointCloudMaterial = function ( parameters ) {
  8222. THREE.Material.call( this );
  8223. this.color = new THREE.Color( 0xffffff );
  8224. this.map = null;
  8225. this.size = 1;
  8226. this.sizeAttenuation = true;
  8227. this.vertexColors = THREE.NoColors;
  8228. this.fog = true;
  8229. this.setValues( parameters );
  8230. };
  8231. THREE.PointCloudMaterial.prototype = Object.create( THREE.Material.prototype );
  8232. THREE.PointCloudMaterial.prototype.clone = function () {
  8233. var material = new THREE.PointCloudMaterial();
  8234. THREE.Material.prototype.clone.call( this, material );
  8235. material.color.copy( this.color );
  8236. material.map = this.map;
  8237. material.size = this.size;
  8238. material.sizeAttenuation = this.sizeAttenuation;
  8239. material.vertexColors = this.vertexColors;
  8240. material.fog = this.fog;
  8241. return material;
  8242. };
  8243. // backwards compatibility
  8244. THREE.ParticleSystemMaterial = function ( parameters ) {
  8245. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointCloudMaterial.' );
  8246. return new THREE.PointCloudMaterial( parameters );
  8247. }
  8248. // File:src/materials/ShaderMaterial.js
  8249. /**
  8250. * @author alteredq / http://alteredqualia.com/
  8251. *
  8252. * parameters = {
  8253. * fragmentShader: <string>,
  8254. * vertexShader: <string>,
  8255. *
  8256. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  8257. *
  8258. * defines: { "label" : "value" },
  8259. *
  8260. * shading: THREE.SmoothShading,
  8261. * blending: THREE.NormalBlending,
  8262. * depthTest: <bool>,
  8263. * depthWrite: <bool>,
  8264. *
  8265. * wireframe: <boolean>,
  8266. * wireframeLinewidth: <float>,
  8267. *
  8268. * lights: <bool>,
  8269. *
  8270. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8271. *
  8272. * skinning: <bool>,
  8273. * morphTargets: <bool>,
  8274. * morphNormals: <bool>,
  8275. *
  8276. * fog: <bool>
  8277. * }
  8278. */
  8279. THREE.ShaderMaterial = function ( parameters ) {
  8280. THREE.Material.call( this );
  8281. this.fragmentShader = 'void main() {}';
  8282. this.vertexShader = 'void main() {}';
  8283. this.uniforms = {};
  8284. this.defines = {};
  8285. this.attributes = null;
  8286. this.shading = THREE.SmoothShading;
  8287. this.linewidth = 1;
  8288. this.wireframe = false;
  8289. this.wireframeLinewidth = 1;
  8290. this.fog = false; // set to use scene fog
  8291. this.lights = false; // set to use scene lights
  8292. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  8293. this.skinning = false; // set to use skinning attribute streams
  8294. this.morphTargets = false; // set to use morph targets
  8295. this.morphNormals = false; // set to use morph normals
  8296. // When rendered geometry doesn't include these attributes but the material does,
  8297. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8298. this.defaultAttributeValues = {
  8299. 'color': [ 1, 1, 1 ],
  8300. 'uv': [ 0, 0 ],
  8301. 'uv2': [ 0, 0 ]
  8302. };
  8303. this.index0AttributeName = undefined;
  8304. this.setValues( parameters );
  8305. };
  8306. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  8307. THREE.ShaderMaterial.prototype.clone = function () {
  8308. var material = new THREE.ShaderMaterial();
  8309. THREE.Material.prototype.clone.call( this, material );
  8310. material.fragmentShader = this.fragmentShader;
  8311. material.vertexShader = this.vertexShader;
  8312. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  8313. material.attributes = this.attributes;
  8314. material.defines = this.defines;
  8315. material.shading = this.shading;
  8316. material.wireframe = this.wireframe;
  8317. material.wireframeLinewidth = this.wireframeLinewidth;
  8318. material.fog = this.fog;
  8319. material.lights = this.lights;
  8320. material.vertexColors = this.vertexColors;
  8321. material.skinning = this.skinning;
  8322. material.morphTargets = this.morphTargets;
  8323. material.morphNormals = this.morphNormals;
  8324. return material;
  8325. };
  8326. // File:src/materials/RawShaderMaterial.js
  8327. /**
  8328. * @author mrdoob / http://mrdoob.com/
  8329. */
  8330. THREE.RawShaderMaterial = function ( parameters ) {
  8331. THREE.ShaderMaterial.call( this, parameters );
  8332. };
  8333. THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype );
  8334. THREE.RawShaderMaterial.prototype.clone = function () {
  8335. var material = new THREE.RawShaderMaterial();
  8336. THREE.ShaderMaterial.prototype.clone.call( this, material );
  8337. return material;
  8338. };
  8339. // File:src/materials/SpriteMaterial.js
  8340. /**
  8341. * @author alteredq / http://alteredqualia.com/
  8342. *
  8343. * parameters = {
  8344. * color: <hex>,
  8345. * opacity: <float>,
  8346. * map: new THREE.Texture( <Image> ),
  8347. *
  8348. * blending: THREE.NormalBlending,
  8349. * depthTest: <bool>,
  8350. * depthWrite: <bool>,
  8351. *
  8352. * uvOffset: new THREE.Vector2(),
  8353. * uvScale: new THREE.Vector2(),
  8354. *
  8355. * fog: <bool>
  8356. * }
  8357. */
  8358. THREE.SpriteMaterial = function ( parameters ) {
  8359. THREE.Material.call( this );
  8360. // defaults
  8361. this.color = new THREE.Color( 0xffffff );
  8362. this.map = null;
  8363. this.rotation = 0;
  8364. this.fog = false;
  8365. // set parameters
  8366. this.setValues( parameters );
  8367. };
  8368. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  8369. THREE.SpriteMaterial.prototype.clone = function () {
  8370. var material = new THREE.SpriteMaterial();
  8371. THREE.Material.prototype.clone.call( this, material );
  8372. material.color.copy( this.color );
  8373. material.map = this.map;
  8374. material.rotation = this.rotation;
  8375. material.fog = this.fog;
  8376. return material;
  8377. };
  8378. // File:src/materials/SpriteCanvasMaterial.js
  8379. /**
  8380. * @author mrdoob / http://mrdoob.com/
  8381. *
  8382. * parameters = {
  8383. * color: <hex>,
  8384. * program: <function>,
  8385. * opacity: <float>,
  8386. * blending: THREE.NormalBlending
  8387. * }
  8388. */
  8389. THREE.SpriteCanvasMaterial = function ( parameters ) {
  8390. THREE.Material.call( this );
  8391. this.color = new THREE.Color( 0xffffff );
  8392. this.program = function ( context, color ) {};
  8393. this.setValues( parameters );
  8394. };
  8395. THREE.SpriteCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  8396. THREE.SpriteCanvasMaterial.prototype.clone = function () {
  8397. var material = new THREE.SpriteCanvasMaterial();
  8398. THREE.Material.prototype.clone.call( this, material );
  8399. material.color.copy( this.color );
  8400. material.program = this.program;
  8401. return material;
  8402. };
  8403. // backwards compatibility
  8404. THREE.ParticleCanvasMaterial = THREE.SpriteCanvasMaterial;
  8405. // File:src/textures/Texture.js
  8406. /**
  8407. * @author mrdoob / http://mrdoob.com/
  8408. * @author alteredq / http://alteredqualia.com/
  8409. * @author szimek / https://github.com/szimek/
  8410. */
  8411. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8412. this.id = THREE.TextureIdCount ++;
  8413. this.uuid = THREE.Math.generateUUID();
  8414. this.name = '';
  8415. this.image = image !== undefined ? image : THREE.Texture.DEFAULT_IMAGE;
  8416. this.mipmaps = [];
  8417. this.mapping = mapping !== undefined ? mapping : THREE.Texture.DEFAULT_MAPPING;
  8418. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  8419. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  8420. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  8421. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  8422. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  8423. this.format = format !== undefined ? format : THREE.RGBAFormat;
  8424. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  8425. this.offset = new THREE.Vector2( 0, 0 );
  8426. this.repeat = new THREE.Vector2( 1, 1 );
  8427. this.generateMipmaps = true;
  8428. this.premultiplyAlpha = false;
  8429. this.flipY = true;
  8430. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  8431. this._needsUpdate = false;
  8432. this.onUpdate = null;
  8433. };
  8434. THREE.Texture.DEFAULT_IMAGE = undefined;
  8435. THREE.Texture.DEFAULT_MAPPING = new THREE.UVMapping();
  8436. THREE.Texture.prototype = {
  8437. constructor: THREE.Texture,
  8438. get needsUpdate () {
  8439. return this._needsUpdate;
  8440. },
  8441. set needsUpdate ( value ) {
  8442. if ( value === true ) this.update();
  8443. this._needsUpdate = value;
  8444. },
  8445. clone: function ( texture ) {
  8446. if ( texture === undefined ) texture = new THREE.Texture();
  8447. texture.image = this.image;
  8448. texture.mipmaps = this.mipmaps.slice( 0 );
  8449. texture.mapping = this.mapping;
  8450. texture.wrapS = this.wrapS;
  8451. texture.wrapT = this.wrapT;
  8452. texture.magFilter = this.magFilter;
  8453. texture.minFilter = this.minFilter;
  8454. texture.anisotropy = this.anisotropy;
  8455. texture.format = this.format;
  8456. texture.type = this.type;
  8457. texture.offset.copy( this.offset );
  8458. texture.repeat.copy( this.repeat );
  8459. texture.generateMipmaps = this.generateMipmaps;
  8460. texture.premultiplyAlpha = this.premultiplyAlpha;
  8461. texture.flipY = this.flipY;
  8462. texture.unpackAlignment = this.unpackAlignment;
  8463. return texture;
  8464. },
  8465. update: function () {
  8466. this.dispatchEvent( { type: 'update' } );
  8467. },
  8468. dispose: function () {
  8469. this.dispatchEvent( { type: 'dispose' } );
  8470. }
  8471. };
  8472. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  8473. THREE.TextureIdCount = 0;
  8474. // File:src/textures/CubeTexture.js
  8475. /**
  8476. * @author mrdoob / http://mrdoob.com/
  8477. */
  8478. THREE.CubeTexture = function ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8479. THREE.Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8480. this.images = images;
  8481. };
  8482. THREE.CubeTexture.prototype = Object.create( THREE.Texture.prototype );
  8483. THREE.CubeTexture.clone = function ( texture ) {
  8484. if ( texture === undefined ) texture = new THREE.CubeTexture();
  8485. THREE.Texture.prototype.clone.call( this, texture );
  8486. texture.images = this.images;
  8487. return texture;
  8488. };
  8489. // File:src/textures/CompressedTexture.js
  8490. /**
  8491. * @author alteredq / http://alteredqualia.com/
  8492. */
  8493. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8494. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8495. this.image = { width: width, height: height };
  8496. this.mipmaps = mipmaps;
  8497. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  8498. };
  8499. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  8500. THREE.CompressedTexture.prototype.clone = function () {
  8501. var texture = new THREE.CompressedTexture();
  8502. THREE.Texture.prototype.clone.call( this, texture );
  8503. return texture;
  8504. };
  8505. // File:src/textures/DataTexture.js
  8506. /**
  8507. * @author alteredq / http://alteredqualia.com/
  8508. */
  8509. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8510. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8511. this.image = { data: data, width: width, height: height };
  8512. };
  8513. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  8514. THREE.DataTexture.prototype.clone = function () {
  8515. var texture = new THREE.DataTexture();
  8516. THREE.Texture.prototype.clone.call( this, texture );
  8517. return texture;
  8518. };
  8519. // File:src/objects/PointCloud.js
  8520. /**
  8521. * @author alteredq / http://alteredqualia.com/
  8522. */
  8523. THREE.PointCloud = function ( geometry, material ) {
  8524. THREE.Object3D.call( this );
  8525. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8526. this.material = material !== undefined ? material : new THREE.PointCloudMaterial( { color: Math.random() * 0xffffff } );
  8527. this.sortParticles = false;
  8528. };
  8529. THREE.PointCloud.prototype = Object.create( THREE.Object3D.prototype );
  8530. THREE.PointCloud.prototype.raycast = ( function () {
  8531. var inverseMatrix = new THREE.Matrix4();
  8532. var ray = new THREE.Ray();
  8533. return function ( raycaster, intersects ) {
  8534. var object = this;
  8535. var geometry = object.geometry;
  8536. var threshold = raycaster.params.PointCloud.threshold;
  8537. inverseMatrix.getInverse( this.matrixWorld );
  8538. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  8539. if ( geometry.boundingBox !== null ) {
  8540. if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) {
  8541. return;
  8542. }
  8543. }
  8544. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  8545. var position = new THREE.Vector3();
  8546. var testPoint = function ( point, index ) {
  8547. var rayPointDistance = ray.distanceToPoint( point );
  8548. if ( rayPointDistance < localThreshold ) {
  8549. var intersectPoint = ray.closestPointToPoint( point );
  8550. intersectPoint.applyMatrix4( object.matrixWorld );
  8551. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  8552. intersects.push( {
  8553. distance: distance,
  8554. distanceToRay: rayPointDistance,
  8555. point: intersectPoint.clone(),
  8556. index: index,
  8557. face: null,
  8558. object: object
  8559. } );
  8560. }
  8561. };
  8562. if ( geometry instanceof THREE.BufferGeometry ) {
  8563. var attributes = geometry.attributes;
  8564. var positions = attributes.position.array;
  8565. if ( attributes.index !== undefined ) {
  8566. var indices = attributes.index.array;
  8567. var offsets = geometry.offsets;
  8568. if ( offsets.length === 0 ) {
  8569. var offset = {
  8570. start: 0,
  8571. count: indices.length,
  8572. index: 0
  8573. };
  8574. offsets = [ offset ];
  8575. }
  8576. for ( var oi = 0, ol = offsets.length; oi < ol; ++oi ) {
  8577. var start = offsets[ oi ].start;
  8578. var count = offsets[ oi ].count;
  8579. var index = offsets[ oi ].index;
  8580. for ( var i = start, il = start + count; i < il; i ++ ) {
  8581. var a = index + indices[ i ];
  8582. position.set(
  8583. positions[ a * 3 ],
  8584. positions[ a * 3 + 1 ],
  8585. positions[ a * 3 + 2 ]
  8586. );
  8587. testPoint( position, a );
  8588. }
  8589. }
  8590. } else {
  8591. var pointCount = positions.length / 3;
  8592. for ( var i = 0; i < pointCount; i ++ ) {
  8593. position.set(
  8594. positions[ 3 * i ],
  8595. positions[ 3 * i + 1 ],
  8596. positions[ 3 * i + 2 ]
  8597. );
  8598. testPoint( position, i );
  8599. }
  8600. }
  8601. } else {
  8602. var vertices = this.geometry.vertices;
  8603. for ( var i = 0; i < vertices.length; i ++ ) {
  8604. testPoint( vertices[ i ], i );
  8605. }
  8606. }
  8607. };
  8608. }() );
  8609. THREE.PointCloud.prototype.clone = function ( object ) {
  8610. if ( object === undefined ) object = new THREE.PointCloud( this.geometry, this.material );
  8611. object.sortParticles = this.sortParticles;
  8612. THREE.Object3D.prototype.clone.call( this, object );
  8613. return object;
  8614. };
  8615. // Backwards compatibility
  8616. THREE.ParticleSystem = function ( geometry, material ) {
  8617. console.warn( 'THREE.ParticleSystem has been renamed to THREE.PointCloud.' );
  8618. return new THREE.PointCloud( geometry, material );
  8619. };
  8620. // File:src/objects/Line.js
  8621. /**
  8622. * @author mrdoob / http://mrdoob.com/
  8623. */
  8624. THREE.Line = function ( geometry, material, type ) {
  8625. THREE.Object3D.call( this );
  8626. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8627. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  8628. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  8629. };
  8630. THREE.LineStrip = 0;
  8631. THREE.LinePieces = 1;
  8632. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  8633. THREE.Line.prototype.raycast = ( function () {
  8634. var inverseMatrix = new THREE.Matrix4();
  8635. var ray = new THREE.Ray();
  8636. var sphere = new THREE.Sphere();
  8637. return function ( raycaster, intersects ) {
  8638. var precision = raycaster.linePrecision;
  8639. var precisionSq = precision * precision;
  8640. var geometry = this.geometry;
  8641. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8642. // Checking boundingSphere distance to ray
  8643. sphere.copy( geometry.boundingSphere );
  8644. sphere.applyMatrix4( this.matrixWorld );
  8645. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  8646. return;
  8647. }
  8648. inverseMatrix.getInverse( this.matrixWorld );
  8649. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  8650. /* if ( geometry instanceof THREE.BufferGeometry ) {
  8651. } else */ if ( geometry instanceof THREE.Geometry ) {
  8652. var vertices = geometry.vertices;
  8653. var nbVertices = vertices.length;
  8654. var interSegment = new THREE.Vector3();
  8655. var interRay = new THREE.Vector3();
  8656. var step = this.type === THREE.LineStrip ? 1 : 2;
  8657. for ( var i = 0; i < nbVertices - 1; i = i + step ) {
  8658. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  8659. if ( distSq > precisionSq ) continue;
  8660. var distance = ray.origin.distanceTo( interRay );
  8661. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  8662. intersects.push( {
  8663. distance: distance,
  8664. // What do we want? intersection point on the ray or on the segment??
  8665. // point: raycaster.ray.at( distance ),
  8666. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  8667. face: null,
  8668. faceIndex: null,
  8669. object: this
  8670. } );
  8671. }
  8672. }
  8673. };
  8674. }() );
  8675. THREE.Line.prototype.clone = function ( object ) {
  8676. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  8677. THREE.Object3D.prototype.clone.call( this, object );
  8678. return object;
  8679. };
  8680. // File:src/objects/Mesh.js
  8681. /**
  8682. * @author mrdoob / http://mrdoob.com/
  8683. * @author alteredq / http://alteredqualia.com/
  8684. * @author mikael emtinger / http://gomo.se/
  8685. * @author jonobr1 / http://jonobr1.com/
  8686. */
  8687. THREE.Mesh = function ( geometry, material ) {
  8688. THREE.Object3D.call( this );
  8689. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8690. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  8691. this.updateMorphTargets();
  8692. };
  8693. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  8694. THREE.Mesh.prototype.updateMorphTargets = function () {
  8695. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  8696. this.morphTargetBase = - 1;
  8697. this.morphTargetForcedOrder = [];
  8698. this.morphTargetInfluences = [];
  8699. this.morphTargetDictionary = {};
  8700. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  8701. this.morphTargetInfluences.push( 0 );
  8702. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  8703. }
  8704. }
  8705. };
  8706. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  8707. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  8708. return this.morphTargetDictionary[ name ];
  8709. }
  8710. console.log( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' );
  8711. return 0;
  8712. };
  8713. THREE.Mesh.prototype.raycast = ( function () {
  8714. var inverseMatrix = new THREE.Matrix4();
  8715. var ray = new THREE.Ray();
  8716. var sphere = new THREE.Sphere();
  8717. var vA = new THREE.Vector3();
  8718. var vB = new THREE.Vector3();
  8719. var vC = new THREE.Vector3();
  8720. return function ( raycaster, intersects ) {
  8721. var geometry = this.geometry;
  8722. // Checking boundingSphere distance to ray
  8723. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8724. sphere.copy( geometry.boundingSphere );
  8725. sphere.applyMatrix4( this.matrixWorld );
  8726. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  8727. return;
  8728. }
  8729. // Check boundingBox before continuing
  8730. inverseMatrix.getInverse( this.matrixWorld );
  8731. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  8732. if ( geometry.boundingBox !== null ) {
  8733. if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) {
  8734. return;
  8735. }
  8736. }
  8737. if ( geometry instanceof THREE.BufferGeometry ) {
  8738. var material = this.material;
  8739. if ( material === undefined ) return;
  8740. var attributes = geometry.attributes;
  8741. var a, b, c;
  8742. var precision = raycaster.precision;
  8743. if ( attributes.index !== undefined ) {
  8744. var indices = attributes.index.array;
  8745. var positions = attributes.position.array;
  8746. var offsets = geometry.offsets;
  8747. if ( offsets.length === 0 ) {
  8748. offsets = [ { start: 0, count: indices.length, index: 0 } ];
  8749. }
  8750. for ( var oi = 0, ol = offsets.length; oi < ol; ++oi ) {
  8751. var start = offsets[ oi ].start;
  8752. var count = offsets[ oi ].count;
  8753. var index = offsets[ oi ].index;
  8754. for ( var i = start, il = start + count; i < il; i += 3 ) {
  8755. a = index + indices[ i ];
  8756. b = index + indices[ i + 1 ];
  8757. c = index + indices[ i + 2 ];
  8758. vA.set(
  8759. positions[ a * 3 ],
  8760. positions[ a * 3 + 1 ],
  8761. positions[ a * 3 + 2 ]
  8762. );
  8763. vB.set(
  8764. positions[ b * 3 ],
  8765. positions[ b * 3 + 1 ],
  8766. positions[ b * 3 + 2 ]
  8767. );
  8768. vC.set(
  8769. positions[ c * 3 ],
  8770. positions[ c * 3 + 1 ],
  8771. positions[ c * 3 + 2 ]
  8772. );
  8773. if ( material.side === THREE.BackSide ) {
  8774. var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true );
  8775. } else {
  8776. var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  8777. }
  8778. if ( intersectionPoint === null ) continue;
  8779. intersectionPoint.applyMatrix4( this.matrixWorld );
  8780. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  8781. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  8782. intersects.push( {
  8783. distance: distance,
  8784. point: intersectionPoint,
  8785. indices: [ a, b, c ],
  8786. face: null,
  8787. faceIndex: null,
  8788. object: this
  8789. } );
  8790. }
  8791. }
  8792. } else {
  8793. var positions = attributes.position.array;
  8794. for ( var i = 0, j = 0, il = positions.length; i < il; i += 3, j += 9 ) {
  8795. a = i;
  8796. b = i + 1;
  8797. c = i + 2;
  8798. vA.set(
  8799. positions[ j ],
  8800. positions[ j + 1 ],
  8801. positions[ j + 2 ]
  8802. );
  8803. vB.set(
  8804. positions[ j + 3 ],
  8805. positions[ j + 4 ],
  8806. positions[ j + 5 ]
  8807. );
  8808. vC.set(
  8809. positions[ j + 6 ],
  8810. positions[ j + 7 ],
  8811. positions[ j + 8 ]
  8812. );
  8813. if ( material.side === THREE.BackSide ) {
  8814. var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true );
  8815. } else {
  8816. var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  8817. }
  8818. if ( intersectionPoint === null ) continue;
  8819. intersectionPoint.applyMatrix4( this.matrixWorld );
  8820. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  8821. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  8822. intersects.push( {
  8823. distance: distance,
  8824. point: intersectionPoint,
  8825. indices: [ a, b, c ],
  8826. face: null,
  8827. faceIndex: null,
  8828. object: this
  8829. } );
  8830. }
  8831. }
  8832. } else if ( geometry instanceof THREE.Geometry ) {
  8833. var isFaceMaterial = this.material instanceof THREE.MeshFaceMaterial;
  8834. var objectMaterials = isFaceMaterial === true ? this.material.materials : null;
  8835. var a, b, c, d;
  8836. var precision = raycaster.precision;
  8837. var vertices = geometry.vertices;
  8838. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  8839. var face = geometry.faces[ f ];
  8840. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : this.material;
  8841. if ( material === undefined ) continue;
  8842. a = vertices[ face.a ];
  8843. b = vertices[ face.b ];
  8844. c = vertices[ face.c ];
  8845. if ( material.morphTargets === true ) {
  8846. var morphTargets = geometry.morphTargets;
  8847. var morphInfluences = this.morphTargetInfluences;
  8848. vA.set( 0, 0, 0 );
  8849. vB.set( 0, 0, 0 );
  8850. vC.set( 0, 0, 0 );
  8851. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  8852. var influence = morphInfluences[ t ];
  8853. if ( influence === 0 ) continue;
  8854. var targets = morphTargets[ t ].vertices;
  8855. vA.x += ( targets[ face.a ].x - a.x ) * influence;
  8856. vA.y += ( targets[ face.a ].y - a.y ) * influence;
  8857. vA.z += ( targets[ face.a ].z - a.z ) * influence;
  8858. vB.x += ( targets[ face.b ].x - b.x ) * influence;
  8859. vB.y += ( targets[ face.b ].y - b.y ) * influence;
  8860. vB.z += ( targets[ face.b ].z - b.z ) * influence;
  8861. vC.x += ( targets[ face.c ].x - c.x ) * influence;
  8862. vC.y += ( targets[ face.c ].y - c.y ) * influence;
  8863. vC.z += ( targets[ face.c ].z - c.z ) * influence;
  8864. }
  8865. vA.add( a );
  8866. vB.add( b );
  8867. vC.add( c );
  8868. a = vA;
  8869. b = vB;
  8870. c = vC;
  8871. }
  8872. if ( material.side === THREE.BackSide ) {
  8873. var intersectionPoint = ray.intersectTriangle( c, b, a, true );
  8874. } else {
  8875. var intersectionPoint = ray.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide );
  8876. }
  8877. if ( intersectionPoint === null ) continue;
  8878. intersectionPoint.applyMatrix4( this.matrixWorld );
  8879. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  8880. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  8881. intersects.push( {
  8882. distance: distance,
  8883. point: intersectionPoint,
  8884. face: face,
  8885. faceIndex: f,
  8886. object: this
  8887. } );
  8888. }
  8889. }
  8890. };
  8891. }() );
  8892. THREE.Mesh.prototype.clone = function ( object, recursive ) {
  8893. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  8894. THREE.Object3D.prototype.clone.call( this, object, recursive );
  8895. return object;
  8896. };
  8897. // File:src/objects/Bone.js
  8898. /**
  8899. * @author mikael emtinger / http://gomo.se/
  8900. * @author alteredq / http://alteredqualia.com/
  8901. */
  8902. THREE.Bone = function ( belongsToSkin ) {
  8903. THREE.Object3D.call( this );
  8904. this.skin = belongsToSkin;
  8905. this.skinMatrix = new THREE.Matrix4();
  8906. this.accumulatedRotWeight = 0;
  8907. this.accumulatedPosWeight = 0;
  8908. this.accumulatedSclWeight = 0;
  8909. };
  8910. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  8911. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  8912. // update local
  8913. if ( this.matrixAutoUpdate ) {
  8914. forceUpdate |= this.updateMatrix();
  8915. }
  8916. // update skin matrix
  8917. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  8918. if ( parentSkinMatrix ) {
  8919. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  8920. } else {
  8921. this.skinMatrix.copy( this.matrix );
  8922. }
  8923. this.matrixWorldNeedsUpdate = false;
  8924. forceUpdate = true;
  8925. // Reset weights to be re-accumulated in the next frame
  8926. this.accumulatedRotWeight = 0;
  8927. this.accumulatedPosWeight = 0;
  8928. this.accumulatedSclWeight = 0;
  8929. }
  8930. // update children
  8931. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  8932. this.children[ i ].update( this.skinMatrix, forceUpdate );
  8933. }
  8934. };
  8935. // File:src/objects/Skeleton.js
  8936. /**
  8937. * @author mikael emtinger / http://gomo.se/
  8938. * @author alteredq / http://alteredqualia.com/
  8939. * @author michael guerrero / http://realitymeltdown.com
  8940. */
  8941. THREE.Skeleton = function ( boneList, useVertexTexture ) {
  8942. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  8943. // init bones
  8944. this.bones = [];
  8945. this.boneMatrices = [];
  8946. var bone, gbone, p, q, s;
  8947. if ( boneList !== undefined ) {
  8948. for ( var b = 0; b < boneList.length; ++b ) {
  8949. gbone = boneList[ b ];
  8950. p = gbone.pos;
  8951. q = gbone.rotq;
  8952. s = gbone.scl;
  8953. bone = this.addBone();
  8954. bone.name = gbone.name;
  8955. bone.position.set( p[ 0 ], p[ 1 ], p[ 2 ] );
  8956. bone.quaternion.set( q[ 0 ], q[ 1 ], q[ 2 ], q[ 3 ] );
  8957. if ( s !== undefined ) {
  8958. bone.scale.set( s[ 0 ], s[ 1 ], s[ 2 ] );
  8959. } else {
  8960. bone.scale.set( 1, 1, 1 );
  8961. }
  8962. }
  8963. for ( var b = 0; b < boneList.length; ++b ) {
  8964. gbone = boneList[ b ];
  8965. if ( gbone.parent !== - 1 ) {
  8966. this.bones[ gbone.parent ].add( this.bones[ b ] );
  8967. }
  8968. }
  8969. //
  8970. var nBones = this.bones.length;
  8971. if ( this.useVertexTexture ) {
  8972. // layout (1 matrix = 4 pixels)
  8973. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8974. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  8975. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  8976. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  8977. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  8978. var size;
  8979. if ( nBones > 256 )
  8980. size = 64;
  8981. else if ( nBones > 64 )
  8982. size = 32;
  8983. else if ( nBones > 16 )
  8984. size = 16;
  8985. else
  8986. size = 8;
  8987. this.boneTextureWidth = size;
  8988. this.boneTextureHeight = size;
  8989. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  8990. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  8991. this.boneTexture.minFilter = THREE.NearestFilter;
  8992. this.boneTexture.magFilter = THREE.NearestFilter;
  8993. this.boneTexture.generateMipmaps = false;
  8994. this.boneTexture.flipY = false;
  8995. } else {
  8996. this.boneMatrices = new Float32Array( 16 * nBones );
  8997. }
  8998. }
  8999. };
  9000. THREE.Skeleton.prototype = Object.create( THREE.Mesh.prototype );
  9001. THREE.Skeleton.prototype.addBone = function ( bone ) {
  9002. if ( bone === undefined ) {
  9003. bone = new THREE.Bone( this );
  9004. }
  9005. this.bones.push( bone );
  9006. return bone;
  9007. };
  9008. THREE.Skeleton.prototype.calculateInverses = function ( bone ) {
  9009. this.boneInverses = [];
  9010. for ( var b = 0, bl = this.bones.length; b < bl; ++b ) {
  9011. var inverse = new THREE.Matrix4();
  9012. inverse.getInverse( this.bones[ b ].skinMatrix );
  9013. this.boneInverses.push( inverse );
  9014. }
  9015. };
  9016. // File:src/objects/SkinnedMesh.js
  9017. /**
  9018. * @author mikael emtinger / http://gomo.se/
  9019. * @author alteredq / http://alteredqualia.com/
  9020. */
  9021. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  9022. THREE.Mesh.call( this, geometry, material );
  9023. this.skeleton = new THREE.Skeleton( this.geometry && this.geometry.bones, useVertexTexture );
  9024. // Add root level bones as children of the mesh
  9025. for ( var b = 0; b < this.skeleton.bones.length; ++b ) {
  9026. var bone = this.skeleton.bones[ b ];
  9027. if ( bone.parent === undefined ) {
  9028. this.add( bone );
  9029. }
  9030. }
  9031. this.identityMatrix = new THREE.Matrix4();
  9032. this.pose();
  9033. };
  9034. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  9035. THREE.SkinnedMesh.prototype.updateMatrixWorld = function () {
  9036. var offsetMatrix = new THREE.Matrix4();
  9037. return function ( force ) {
  9038. this.matrixAutoUpdate && this.updateMatrix();
  9039. // update matrixWorld
  9040. if ( this.matrixWorldNeedsUpdate || force ) {
  9041. if ( this.parent ) {
  9042. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9043. } else {
  9044. this.matrixWorld.copy( this.matrix );
  9045. }
  9046. this.matrixWorldNeedsUpdate = false;
  9047. force = true;
  9048. }
  9049. // update children
  9050. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  9051. var child = this.children[ i ];
  9052. if ( child instanceof THREE.Bone ) {
  9053. child.update( this.identityMatrix, false );
  9054. } else {
  9055. child.updateMatrixWorld( true );
  9056. }
  9057. }
  9058. // make a snapshot of the bones' rest position
  9059. if ( this.skeleton.boneInverses === undefined ) {
  9060. this.skeleton.calculateInverses();
  9061. }
  9062. // flatten bone matrices to array
  9063. for ( var b = 0, bl = this.skeleton.bones.length; b < bl; b ++ ) {
  9064. // compute the offset between the current and the original transform;
  9065. // TODO: we could get rid of this multiplication step if the skinMatrix
  9066. // was already representing the offset; however, this requires some
  9067. // major changes to the animation system
  9068. offsetMatrix.multiplyMatrices( this.skeleton.bones[ b ].skinMatrix, this.skeleton.boneInverses[ b ] );
  9069. offsetMatrix.flattenToArrayOffset( this.skeleton.boneMatrices, b * 16 );
  9070. }
  9071. if ( this.skeleton.useVertexTexture ) {
  9072. this.skeleton.boneTexture.needsUpdate = true;
  9073. }
  9074. };
  9075. }();
  9076. THREE.SkinnedMesh.prototype.pose = function () {
  9077. this.updateMatrixWorld( true );
  9078. this.normalizeSkinWeights();
  9079. };
  9080. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  9081. if ( this.geometry instanceof THREE.Geometry ) {
  9082. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  9083. var sw = this.geometry.skinWeights[ i ];
  9084. var scale = 1.0 / sw.lengthManhattan();
  9085. if ( scale !== Infinity ) {
  9086. sw.multiplyScalar( scale );
  9087. } else {
  9088. sw.set( 1 ); // this will be normalized by the shader anyway
  9089. }
  9090. }
  9091. } else {
  9092. // skinning weights assumed to be normalized for THREE.BufferGeometry
  9093. }
  9094. };
  9095. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  9096. if ( object === undefined ) {
  9097. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  9098. }
  9099. THREE.Mesh.prototype.clone.call( this, object );
  9100. return object;
  9101. };
  9102. // File:src/objects/MorphAnimMesh.js
  9103. /**
  9104. * @author alteredq / http://alteredqualia.com/
  9105. */
  9106. THREE.MorphAnimMesh = function ( geometry, material ) {
  9107. THREE.Mesh.call( this, geometry, material );
  9108. // API
  9109. this.duration = 1000; // milliseconds
  9110. this.mirroredLoop = false;
  9111. this.time = 0;
  9112. // internals
  9113. this.lastKeyframe = 0;
  9114. this.currentKeyframe = 0;
  9115. this.direction = 1;
  9116. this.directionBackwards = false;
  9117. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  9118. };
  9119. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  9120. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  9121. this.startKeyframe = start;
  9122. this.endKeyframe = end;
  9123. this.length = this.endKeyframe - this.startKeyframe + 1;
  9124. };
  9125. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  9126. this.direction = 1;
  9127. this.directionBackwards = false;
  9128. };
  9129. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  9130. this.direction = - 1;
  9131. this.directionBackwards = true;
  9132. };
  9133. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  9134. var geometry = this.geometry;
  9135. if ( ! geometry.animations ) geometry.animations = {};
  9136. var firstAnimation, animations = geometry.animations;
  9137. var pattern = /([a-z]+)_?(\d+)/;
  9138. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  9139. var morph = geometry.morphTargets[ i ];
  9140. var parts = morph.name.match( pattern );
  9141. if ( parts && parts.length > 1 ) {
  9142. var label = parts[ 1 ];
  9143. var num = parts[ 2 ];
  9144. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: - Infinity };
  9145. var animation = animations[ label ];
  9146. if ( i < animation.start ) animation.start = i;
  9147. if ( i > animation.end ) animation.end = i;
  9148. if ( ! firstAnimation ) firstAnimation = label;
  9149. }
  9150. }
  9151. geometry.firstAnimation = firstAnimation;
  9152. };
  9153. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  9154. if ( ! this.geometry.animations ) this.geometry.animations = {};
  9155. this.geometry.animations[ label ] = { start: start, end: end };
  9156. };
  9157. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  9158. var animation = this.geometry.animations[ label ];
  9159. if ( animation ) {
  9160. this.setFrameRange( animation.start, animation.end );
  9161. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  9162. this.time = 0;
  9163. } else {
  9164. console.warn( 'animation[' + label + '] undefined' );
  9165. }
  9166. };
  9167. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  9168. var frameTime = this.duration / this.length;
  9169. this.time += this.direction * delta;
  9170. if ( this.mirroredLoop ) {
  9171. if ( this.time > this.duration || this.time < 0 ) {
  9172. this.direction *= - 1;
  9173. if ( this.time > this.duration ) {
  9174. this.time = this.duration;
  9175. this.directionBackwards = true;
  9176. }
  9177. if ( this.time < 0 ) {
  9178. this.time = 0;
  9179. this.directionBackwards = false;
  9180. }
  9181. }
  9182. } else {
  9183. this.time = this.time % this.duration;
  9184. if ( this.time < 0 ) this.time += this.duration;
  9185. }
  9186. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  9187. if ( keyframe !== this.currentKeyframe ) {
  9188. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  9189. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  9190. this.morphTargetInfluences[ keyframe ] = 0;
  9191. this.lastKeyframe = this.currentKeyframe;
  9192. this.currentKeyframe = keyframe;
  9193. }
  9194. var mix = ( this.time % frameTime ) / frameTime;
  9195. if ( this.directionBackwards ) {
  9196. mix = 1 - mix;
  9197. }
  9198. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  9199. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  9200. };
  9201. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  9202. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  9203. object.duration = this.duration;
  9204. object.mirroredLoop = this.mirroredLoop;
  9205. object.time = this.time;
  9206. object.lastKeyframe = this.lastKeyframe;
  9207. object.currentKeyframe = this.currentKeyframe;
  9208. object.direction = this.direction;
  9209. object.directionBackwards = this.directionBackwards;
  9210. THREE.Mesh.prototype.clone.call( this, object );
  9211. return object;
  9212. };
  9213. // File:src/objects/LOD.js
  9214. /**
  9215. * @author mikael emtinger / http://gomo.se/
  9216. * @author alteredq / http://alteredqualia.com/
  9217. * @author mrdoob / http://mrdoob.com/
  9218. */
  9219. THREE.LOD = function () {
  9220. THREE.Object3D.call( this );
  9221. this.objects = [];
  9222. };
  9223. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  9224. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  9225. if ( distance === undefined ) distance = 0;
  9226. distance = Math.abs( distance );
  9227. for ( var l = 0; l < this.objects.length; l ++ ) {
  9228. if ( distance < this.objects[ l ].distance ) {
  9229. break;
  9230. }
  9231. }
  9232. this.objects.splice( l, 0, { distance: distance, object: object } );
  9233. this.add( object );
  9234. };
  9235. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  9236. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9237. if ( distance < this.objects[ i ].distance ) {
  9238. break;
  9239. }
  9240. }
  9241. return this.objects[ i - 1 ].object;
  9242. };
  9243. THREE.LOD.prototype.raycast = ( function () {
  9244. var matrixPosition = new THREE.Vector3();
  9245. return function ( raycaster, intersects ) {
  9246. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  9247. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  9248. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  9249. };
  9250. }() );
  9251. THREE.LOD.prototype.update = function () {
  9252. var v1 = new THREE.Vector3();
  9253. var v2 = new THREE.Vector3();
  9254. return function ( camera ) {
  9255. if ( this.objects.length > 1 ) {
  9256. v1.setFromMatrixPosition( camera.matrixWorld );
  9257. v2.setFromMatrixPosition( this.matrixWorld );
  9258. var distance = v1.distanceTo( v2 );
  9259. this.objects[ 0 ].object.visible = true;
  9260. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9261. if ( distance >= this.objects[ i ].distance ) {
  9262. this.objects[ i - 1 ].object.visible = false;
  9263. this.objects[ i ].object.visible = true;
  9264. } else {
  9265. break;
  9266. }
  9267. }
  9268. for ( ; i < l; i ++ ) {
  9269. this.objects[ i ].object.visible = false;
  9270. }
  9271. }
  9272. };
  9273. }();
  9274. THREE.LOD.prototype.clone = function ( object ) {
  9275. if ( object === undefined ) object = new THREE.LOD();
  9276. THREE.Object3D.prototype.clone.call( this, object );
  9277. for ( var i = 0, l = this.objects.length; i < l; i ++ ) {
  9278. var x = this.objects[ i ].object.clone();
  9279. x.visible = i === 0;
  9280. object.addLevel( x, this.objects[ i ].distance );
  9281. }
  9282. return object;
  9283. };
  9284. // File:src/objects/Sprite.js
  9285. /**
  9286. * @author mikael emtinger / http://gomo.se/
  9287. * @author alteredq / http://alteredqualia.com/
  9288. */
  9289. THREE.Sprite = ( function () {
  9290. var vertices = new Float32Array( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0 ] );
  9291. var geometry = new THREE.BufferGeometry();
  9292. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  9293. return function ( material ) {
  9294. THREE.Object3D.call( this );
  9295. this.geometry = geometry;
  9296. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  9297. };
  9298. } )();
  9299. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  9300. THREE.Sprite.prototype.raycast = ( function () {
  9301. var matrixPosition = new THREE.Vector3();
  9302. return function ( raycaster, intersects ) {
  9303. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  9304. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  9305. if ( distance > this.scale.x ) {
  9306. return;
  9307. }
  9308. intersects.push( {
  9309. distance: distance,
  9310. point: this.position,
  9311. face: null,
  9312. object: this
  9313. } );
  9314. };
  9315. }() );
  9316. THREE.Sprite.prototype.updateMatrix = function () {
  9317. this.matrix.compose( this.position, this.quaternion, this.scale );
  9318. this.matrixWorldNeedsUpdate = true;
  9319. };
  9320. THREE.Sprite.prototype.clone = function ( object ) {
  9321. if ( object === undefined ) object = new THREE.Sprite( this.material );
  9322. THREE.Object3D.prototype.clone.call( this, object );
  9323. return object;
  9324. };
  9325. // Backwards compatibility
  9326. THREE.Particle = THREE.Sprite;
  9327. // File:src/scenes/Scene.js
  9328. /**
  9329. * @author mrdoob / http://mrdoob.com/
  9330. */
  9331. THREE.Scene = function () {
  9332. THREE.Object3D.call( this );
  9333. this.fog = null;
  9334. this.overrideMaterial = null;
  9335. this.autoUpdate = true; // checked by the renderer
  9336. this.matrixAutoUpdate = false;
  9337. this.__lights = [];
  9338. this.__objectsAdded = [];
  9339. this.__objectsRemoved = [];
  9340. };
  9341. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  9342. THREE.Scene.prototype.__addObject = function ( object ) {
  9343. if ( object instanceof THREE.Light ) {
  9344. if ( this.__lights.indexOf( object ) === - 1 ) {
  9345. this.__lights.push( object );
  9346. }
  9347. if ( object.target && object.target.parent === undefined ) {
  9348. this.add( object.target );
  9349. }
  9350. } else if ( ! ( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  9351. this.__objectsAdded.push( object );
  9352. // check if previously removed
  9353. var i = this.__objectsRemoved.indexOf( object );
  9354. if ( i !== - 1 ) {
  9355. this.__objectsRemoved.splice( i, 1 );
  9356. }
  9357. }
  9358. this.dispatchEvent( { type: 'objectAdded', object: object } );
  9359. object.dispatchEvent( { type: 'addedToScene', scene: this } );
  9360. for ( var c = 0; c < object.children.length; c ++ ) {
  9361. this.__addObject( object.children[ c ] );
  9362. }
  9363. };
  9364. THREE.Scene.prototype.__removeObject = function ( object ) {
  9365. if ( object instanceof THREE.Light ) {
  9366. var i = this.__lights.indexOf( object );
  9367. if ( i !== - 1 ) {
  9368. this.__lights.splice( i, 1 );
  9369. }
  9370. if ( object.shadowCascadeArray ) {
  9371. for ( var x = 0; x < object.shadowCascadeArray.length; x ++ ) {
  9372. this.__removeObject( object.shadowCascadeArray[ x ] );
  9373. }
  9374. }
  9375. } else if ( ! ( object instanceof THREE.Camera ) ) {
  9376. this.__objectsRemoved.push( object );
  9377. // check if previously added
  9378. var i = this.__objectsAdded.indexOf( object );
  9379. if ( i !== - 1 ) {
  9380. this.__objectsAdded.splice( i, 1 );
  9381. }
  9382. }
  9383. this.dispatchEvent( { type: 'objectRemoved', object: object } );
  9384. object.dispatchEvent( { type: 'removedFromScene', scene: this } );
  9385. for ( var c = 0; c < object.children.length; c ++ ) {
  9386. this.__removeObject( object.children[ c ] );
  9387. }
  9388. };
  9389. THREE.Scene.prototype.clone = function ( object ) {
  9390. if ( object === undefined ) object = new THREE.Scene();
  9391. THREE.Object3D.prototype.clone.call( this, object );
  9392. if ( this.fog !== null ) object.fog = this.fog.clone();
  9393. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  9394. object.autoUpdate = this.autoUpdate;
  9395. object.matrixAutoUpdate = this.matrixAutoUpdate;
  9396. return object;
  9397. };
  9398. // File:src/scenes/Fog.js
  9399. /**
  9400. * @author mrdoob / http://mrdoob.com/
  9401. * @author alteredq / http://alteredqualia.com/
  9402. */
  9403. THREE.Fog = function ( color, near, far ) {
  9404. this.name = '';
  9405. this.color = new THREE.Color( color );
  9406. this.near = ( near !== undefined ) ? near : 1;
  9407. this.far = ( far !== undefined ) ? far : 1000;
  9408. };
  9409. THREE.Fog.prototype.clone = function () {
  9410. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  9411. };
  9412. // File:src/scenes/FogExp2.js
  9413. /**
  9414. * @author mrdoob / http://mrdoob.com/
  9415. * @author alteredq / http://alteredqualia.com/
  9416. */
  9417. THREE.FogExp2 = function ( color, density ) {
  9418. this.name = '';
  9419. this.color = new THREE.Color( color );
  9420. this.density = ( density !== undefined ) ? density : 0.00025;
  9421. };
  9422. THREE.FogExp2.prototype.clone = function () {
  9423. return new THREE.FogExp2( this.color.getHex(), this.density );
  9424. };
  9425. // File:src/renderers/CanvasRenderer.js
  9426. /**
  9427. * @author mrdoob / http://mrdoob.com/
  9428. */
  9429. THREE.CanvasRenderer = function ( parameters ) {
  9430. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  9431. var smoothstep = THREE.Math.smoothstep;
  9432. parameters = parameters || {};
  9433. var _this = this,
  9434. _renderData, _elements, _lights,
  9435. _projector = new THREE.Projector(),
  9436. _canvas = parameters.canvas !== undefined
  9437. ? parameters.canvas
  9438. : document.createElement( 'canvas' ),
  9439. _canvasWidth = _canvas.width,
  9440. _canvasHeight = _canvas.height,
  9441. _canvasWidthHalf = Math.floor( _canvasWidth / 2 ),
  9442. _canvasHeightHalf = Math.floor( _canvasHeight / 2 ),
  9443. _context = _canvas.getContext( '2d', {
  9444. alpha: parameters.alpha === true
  9445. } ),
  9446. _clearColor = new THREE.Color( 0x000000 ),
  9447. _clearAlpha = 0,
  9448. _contextGlobalAlpha = 1,
  9449. _contextGlobalCompositeOperation = 0,
  9450. _contextStrokeStyle = null,
  9451. _contextFillStyle = null,
  9452. _contextLineWidth = null,
  9453. _contextLineCap = null,
  9454. _contextLineJoin = null,
  9455. _contextLineDash = [],
  9456. _camera,
  9457. _v1, _v2, _v3, _v4,
  9458. _v5 = new THREE.RenderableVertex(),
  9459. _v6 = new THREE.RenderableVertex(),
  9460. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  9461. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  9462. _color = new THREE.Color(),
  9463. _color1 = new THREE.Color(),
  9464. _color2 = new THREE.Color(),
  9465. _color3 = new THREE.Color(),
  9466. _color4 = new THREE.Color(),
  9467. _diffuseColor = new THREE.Color(),
  9468. _emissiveColor = new THREE.Color(),
  9469. _lightColor = new THREE.Color(),
  9470. _patterns = {},
  9471. _image, _uvs,
  9472. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  9473. _clipBox = new THREE.Box2(),
  9474. _clearBox = new THREE.Box2(),
  9475. _elemBox = new THREE.Box2(),
  9476. _ambientLight = new THREE.Color(),
  9477. _directionalLights = new THREE.Color(),
  9478. _pointLights = new THREE.Color(),
  9479. _vector3 = new THREE.Vector3(), // Needed for PointLight
  9480. _centroid = new THREE.Vector3(),
  9481. _normal = new THREE.Vector3(),
  9482. _normalViewMatrix = new THREE.Matrix3();
  9483. // dash+gap fallbacks for Firefox and everything else
  9484. if ( _context.setLineDash === undefined ) {
  9485. _context.setLineDash = function () {}
  9486. }
  9487. this.domElement = _canvas;
  9488. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  9489. ? parameters.devicePixelRatio
  9490. : self.devicePixelRatio !== undefined
  9491. ? self.devicePixelRatio
  9492. : 1;
  9493. this.autoClear = true;
  9494. this.sortObjects = true;
  9495. this.sortElements = true;
  9496. this.info = {
  9497. render: {
  9498. vertices: 0,
  9499. faces: 0
  9500. }
  9501. }
  9502. // WebGLRenderer compatibility
  9503. this.supportsVertexTextures = function () {};
  9504. this.setFaceCulling = function () {};
  9505. this.setSize = function ( width, height, updateStyle ) {
  9506. _canvasWidth = width * this.devicePixelRatio;
  9507. _canvasHeight = height * this.devicePixelRatio;
  9508. _canvas.width = _canvasWidth;
  9509. _canvas.height = _canvasHeight;
  9510. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  9511. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  9512. if ( updateStyle !== false ) {
  9513. _canvas.style.width = width + 'px';
  9514. _canvas.style.height = height + 'px';
  9515. }
  9516. _clipBox.min.set( -_canvasWidthHalf, -_canvasHeightHalf ),
  9517. _clipBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9518. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  9519. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9520. _contextGlobalAlpha = 1;
  9521. _contextGlobalCompositeOperation = 0;
  9522. _contextStrokeStyle = null;
  9523. _contextFillStyle = null;
  9524. _contextLineWidth = null;
  9525. _contextLineCap = null;
  9526. _contextLineJoin = null;
  9527. this.setViewport( 0, 0, width, height );
  9528. };
  9529. this.setViewport = function ( x, y, width, height ) {
  9530. var viewportX = x * this.devicePixelRatio;
  9531. var viewportY = y * this.devicePixelRatio;
  9532. var viewportWidth = width * this.devicePixelRatio;
  9533. var viewportHeight = height * this.devicePixelRatio;
  9534. _context.setTransform( viewportWidth / _canvasWidth, 0, 0, - viewportHeight / _canvasHeight, viewportX, _canvasHeight - viewportY );
  9535. _context.translate( _canvasWidthHalf, _canvasHeightHalf );
  9536. };
  9537. this.setScissor = function () {};
  9538. this.enableScissorTest = function () {};
  9539. this.setClearColor = function ( color, alpha ) {
  9540. _clearColor.set( color );
  9541. _clearAlpha = alpha !== undefined ? alpha : 1;
  9542. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  9543. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9544. };
  9545. this.setClearColorHex = function ( hex, alpha ) {
  9546. console.warn( 'THREE.CanvasRenderer: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  9547. this.setClearColor( hex, alpha );
  9548. };
  9549. this.getMaxAnisotropy = function () {
  9550. return 0;
  9551. };
  9552. this.clear = function () {
  9553. if ( _clearBox.empty() === false ) {
  9554. _clearBox.intersect( _clipBox );
  9555. _clearBox.expandByScalar( 2 );
  9556. if ( _clearAlpha < 1 ) {
  9557. _context.clearRect(
  9558. _clearBox.min.x | 0,
  9559. _clearBox.min.y | 0,
  9560. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9561. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9562. );
  9563. }
  9564. if ( _clearAlpha > 0 ) {
  9565. setBlending( THREE.NormalBlending );
  9566. setOpacity( 1 );
  9567. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  9568. _context.fillRect(
  9569. _clearBox.min.x | 0,
  9570. _clearBox.min.y | 0,
  9571. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9572. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9573. );
  9574. }
  9575. _clearBox.makeEmpty();
  9576. }
  9577. };
  9578. // compatibility
  9579. this.clearColor = function () {};
  9580. this.clearDepth = function () {};
  9581. this.clearStencil = function () {};
  9582. this.render = function ( scene, camera ) {
  9583. if ( camera instanceof THREE.Camera === false ) {
  9584. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  9585. return;
  9586. }
  9587. if ( this.autoClear === true ) this.clear();
  9588. _this.info.render.vertices = 0;
  9589. _this.info.render.faces = 0;
  9590. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  9591. _elements = _renderData.elements;
  9592. _lights = _renderData.lights;
  9593. _camera = camera;
  9594. _normalViewMatrix.getNormalMatrix( camera.matrixWorldInverse );
  9595. /* DEBUG
  9596. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  9597. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  9598. */
  9599. calculateLights();
  9600. for ( var e = 0, el = _elements.length; e < el; e ++ ) {
  9601. var element = _elements[ e ];
  9602. var material = element.material;
  9603. if ( material === undefined || material.opacity === 0 ) continue;
  9604. _elemBox.makeEmpty();
  9605. if ( element instanceof THREE.RenderableSprite ) {
  9606. _v1 = element;
  9607. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  9608. renderSprite( _v1, element, material );
  9609. } else if ( element instanceof THREE.RenderableLine ) {
  9610. _v1 = element.v1; _v2 = element.v2;
  9611. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9612. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9613. _elemBox.setFromPoints( [
  9614. _v1.positionScreen,
  9615. _v2.positionScreen
  9616. ] );
  9617. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9618. renderLine( _v1, _v2, element, material );
  9619. }
  9620. } else if ( element instanceof THREE.RenderableFace ) {
  9621. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  9622. if ( _v1.positionScreen.z < - 1 || _v1.positionScreen.z > 1 ) continue;
  9623. if ( _v2.positionScreen.z < - 1 || _v2.positionScreen.z > 1 ) continue;
  9624. if ( _v3.positionScreen.z < - 1 || _v3.positionScreen.z > 1 ) continue;
  9625. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9626. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9627. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  9628. if ( material.overdraw > 0 ) {
  9629. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  9630. expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
  9631. expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
  9632. }
  9633. _elemBox.setFromPoints( [
  9634. _v1.positionScreen,
  9635. _v2.positionScreen,
  9636. _v3.positionScreen
  9637. ] );
  9638. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9639. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  9640. }
  9641. }
  9642. /* DEBUG
  9643. setLineWidth( 1 );
  9644. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  9645. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  9646. */
  9647. _clearBox.union( _elemBox );
  9648. }
  9649. /* DEBUG
  9650. setLineWidth( 1 );
  9651. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  9652. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  9653. */
  9654. // _context.setTransform( 1, 0, 0, 1, 0, 0 );
  9655. };
  9656. //
  9657. function calculateLights() {
  9658. _ambientLight.setRGB( 0, 0, 0 );
  9659. _directionalLights.setRGB( 0, 0, 0 );
  9660. _pointLights.setRGB( 0, 0, 0 );
  9661. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9662. var light = _lights[ l ];
  9663. var lightColor = light.color;
  9664. if ( light instanceof THREE.AmbientLight ) {
  9665. _ambientLight.add( lightColor );
  9666. } else if ( light instanceof THREE.DirectionalLight ) {
  9667. // for sprites
  9668. _directionalLights.add( lightColor );
  9669. } else if ( light instanceof THREE.PointLight ) {
  9670. // for sprites
  9671. _pointLights.add( lightColor );
  9672. }
  9673. }
  9674. }
  9675. function calculateLight( position, normal, color ) {
  9676. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9677. var light = _lights[ l ];
  9678. _lightColor.copy( light.color );
  9679. if ( light instanceof THREE.DirectionalLight ) {
  9680. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld ).normalize();
  9681. var amount = normal.dot( lightPosition );
  9682. if ( amount <= 0 ) continue;
  9683. amount *= light.intensity;
  9684. color.add( _lightColor.multiplyScalar( amount ) );
  9685. } else if ( light instanceof THREE.PointLight ) {
  9686. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld );
  9687. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  9688. if ( amount <= 0 ) continue;
  9689. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  9690. if ( amount == 0 ) continue;
  9691. amount *= light.intensity;
  9692. color.add( _lightColor.multiplyScalar( amount ) );
  9693. }
  9694. }
  9695. }
  9696. function renderSprite( v1, element, material ) {
  9697. setOpacity( material.opacity );
  9698. setBlending( material.blending );
  9699. var scaleX = element.scale.x * _canvasWidthHalf;
  9700. var scaleY = element.scale.y * _canvasHeightHalf;
  9701. var dist = 0.5 * Math.sqrt( scaleX * scaleX + scaleY * scaleY ); // allow for rotated sprite
  9702. _elemBox.min.set( v1.x - dist, v1.y - dist );
  9703. _elemBox.max.set( v1.x + dist, v1.y + dist );
  9704. if ( material instanceof THREE.SpriteMaterial ) {
  9705. var texture = material.map;
  9706. if ( texture !== null && texture.image !== undefined ) {
  9707. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  9708. if ( texture.image.width > 0 ) {
  9709. textureToPattern( texture );
  9710. }
  9711. texture.addEventListener( 'update', onTextureUpdate );
  9712. }
  9713. var pattern = _patterns[ texture.id ];
  9714. if ( pattern !== undefined ) {
  9715. setFillStyle( pattern );
  9716. } else {
  9717. setFillStyle( 'rgba( 0, 0, 0, 1 )' );
  9718. }
  9719. //
  9720. var bitmap = texture.image;
  9721. var ox = bitmap.width * texture.offset.x;
  9722. var oy = bitmap.height * texture.offset.y;
  9723. var sx = bitmap.width * texture.repeat.x;
  9724. var sy = bitmap.height * texture.repeat.y;
  9725. var cx = scaleX / sx;
  9726. var cy = scaleY / sy;
  9727. _context.save();
  9728. _context.translate( v1.x, v1.y );
  9729. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9730. _context.translate( - scaleX / 2, - scaleY / 2 );
  9731. _context.scale( cx, cy );
  9732. _context.translate( - ox, - oy );
  9733. _context.fillRect( ox, oy, sx, sy );
  9734. _context.restore();
  9735. } else {
  9736. // no texture
  9737. setFillStyle( material.color.getStyle() );
  9738. _context.save();
  9739. _context.translate( v1.x, v1.y );
  9740. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9741. _context.scale( scaleX, - scaleY );
  9742. _context.fillRect( - 0.5, - 0.5, 1, 1 );
  9743. _context.restore();
  9744. }
  9745. } else if ( material instanceof THREE.SpriteCanvasMaterial ) {
  9746. setStrokeStyle( material.color.getStyle() );
  9747. setFillStyle( material.color.getStyle() );
  9748. _context.save();
  9749. _context.translate( v1.x, v1.y );
  9750. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9751. _context.scale( scaleX, scaleY );
  9752. material.program( _context );
  9753. _context.restore();
  9754. }
  9755. /* DEBUG
  9756. setStrokeStyle( 'rgb(255,255,0)' );
  9757. _context.beginPath();
  9758. _context.moveTo( v1.x - 10, v1.y );
  9759. _context.lineTo( v1.x + 10, v1.y );
  9760. _context.moveTo( v1.x, v1.y - 10 );
  9761. _context.lineTo( v1.x, v1.y + 10 );
  9762. _context.stroke();
  9763. */
  9764. }
  9765. function renderLine( v1, v2, element, material ) {
  9766. setOpacity( material.opacity );
  9767. setBlending( material.blending );
  9768. _context.beginPath();
  9769. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  9770. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  9771. if ( material instanceof THREE.LineBasicMaterial ) {
  9772. setLineWidth( material.linewidth );
  9773. setLineCap( material.linecap );
  9774. setLineJoin( material.linejoin );
  9775. if ( material.vertexColors !== THREE.VertexColors ) {
  9776. setStrokeStyle( material.color.getStyle() );
  9777. } else {
  9778. var colorStyle1 = element.vertexColors[ 0 ].getStyle();
  9779. var colorStyle2 = element.vertexColors[ 1 ].getStyle();
  9780. if ( colorStyle1 === colorStyle2 ) {
  9781. setStrokeStyle( colorStyle1 );
  9782. } else {
  9783. try {
  9784. var grad = _context.createLinearGradient(
  9785. v1.positionScreen.x,
  9786. v1.positionScreen.y,
  9787. v2.positionScreen.x,
  9788. v2.positionScreen.y
  9789. );
  9790. grad.addColorStop( 0, colorStyle1 );
  9791. grad.addColorStop( 1, colorStyle2 );
  9792. } catch ( exception ) {
  9793. grad = colorStyle1;
  9794. }
  9795. setStrokeStyle( grad );
  9796. }
  9797. }
  9798. _context.stroke();
  9799. _elemBox.expandByScalar( material.linewidth * 2 );
  9800. } else if ( material instanceof THREE.LineDashedMaterial ) {
  9801. setLineWidth( material.linewidth );
  9802. setLineCap( material.linecap );
  9803. setLineJoin( material.linejoin );
  9804. setStrokeStyle( material.color.getStyle() );
  9805. setLineDash( [ material.dashSize, material.gapSize ] );
  9806. _context.stroke();
  9807. _elemBox.expandByScalar( material.linewidth * 2 );
  9808. setLineDash( [] );
  9809. }
  9810. }
  9811. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  9812. _this.info.render.vertices += 3;
  9813. _this.info.render.faces ++;
  9814. setOpacity( material.opacity );
  9815. setBlending( material.blending );
  9816. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9817. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9818. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9819. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  9820. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  9821. _diffuseColor.copy( material.color );
  9822. _emissiveColor.copy( material.emissive );
  9823. if ( material.vertexColors === THREE.FaceColors ) {
  9824. _diffuseColor.multiply( element.color );
  9825. }
  9826. _color.copy( _ambientLight );
  9827. _centroid.copy( v1.positionWorld ).add( v2.positionWorld ).add( v3.positionWorld ).divideScalar( 3 );
  9828. calculateLight( _centroid, element.normalModel, _color );
  9829. _color.multiply( _diffuseColor ).add( _emissiveColor );
  9830. material.wireframe === true
  9831. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9832. : fillPath( _color );
  9833. } else if ( material instanceof THREE.MeshBasicMaterial ||
  9834. material instanceof THREE.MeshLambertMaterial ||
  9835. material instanceof THREE.MeshPhongMaterial ) {
  9836. if ( material.map !== null ) {
  9837. if ( material.map.mapping instanceof THREE.UVMapping ) {
  9838. _uvs = element.uvs;
  9839. 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 );
  9840. }
  9841. } else if ( material.envMap !== null ) {
  9842. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  9843. _normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix );
  9844. _uv1x = 0.5 * _normal.x + 0.5;
  9845. _uv1y = 0.5 * _normal.y + 0.5;
  9846. _normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix );
  9847. _uv2x = 0.5 * _normal.x + 0.5;
  9848. _uv2y = 0.5 * _normal.y + 0.5;
  9849. _normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix );
  9850. _uv3x = 0.5 * _normal.x + 0.5;
  9851. _uv3y = 0.5 * _normal.y + 0.5;
  9852. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  9853. } else if ( material.envMap.mapping instanceof THREE.SphericalRefractionMapping ) {
  9854. _normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix );
  9855. _uv1x = - 0.5 * _normal.x + 0.5;
  9856. _uv1y = - 0.5 * _normal.y + 0.5;
  9857. _normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix );
  9858. _uv2x = - 0.5 * _normal.x + 0.5;
  9859. _uv2y = - 0.5 * _normal.y + 0.5;
  9860. _normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix );
  9861. _uv3x = - 0.5 * _normal.x + 0.5;
  9862. _uv3y = - 0.5 * _normal.y + 0.5;
  9863. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  9864. }
  9865. } else {
  9866. _color.copy( material.color );
  9867. if ( material.vertexColors === THREE.FaceColors ) {
  9868. _color.multiply( element.color );
  9869. }
  9870. material.wireframe === true
  9871. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9872. : fillPath( _color );
  9873. }
  9874. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  9875. _color.r = _color.g = _color.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _camera.near, _camera.far );
  9876. material.wireframe === true
  9877. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9878. : fillPath( _color );
  9879. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  9880. _normal.copy( element.normalModel ).applyMatrix3( _normalViewMatrix );
  9881. _color.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9882. material.wireframe === true
  9883. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9884. : fillPath( _color );
  9885. } else {
  9886. _color.setRGB( 1, 1, 1 );
  9887. material.wireframe === true
  9888. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9889. : fillPath( _color );
  9890. }
  9891. }
  9892. //
  9893. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  9894. _context.beginPath();
  9895. _context.moveTo( x0, y0 );
  9896. _context.lineTo( x1, y1 );
  9897. _context.lineTo( x2, y2 );
  9898. _context.closePath();
  9899. }
  9900. function strokePath( color, linewidth, linecap, linejoin ) {
  9901. setLineWidth( linewidth );
  9902. setLineCap( linecap );
  9903. setLineJoin( linejoin );
  9904. setStrokeStyle( color.getStyle() );
  9905. _context.stroke();
  9906. _elemBox.expandByScalar( linewidth * 2 );
  9907. }
  9908. function fillPath( color ) {
  9909. setFillStyle( color.getStyle() );
  9910. _context.fill();
  9911. }
  9912. function onTextureUpdate ( event ) {
  9913. textureToPattern( event.target );
  9914. }
  9915. function textureToPattern( texture ) {
  9916. var repeatX = texture.wrapS === THREE.RepeatWrapping;
  9917. var repeatY = texture.wrapT === THREE.RepeatWrapping;
  9918. var image = texture.image;
  9919. var canvas = document.createElement( 'canvas' );
  9920. canvas.width = image.width;
  9921. canvas.height = image.height;
  9922. var context = canvas.getContext( '2d' );
  9923. context.setTransform( 1, 0, 0, - 1, 0, image.height );
  9924. context.drawImage( image, 0, 0 );
  9925. _patterns[ texture.id ] = _context.createPattern(
  9926. canvas, repeatX === true && repeatY === true
  9927. ? 'repeat'
  9928. : repeatX === true && repeatY === false
  9929. ? 'repeat-x'
  9930. : repeatX === false && repeatY === true
  9931. ? 'repeat-y'
  9932. : 'no-repeat'
  9933. );
  9934. }
  9935. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  9936. if ( texture instanceof THREE.DataTexture ) return;
  9937. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  9938. if ( texture.image !== undefined && texture.image.width > 0 ) {
  9939. textureToPattern( texture );
  9940. }
  9941. texture.addEventListener( 'update', onTextureUpdate );
  9942. }
  9943. var pattern = _patterns[ texture.id ];
  9944. if ( pattern !== undefined ) {
  9945. setFillStyle( pattern );
  9946. } else {
  9947. setFillStyle( 'rgba(0,0,0,1)' );
  9948. _context.fill();
  9949. return;
  9950. }
  9951. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9952. var a, b, c, d, e, f, det, idet,
  9953. offsetX = texture.offset.x / texture.repeat.x,
  9954. offsetY = texture.offset.y / texture.repeat.y,
  9955. width = texture.image.width * texture.repeat.x,
  9956. height = texture.image.height * texture.repeat.y;
  9957. u0 = ( u0 + offsetX ) * width;
  9958. v0 = ( v0 + offsetY ) * height;
  9959. u1 = ( u1 + offsetX ) * width;
  9960. v1 = ( v1 + offsetY ) * height;
  9961. u2 = ( u2 + offsetX ) * width;
  9962. v2 = ( v2 + offsetY ) * height;
  9963. x1 -= x0; y1 -= y0;
  9964. x2 -= x0; y2 -= y0;
  9965. u1 -= u0; v1 -= v0;
  9966. u2 -= u0; v2 -= v0;
  9967. det = u1 * v2 - u2 * v1;
  9968. if ( det === 0 ) return;
  9969. idet = 1 / det;
  9970. a = ( v2 * x1 - v1 * x2 ) * idet;
  9971. b = ( v2 * y1 - v1 * y2 ) * idet;
  9972. c = ( u1 * x2 - u2 * x1 ) * idet;
  9973. d = ( u1 * y2 - u2 * y1 ) * idet;
  9974. e = x0 - a * u0 - c * v0;
  9975. f = y0 - b * u0 - d * v0;
  9976. _context.save();
  9977. _context.transform( a, b, c, d, e, f );
  9978. _context.fill();
  9979. _context.restore();
  9980. }
  9981. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  9982. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9983. var a, b, c, d, e, f, det, idet,
  9984. width = image.width - 1,
  9985. height = image.height - 1;
  9986. u0 *= width; v0 *= height;
  9987. u1 *= width; v1 *= height;
  9988. u2 *= width; v2 *= height;
  9989. x1 -= x0; y1 -= y0;
  9990. x2 -= x0; y2 -= y0;
  9991. u1 -= u0; v1 -= v0;
  9992. u2 -= u0; v2 -= v0;
  9993. det = u1 * v2 - u2 * v1;
  9994. idet = 1 / det;
  9995. a = ( v2 * x1 - v1 * x2 ) * idet;
  9996. b = ( v2 * y1 - v1 * y2 ) * idet;
  9997. c = ( u1 * x2 - u2 * x1 ) * idet;
  9998. d = ( u1 * y2 - u2 * y1 ) * idet;
  9999. e = x0 - a * u0 - c * v0;
  10000. f = y0 - b * u0 - d * v0;
  10001. _context.save();
  10002. _context.transform( a, b, c, d, e, f );
  10003. _context.clip();
  10004. _context.drawImage( image, 0, 0 );
  10005. _context.restore();
  10006. }
  10007. // Hide anti-alias gaps
  10008. function expand( v1, v2, pixels ) {
  10009. var x = v2.x - v1.x, y = v2.y - v1.y,
  10010. det = x * x + y * y, idet;
  10011. if ( det === 0 ) return;
  10012. idet = pixels / Math.sqrt( det );
  10013. x *= idet; y *= idet;
  10014. v2.x += x; v2.y += y;
  10015. v1.x -= x; v1.y -= y;
  10016. }
  10017. // Context cached methods.
  10018. function setOpacity( value ) {
  10019. if ( _contextGlobalAlpha !== value ) {
  10020. _context.globalAlpha = value;
  10021. _contextGlobalAlpha = value;
  10022. }
  10023. }
  10024. function setBlending( value ) {
  10025. if ( _contextGlobalCompositeOperation !== value ) {
  10026. if ( value === THREE.NormalBlending ) {
  10027. _context.globalCompositeOperation = 'source-over';
  10028. } else if ( value === THREE.AdditiveBlending ) {
  10029. _context.globalCompositeOperation = 'lighter';
  10030. } else if ( value === THREE.SubtractiveBlending ) {
  10031. _context.globalCompositeOperation = 'darker';
  10032. }
  10033. _contextGlobalCompositeOperation = value;
  10034. }
  10035. }
  10036. function setLineWidth( value ) {
  10037. if ( _contextLineWidth !== value ) {
  10038. _context.lineWidth = value;
  10039. _contextLineWidth = value;
  10040. }
  10041. }
  10042. function setLineCap( value ) {
  10043. // "butt", "round", "square"
  10044. if ( _contextLineCap !== value ) {
  10045. _context.lineCap = value;
  10046. _contextLineCap = value;
  10047. }
  10048. }
  10049. function setLineJoin( value ) {
  10050. // "round", "bevel", "miter"
  10051. if ( _contextLineJoin !== value ) {
  10052. _context.lineJoin = value;
  10053. _contextLineJoin = value;
  10054. }
  10055. }
  10056. function setStrokeStyle( value ) {
  10057. if ( _contextStrokeStyle !== value ) {
  10058. _context.strokeStyle = value;
  10059. _contextStrokeStyle = value;
  10060. }
  10061. }
  10062. function setFillStyle( value ) {
  10063. if ( _contextFillStyle !== value ) {
  10064. _context.fillStyle = value;
  10065. _contextFillStyle = value;
  10066. }
  10067. }
  10068. function setLineDash( value ) {
  10069. if ( _contextLineDash.length !== value.length ) {
  10070. _context.setLineDash( value );
  10071. _contextLineDash = value;
  10072. }
  10073. }
  10074. };
  10075. // File:src/renderers/shaders/ShaderChunk.js
  10076. /**
  10077. * Shader chunks for WebLG Shader library
  10078. *
  10079. * @author alteredq / http://alteredqualia.com/
  10080. * @author mrdoob / http://mrdoob.com/
  10081. * @author mikael emtinger / http://gomo.se/
  10082. */
  10083. THREE.ShaderChunk = {
  10084. // FOG
  10085. fog_pars_fragment: [
  10086. "#ifdef USE_FOG",
  10087. " uniform vec3 fogColor;",
  10088. " #ifdef FOG_EXP2",
  10089. " uniform float fogDensity;",
  10090. " #else",
  10091. " uniform float fogNear;",
  10092. " uniform float fogFar;",
  10093. " #endif",
  10094. "#endif"
  10095. ].join("\n"),
  10096. fog_fragment: [
  10097. "#ifdef USE_FOG",
  10098. " #ifdef USE_LOGDEPTHBUF_EXT",
  10099. " float depth = gl_FragDepthEXT / gl_FragCoord.w;",
  10100. " #else",
  10101. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10102. " #endif",
  10103. " #ifdef FOG_EXP2",
  10104. " const float LOG2 = 1.442695;",
  10105. " float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  10106. " fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  10107. " #else",
  10108. " float fogFactor = smoothstep( fogNear, fogFar, depth );",
  10109. " #endif",
  10110. " gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  10111. "#endif"
  10112. ].join("\n"),
  10113. // ENVIRONMENT MAP
  10114. envmap_pars_fragment: [
  10115. "#ifdef USE_ENVMAP",
  10116. " uniform float reflectivity;",
  10117. " uniform samplerCube envMap;",
  10118. " uniform float flipEnvMap;",
  10119. " uniform int combine;",
  10120. " #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  10121. " uniform bool useRefract;",
  10122. " uniform float refractionRatio;",
  10123. " #else",
  10124. " varying vec3 vReflect;",
  10125. " #endif",
  10126. "#endif"
  10127. ].join("\n"),
  10128. envmap_fragment: [
  10129. "#ifdef USE_ENVMAP",
  10130. " vec3 reflectVec;",
  10131. " #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  10132. " vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  10133. // http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations
  10134. // "Transforming Normal Vectors with the Inverse Transformation"
  10135. " vec3 worldNormal = normalize( vec3( vec4( normal, 0.0 ) * viewMatrix ) );",
  10136. " if ( useRefract ) {",
  10137. " reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );",
  10138. " } else { ",
  10139. " reflectVec = reflect( cameraToVertex, worldNormal );",
  10140. " }",
  10141. " #else",
  10142. " reflectVec = vReflect;",
  10143. " #endif",
  10144. " #ifdef DOUBLE_SIDED",
  10145. " float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10146. " vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  10147. " #else",
  10148. " vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  10149. " #endif",
  10150. " #ifdef GAMMA_INPUT",
  10151. " cubeColor.xyz *= cubeColor.xyz;",
  10152. " #endif",
  10153. " if ( combine == 1 ) {",
  10154. " gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  10155. " } else if ( combine == 2 ) {",
  10156. " gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  10157. " } else {",
  10158. " gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  10159. " }",
  10160. "#endif"
  10161. ].join("\n"),
  10162. envmap_pars_vertex: [
  10163. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  10164. " varying vec3 vReflect;",
  10165. " uniform float refractionRatio;",
  10166. " uniform bool useRefract;",
  10167. "#endif"
  10168. ].join("\n"),
  10169. worldpos_vertex : [
  10170. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  10171. " #ifdef USE_SKINNING",
  10172. " vec4 worldPosition = modelMatrix * skinned;",
  10173. " #endif",
  10174. " #if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  10175. " vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  10176. " #endif",
  10177. " #if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  10178. " vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  10179. " #endif",
  10180. "#endif"
  10181. ].join("\n"),
  10182. envmap_vertex : [
  10183. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  10184. " vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  10185. " worldNormal = normalize( worldNormal );",
  10186. " vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  10187. " if ( useRefract ) {",
  10188. " vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  10189. " } else {",
  10190. " vReflect = reflect( cameraToVertex, worldNormal );",
  10191. " }",
  10192. "#endif"
  10193. ].join("\n"),
  10194. // COLOR MAP (particles)
  10195. map_particle_pars_fragment: [
  10196. "#ifdef USE_MAP",
  10197. " uniform sampler2D map;",
  10198. "#endif"
  10199. ].join("\n"),
  10200. map_particle_fragment: [
  10201. "#ifdef USE_MAP",
  10202. " gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  10203. "#endif"
  10204. ].join("\n"),
  10205. // COLOR MAP (triangles)
  10206. map_pars_vertex: [
  10207. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10208. " varying vec2 vUv;",
  10209. " uniform vec4 offsetRepeat;",
  10210. "#endif"
  10211. ].join("\n"),
  10212. map_pars_fragment: [
  10213. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10214. " varying vec2 vUv;",
  10215. "#endif",
  10216. "#ifdef USE_MAP",
  10217. " uniform sampler2D map;",
  10218. "#endif"
  10219. ].join("\n"),
  10220. map_vertex: [
  10221. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10222. " vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  10223. "#endif"
  10224. ].join("\n"),
  10225. map_fragment: [
  10226. "#ifdef USE_MAP",
  10227. " vec4 texelColor = texture2D( map, vUv );",
  10228. " #ifdef GAMMA_INPUT",
  10229. " texelColor.xyz *= texelColor.xyz;",
  10230. " #endif",
  10231. " gl_FragColor = gl_FragColor * texelColor;",
  10232. "#endif"
  10233. ].join("\n"),
  10234. // LIGHT MAP
  10235. lightmap_pars_fragment: [
  10236. "#ifdef USE_LIGHTMAP",
  10237. " varying vec2 vUv2;",
  10238. " uniform sampler2D lightMap;",
  10239. "#endif"
  10240. ].join("\n"),
  10241. lightmap_pars_vertex: [
  10242. "#ifdef USE_LIGHTMAP",
  10243. " varying vec2 vUv2;",
  10244. "#endif"
  10245. ].join("\n"),
  10246. lightmap_fragment: [
  10247. "#ifdef USE_LIGHTMAP",
  10248. " gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  10249. "#endif"
  10250. ].join("\n"),
  10251. lightmap_vertex: [
  10252. "#ifdef USE_LIGHTMAP",
  10253. " vUv2 = uv2;",
  10254. "#endif"
  10255. ].join("\n"),
  10256. // BUMP MAP
  10257. bumpmap_pars_fragment: [
  10258. "#ifdef USE_BUMPMAP",
  10259. " uniform sampler2D bumpMap;",
  10260. " uniform float bumpScale;",
  10261. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  10262. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  10263. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  10264. " vec2 dHdxy_fwd() {",
  10265. " vec2 dSTdx = dFdx( vUv );",
  10266. " vec2 dSTdy = dFdy( vUv );",
  10267. " float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  10268. " float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  10269. " float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  10270. " return vec2( dBx, dBy );",
  10271. " }",
  10272. " vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  10273. " vec3 vSigmaX = dFdx( surf_pos );",
  10274. " vec3 vSigmaY = dFdy( surf_pos );",
  10275. " vec3 vN = surf_norm;", // normalized
  10276. " vec3 R1 = cross( vSigmaY, vN );",
  10277. " vec3 R2 = cross( vN, vSigmaX );",
  10278. " float fDet = dot( vSigmaX, R1 );",
  10279. " vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  10280. " return normalize( abs( fDet ) * surf_norm - vGrad );",
  10281. " }",
  10282. "#endif"
  10283. ].join("\n"),
  10284. // NORMAL MAP
  10285. normalmap_pars_fragment: [
  10286. "#ifdef USE_NORMALMAP",
  10287. " uniform sampler2D normalMap;",
  10288. " uniform vec2 normalScale;",
  10289. // Per-Pixel Tangent Space Normal Mapping
  10290. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  10291. " vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  10292. " vec3 q0 = dFdx( eye_pos.xyz );",
  10293. " vec3 q1 = dFdy( eye_pos.xyz );",
  10294. " vec2 st0 = dFdx( vUv.st );",
  10295. " vec2 st1 = dFdy( vUv.st );",
  10296. " vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  10297. " vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  10298. " vec3 N = normalize( surf_norm );",
  10299. " vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  10300. " mapN.xy = normalScale * mapN.xy;",
  10301. " mat3 tsn = mat3( S, T, N );",
  10302. " return normalize( tsn * mapN );",
  10303. " }",
  10304. "#endif"
  10305. ].join("\n"),
  10306. // SPECULAR MAP
  10307. specularmap_pars_fragment: [
  10308. "#ifdef USE_SPECULARMAP",
  10309. " uniform sampler2D specularMap;",
  10310. "#endif"
  10311. ].join("\n"),
  10312. specularmap_fragment: [
  10313. "float specularStrength;",
  10314. "#ifdef USE_SPECULARMAP",
  10315. " vec4 texelSpecular = texture2D( specularMap, vUv );",
  10316. " specularStrength = texelSpecular.r;",
  10317. "#else",
  10318. " specularStrength = 1.0;",
  10319. "#endif"
  10320. ].join("\n"),
  10321. // LIGHTS LAMBERT
  10322. lights_lambert_pars_vertex: [
  10323. "uniform vec3 ambient;",
  10324. "uniform vec3 diffuse;",
  10325. "uniform vec3 emissive;",
  10326. "uniform vec3 ambientLightColor;",
  10327. "#if MAX_DIR_LIGHTS > 0",
  10328. " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10329. " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10330. "#endif",
  10331. "#if MAX_HEMI_LIGHTS > 0",
  10332. " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10333. " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10334. " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10335. "#endif",
  10336. "#if MAX_POINT_LIGHTS > 0",
  10337. " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10338. " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10339. " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10340. "#endif",
  10341. "#if MAX_SPOT_LIGHTS > 0",
  10342. " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10343. " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10344. " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10345. " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10346. " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10347. " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10348. "#endif",
  10349. "#ifdef WRAP_AROUND",
  10350. " uniform vec3 wrapRGB;",
  10351. "#endif"
  10352. ].join("\n"),
  10353. lights_lambert_vertex: [
  10354. "vLightFront = vec3( 0.0 );",
  10355. "#ifdef DOUBLE_SIDED",
  10356. " vLightBack = vec3( 0.0 );",
  10357. "#endif",
  10358. "transformedNormal = normalize( transformedNormal );",
  10359. "#if MAX_DIR_LIGHTS > 0",
  10360. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10361. " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10362. " vec3 dirVector = normalize( lDirection.xyz );",
  10363. " float dotProduct = dot( transformedNormal, dirVector );",
  10364. " vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10365. " #ifdef DOUBLE_SIDED",
  10366. " vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10367. " #ifdef WRAP_AROUND",
  10368. " vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10369. " #endif",
  10370. " #endif",
  10371. " #ifdef WRAP_AROUND",
  10372. " vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10373. " directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  10374. " #ifdef DOUBLE_SIDED",
  10375. " directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  10376. " #endif",
  10377. " #endif",
  10378. " vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  10379. " #ifdef DOUBLE_SIDED",
  10380. " vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  10381. " #endif",
  10382. "}",
  10383. "#endif",
  10384. "#if MAX_POINT_LIGHTS > 0",
  10385. " for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10386. " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10387. " vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10388. " float lDistance = 1.0;",
  10389. " if ( pointLightDistance[ i ] > 0.0 )",
  10390. " lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10391. " lVector = normalize( lVector );",
  10392. " float dotProduct = dot( transformedNormal, lVector );",
  10393. " vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10394. " #ifdef DOUBLE_SIDED",
  10395. " vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10396. " #ifdef WRAP_AROUND",
  10397. " vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10398. " #endif",
  10399. " #endif",
  10400. " #ifdef WRAP_AROUND",
  10401. " vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10402. " pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  10403. " #ifdef DOUBLE_SIDED",
  10404. " pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  10405. " #endif",
  10406. " #endif",
  10407. " vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  10408. " #ifdef DOUBLE_SIDED",
  10409. " vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  10410. " #endif",
  10411. " }",
  10412. "#endif",
  10413. "#if MAX_SPOT_LIGHTS > 0",
  10414. " for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10415. " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10416. " vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10417. " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  10418. " if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10419. " spotEffect = max( pow( max( spotEffect, 0.0 ), spotLightExponent[ i ] ), 0.0 );",
  10420. " float lDistance = 1.0;",
  10421. " if ( spotLightDistance[ i ] > 0.0 )",
  10422. " lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10423. " lVector = normalize( lVector );",
  10424. " float dotProduct = dot( transformedNormal, lVector );",
  10425. " vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10426. " #ifdef DOUBLE_SIDED",
  10427. " vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10428. " #ifdef WRAP_AROUND",
  10429. " vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10430. " #endif",
  10431. " #endif",
  10432. " #ifdef WRAP_AROUND",
  10433. " vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10434. " spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  10435. " #ifdef DOUBLE_SIDED",
  10436. " spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  10437. " #endif",
  10438. " #endif",
  10439. " vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  10440. " #ifdef DOUBLE_SIDED",
  10441. " vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  10442. " #endif",
  10443. " }",
  10444. " }",
  10445. "#endif",
  10446. "#if MAX_HEMI_LIGHTS > 0",
  10447. " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10448. " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10449. " vec3 lVector = normalize( lDirection.xyz );",
  10450. " float dotProduct = dot( transformedNormal, lVector );",
  10451. " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10452. " float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  10453. " vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10454. " #ifdef DOUBLE_SIDED",
  10455. " vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  10456. " #endif",
  10457. " }",
  10458. "#endif",
  10459. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  10460. "#ifdef DOUBLE_SIDED",
  10461. " vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  10462. "#endif"
  10463. ].join("\n"),
  10464. // LIGHTS PHONG
  10465. lights_phong_pars_vertex: [
  10466. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )",
  10467. " varying vec3 vWorldPosition;",
  10468. "#endif"
  10469. ].join("\n"),
  10470. lights_phong_vertex: [
  10471. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )",
  10472. " vWorldPosition = worldPosition.xyz;",
  10473. "#endif"
  10474. ].join("\n"),
  10475. lights_phong_pars_fragment: [
  10476. "uniform vec3 ambientLightColor;",
  10477. "#if MAX_DIR_LIGHTS > 0",
  10478. " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10479. " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10480. "#endif",
  10481. "#if MAX_HEMI_LIGHTS > 0",
  10482. " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10483. " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10484. " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10485. "#endif",
  10486. "#if MAX_POINT_LIGHTS > 0",
  10487. " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10488. " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10489. " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10490. "#endif",
  10491. "#if MAX_SPOT_LIGHTS > 0",
  10492. " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10493. " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10494. " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10495. " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10496. " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10497. " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10498. "#endif",
  10499. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )",
  10500. " varying vec3 vWorldPosition;",
  10501. "#endif",
  10502. "#ifdef WRAP_AROUND",
  10503. " uniform vec3 wrapRGB;",
  10504. "#endif",
  10505. "varying vec3 vViewPosition;",
  10506. "varying vec3 vNormal;"
  10507. ].join("\n"),
  10508. lights_phong_fragment: [
  10509. "vec3 normal = normalize( vNormal );",
  10510. "vec3 viewPosition = normalize( vViewPosition );",
  10511. "#ifdef DOUBLE_SIDED",
  10512. " normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10513. "#endif",
  10514. "#ifdef USE_NORMALMAP",
  10515. " normal = perturbNormal2Arb( -vViewPosition, normal );",
  10516. "#elif defined( USE_BUMPMAP )",
  10517. " normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  10518. "#endif",
  10519. "#if MAX_POINT_LIGHTS > 0",
  10520. " vec3 pointDiffuse = vec3( 0.0 );",
  10521. " vec3 pointSpecular = vec3( 0.0 );",
  10522. " for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10523. " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10524. " vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10525. " float lDistance = 1.0;",
  10526. " if ( pointLightDistance[ i ] > 0.0 )",
  10527. " lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10528. " lVector = normalize( lVector );",
  10529. // diffuse
  10530. " float dotProduct = dot( normal, lVector );",
  10531. " #ifdef WRAP_AROUND",
  10532. " float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  10533. " float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10534. " vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10535. " #else",
  10536. " float pointDiffuseWeight = max( dotProduct, 0.0 );",
  10537. " #endif",
  10538. " pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  10539. // specular
  10540. " vec3 pointHalfVector = normalize( lVector + viewPosition );",
  10541. " float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10542. " float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  10543. " float specularNormalization = ( shininess + 2.0 ) / 8.0;",
  10544. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, pointHalfVector ), 0.0 ), 5.0 );",
  10545. " pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  10546. " }",
  10547. "#endif",
  10548. "#if MAX_SPOT_LIGHTS > 0",
  10549. " vec3 spotDiffuse = vec3( 0.0 );",
  10550. " vec3 spotSpecular = vec3( 0.0 );",
  10551. " for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10552. " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10553. " vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10554. " float lDistance = 1.0;",
  10555. " if ( spotLightDistance[ i ] > 0.0 )",
  10556. " lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10557. " lVector = normalize( lVector );",
  10558. " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10559. " if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10560. " spotEffect = max( pow( max( spotEffect, 0.0 ), spotLightExponent[ i ] ), 0.0 );",
  10561. // diffuse
  10562. " float dotProduct = dot( normal, lVector );",
  10563. " #ifdef WRAP_AROUND",
  10564. " float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  10565. " float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10566. " vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10567. " #else",
  10568. " float spotDiffuseWeight = max( dotProduct, 0.0 );",
  10569. " #endif",
  10570. " spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  10571. // specular
  10572. " vec3 spotHalfVector = normalize( lVector + viewPosition );",
  10573. " float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10574. " float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  10575. " float specularNormalization = ( shininess + 2.0 ) / 8.0;",
  10576. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, spotHalfVector ), 0.0 ), 5.0 );",
  10577. " spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  10578. " }",
  10579. " }",
  10580. "#endif",
  10581. "#if MAX_DIR_LIGHTS > 0",
  10582. " vec3 dirDiffuse = vec3( 0.0 );",
  10583. " vec3 dirSpecular = vec3( 0.0 );" ,
  10584. " for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10585. " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10586. " vec3 dirVector = normalize( lDirection.xyz );",
  10587. // diffuse
  10588. " float dotProduct = dot( normal, dirVector );",
  10589. " #ifdef WRAP_AROUND",
  10590. " float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  10591. " float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10592. " vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  10593. " #else",
  10594. " float dirDiffuseWeight = max( dotProduct, 0.0 );",
  10595. " #endif",
  10596. " dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  10597. // specular
  10598. " vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10599. " float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10600. " float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  10601. /*
  10602. // fresnel term from skin shader
  10603. " const float F0 = 0.128;",
  10604. " float base = 1.0 - dot( viewPosition, dirHalfVector );",
  10605. " float exponential = pow( base, 5.0 );",
  10606. " float fresnel = exponential + F0 * ( 1.0 - exponential );",
  10607. */
  10608. /*
  10609. // fresnel term from fresnel shader
  10610. " const float mFresnelBias = 0.08;",
  10611. " const float mFresnelScale = 0.3;",
  10612. " const float mFresnelPower = 5.0;",
  10613. " float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  10614. */
  10615. " float specularNormalization = ( shininess + 2.0 ) / 8.0;",
  10616. // " dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  10617. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( dirVector, dirHalfVector ), 0.0 ), 5.0 );",
  10618. " dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10619. " }",
  10620. "#endif",
  10621. "#if MAX_HEMI_LIGHTS > 0",
  10622. " vec3 hemiDiffuse = vec3( 0.0 );",
  10623. " vec3 hemiSpecular = vec3( 0.0 );" ,
  10624. " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10625. " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10626. " vec3 lVector = normalize( lDirection.xyz );",
  10627. // diffuse
  10628. " float dotProduct = dot( normal, lVector );",
  10629. " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10630. " vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10631. " hemiDiffuse += diffuse * hemiColor;",
  10632. // specular (sky light)
  10633. " vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10634. " float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10635. " float hemiSpecularWeightSky = specularStrength * max( pow( max( hemiDotNormalHalfSky, 0.0 ), shininess ), 0.0 );",
  10636. // specular (ground light)
  10637. " vec3 lVectorGround = -lVector;",
  10638. " vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10639. " float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10640. " float hemiSpecularWeightGround = specularStrength * max( pow( max( hemiDotNormalHalfGround, 0.0 ), shininess ), 0.0 );",
  10641. " float dotProductGround = dot( normal, lVectorGround );",
  10642. " float specularNormalization = ( shininess + 2.0 ) / 8.0;",
  10643. " vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, hemiHalfVectorSky ), 0.0 ), 5.0 );",
  10644. " vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 0.0 ), 5.0 );",
  10645. " hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10646. " }",
  10647. "#endif",
  10648. "vec3 totalDiffuse = vec3( 0.0 );",
  10649. "vec3 totalSpecular = vec3( 0.0 );",
  10650. "#if MAX_DIR_LIGHTS > 0",
  10651. " totalDiffuse += dirDiffuse;",
  10652. " totalSpecular += dirSpecular;",
  10653. "#endif",
  10654. "#if MAX_HEMI_LIGHTS > 0",
  10655. " totalDiffuse += hemiDiffuse;",
  10656. " totalSpecular += hemiSpecular;",
  10657. "#endif",
  10658. "#if MAX_POINT_LIGHTS > 0",
  10659. " totalDiffuse += pointDiffuse;",
  10660. " totalSpecular += pointSpecular;",
  10661. "#endif",
  10662. "#if MAX_SPOT_LIGHTS > 0",
  10663. " totalDiffuse += spotDiffuse;",
  10664. " totalSpecular += spotSpecular;",
  10665. "#endif",
  10666. "#ifdef METAL",
  10667. " gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  10668. "#else",
  10669. " gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  10670. "#endif"
  10671. ].join("\n"),
  10672. // VERTEX COLORS
  10673. color_pars_fragment: [
  10674. "#ifdef USE_COLOR",
  10675. " varying vec3 vColor;",
  10676. "#endif"
  10677. ].join("\n"),
  10678. color_fragment: [
  10679. "#ifdef USE_COLOR",
  10680. " gl_FragColor = gl_FragColor * vec4( vColor, 1.0 );",
  10681. "#endif"
  10682. ].join("\n"),
  10683. color_pars_vertex: [
  10684. "#ifdef USE_COLOR",
  10685. " varying vec3 vColor;",
  10686. "#endif"
  10687. ].join("\n"),
  10688. color_vertex: [
  10689. "#ifdef USE_COLOR",
  10690. " #ifdef GAMMA_INPUT",
  10691. " vColor = color * color;",
  10692. " #else",
  10693. " vColor = color;",
  10694. " #endif",
  10695. "#endif"
  10696. ].join("\n"),
  10697. // SKINNING
  10698. skinning_pars_vertex: [
  10699. "#ifdef USE_SKINNING",
  10700. " #ifdef BONE_TEXTURE",
  10701. " uniform sampler2D boneTexture;",
  10702. " uniform int boneTextureWidth;",
  10703. " uniform int boneTextureHeight;",
  10704. " mat4 getBoneMatrix( const in float i ) {",
  10705. " float j = i * 4.0;",
  10706. " float x = mod( j, float( boneTextureWidth ) );",
  10707. " float y = floor( j / float( boneTextureWidth ) );",
  10708. " float dx = 1.0 / float( boneTextureWidth );",
  10709. " float dy = 1.0 / float( boneTextureHeight );",
  10710. " y = dy * ( y + 0.5 );",
  10711. " vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  10712. " vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  10713. " vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  10714. " vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  10715. " mat4 bone = mat4( v1, v2, v3, v4 );",
  10716. " return bone;",
  10717. " }",
  10718. " #else",
  10719. " uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  10720. " mat4 getBoneMatrix( const in float i ) {",
  10721. " mat4 bone = boneGlobalMatrices[ int(i) ];",
  10722. " return bone;",
  10723. " }",
  10724. " #endif",
  10725. "#endif"
  10726. ].join("\n"),
  10727. skinbase_vertex: [
  10728. "#ifdef USE_SKINNING",
  10729. " mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  10730. " mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  10731. " mat4 boneMatZ = getBoneMatrix( skinIndex.z );",
  10732. " mat4 boneMatW = getBoneMatrix( skinIndex.w );",
  10733. "#endif"
  10734. ].join("\n"),
  10735. skinning_vertex: [
  10736. "#ifdef USE_SKINNING",
  10737. " #ifdef USE_MORPHTARGETS",
  10738. " vec4 skinVertex = vec4( morphed, 1.0 );",
  10739. " #else",
  10740. " vec4 skinVertex = vec4( position, 1.0 );",
  10741. " #endif",
  10742. " vec4 skinned = vec4( 0.0 );",
  10743. " skinned += boneMatX * skinVertex * skinWeight.x;",
  10744. " skinned += boneMatY * skinVertex * skinWeight.y;",
  10745. " skinned += boneMatZ * skinVertex * skinWeight.z;",
  10746. " skinned += boneMatW * skinVertex * skinWeight.w;",
  10747. "#endif"
  10748. ].join("\n"),
  10749. // MORPHING
  10750. morphtarget_pars_vertex: [
  10751. "#ifdef USE_MORPHTARGETS",
  10752. " #ifndef USE_MORPHNORMALS",
  10753. " uniform float morphTargetInfluences[ 8 ];",
  10754. " #else",
  10755. " uniform float morphTargetInfluences[ 4 ];",
  10756. " #endif",
  10757. "#endif"
  10758. ].join("\n"),
  10759. morphtarget_vertex: [
  10760. "#ifdef USE_MORPHTARGETS",
  10761. " vec3 morphed = vec3( 0.0 );",
  10762. " morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  10763. " morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  10764. " morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  10765. " morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  10766. " #ifndef USE_MORPHNORMALS",
  10767. " morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  10768. " morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  10769. " morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  10770. " morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  10771. " #endif",
  10772. " morphed += position;",
  10773. "#endif"
  10774. ].join("\n"),
  10775. default_vertex : [
  10776. "vec4 mvPosition;",
  10777. "#ifdef USE_SKINNING",
  10778. " mvPosition = modelViewMatrix * skinned;",
  10779. "#endif",
  10780. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  10781. " mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  10782. "#endif",
  10783. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  10784. " mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10785. "#endif",
  10786. "gl_Position = projectionMatrix * mvPosition;"
  10787. ].join("\n"),
  10788. morphnormal_vertex: [
  10789. "#ifdef USE_MORPHNORMALS",
  10790. " vec3 morphedNormal = vec3( 0.0 );",
  10791. " morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  10792. " morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  10793. " morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  10794. " morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  10795. " morphedNormal += normal;",
  10796. "#endif"
  10797. ].join("\n"),
  10798. skinnormal_vertex: [
  10799. "#ifdef USE_SKINNING",
  10800. " mat4 skinMatrix = mat4( 0.0 );",
  10801. " skinMatrix += skinWeight.x * boneMatX;",
  10802. " skinMatrix += skinWeight.y * boneMatY;",
  10803. " skinMatrix += skinWeight.z * boneMatZ;",
  10804. " skinMatrix += skinWeight.w * boneMatW;",
  10805. " #ifdef USE_MORPHNORMALS",
  10806. " vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  10807. " #else",
  10808. " vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  10809. " #endif",
  10810. "#endif"
  10811. ].join("\n"),
  10812. defaultnormal_vertex: [
  10813. "vec3 objectNormal;",
  10814. "#ifdef USE_SKINNING",
  10815. " objectNormal = skinnedNormal.xyz;",
  10816. "#endif",
  10817. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  10818. " objectNormal = morphedNormal;",
  10819. "#endif",
  10820. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  10821. " objectNormal = normal;",
  10822. "#endif",
  10823. "#ifdef FLIP_SIDED",
  10824. " objectNormal = -objectNormal;",
  10825. "#endif",
  10826. "vec3 transformedNormal = normalMatrix * objectNormal;"
  10827. ].join("\n"),
  10828. // SHADOW MAP
  10829. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  10830. // http://spidergl.org/example.php?id=6
  10831. // http://fabiensanglard.net/shadowmapping
  10832. shadowmap_pars_fragment: [
  10833. "#ifdef USE_SHADOWMAP",
  10834. " uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  10835. " uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  10836. " uniform float shadowDarkness[ MAX_SHADOWS ];",
  10837. " uniform float shadowBias[ MAX_SHADOWS ];",
  10838. " varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10839. " float unpackDepth( const in vec4 rgba_depth ) {",
  10840. " 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 );",
  10841. " float depth = dot( rgba_depth, bit_shift );",
  10842. " return depth;",
  10843. " }",
  10844. "#endif"
  10845. ].join("\n"),
  10846. shadowmap_fragment: [
  10847. "#ifdef USE_SHADOWMAP",
  10848. " #ifdef SHADOWMAP_DEBUG",
  10849. " vec3 frustumColors[3];",
  10850. " frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  10851. " frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  10852. " frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  10853. " #endif",
  10854. " #ifdef SHADOWMAP_CASCADE",
  10855. " int inFrustumCount = 0;",
  10856. " #endif",
  10857. " float fDepth;",
  10858. " vec3 shadowColor = vec3( 1.0 );",
  10859. " for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10860. " vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  10861. // "if ( something && something )" breaks ATI OpenGL shader compiler
  10862. // "if ( all( something, something ) )" using this instead
  10863. " bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  10864. " bool inFrustum = all( inFrustumVec );",
  10865. // don't shadow pixels outside of light frustum
  10866. // use just first frustum (for cascades)
  10867. // don't shadow pixels behind far plane of light frustum
  10868. " #ifdef SHADOWMAP_CASCADE",
  10869. " inFrustumCount += int( inFrustum );",
  10870. " bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  10871. " #else",
  10872. " bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  10873. " #endif",
  10874. " bool frustumTest = all( frustumTestVec );",
  10875. " if ( frustumTest ) {",
  10876. " shadowCoord.z += shadowBias[ i ];",
  10877. " #if defined( SHADOWMAP_TYPE_PCF )",
  10878. // Percentage-close filtering
  10879. // (9 pixel kernel)
  10880. // http://fabiensanglard.net/shadowmappingPCF/
  10881. " float shadow = 0.0;",
  10882. /*
  10883. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  10884. // must enroll loop manually
  10885. " for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  10886. " for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  10887. " vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  10888. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  10889. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  10890. " float fDepth = unpackDepth( rgbaDepth );",
  10891. " if ( fDepth < shadowCoord.z )",
  10892. " shadow += 1.0;",
  10893. " }",
  10894. " shadow /= 9.0;",
  10895. */
  10896. " const float shadowDelta = 1.0 / 9.0;",
  10897. " float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10898. " float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10899. " float dx0 = -1.25 * xPixelOffset;",
  10900. " float dy0 = -1.25 * yPixelOffset;",
  10901. " float dx1 = 1.25 * xPixelOffset;",
  10902. " float dy1 = 1.25 * yPixelOffset;",
  10903. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10904. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10905. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10906. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10907. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10908. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10909. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10910. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10911. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10912. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10913. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10914. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10915. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10916. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10917. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10918. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10919. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10920. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10921. " shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10922. " #elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  10923. // Percentage-close filtering
  10924. // (9 pixel kernel)
  10925. // http://fabiensanglard.net/shadowmappingPCF/
  10926. " float shadow = 0.0;",
  10927. " float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10928. " float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10929. " float dx0 = -1.0 * xPixelOffset;",
  10930. " float dy0 = -1.0 * yPixelOffset;",
  10931. " float dx1 = 1.0 * xPixelOffset;",
  10932. " float dy1 = 1.0 * yPixelOffset;",
  10933. " mat3 shadowKernel;",
  10934. " mat3 depthKernel;",
  10935. " depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10936. " depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10937. " depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10938. " depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10939. " depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10940. " depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10941. " depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10942. " depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10943. " depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10944. " vec3 shadowZ = vec3( shadowCoord.z );",
  10945. " shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  10946. " shadowKernel[0] *= vec3(0.25);",
  10947. " shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  10948. " shadowKernel[1] *= vec3(0.25);",
  10949. " shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  10950. " shadowKernel[2] *= vec3(0.25);",
  10951. " vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  10952. " shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  10953. " shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  10954. " vec4 shadowValues;",
  10955. " shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  10956. " shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  10957. " shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  10958. " shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  10959. " shadow = dot( shadowValues, vec4( 1.0 ) );",
  10960. " shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10961. " #else",
  10962. " vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  10963. " float fDepth = unpackDepth( rgbaDepth );",
  10964. " if ( fDepth < shadowCoord.z )",
  10965. // spot with multiple shadows is darker
  10966. " shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  10967. // spot with multiple shadows has the same color as single shadow spot
  10968. // " shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  10969. " #endif",
  10970. " }",
  10971. " #ifdef SHADOWMAP_DEBUG",
  10972. " #ifdef SHADOWMAP_CASCADE",
  10973. " if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  10974. " #else",
  10975. " if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  10976. " #endif",
  10977. " #endif",
  10978. " }",
  10979. " #ifdef GAMMA_OUTPUT",
  10980. " shadowColor *= shadowColor;",
  10981. " #endif",
  10982. " gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  10983. "#endif"
  10984. ].join("\n"),
  10985. shadowmap_pars_vertex: [
  10986. "#ifdef USE_SHADOWMAP",
  10987. " varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10988. " uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  10989. "#endif"
  10990. ].join("\n"),
  10991. shadowmap_vertex: [
  10992. "#ifdef USE_SHADOWMAP",
  10993. " for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10994. " vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10995. " }",
  10996. "#endif"
  10997. ].join("\n"),
  10998. // ALPHATEST
  10999. alphatest_fragment: [
  11000. "#ifdef ALPHATEST",
  11001. " if ( gl_FragColor.a < ALPHATEST ) discard;",
  11002. "#endif"
  11003. ].join("\n"),
  11004. // LINEAR SPACE
  11005. linear_to_gamma_fragment: [
  11006. "#ifdef GAMMA_OUTPUT",
  11007. " gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  11008. "#endif"
  11009. ].join("\n"),
  11010. // LOGARITHMIC DEPTH BUFFER
  11011. // http://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html
  11012. // WebGL doesn't support gl_FragDepth out of the box, unless the EXT_frag_depth extension is available. On platforms
  11013. // without EXT_frag_depth, we have to fall back on linear z-buffer in the fragment shader, which means that some long
  11014. // faces close to the camera may have issues. This can be worked around by tesselating the model more finely when
  11015. // the camera is near the surface.
  11016. logdepthbuf_pars_vertex: [
  11017. "#ifdef USE_LOGDEPTHBUF",
  11018. " #ifdef USE_LOGDEPTHBUF_EXT",
  11019. " varying float vFragDepth;",
  11020. " #endif",
  11021. " uniform float logDepthBufFC;",
  11022. "#endif",
  11023. ].join('\n'),
  11024. logdepthbuf_vertex: [
  11025. "#ifdef USE_LOGDEPTHBUF",
  11026. " gl_Position.z = log2(max(1e-6, gl_Position.w + 1.0)) * logDepthBufFC;",
  11027. " #ifdef USE_LOGDEPTHBUF_EXT",
  11028. " vFragDepth = 1.0 + gl_Position.w;",
  11029. "#else",
  11030. " gl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;",
  11031. " #endif",
  11032. "#endif"
  11033. ].join("\n"),
  11034. logdepthbuf_pars_fragment: [
  11035. "#ifdef USE_LOGDEPTHBUF",
  11036. " uniform float logDepthBufFC;",
  11037. " #ifdef USE_LOGDEPTHBUF_EXT",
  11038. " #extension GL_EXT_frag_depth : enable",
  11039. " varying float vFragDepth;",
  11040. " #endif",
  11041. "#endif"
  11042. ].join('\n'),
  11043. logdepthbuf_fragment: [
  11044. "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)",
  11045. " gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;",
  11046. "#endif"
  11047. ].join("\n")
  11048. };
  11049. // File:src/renderers/shaders/UniformsUtils.js
  11050. /**
  11051. * Uniform Utilities
  11052. */
  11053. THREE.UniformsUtils = {
  11054. merge: function ( uniforms ) {
  11055. var u, p, tmp, merged = {};
  11056. for ( u = 0; u < uniforms.length; u ++ ) {
  11057. tmp = this.clone( uniforms[ u ] );
  11058. for ( p in tmp ) {
  11059. merged[ p ] = tmp[ p ];
  11060. }
  11061. }
  11062. return merged;
  11063. },
  11064. clone: function ( uniforms_src ) {
  11065. var u, p, parameter, parameter_src, uniforms_dst = {};
  11066. for ( u in uniforms_src ) {
  11067. uniforms_dst[ u ] = {};
  11068. for ( p in uniforms_src[ u ] ) {
  11069. parameter_src = uniforms_src[ u ][ p ];
  11070. if ( parameter_src instanceof THREE.Color ||
  11071. parameter_src instanceof THREE.Vector2 ||
  11072. parameter_src instanceof THREE.Vector3 ||
  11073. parameter_src instanceof THREE.Vector4 ||
  11074. parameter_src instanceof THREE.Matrix4 ||
  11075. parameter_src instanceof THREE.Texture ) {
  11076. uniforms_dst[ u ][ p ] = parameter_src.clone();
  11077. } else if ( parameter_src instanceof Array ) {
  11078. uniforms_dst[ u ][ p ] = parameter_src.slice();
  11079. } else {
  11080. uniforms_dst[ u ][ p ] = parameter_src;
  11081. }
  11082. }
  11083. }
  11084. return uniforms_dst;
  11085. }
  11086. };
  11087. // File:src/renderers/shaders/UniformsLib.js
  11088. /**
  11089. * Uniforms library for shared webgl shaders
  11090. */
  11091. THREE.UniformsLib = {
  11092. common: {
  11093. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  11094. "opacity" : { type: "f", value: 1.0 },
  11095. "map" : { type: "t", value: null },
  11096. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  11097. "lightMap" : { type: "t", value: null },
  11098. "specularMap" : { type: "t", value: null },
  11099. "envMap" : { type: "t", value: null },
  11100. "flipEnvMap" : { type: "f", value: - 1 },
  11101. "useRefract" : { type: "i", value: 0 },
  11102. "reflectivity" : { type: "f", value: 1.0 },
  11103. "refractionRatio" : { type: "f", value: 0.98 },
  11104. "combine" : { type: "i", value: 0 },
  11105. "morphTargetInfluences" : { type: "f", value: 0 }
  11106. },
  11107. bump: {
  11108. "bumpMap" : { type: "t", value: null },
  11109. "bumpScale" : { type: "f", value: 1 }
  11110. },
  11111. normalmap: {
  11112. "normalMap" : { type: "t", value: null },
  11113. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  11114. },
  11115. fog : {
  11116. "fogDensity" : { type: "f", value: 0.00025 },
  11117. "fogNear" : { type: "f", value: 1 },
  11118. "fogFar" : { type: "f", value: 2000 },
  11119. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  11120. },
  11121. lights: {
  11122. "ambientLightColor" : { type: "fv", value: [] },
  11123. "directionalLightDirection" : { type: "fv", value: [] },
  11124. "directionalLightColor" : { type: "fv", value: [] },
  11125. "hemisphereLightDirection" : { type: "fv", value: [] },
  11126. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  11127. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  11128. "pointLightColor" : { type: "fv", value: [] },
  11129. "pointLightPosition" : { type: "fv", value: [] },
  11130. "pointLightDistance" : { type: "fv1", value: [] },
  11131. "spotLightColor" : { type: "fv", value: [] },
  11132. "spotLightPosition" : { type: "fv", value: [] },
  11133. "spotLightDirection" : { type: "fv", value: [] },
  11134. "spotLightDistance" : { type: "fv1", value: [] },
  11135. "spotLightAngleCos" : { type: "fv1", value: [] },
  11136. "spotLightExponent" : { type: "fv1", value: [] }
  11137. },
  11138. particle: {
  11139. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  11140. "opacity" : { type: "f", value: 1.0 },
  11141. "size" : { type: "f", value: 1.0 },
  11142. "scale" : { type: "f", value: 1.0 },
  11143. "map" : { type: "t", value: null },
  11144. "fogDensity" : { type: "f", value: 0.00025 },
  11145. "fogNear" : { type: "f", value: 1 },
  11146. "fogFar" : { type: "f", value: 2000 },
  11147. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  11148. },
  11149. shadowmap: {
  11150. "shadowMap": { type: "tv", value: [] },
  11151. "shadowMapSize": { type: "v2v", value: [] },
  11152. "shadowBias" : { type: "fv1", value: [] },
  11153. "shadowDarkness": { type: "fv1", value: [] },
  11154. "shadowMatrix" : { type: "m4v", value: [] }
  11155. }
  11156. };
  11157. // File:src/renderers/shaders/ShaderLib.js
  11158. /**
  11159. * Webgl Shader Library for three.js
  11160. *
  11161. * @author alteredq / http://alteredqualia.com/
  11162. * @author mrdoob / http://mrdoob.com/
  11163. * @author mikael emtinger / http://gomo.se/
  11164. */
  11165. THREE.ShaderLib = {
  11166. 'basic': {
  11167. uniforms: THREE.UniformsUtils.merge( [
  11168. THREE.UniformsLib[ "common" ],
  11169. THREE.UniformsLib[ "fog" ],
  11170. THREE.UniformsLib[ "shadowmap" ]
  11171. ] ),
  11172. vertexShader: [
  11173. THREE.ShaderChunk[ "map_pars_vertex" ],
  11174. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11175. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11176. THREE.ShaderChunk[ "color_pars_vertex" ],
  11177. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11178. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11179. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11180. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11181. "void main() {",
  11182. THREE.ShaderChunk[ "map_vertex" ],
  11183. THREE.ShaderChunk[ "lightmap_vertex" ],
  11184. THREE.ShaderChunk[ "color_vertex" ],
  11185. THREE.ShaderChunk[ "skinbase_vertex" ],
  11186. " #ifdef USE_ENVMAP",
  11187. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11188. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11189. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11190. " #endif",
  11191. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11192. THREE.ShaderChunk[ "skinning_vertex" ],
  11193. THREE.ShaderChunk[ "default_vertex" ],
  11194. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11195. THREE.ShaderChunk[ "worldpos_vertex" ],
  11196. THREE.ShaderChunk[ "envmap_vertex" ],
  11197. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11198. "}"
  11199. ].join("\n"),
  11200. fragmentShader: [
  11201. "uniform vec3 diffuse;",
  11202. "uniform float opacity;",
  11203. THREE.ShaderChunk[ "color_pars_fragment" ],
  11204. THREE.ShaderChunk[ "map_pars_fragment" ],
  11205. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11206. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11207. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11208. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11209. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11210. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11211. "void main() {",
  11212. " gl_FragColor = vec4( diffuse, opacity );",
  11213. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11214. THREE.ShaderChunk[ "map_fragment" ],
  11215. THREE.ShaderChunk[ "alphatest_fragment" ],
  11216. THREE.ShaderChunk[ "specularmap_fragment" ],
  11217. THREE.ShaderChunk[ "lightmap_fragment" ],
  11218. THREE.ShaderChunk[ "color_fragment" ],
  11219. THREE.ShaderChunk[ "envmap_fragment" ],
  11220. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11221. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11222. THREE.ShaderChunk[ "fog_fragment" ],
  11223. "}"
  11224. ].join("\n")
  11225. },
  11226. 'lambert': {
  11227. uniforms: THREE.UniformsUtils.merge( [
  11228. THREE.UniformsLib[ "common" ],
  11229. THREE.UniformsLib[ "fog" ],
  11230. THREE.UniformsLib[ "lights" ],
  11231. THREE.UniformsLib[ "shadowmap" ],
  11232. {
  11233. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  11234. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  11235. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11236. }
  11237. ] ),
  11238. vertexShader: [
  11239. "#define LAMBERT",
  11240. "varying vec3 vLightFront;",
  11241. "#ifdef DOUBLE_SIDED",
  11242. " varying vec3 vLightBack;",
  11243. "#endif",
  11244. THREE.ShaderChunk[ "map_pars_vertex" ],
  11245. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11246. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11247. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  11248. THREE.ShaderChunk[ "color_pars_vertex" ],
  11249. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11250. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11251. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11252. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11253. "void main() {",
  11254. THREE.ShaderChunk[ "map_vertex" ],
  11255. THREE.ShaderChunk[ "lightmap_vertex" ],
  11256. THREE.ShaderChunk[ "color_vertex" ],
  11257. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11258. THREE.ShaderChunk[ "skinbase_vertex" ],
  11259. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11260. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11261. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11262. THREE.ShaderChunk[ "skinning_vertex" ],
  11263. THREE.ShaderChunk[ "default_vertex" ],
  11264. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11265. THREE.ShaderChunk[ "worldpos_vertex" ],
  11266. THREE.ShaderChunk[ "envmap_vertex" ],
  11267. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  11268. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11269. "}"
  11270. ].join("\n"),
  11271. fragmentShader: [
  11272. "uniform float opacity;",
  11273. "varying vec3 vLightFront;",
  11274. "#ifdef DOUBLE_SIDED",
  11275. " varying vec3 vLightBack;",
  11276. "#endif",
  11277. THREE.ShaderChunk[ "color_pars_fragment" ],
  11278. THREE.ShaderChunk[ "map_pars_fragment" ],
  11279. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11280. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11281. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11282. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11283. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11284. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11285. "void main() {",
  11286. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  11287. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11288. THREE.ShaderChunk[ "map_fragment" ],
  11289. THREE.ShaderChunk[ "alphatest_fragment" ],
  11290. THREE.ShaderChunk[ "specularmap_fragment" ],
  11291. " #ifdef DOUBLE_SIDED",
  11292. //"float isFront = float( gl_FrontFacing );",
  11293. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  11294. " if ( gl_FrontFacing )",
  11295. " gl_FragColor.xyz *= vLightFront;",
  11296. " else",
  11297. " gl_FragColor.xyz *= vLightBack;",
  11298. " #else",
  11299. " gl_FragColor.xyz *= vLightFront;",
  11300. " #endif",
  11301. THREE.ShaderChunk[ "lightmap_fragment" ],
  11302. THREE.ShaderChunk[ "color_fragment" ],
  11303. THREE.ShaderChunk[ "envmap_fragment" ],
  11304. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11305. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11306. THREE.ShaderChunk[ "fog_fragment" ],
  11307. "}"
  11308. ].join("\n")
  11309. },
  11310. 'phong': {
  11311. uniforms: THREE.UniformsUtils.merge( [
  11312. THREE.UniformsLib[ "common" ],
  11313. THREE.UniformsLib[ "bump" ],
  11314. THREE.UniformsLib[ "normalmap" ],
  11315. THREE.UniformsLib[ "fog" ],
  11316. THREE.UniformsLib[ "lights" ],
  11317. THREE.UniformsLib[ "shadowmap" ],
  11318. {
  11319. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  11320. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  11321. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  11322. "shininess": { type: "f", value: 30 },
  11323. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11324. }
  11325. ] ),
  11326. vertexShader: [
  11327. "#define PHONG",
  11328. "varying vec3 vViewPosition;",
  11329. "varying vec3 vNormal;",
  11330. THREE.ShaderChunk[ "map_pars_vertex" ],
  11331. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11332. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11333. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  11334. THREE.ShaderChunk[ "color_pars_vertex" ],
  11335. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11336. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11337. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11338. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11339. "void main() {",
  11340. THREE.ShaderChunk[ "map_vertex" ],
  11341. THREE.ShaderChunk[ "lightmap_vertex" ],
  11342. THREE.ShaderChunk[ "color_vertex" ],
  11343. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11344. THREE.ShaderChunk[ "skinbase_vertex" ],
  11345. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11346. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11347. " vNormal = normalize( transformedNormal );",
  11348. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11349. THREE.ShaderChunk[ "skinning_vertex" ],
  11350. THREE.ShaderChunk[ "default_vertex" ],
  11351. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11352. " vViewPosition = -mvPosition.xyz;",
  11353. THREE.ShaderChunk[ "worldpos_vertex" ],
  11354. THREE.ShaderChunk[ "envmap_vertex" ],
  11355. THREE.ShaderChunk[ "lights_phong_vertex" ],
  11356. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11357. "}"
  11358. ].join("\n"),
  11359. fragmentShader: [
  11360. "uniform vec3 diffuse;",
  11361. "uniform float opacity;",
  11362. "uniform vec3 ambient;",
  11363. "uniform vec3 emissive;",
  11364. "uniform vec3 specular;",
  11365. "uniform float shininess;",
  11366. THREE.ShaderChunk[ "color_pars_fragment" ],
  11367. THREE.ShaderChunk[ "map_pars_fragment" ],
  11368. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11369. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11370. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11371. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  11372. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11373. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  11374. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  11375. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11376. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11377. "void main() {",
  11378. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  11379. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11380. THREE.ShaderChunk[ "map_fragment" ],
  11381. THREE.ShaderChunk[ "alphatest_fragment" ],
  11382. THREE.ShaderChunk[ "specularmap_fragment" ],
  11383. THREE.ShaderChunk[ "lights_phong_fragment" ],
  11384. THREE.ShaderChunk[ "lightmap_fragment" ],
  11385. THREE.ShaderChunk[ "color_fragment" ],
  11386. THREE.ShaderChunk[ "envmap_fragment" ],
  11387. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11388. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11389. THREE.ShaderChunk[ "fog_fragment" ],
  11390. "}"
  11391. ].join("\n")
  11392. },
  11393. 'particle_basic': {
  11394. uniforms: THREE.UniformsUtils.merge( [
  11395. THREE.UniformsLib[ "particle" ],
  11396. THREE.UniformsLib[ "shadowmap" ]
  11397. ] ),
  11398. vertexShader: [
  11399. "uniform float size;",
  11400. "uniform float scale;",
  11401. THREE.ShaderChunk[ "color_pars_vertex" ],
  11402. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11403. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11404. "void main() {",
  11405. THREE.ShaderChunk[ "color_vertex" ],
  11406. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11407. " #ifdef USE_SIZEATTENUATION",
  11408. " gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  11409. " #else",
  11410. " gl_PointSize = size;",
  11411. " #endif",
  11412. " gl_Position = projectionMatrix * mvPosition;",
  11413. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11414. THREE.ShaderChunk[ "worldpos_vertex" ],
  11415. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11416. "}"
  11417. ].join("\n"),
  11418. fragmentShader: [
  11419. "uniform vec3 psColor;",
  11420. "uniform float opacity;",
  11421. THREE.ShaderChunk[ "color_pars_fragment" ],
  11422. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  11423. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11424. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11425. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11426. "void main() {",
  11427. " gl_FragColor = vec4( psColor, opacity );",
  11428. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11429. THREE.ShaderChunk[ "map_particle_fragment" ],
  11430. THREE.ShaderChunk[ "alphatest_fragment" ],
  11431. THREE.ShaderChunk[ "color_fragment" ],
  11432. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11433. THREE.ShaderChunk[ "fog_fragment" ],
  11434. "}"
  11435. ].join("\n")
  11436. },
  11437. 'dashed': {
  11438. uniforms: THREE.UniformsUtils.merge( [
  11439. THREE.UniformsLib[ "common" ],
  11440. THREE.UniformsLib[ "fog" ],
  11441. {
  11442. "scale" : { type: "f", value: 1 },
  11443. "dashSize" : { type: "f", value: 1 },
  11444. "totalSize": { type: "f", value: 2 }
  11445. }
  11446. ] ),
  11447. vertexShader: [
  11448. "uniform float scale;",
  11449. "attribute float lineDistance;",
  11450. "varying float vLineDistance;",
  11451. THREE.ShaderChunk[ "color_pars_vertex" ],
  11452. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11453. "void main() {",
  11454. THREE.ShaderChunk[ "color_vertex" ],
  11455. " vLineDistance = scale * lineDistance;",
  11456. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11457. " gl_Position = projectionMatrix * mvPosition;",
  11458. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11459. "}"
  11460. ].join("\n"),
  11461. fragmentShader: [
  11462. "uniform vec3 diffuse;",
  11463. "uniform float opacity;",
  11464. "uniform float dashSize;",
  11465. "uniform float totalSize;",
  11466. "varying float vLineDistance;",
  11467. THREE.ShaderChunk[ "color_pars_fragment" ],
  11468. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11469. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11470. "void main() {",
  11471. " if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  11472. " discard;",
  11473. " }",
  11474. " gl_FragColor = vec4( diffuse, opacity );",
  11475. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11476. THREE.ShaderChunk[ "color_fragment" ],
  11477. THREE.ShaderChunk[ "fog_fragment" ],
  11478. "}"
  11479. ].join("\n")
  11480. },
  11481. 'depth': {
  11482. uniforms: {
  11483. "mNear": { type: "f", value: 1.0 },
  11484. "mFar" : { type: "f", value: 2000.0 },
  11485. "opacity" : { type: "f", value: 1.0 }
  11486. },
  11487. vertexShader: [
  11488. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11489. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11490. "void main() {",
  11491. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11492. THREE.ShaderChunk[ "default_vertex" ],
  11493. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11494. "}"
  11495. ].join("\n"),
  11496. fragmentShader: [
  11497. "uniform float mNear;",
  11498. "uniform float mFar;",
  11499. "uniform float opacity;",
  11500. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11501. "void main() {",
  11502. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11503. " #ifdef USE_LOGDEPTHBUF_EXT",
  11504. " float depth = gl_FragDepthEXT / gl_FragCoord.w;",
  11505. " #else",
  11506. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  11507. " #endif",
  11508. " float color = 1.0 - smoothstep( mNear, mFar, depth );",
  11509. " gl_FragColor = vec4( vec3( color ), opacity );",
  11510. "}"
  11511. ].join("\n")
  11512. },
  11513. 'normal': {
  11514. uniforms: {
  11515. "opacity" : { type: "f", value: 1.0 }
  11516. },
  11517. vertexShader: [
  11518. "varying vec3 vNormal;",
  11519. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11520. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11521. "void main() {",
  11522. " vNormal = normalize( normalMatrix * normal );",
  11523. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11524. THREE.ShaderChunk[ "default_vertex" ],
  11525. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11526. "}"
  11527. ].join("\n"),
  11528. fragmentShader: [
  11529. "uniform float opacity;",
  11530. "varying vec3 vNormal;",
  11531. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11532. "void main() {",
  11533. " gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  11534. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11535. "}"
  11536. ].join("\n")
  11537. },
  11538. /* -------------------------------------------------------------------------
  11539. // Normal map shader
  11540. // - Blinn-Phong
  11541. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  11542. // - point and directional lights (use with "lights: true" material option)
  11543. ------------------------------------------------------------------------- */
  11544. 'normalmap' : {
  11545. uniforms: THREE.UniformsUtils.merge( [
  11546. THREE.UniformsLib[ "fog" ],
  11547. THREE.UniformsLib[ "lights" ],
  11548. THREE.UniformsLib[ "shadowmap" ],
  11549. {
  11550. "enableAO" : { type: "i", value: 0 },
  11551. "enableDiffuse" : { type: "i", value: 0 },
  11552. "enableSpecular" : { type: "i", value: 0 },
  11553. "enableReflection" : { type: "i", value: 0 },
  11554. "enableDisplacement": { type: "i", value: 0 },
  11555. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  11556. "tDiffuse" : { type: "t", value: null },
  11557. "tCube" : { type: "t", value: null },
  11558. "tNormal" : { type: "t", value: null },
  11559. "tSpecular" : { type: "t", value: null },
  11560. "tAO" : { type: "t", value: null },
  11561. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11562. "uDisplacementBias": { type: "f", value: 0.0 },
  11563. "uDisplacementScale": { type: "f", value: 1.0 },
  11564. "diffuse": { type: "c", value: new THREE.Color( 0xffffff ) },
  11565. "specular": { type: "c", value: new THREE.Color( 0x111111 ) },
  11566. "ambient": { type: "c", value: new THREE.Color( 0xffffff ) },
  11567. "shininess": { type: "f", value: 30 },
  11568. "opacity": { type: "f", value: 1 },
  11569. "useRefract": { type: "i", value: 0 },
  11570. "refractionRatio": { type: "f", value: 0.98 },
  11571. "reflectivity": { type: "f", value: 0.5 },
  11572. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  11573. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11574. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11575. }
  11576. ] ),
  11577. fragmentShader: [
  11578. "uniform vec3 ambient;",
  11579. "uniform vec3 diffuse;",
  11580. "uniform vec3 specular;",
  11581. "uniform float shininess;",
  11582. "uniform float opacity;",
  11583. "uniform bool enableDiffuse;",
  11584. "uniform bool enableSpecular;",
  11585. "uniform bool enableAO;",
  11586. "uniform bool enableReflection;",
  11587. "uniform sampler2D tDiffuse;",
  11588. "uniform sampler2D tNormal;",
  11589. "uniform sampler2D tSpecular;",
  11590. "uniform sampler2D tAO;",
  11591. "uniform samplerCube tCube;",
  11592. "uniform vec2 uNormalScale;",
  11593. "uniform bool useRefract;",
  11594. "uniform float refractionRatio;",
  11595. "uniform float reflectivity;",
  11596. "varying vec3 vTangent;",
  11597. "varying vec3 vBinormal;",
  11598. "varying vec3 vNormal;",
  11599. "varying vec2 vUv;",
  11600. "uniform vec3 ambientLightColor;",
  11601. "#if MAX_DIR_LIGHTS > 0",
  11602. " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11603. " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11604. "#endif",
  11605. "#if MAX_HEMI_LIGHTS > 0",
  11606. " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  11607. " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  11608. " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  11609. "#endif",
  11610. "#if MAX_POINT_LIGHTS > 0",
  11611. " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11612. " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11613. " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11614. "#endif",
  11615. "#if MAX_SPOT_LIGHTS > 0",
  11616. " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  11617. " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  11618. " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  11619. " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  11620. " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  11621. " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  11622. "#endif",
  11623. "#ifdef WRAP_AROUND",
  11624. " uniform vec3 wrapRGB;",
  11625. "#endif",
  11626. "varying vec3 vWorldPosition;",
  11627. "varying vec3 vViewPosition;",
  11628. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11629. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11630. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11631. "void main() {",
  11632. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11633. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  11634. " vec3 specularTex = vec3( 1.0 );",
  11635. " vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  11636. " normalTex.xy *= uNormalScale;",
  11637. " normalTex = normalize( normalTex );",
  11638. " if( enableDiffuse ) {",
  11639. " #ifdef GAMMA_INPUT",
  11640. " vec4 texelColor = texture2D( tDiffuse, vUv );",
  11641. " texelColor.xyz *= texelColor.xyz;",
  11642. " gl_FragColor = gl_FragColor * texelColor;",
  11643. " #else",
  11644. " gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  11645. " #endif",
  11646. " }",
  11647. " if( enableAO ) {",
  11648. " #ifdef GAMMA_INPUT",
  11649. " vec4 aoColor = texture2D( tAO, vUv );",
  11650. " aoColor.xyz *= aoColor.xyz;",
  11651. " gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  11652. " #else",
  11653. " gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  11654. " #endif",
  11655. " }",
  11656. " if( enableSpecular )",
  11657. " specularTex = texture2D( tSpecular, vUv ).xyz;",
  11658. " mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  11659. " vec3 finalNormal = tsb * normalTex;",
  11660. " #ifdef FLIP_SIDED",
  11661. " finalNormal = -finalNormal;",
  11662. " #endif",
  11663. " vec3 normal = normalize( finalNormal );",
  11664. " vec3 viewPosition = normalize( vViewPosition );",
  11665. // point lights
  11666. " #if MAX_POINT_LIGHTS > 0",
  11667. " vec3 pointDiffuse = vec3( 0.0 );",
  11668. " vec3 pointSpecular = vec3( 0.0 );",
  11669. " for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11670. " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11671. " vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  11672. " float pointDistance = 1.0;",
  11673. " if ( pointLightDistance[ i ] > 0.0 )",
  11674. " pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  11675. " pointVector = normalize( pointVector );",
  11676. // diffuse
  11677. " #ifdef WRAP_AROUND",
  11678. " float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  11679. " float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  11680. " vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11681. " #else",
  11682. " float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  11683. " #endif",
  11684. " pointDiffuse += pointDistance * pointLightColor[ i ] * diffuse * pointDiffuseWeight;",
  11685. // specular
  11686. " vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  11687. " float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11688. " float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  11689. " float specularNormalization = ( shininess + 2.0 ) / 8.0;",
  11690. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( pointVector, pointHalfVector ), 0.0 ), 5.0 );",
  11691. " pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  11692. " }",
  11693. " #endif",
  11694. // spot lights
  11695. " #if MAX_SPOT_LIGHTS > 0",
  11696. " vec3 spotDiffuse = vec3( 0.0 );",
  11697. " vec3 spotSpecular = vec3( 0.0 );",
  11698. " for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  11699. " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  11700. " vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  11701. " float spotDistance = 1.0;",
  11702. " if ( spotLightDistance[ i ] > 0.0 )",
  11703. " spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  11704. " spotVector = normalize( spotVector );",
  11705. " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  11706. " if ( spotEffect > spotLightAngleCos[ i ] ) {",
  11707. " spotEffect = max( pow( max( spotEffect, 0.0 ), spotLightExponent[ i ] ), 0.0 );",
  11708. // diffuse
  11709. " #ifdef WRAP_AROUND",
  11710. " float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  11711. " float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  11712. " vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  11713. " #else",
  11714. " float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  11715. " #endif",
  11716. " spotDiffuse += spotDistance * spotLightColor[ i ] * diffuse * spotDiffuseWeight * spotEffect;",
  11717. // specular
  11718. " vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  11719. " float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  11720. " float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  11721. " float specularNormalization = ( shininess + 2.0 ) / 8.0;",
  11722. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( spotVector, spotHalfVector ), 0.0 ), 5.0 );",
  11723. " spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  11724. " }",
  11725. " }",
  11726. " #endif",
  11727. // directional lights
  11728. " #if MAX_DIR_LIGHTS > 0",
  11729. " vec3 dirDiffuse = vec3( 0.0 );",
  11730. " vec3 dirSpecular = vec3( 0.0 );",
  11731. " for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  11732. " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11733. " vec3 dirVector = normalize( lDirection.xyz );",
  11734. // diffuse
  11735. " #ifdef WRAP_AROUND",
  11736. " float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  11737. " float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  11738. " vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  11739. " #else",
  11740. " float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  11741. " #endif",
  11742. " dirDiffuse += directionalLightColor[ i ] * diffuse * dirDiffuseWeight;",
  11743. // specular
  11744. " vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11745. " float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11746. " float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  11747. " float specularNormalization = ( shininess + 2.0 ) / 8.0;",
  11748. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( dirVector, dirHalfVector ), 0.0 ), 5.0 );",
  11749. " dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11750. " }",
  11751. " #endif",
  11752. // hemisphere lights
  11753. " #if MAX_HEMI_LIGHTS > 0",
  11754. " vec3 hemiDiffuse = vec3( 0.0 );",
  11755. " vec3 hemiSpecular = vec3( 0.0 );" ,
  11756. " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  11757. " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  11758. " vec3 lVector = normalize( lDirection.xyz );",
  11759. // diffuse
  11760. " float dotProduct = dot( normal, lVector );",
  11761. " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  11762. " vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  11763. " hemiDiffuse += diffuse * hemiColor;",
  11764. // specular (sky light)
  11765. " vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  11766. " float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  11767. " float hemiSpecularWeightSky = specularTex.r * max( pow( max( hemiDotNormalHalfSky, 0.0 ), shininess ), 0.0 );",
  11768. // specular (ground light)
  11769. " vec3 lVectorGround = -lVector;",
  11770. " vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  11771. " float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  11772. " float hemiSpecularWeightGround = specularTex.r * max( pow( max( hemiDotNormalHalfGround, 0.0 ), shininess ), 0.0 );",
  11773. " float dotProductGround = dot( normal, lVectorGround );",
  11774. " float specularNormalization = ( shininess + 2.0 ) / 8.0;",
  11775. " vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, hemiHalfVectorSky ), 0.0 ), 5.0 );",
  11776. " vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 0.0 ), 5.0 );",
  11777. " hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  11778. " }",
  11779. " #endif",
  11780. // all lights contribution summation
  11781. " vec3 totalDiffuse = vec3( 0.0 );",
  11782. " vec3 totalSpecular = vec3( 0.0 );",
  11783. " #if MAX_DIR_LIGHTS > 0",
  11784. " totalDiffuse += dirDiffuse;",
  11785. " totalSpecular += dirSpecular;",
  11786. " #endif",
  11787. " #if MAX_HEMI_LIGHTS > 0",
  11788. " totalDiffuse += hemiDiffuse;",
  11789. " totalSpecular += hemiSpecular;",
  11790. " #endif",
  11791. " #if MAX_POINT_LIGHTS > 0",
  11792. " totalDiffuse += pointDiffuse;",
  11793. " totalSpecular += pointSpecular;",
  11794. " #endif",
  11795. " #if MAX_SPOT_LIGHTS > 0",
  11796. " totalDiffuse += spotDiffuse;",
  11797. " totalSpecular += spotSpecular;",
  11798. " #endif",
  11799. " #ifdef METAL",
  11800. " gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  11801. " #else",
  11802. " gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  11803. " #endif",
  11804. " if ( enableReflection ) {",
  11805. " vec3 vReflect;",
  11806. " vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  11807. " if ( useRefract ) {",
  11808. " vReflect = refract( cameraToVertex, normal, refractionRatio );",
  11809. " } else {",
  11810. " vReflect = reflect( cameraToVertex, normal );",
  11811. " }",
  11812. " vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  11813. " #ifdef GAMMA_INPUT",
  11814. " cubeColor.xyz *= cubeColor.xyz;",
  11815. " #endif",
  11816. " gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * reflectivity );",
  11817. " }",
  11818. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11819. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11820. THREE.ShaderChunk[ "fog_fragment" ],
  11821. "}"
  11822. ].join("\n"),
  11823. vertexShader: [
  11824. "attribute vec4 tangent;",
  11825. "uniform vec2 uOffset;",
  11826. "uniform vec2 uRepeat;",
  11827. "uniform bool enableDisplacement;",
  11828. "#ifdef VERTEX_TEXTURES",
  11829. " uniform sampler2D tDisplacement;",
  11830. " uniform float uDisplacementScale;",
  11831. " uniform float uDisplacementBias;",
  11832. "#endif",
  11833. "varying vec3 vTangent;",
  11834. "varying vec3 vBinormal;",
  11835. "varying vec3 vNormal;",
  11836. "varying vec2 vUv;",
  11837. "varying vec3 vWorldPosition;",
  11838. "varying vec3 vViewPosition;",
  11839. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11840. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11841. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11842. "void main() {",
  11843. THREE.ShaderChunk[ "skinbase_vertex" ],
  11844. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11845. // normal, tangent and binormal vectors
  11846. " #ifdef USE_SKINNING",
  11847. " vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  11848. " vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  11849. " vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  11850. " #else",
  11851. " vNormal = normalize( normalMatrix * normal );",
  11852. " vTangent = normalize( normalMatrix * tangent.xyz );",
  11853. " #endif",
  11854. " vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  11855. " vUv = uv * uRepeat + uOffset;",
  11856. // displacement mapping
  11857. " vec3 displacedPosition;",
  11858. " #ifdef VERTEX_TEXTURES",
  11859. " if ( enableDisplacement ) {",
  11860. " vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  11861. " float df = uDisplacementScale * dv.x + uDisplacementBias;",
  11862. " displacedPosition = position + normalize( normal ) * df;",
  11863. " } else {",
  11864. " #ifdef USE_SKINNING",
  11865. " vec4 skinVertex = vec4( position, 1.0 );",
  11866. " vec4 skinned = vec4( 0.0 );",
  11867. " skinned += boneMatX * skinVertex * skinWeight.x;",
  11868. " skinned += boneMatY * skinVertex * skinWeight.y;",
  11869. " skinned += boneMatZ * skinVertex * skinWeight.z;",
  11870. " skinned += boneMatW * skinVertex * skinWeight.w;",
  11871. " displacedPosition = skinned.xyz;",
  11872. " #else",
  11873. " displacedPosition = position;",
  11874. " #endif",
  11875. " }",
  11876. " #else",
  11877. " #ifdef USE_SKINNING",
  11878. " vec4 skinVertex = vec4( position, 1.0 );",
  11879. " vec4 skinned = vec4( 0.0 );",
  11880. " skinned += boneMatX * skinVertex * skinWeight.x;",
  11881. " skinned += boneMatY * skinVertex * skinWeight.y;",
  11882. " skinned += boneMatZ * skinVertex * skinWeight.z;",
  11883. " skinned += boneMatW * skinVertex * skinWeight.w;",
  11884. " displacedPosition = skinned.xyz;",
  11885. " #else",
  11886. " displacedPosition = position;",
  11887. " #endif",
  11888. " #endif",
  11889. //
  11890. " vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  11891. " vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  11892. " gl_Position = projectionMatrix * mvPosition;",
  11893. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11894. //
  11895. " vWorldPosition = worldPosition.xyz;",
  11896. " vViewPosition = -mvPosition.xyz;",
  11897. // shadows
  11898. " #ifdef USE_SHADOWMAP",
  11899. " for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11900. " vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11901. " }",
  11902. " #endif",
  11903. "}"
  11904. ].join("\n")
  11905. },
  11906. /* -------------------------------------------------------------------------
  11907. // Cube map shader
  11908. ------------------------------------------------------------------------- */
  11909. 'cube': {
  11910. uniforms: { "tCube": { type: "t", value: null },
  11911. "tFlip": { type: "f", value: - 1 } },
  11912. vertexShader: [
  11913. "varying vec3 vWorldPosition;",
  11914. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11915. "void main() {",
  11916. " vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  11917. " vWorldPosition = worldPosition.xyz;",
  11918. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11919. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11920. "}"
  11921. ].join("\n"),
  11922. fragmentShader: [
  11923. "uniform samplerCube tCube;",
  11924. "uniform float tFlip;",
  11925. "varying vec3 vWorldPosition;",
  11926. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11927. "void main() {",
  11928. " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  11929. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11930. "}"
  11931. ].join("\n")
  11932. },
  11933. /* Depth encoding into RGBA texture
  11934. *
  11935. * based on SpiderGL shadow map example
  11936. * http://spidergl.org/example.php?id=6
  11937. *
  11938. * originally from
  11939. * http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  11940. *
  11941. * see also
  11942. * http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  11943. */
  11944. 'depthRGBA': {
  11945. uniforms: {},
  11946. vertexShader: [
  11947. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11948. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11949. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11950. "void main() {",
  11951. THREE.ShaderChunk[ "skinbase_vertex" ],
  11952. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11953. THREE.ShaderChunk[ "skinning_vertex" ],
  11954. THREE.ShaderChunk[ "default_vertex" ],
  11955. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11956. "}"
  11957. ].join("\n"),
  11958. fragmentShader: [
  11959. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11960. "vec4 pack_depth( const in float depth ) {",
  11961. " const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  11962. " const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  11963. " vec4 res = mod( depth * bit_shift * vec4( 255 ), vec4( 256 ) ) / vec4( 255 );", // " vec4 res = fract( depth * bit_shift );",
  11964. " res -= res.xxyz * bit_mask;",
  11965. " return res;",
  11966. "}",
  11967. "void main() {",
  11968. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11969. " #ifdef USE_LOGDEPTHBUF_EXT",
  11970. " gl_FragData[ 0 ] = pack_depth( gl_FragDepthEXT );",
  11971. " #else",
  11972. " gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  11973. " #endif",
  11974. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  11975. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  11976. //"gl_FragData[ 0 ] = pack_depth( z );",
  11977. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  11978. "}"
  11979. ].join("\n")
  11980. }
  11981. };
  11982. // File:src/renderers/WebGLRenderer.js
  11983. /**
  11984. * @author supereggbert / http://www.paulbrunt.co.uk/
  11985. * @author mrdoob / http://mrdoob.com/
  11986. * @author alteredq / http://alteredqualia.com/
  11987. * @author szimek / https://github.com/szimek/
  11988. */
  11989. THREE.WebGLRenderer = function ( parameters ) {
  11990. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  11991. parameters = parameters || {};
  11992. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  11993. _context = parameters.context !== undefined ? parameters.context : null,
  11994. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  11995. _buffers = {},
  11996. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  11997. _depth = parameters.depth !== undefined ? parameters.depth : true,
  11998. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11999. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  12000. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  12001. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  12002. _logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false,
  12003. _clearColor = new THREE.Color( 0x000000 ),
  12004. _clearAlpha = 0;
  12005. var opaqueObjects = [];
  12006. var transparentObjects = [];
  12007. var _sortObjects = true;
  12008. // public properties
  12009. this.domElement = _canvas;
  12010. this.context = null;
  12011. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  12012. ? parameters.devicePixelRatio
  12013. : self.devicePixelRatio !== undefined
  12014. ? self.devicePixelRatio
  12015. : 1;
  12016. // clearing
  12017. this.autoClear = true;
  12018. this.autoClearColor = true;
  12019. this.autoClearDepth = true;
  12020. this.autoClearStencil = true;
  12021. // scene graph
  12022. this.sortObjects = true;
  12023. this.autoUpdateObjects = true;
  12024. // physically based shading
  12025. this.gammaInput = false;
  12026. this.gammaOutput = false;
  12027. // shadow map
  12028. this.shadowMapEnabled = false;
  12029. this.shadowMapAutoUpdate = true;
  12030. this.shadowMapType = THREE.PCFShadowMap;
  12031. this.shadowMapCullFace = THREE.CullFaceFront;
  12032. this.shadowMapDebug = false;
  12033. this.shadowMapCascade = false;
  12034. // morphs
  12035. this.maxMorphTargets = 8;
  12036. this.maxMorphNormals = 4;
  12037. // flags
  12038. this.autoScaleCubemaps = true;
  12039. // custom render plugins
  12040. this.renderPluginsPre = [];
  12041. this.renderPluginsPost = [];
  12042. // info
  12043. this.info = {
  12044. memory: {
  12045. programs: 0,
  12046. geometries: 0,
  12047. textures: 0
  12048. },
  12049. render: {
  12050. calls: 0,
  12051. vertices: 0,
  12052. faces: 0,
  12053. points: 0
  12054. }
  12055. };
  12056. // internal properties
  12057. var _this = this,
  12058. _programs = [],
  12059. // internal state cache
  12060. _currentProgram = null,
  12061. _currentFramebuffer = null,
  12062. _currentMaterialId = - 1,
  12063. _currentGeometryGroupHash = null,
  12064. _currentCamera = null,
  12065. _usedTextureUnits = 0,
  12066. // GL state cache
  12067. _oldDoubleSided = - 1,
  12068. _oldFlipSided = - 1,
  12069. _oldBlending = - 1,
  12070. _oldBlendEquation = - 1,
  12071. _oldBlendSrc = - 1,
  12072. _oldBlendDst = - 1,
  12073. _oldDepthTest = - 1,
  12074. _oldDepthWrite = - 1,
  12075. _oldPolygonOffset = null,
  12076. _oldPolygonOffsetFactor = null,
  12077. _oldPolygonOffsetUnits = null,
  12078. _oldLineWidth = null,
  12079. _viewportX = 0,
  12080. _viewportY = 0,
  12081. _viewportWidth = _canvas.width,
  12082. _viewportHeight = _canvas.height,
  12083. _currentWidth = 0,
  12084. _currentHeight = 0,
  12085. _newAttributes = new Uint8Array( 16 ),
  12086. _enabledAttributes = new Uint8Array( 16 ),
  12087. // frustum
  12088. _frustum = new THREE.Frustum(),
  12089. // camera matrices cache
  12090. _projScreenMatrix = new THREE.Matrix4(),
  12091. _projScreenMatrixPS = new THREE.Matrix4(),
  12092. _vector3 = new THREE.Vector3(),
  12093. // light arrays cache
  12094. _direction = new THREE.Vector3(),
  12095. _lightsNeedUpdate = true,
  12096. _lights = {
  12097. ambient: [ 0, 0, 0 ],
  12098. directional: { length: 0, colors: new Array(), positions: new Array() },
  12099. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  12100. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  12101. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  12102. };
  12103. // initialize
  12104. var _gl;
  12105. var _glExtensionTextureFloat;
  12106. var _glExtensionTextureFloatLinear;
  12107. var _glExtensionStandardDerivatives;
  12108. var _glExtensionTextureFilterAnisotropic;
  12109. var _glExtensionCompressedTextureS3TC;
  12110. var _glExtensionElementIndexUint;
  12111. var _glExtensionFragDepth;
  12112. initGL();
  12113. setDefaultGLState();
  12114. this.context = _gl;
  12115. // GPU capabilities
  12116. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  12117. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  12118. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  12119. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  12120. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  12121. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  12122. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  12123. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  12124. //
  12125. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  12126. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  12127. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  12128. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  12129. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  12130. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  12131. /*
  12132. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  12133. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  12134. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  12135. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  12136. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  12137. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  12138. */
  12139. // clamp precision to maximum available
  12140. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  12141. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  12142. if ( _precision === 'highp' && ! highpAvailable ) {
  12143. if ( mediumpAvailable ) {
  12144. _precision = 'mediump';
  12145. console.warn( 'THREE.WebGLRenderer: highp not supported, using mediump.' );
  12146. } else {
  12147. _precision = 'lowp';
  12148. console.warn( 'THREE.WebGLRenderer: highp and mediump not supported, using lowp.' );
  12149. }
  12150. }
  12151. if ( _precision === 'mediump' && ! mediumpAvailable ) {
  12152. _precision = 'lowp';
  12153. console.warn( 'THREE.WebGLRenderer: mediump not supported, using lowp.' );
  12154. }
  12155. // API
  12156. this.getContext = function () {
  12157. return _gl;
  12158. };
  12159. this.supportsVertexTextures = function () {
  12160. return _supportsVertexTextures;
  12161. };
  12162. this.supportsFloatTextures = function () {
  12163. return _glExtensionTextureFloat;
  12164. };
  12165. this.supportsStandardDerivatives = function () {
  12166. return _glExtensionStandardDerivatives;
  12167. };
  12168. this.supportsCompressedTextureS3TC = function () {
  12169. return _glExtensionCompressedTextureS3TC;
  12170. };
  12171. this.getMaxAnisotropy = function () {
  12172. return _maxAnisotropy;
  12173. };
  12174. this.getPrecision = function () {
  12175. return _precision;
  12176. };
  12177. this.setSize = function ( width, height, updateStyle ) {
  12178. _canvas.width = width * this.devicePixelRatio;
  12179. _canvas.height = height * this.devicePixelRatio;
  12180. if ( updateStyle !== false ) {
  12181. _canvas.style.width = width + 'px';
  12182. _canvas.style.height = height + 'px';
  12183. }
  12184. this.setViewport( 0, 0, width, height );
  12185. };
  12186. this.setViewport = function ( x, y, width, height ) {
  12187. _viewportX = x * this.devicePixelRatio;
  12188. _viewportY = y * this.devicePixelRatio;
  12189. _viewportWidth = width * this.devicePixelRatio;
  12190. _viewportHeight = height * this.devicePixelRatio;
  12191. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  12192. };
  12193. this.setScissor = function ( x, y, width, height ) {
  12194. _gl.scissor(
  12195. x * this.devicePixelRatio,
  12196. y * this.devicePixelRatio,
  12197. width * this.devicePixelRatio,
  12198. height * this.devicePixelRatio
  12199. );
  12200. };
  12201. this.enableScissorTest = function ( enable ) {
  12202. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  12203. };
  12204. // Clearing
  12205. this.setClearColor = function ( color, alpha ) {
  12206. _clearColor.set( color );
  12207. _clearAlpha = alpha !== undefined ? alpha : 1;
  12208. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  12209. };
  12210. this.setClearColorHex = function ( hex, alpha ) {
  12211. console.warn( 'THREE.WebGLRenderer: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  12212. this.setClearColor( hex, alpha );
  12213. };
  12214. this.getClearColor = function () {
  12215. return _clearColor;
  12216. };
  12217. this.getClearAlpha = function () {
  12218. return _clearAlpha;
  12219. };
  12220. this.clear = function ( color, depth, stencil ) {
  12221. var bits = 0;
  12222. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  12223. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  12224. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  12225. _gl.clear( bits );
  12226. };
  12227. this.clearColor = function () {
  12228. _gl.clear( _gl.COLOR_BUFFER_BIT );
  12229. };
  12230. this.clearDepth = function () {
  12231. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  12232. };
  12233. this.clearStencil = function () {
  12234. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  12235. };
  12236. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  12237. this.setRenderTarget( renderTarget );
  12238. this.clear( color, depth, stencil );
  12239. };
  12240. // Plugins
  12241. this.addPostPlugin = function ( plugin ) {
  12242. plugin.init( this );
  12243. this.renderPluginsPost.push( plugin );
  12244. };
  12245. this.addPrePlugin = function ( plugin ) {
  12246. plugin.init( this );
  12247. this.renderPluginsPre.push( plugin );
  12248. };
  12249. // Rendering
  12250. this.updateShadowMap = function ( scene, camera ) {
  12251. _currentProgram = null;
  12252. _oldBlending = - 1;
  12253. _oldDepthTest = - 1;
  12254. _oldDepthWrite = - 1;
  12255. _currentGeometryGroupHash = - 1;
  12256. _currentMaterialId = - 1;
  12257. _lightsNeedUpdate = true;
  12258. _oldDoubleSided = - 1;
  12259. _oldFlipSided = - 1;
  12260. this.shadowMapPlugin.update( scene, camera );
  12261. };
  12262. // Internal functions
  12263. // Buffer allocation
  12264. function createParticleBuffers ( geometry ) {
  12265. geometry.__webglVertexBuffer = _gl.createBuffer();
  12266. geometry.__webglColorBuffer = _gl.createBuffer();
  12267. _this.info.memory.geometries ++;
  12268. };
  12269. function createLineBuffers ( geometry ) {
  12270. geometry.__webglVertexBuffer = _gl.createBuffer();
  12271. geometry.__webglColorBuffer = _gl.createBuffer();
  12272. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  12273. _this.info.memory.geometries ++;
  12274. };
  12275. function createMeshBuffers ( geometryGroup ) {
  12276. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  12277. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  12278. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  12279. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  12280. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  12281. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  12282. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  12283. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  12284. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  12285. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  12286. var m, ml;
  12287. if ( geometryGroup.numMorphTargets ) {
  12288. geometryGroup.__webglMorphTargetsBuffers = [];
  12289. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12290. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  12291. }
  12292. }
  12293. if ( geometryGroup.numMorphNormals ) {
  12294. geometryGroup.__webglMorphNormalsBuffers = [];
  12295. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12296. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  12297. }
  12298. }
  12299. _this.info.memory.geometries ++;
  12300. };
  12301. // Events
  12302. var onGeometryDispose = function ( event ) {
  12303. var geometry = event.target;
  12304. geometry.removeEventListener( 'dispose', onGeometryDispose );
  12305. deallocateGeometry( geometry );
  12306. };
  12307. var onTextureDispose = function ( event ) {
  12308. var texture = event.target;
  12309. texture.removeEventListener( 'dispose', onTextureDispose );
  12310. deallocateTexture( texture );
  12311. _this.info.memory.textures --;
  12312. };
  12313. var onRenderTargetDispose = function ( event ) {
  12314. var renderTarget = event.target;
  12315. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  12316. deallocateRenderTarget( renderTarget );
  12317. _this.info.memory.textures --;
  12318. };
  12319. var onMaterialDispose = function ( event ) {
  12320. var material = event.target;
  12321. material.removeEventListener( 'dispose', onMaterialDispose );
  12322. deallocateMaterial( material );
  12323. };
  12324. // Buffer deallocation
  12325. var deleteBuffers = function ( geometry ) {
  12326. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  12327. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  12328. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  12329. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  12330. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  12331. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  12332. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  12333. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  12334. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  12335. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  12336. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  12337. // custom attributes
  12338. if ( geometry.__webglCustomAttributesList !== undefined ) {
  12339. for ( var id in geometry.__webglCustomAttributesList ) {
  12340. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  12341. }
  12342. }
  12343. _this.info.memory.geometries --;
  12344. };
  12345. var deallocateGeometry = function ( geometry ) {
  12346. geometry.__webglInit = undefined;
  12347. if ( geometry instanceof THREE.BufferGeometry ) {
  12348. var attributes = geometry.attributes;
  12349. for ( var key in attributes ) {
  12350. if ( attributes[ key ].buffer !== undefined ) {
  12351. _gl.deleteBuffer( attributes[ key ].buffer );
  12352. }
  12353. }
  12354. _this.info.memory.geometries --;
  12355. } else {
  12356. if ( geometry.geometryGroups !== undefined ) {
  12357. for ( var i = 0,l = geometry.geometryGroupsList.length; i<l;i++ ) {
  12358. var geometryGroup = geometry.geometryGroupsList[ i ];
  12359. if ( geometryGroup.numMorphTargets !== undefined ) {
  12360. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12361. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  12362. }
  12363. }
  12364. if ( geometryGroup.numMorphNormals !== undefined ) {
  12365. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12366. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  12367. }
  12368. }
  12369. deleteBuffers( geometryGroup );
  12370. }
  12371. } else {
  12372. deleteBuffers( geometry );
  12373. }
  12374. }
  12375. };
  12376. var deallocateTexture = function ( texture ) {
  12377. if ( texture.image && texture.image.__webglTextureCube ) {
  12378. // cube texture
  12379. _gl.deleteTexture( texture.image.__webglTextureCube );
  12380. } else {
  12381. // 2D texture
  12382. if ( ! texture.__webglInit ) return;
  12383. texture.__webglInit = false;
  12384. _gl.deleteTexture( texture.__webglTexture );
  12385. }
  12386. };
  12387. var deallocateRenderTarget = function ( renderTarget ) {
  12388. if ( ! renderTarget || ! renderTarget.__webglTexture ) return;
  12389. _gl.deleteTexture( renderTarget.__webglTexture );
  12390. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  12391. for ( var i = 0; i < 6; i ++ ) {
  12392. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  12393. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  12394. }
  12395. } else {
  12396. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  12397. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  12398. }
  12399. };
  12400. var deallocateMaterial = function ( material ) {
  12401. var program = material.program.program;
  12402. if ( program === undefined ) return;
  12403. material.program = undefined;
  12404. // only deallocate GL program if this was the last use of shared program
  12405. // assumed there is only single copy of any program in the _programs list
  12406. // (that's how it's constructed)
  12407. var i, il, programInfo;
  12408. var deleteProgram = false;
  12409. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12410. programInfo = _programs[ i ];
  12411. if ( programInfo.program === program ) {
  12412. programInfo.usedTimes --;
  12413. if ( programInfo.usedTimes === 0 ) {
  12414. deleteProgram = true;
  12415. }
  12416. break;
  12417. }
  12418. }
  12419. if ( deleteProgram === true ) {
  12420. // avoid using array.splice, this is costlier than creating new array from scratch
  12421. var newPrograms = [];
  12422. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12423. programInfo = _programs[ i ];
  12424. if ( programInfo.program !== program ) {
  12425. newPrograms.push( programInfo );
  12426. }
  12427. }
  12428. _programs = newPrograms;
  12429. _gl.deleteProgram( program );
  12430. _this.info.memory.programs --;
  12431. }
  12432. };
  12433. // Buffer initialization
  12434. function initCustomAttributes ( geometry, object ) {
  12435. var nvertices = geometry.vertices.length;
  12436. var material = object.material;
  12437. if ( material.attributes ) {
  12438. if ( geometry.__webglCustomAttributesList === undefined ) {
  12439. geometry.__webglCustomAttributesList = [];
  12440. }
  12441. for ( var a in material.attributes ) {
  12442. var attribute = material.attributes[ a ];
  12443. if ( ! attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12444. attribute.__webglInitialized = true;
  12445. var size = 1; // "f" and "i"
  12446. if ( attribute.type === 'v2' ) size = 2;
  12447. else if ( attribute.type === 'v3' ) size = 3;
  12448. else if ( attribute.type === 'v4' ) size = 4;
  12449. else if ( attribute.type === 'c' ) size = 3;
  12450. attribute.size = size;
  12451. attribute.array = new Float32Array( nvertices * size );
  12452. attribute.buffer = _gl.createBuffer();
  12453. attribute.buffer.belongsToAttribute = a;
  12454. attribute.needsUpdate = true;
  12455. }
  12456. geometry.__webglCustomAttributesList.push( attribute );
  12457. }
  12458. }
  12459. };
  12460. function initParticleBuffers ( geometry, object ) {
  12461. var nvertices = geometry.vertices.length;
  12462. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12463. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12464. geometry.__sortArray = [];
  12465. geometry.__webglParticleCount = nvertices;
  12466. initCustomAttributes ( geometry, object );
  12467. };
  12468. function initLineBuffers ( geometry, object ) {
  12469. var nvertices = geometry.vertices.length;
  12470. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12471. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12472. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  12473. geometry.__webglLineCount = nvertices;
  12474. initCustomAttributes ( geometry, object );
  12475. };
  12476. function initMeshBuffers ( geometryGroup, object ) {
  12477. var geometry = object.geometry,
  12478. faces3 = geometryGroup.faces3,
  12479. nvertices = faces3.length * 3,
  12480. ntris = faces3.length * 1,
  12481. nlines = faces3.length * 3,
  12482. material = getBufferMaterial( object, geometryGroup ),
  12483. uvType = bufferGuessUVType( material ),
  12484. normalType = bufferGuessNormalType( material ),
  12485. vertexColorType = bufferGuessVertexColorType( material );
  12486. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  12487. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  12488. if ( normalType ) {
  12489. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  12490. }
  12491. if ( geometry.hasTangents ) {
  12492. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  12493. }
  12494. if ( vertexColorType ) {
  12495. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  12496. }
  12497. if ( uvType ) {
  12498. if ( geometry.faceVertexUvs.length > 0 ) {
  12499. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  12500. }
  12501. if ( geometry.faceVertexUvs.length > 1 ) {
  12502. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  12503. }
  12504. }
  12505. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  12506. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  12507. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  12508. }
  12509. var UintArray = _glExtensionElementIndexUint !== null && ntris > 21845 ? Uint32Array : Uint16Array; // 65535 / 3
  12510. geometryGroup.__typeArray = UintArray;
  12511. geometryGroup.__faceArray = new UintArray( ntris * 3 );
  12512. geometryGroup.__lineArray = new UintArray( nlines * 2 );
  12513. var m, ml;
  12514. if ( geometryGroup.numMorphTargets ) {
  12515. geometryGroup.__morphTargetsArrays = [];
  12516. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12517. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  12518. }
  12519. }
  12520. if ( geometryGroup.numMorphNormals ) {
  12521. geometryGroup.__morphNormalsArrays = [];
  12522. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12523. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  12524. }
  12525. }
  12526. geometryGroup.__webglFaceCount = ntris * 3;
  12527. geometryGroup.__webglLineCount = nlines * 2;
  12528. // custom attributes
  12529. if ( material.attributes ) {
  12530. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  12531. geometryGroup.__webglCustomAttributesList = [];
  12532. }
  12533. for ( var a in material.attributes ) {
  12534. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  12535. // attribute buffers which are correctly indexed in the setMeshBuffers function
  12536. var originalAttribute = material.attributes[ a ];
  12537. var attribute = {};
  12538. for ( var property in originalAttribute ) {
  12539. attribute[ property ] = originalAttribute[ property ];
  12540. }
  12541. if ( ! attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12542. attribute.__webglInitialized = true;
  12543. var size = 1; // "f" and "i"
  12544. if ( attribute.type === 'v2' ) size = 2;
  12545. else if ( attribute.type === 'v3' ) size = 3;
  12546. else if ( attribute.type === 'v4' ) size = 4;
  12547. else if ( attribute.type === 'c' ) size = 3;
  12548. attribute.size = size;
  12549. attribute.array = new Float32Array( nvertices * size );
  12550. attribute.buffer = _gl.createBuffer();
  12551. attribute.buffer.belongsToAttribute = a;
  12552. originalAttribute.needsUpdate = true;
  12553. attribute.__original = originalAttribute;
  12554. }
  12555. geometryGroup.__webglCustomAttributesList.push( attribute );
  12556. }
  12557. }
  12558. geometryGroup.__inittedArrays = true;
  12559. };
  12560. function getBufferMaterial( object, geometryGroup ) {
  12561. return object.material instanceof THREE.MeshFaceMaterial
  12562. ? object.material.materials[ geometryGroup.materialIndex ]
  12563. : object.material;
  12564. };
  12565. function materialNeedsSmoothNormals ( material ) {
  12566. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  12567. };
  12568. function bufferGuessNormalType ( material ) {
  12569. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  12570. if ( ( material instanceof THREE.MeshBasicMaterial && ! material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  12571. return false;
  12572. }
  12573. if ( materialNeedsSmoothNormals( material ) ) {
  12574. return THREE.SmoothShading;
  12575. } else {
  12576. return THREE.FlatShading;
  12577. }
  12578. };
  12579. function bufferGuessVertexColorType( material ) {
  12580. if ( material.vertexColors ) {
  12581. return material.vertexColors;
  12582. }
  12583. return false;
  12584. };
  12585. function bufferGuessUVType( material ) {
  12586. // material must use some texture to require uvs
  12587. if ( material.map ||
  12588. material.lightMap ||
  12589. material.bumpMap ||
  12590. material.normalMap ||
  12591. material.specularMap ||
  12592. material instanceof THREE.ShaderMaterial ) {
  12593. return true;
  12594. }
  12595. return false;
  12596. };
  12597. //
  12598. function initDirectBuffers( geometry ) {
  12599. for ( var name in geometry.attributes ) {
  12600. var bufferType = ( name === 'index' ) ? _gl.ELEMENT_ARRAY_BUFFER : _gl.ARRAY_BUFFER;
  12601. var attribute = geometry.attributes[ name ];
  12602. attribute.buffer = _gl.createBuffer();
  12603. _gl.bindBuffer( bufferType, attribute.buffer );
  12604. _gl.bufferData( bufferType, attribute.array, _gl.STATIC_DRAW );
  12605. }
  12606. }
  12607. // Buffer setting
  12608. function setParticleBuffers ( geometry, hint, object ) {
  12609. var v, c, vertex, offset, index, color,
  12610. vertices = geometry.vertices,
  12611. vl = vertices.length,
  12612. colors = geometry.colors,
  12613. cl = colors.length,
  12614. vertexArray = geometry.__vertexArray,
  12615. colorArray = geometry.__colorArray,
  12616. sortArray = geometry.__sortArray,
  12617. dirtyVertices = geometry.verticesNeedUpdate,
  12618. dirtyElements = geometry.elementsNeedUpdate,
  12619. dirtyColors = geometry.colorsNeedUpdate,
  12620. customAttributes = geometry.__webglCustomAttributesList,
  12621. i, il,
  12622. a, ca, cal, value,
  12623. customAttribute;
  12624. if ( object.sortParticles ) {
  12625. _projScreenMatrixPS.copy( _projScreenMatrix );
  12626. _projScreenMatrixPS.multiply( object.matrixWorld );
  12627. for ( v = 0; v < vl; v ++ ) {
  12628. vertex = vertices[ v ];
  12629. _vector3.copy( vertex );
  12630. _vector3.applyProjection( _projScreenMatrixPS );
  12631. sortArray[ v ] = [ _vector3.z, v ];
  12632. }
  12633. sortArray.sort( numericalSort );
  12634. for ( v = 0; v < vl; v ++ ) {
  12635. vertex = vertices[ sortArray[ v ][ 1 ] ];
  12636. offset = v * 3;
  12637. vertexArray[ offset ] = vertex.x;
  12638. vertexArray[ offset + 1 ] = vertex.y;
  12639. vertexArray[ offset + 2 ] = vertex.z;
  12640. }
  12641. for ( c = 0; c < cl; c ++ ) {
  12642. offset = c * 3;
  12643. color = colors[ sortArray[ c ][ 1 ] ];
  12644. colorArray[ offset ] = color.r;
  12645. colorArray[ offset + 1 ] = color.g;
  12646. colorArray[ offset + 2 ] = color.b;
  12647. }
  12648. if ( customAttributes ) {
  12649. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12650. customAttribute = customAttributes[ i ];
  12651. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) ) continue;
  12652. offset = 0;
  12653. cal = customAttribute.value.length;
  12654. if ( customAttribute.size === 1 ) {
  12655. for ( ca = 0; ca < cal; ca ++ ) {
  12656. index = sortArray[ ca ][ 1 ];
  12657. customAttribute.array[ ca ] = customAttribute.value[ index ];
  12658. }
  12659. } else if ( customAttribute.size === 2 ) {
  12660. for ( ca = 0; ca < cal; ca ++ ) {
  12661. index = sortArray[ ca ][ 1 ];
  12662. value = customAttribute.value[ index ];
  12663. customAttribute.array[ offset ] = value.x;
  12664. customAttribute.array[ offset + 1 ] = value.y;
  12665. offset += 2;
  12666. }
  12667. } else if ( customAttribute.size === 3 ) {
  12668. if ( customAttribute.type === 'c' ) {
  12669. for ( ca = 0; ca < cal; ca ++ ) {
  12670. index = sortArray[ ca ][ 1 ];
  12671. value = customAttribute.value[ index ];
  12672. customAttribute.array[ offset ] = value.r;
  12673. customAttribute.array[ offset + 1 ] = value.g;
  12674. customAttribute.array[ offset + 2 ] = value.b;
  12675. offset += 3;
  12676. }
  12677. } else {
  12678. for ( ca = 0; ca < cal; ca ++ ) {
  12679. index = sortArray[ ca ][ 1 ];
  12680. value = customAttribute.value[ index ];
  12681. customAttribute.array[ offset ] = value.x;
  12682. customAttribute.array[ offset + 1 ] = value.y;
  12683. customAttribute.array[ offset + 2 ] = value.z;
  12684. offset += 3;
  12685. }
  12686. }
  12687. } else if ( customAttribute.size === 4 ) {
  12688. for ( ca = 0; ca < cal; ca ++ ) {
  12689. index = sortArray[ ca ][ 1 ];
  12690. value = customAttribute.value[ index ];
  12691. customAttribute.array[ offset ] = value.x;
  12692. customAttribute.array[ offset + 1 ] = value.y;
  12693. customAttribute.array[ offset + 2 ] = value.z;
  12694. customAttribute.array[ offset + 3 ] = value.w;
  12695. offset += 4;
  12696. }
  12697. }
  12698. }
  12699. }
  12700. } else {
  12701. if ( dirtyVertices ) {
  12702. for ( v = 0; v < vl; v ++ ) {
  12703. vertex = vertices[ v ];
  12704. offset = v * 3;
  12705. vertexArray[ offset ] = vertex.x;
  12706. vertexArray[ offset + 1 ] = vertex.y;
  12707. vertexArray[ offset + 2 ] = vertex.z;
  12708. }
  12709. }
  12710. if ( dirtyColors ) {
  12711. for ( c = 0; c < cl; c ++ ) {
  12712. color = colors[ c ];
  12713. offset = c * 3;
  12714. colorArray[ offset ] = color.r;
  12715. colorArray[ offset + 1 ] = color.g;
  12716. colorArray[ offset + 2 ] = color.b;
  12717. }
  12718. }
  12719. if ( customAttributes ) {
  12720. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12721. customAttribute = customAttributes[ i ];
  12722. if ( customAttribute.needsUpdate &&
  12723. ( customAttribute.boundTo === undefined ||
  12724. customAttribute.boundTo === 'vertices' ) ) {
  12725. cal = customAttribute.value.length;
  12726. offset = 0;
  12727. if ( customAttribute.size === 1 ) {
  12728. for ( ca = 0; ca < cal; ca ++ ) {
  12729. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12730. }
  12731. } else if ( customAttribute.size === 2 ) {
  12732. for ( ca = 0; ca < cal; ca ++ ) {
  12733. value = customAttribute.value[ ca ];
  12734. customAttribute.array[ offset ] = value.x;
  12735. customAttribute.array[ offset + 1 ] = value.y;
  12736. offset += 2;
  12737. }
  12738. } else if ( customAttribute.size === 3 ) {
  12739. if ( customAttribute.type === 'c' ) {
  12740. for ( ca = 0; ca < cal; ca ++ ) {
  12741. value = customAttribute.value[ ca ];
  12742. customAttribute.array[ offset ] = value.r;
  12743. customAttribute.array[ offset + 1 ] = value.g;
  12744. customAttribute.array[ offset + 2 ] = value.b;
  12745. offset += 3;
  12746. }
  12747. } else {
  12748. for ( ca = 0; ca < cal; ca ++ ) {
  12749. value = customAttribute.value[ ca ];
  12750. customAttribute.array[ offset ] = value.x;
  12751. customAttribute.array[ offset + 1 ] = value.y;
  12752. customAttribute.array[ offset + 2 ] = value.z;
  12753. offset += 3;
  12754. }
  12755. }
  12756. } else if ( customAttribute.size === 4 ) {
  12757. for ( ca = 0; ca < cal; ca ++ ) {
  12758. value = customAttribute.value[ ca ];
  12759. customAttribute.array[ offset ] = value.x;
  12760. customAttribute.array[ offset + 1 ] = value.y;
  12761. customAttribute.array[ offset + 2 ] = value.z;
  12762. customAttribute.array[ offset + 3 ] = value.w;
  12763. offset += 4;
  12764. }
  12765. }
  12766. }
  12767. }
  12768. }
  12769. }
  12770. if ( dirtyVertices || object.sortParticles ) {
  12771. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12772. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12773. }
  12774. if ( dirtyColors || object.sortParticles ) {
  12775. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12776. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12777. }
  12778. if ( customAttributes ) {
  12779. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12780. customAttribute = customAttributes[ i ];
  12781. if ( customAttribute.needsUpdate || object.sortParticles ) {
  12782. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12783. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12784. }
  12785. }
  12786. }
  12787. }
  12788. function setLineBuffers ( geometry, hint ) {
  12789. var v, c, d, vertex, offset, color,
  12790. vertices = geometry.vertices,
  12791. colors = geometry.colors,
  12792. lineDistances = geometry.lineDistances,
  12793. vl = vertices.length,
  12794. cl = colors.length,
  12795. dl = lineDistances.length,
  12796. vertexArray = geometry.__vertexArray,
  12797. colorArray = geometry.__colorArray,
  12798. lineDistanceArray = geometry.__lineDistanceArray,
  12799. dirtyVertices = geometry.verticesNeedUpdate,
  12800. dirtyColors = geometry.colorsNeedUpdate,
  12801. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  12802. customAttributes = geometry.__webglCustomAttributesList,
  12803. i, il,
  12804. a, ca, cal, value,
  12805. customAttribute;
  12806. if ( dirtyVertices ) {
  12807. for ( v = 0; v < vl; v ++ ) {
  12808. vertex = vertices[ v ];
  12809. offset = v * 3;
  12810. vertexArray[ offset ] = vertex.x;
  12811. vertexArray[ offset + 1 ] = vertex.y;
  12812. vertexArray[ offset + 2 ] = vertex.z;
  12813. }
  12814. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12815. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12816. }
  12817. if ( dirtyColors ) {
  12818. for ( c = 0; c < cl; c ++ ) {
  12819. color = colors[ c ];
  12820. offset = c * 3;
  12821. colorArray[ offset ] = color.r;
  12822. colorArray[ offset + 1 ] = color.g;
  12823. colorArray[ offset + 2 ] = color.b;
  12824. }
  12825. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12826. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12827. }
  12828. if ( dirtyLineDistances ) {
  12829. for ( d = 0; d < dl; d ++ ) {
  12830. lineDistanceArray[ d ] = lineDistances[ d ];
  12831. }
  12832. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  12833. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  12834. }
  12835. if ( customAttributes ) {
  12836. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12837. customAttribute = customAttributes[ i ];
  12838. if ( customAttribute.needsUpdate &&
  12839. ( customAttribute.boundTo === undefined ||
  12840. customAttribute.boundTo === 'vertices' ) ) {
  12841. offset = 0;
  12842. cal = customAttribute.value.length;
  12843. if ( customAttribute.size === 1 ) {
  12844. for ( ca = 0; ca < cal; ca ++ ) {
  12845. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12846. }
  12847. } else if ( customAttribute.size === 2 ) {
  12848. for ( ca = 0; ca < cal; ca ++ ) {
  12849. value = customAttribute.value[ ca ];
  12850. customAttribute.array[ offset ] = value.x;
  12851. customAttribute.array[ offset + 1 ] = value.y;
  12852. offset += 2;
  12853. }
  12854. } else if ( customAttribute.size === 3 ) {
  12855. if ( customAttribute.type === 'c' ) {
  12856. for ( ca = 0; ca < cal; ca ++ ) {
  12857. value = customAttribute.value[ ca ];
  12858. customAttribute.array[ offset ] = value.r;
  12859. customAttribute.array[ offset + 1 ] = value.g;
  12860. customAttribute.array[ offset + 2 ] = value.b;
  12861. offset += 3;
  12862. }
  12863. } else {
  12864. for ( ca = 0; ca < cal; ca ++ ) {
  12865. value = customAttribute.value[ ca ];
  12866. customAttribute.array[ offset ] = value.x;
  12867. customAttribute.array[ offset + 1 ] = value.y;
  12868. customAttribute.array[ offset + 2 ] = value.z;
  12869. offset += 3;
  12870. }
  12871. }
  12872. } else if ( customAttribute.size === 4 ) {
  12873. for ( ca = 0; ca < cal; ca ++ ) {
  12874. value = customAttribute.value[ ca ];
  12875. customAttribute.array[ offset ] = value.x;
  12876. customAttribute.array[ offset + 1 ] = value.y;
  12877. customAttribute.array[ offset + 2 ] = value.z;
  12878. customAttribute.array[ offset + 3 ] = value.w;
  12879. offset += 4;
  12880. }
  12881. }
  12882. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12883. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12884. }
  12885. }
  12886. }
  12887. }
  12888. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  12889. if ( ! geometryGroup.__inittedArrays ) {
  12890. return;
  12891. }
  12892. var normalType = bufferGuessNormalType( material ),
  12893. vertexColorType = bufferGuessVertexColorType( material ),
  12894. uvType = bufferGuessUVType( material ),
  12895. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  12896. var f, fl, fi, face,
  12897. vertexNormals, faceNormal, normal,
  12898. vertexColors, faceColor,
  12899. vertexTangents,
  12900. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  12901. c1, c2, c3,
  12902. sw1, sw2, sw3, sw4,
  12903. si1, si2, si3, si4,
  12904. sa1, sa2, sa3, sa4,
  12905. sb1, sb2, sb3, sb4,
  12906. m, ml, i, il,
  12907. vn, uvi, uv2i,
  12908. vk, vkl, vka,
  12909. nka, chf, faceVertexNormals,
  12910. a,
  12911. vertexIndex = 0,
  12912. offset = 0,
  12913. offset_uv = 0,
  12914. offset_uv2 = 0,
  12915. offset_face = 0,
  12916. offset_normal = 0,
  12917. offset_tangent = 0,
  12918. offset_line = 0,
  12919. offset_color = 0,
  12920. offset_skin = 0,
  12921. offset_morphTarget = 0,
  12922. offset_custom = 0,
  12923. offset_customSrc = 0,
  12924. value,
  12925. vertexArray = geometryGroup.__vertexArray,
  12926. uvArray = geometryGroup.__uvArray,
  12927. uv2Array = geometryGroup.__uv2Array,
  12928. normalArray = geometryGroup.__normalArray,
  12929. tangentArray = geometryGroup.__tangentArray,
  12930. colorArray = geometryGroup.__colorArray,
  12931. skinIndexArray = geometryGroup.__skinIndexArray,
  12932. skinWeightArray = geometryGroup.__skinWeightArray,
  12933. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  12934. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  12935. customAttributes = geometryGroup.__webglCustomAttributesList,
  12936. customAttribute,
  12937. faceArray = geometryGroup.__faceArray,
  12938. lineArray = geometryGroup.__lineArray,
  12939. geometry = object.geometry, // this is shared for all chunks
  12940. dirtyVertices = geometry.verticesNeedUpdate,
  12941. dirtyElements = geometry.elementsNeedUpdate,
  12942. dirtyUvs = geometry.uvsNeedUpdate,
  12943. dirtyNormals = geometry.normalsNeedUpdate,
  12944. dirtyTangents = geometry.tangentsNeedUpdate,
  12945. dirtyColors = geometry.colorsNeedUpdate,
  12946. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  12947. vertices = geometry.vertices,
  12948. chunk_faces3 = geometryGroup.faces3,
  12949. obj_faces = geometry.faces,
  12950. obj_uvs = geometry.faceVertexUvs[ 0 ],
  12951. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  12952. obj_colors = geometry.colors,
  12953. obj_skinIndices = geometry.skinIndices,
  12954. obj_skinWeights = geometry.skinWeights,
  12955. morphTargets = geometry.morphTargets,
  12956. morphNormals = geometry.morphNormals;
  12957. if ( dirtyVertices ) {
  12958. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12959. face = obj_faces[ chunk_faces3[ f ] ];
  12960. v1 = vertices[ face.a ];
  12961. v2 = vertices[ face.b ];
  12962. v3 = vertices[ face.c ];
  12963. vertexArray[ offset ] = v1.x;
  12964. vertexArray[ offset + 1 ] = v1.y;
  12965. vertexArray[ offset + 2 ] = v1.z;
  12966. vertexArray[ offset + 3 ] = v2.x;
  12967. vertexArray[ offset + 4 ] = v2.y;
  12968. vertexArray[ offset + 5 ] = v2.z;
  12969. vertexArray[ offset + 6 ] = v3.x;
  12970. vertexArray[ offset + 7 ] = v3.y;
  12971. vertexArray[ offset + 8 ] = v3.z;
  12972. offset += 9;
  12973. }
  12974. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12975. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12976. }
  12977. if ( dirtyMorphTargets ) {
  12978. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  12979. offset_morphTarget = 0;
  12980. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12981. chf = chunk_faces3[ f ];
  12982. face = obj_faces[ chf ];
  12983. // morph positions
  12984. v1 = morphTargets[ vk ].vertices[ face.a ];
  12985. v2 = morphTargets[ vk ].vertices[ face.b ];
  12986. v3 = morphTargets[ vk ].vertices[ face.c ];
  12987. vka = morphTargetsArrays[ vk ];
  12988. vka[ offset_morphTarget ] = v1.x;
  12989. vka[ offset_morphTarget + 1 ] = v1.y;
  12990. vka[ offset_morphTarget + 2 ] = v1.z;
  12991. vka[ offset_morphTarget + 3 ] = v2.x;
  12992. vka[ offset_morphTarget + 4 ] = v2.y;
  12993. vka[ offset_morphTarget + 5 ] = v2.z;
  12994. vka[ offset_morphTarget + 6 ] = v3.x;
  12995. vka[ offset_morphTarget + 7 ] = v3.y;
  12996. vka[ offset_morphTarget + 8 ] = v3.z;
  12997. // morph normals
  12998. if ( material.morphNormals ) {
  12999. if ( needsSmoothNormals ) {
  13000. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  13001. n1 = faceVertexNormals.a;
  13002. n2 = faceVertexNormals.b;
  13003. n3 = faceVertexNormals.c;
  13004. } else {
  13005. n1 = morphNormals[ vk ].faceNormals[ chf ];
  13006. n2 = n1;
  13007. n3 = n1;
  13008. }
  13009. nka = morphNormalsArrays[ vk ];
  13010. nka[ offset_morphTarget ] = n1.x;
  13011. nka[ offset_morphTarget + 1 ] = n1.y;
  13012. nka[ offset_morphTarget + 2 ] = n1.z;
  13013. nka[ offset_morphTarget + 3 ] = n2.x;
  13014. nka[ offset_morphTarget + 4 ] = n2.y;
  13015. nka[ offset_morphTarget + 5 ] = n2.z;
  13016. nka[ offset_morphTarget + 6 ] = n3.x;
  13017. nka[ offset_morphTarget + 7 ] = n3.y;
  13018. nka[ offset_morphTarget + 8 ] = n3.z;
  13019. }
  13020. //
  13021. offset_morphTarget += 9;
  13022. }
  13023. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  13024. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  13025. if ( material.morphNormals ) {
  13026. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  13027. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  13028. }
  13029. }
  13030. }
  13031. if ( obj_skinWeights.length ) {
  13032. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13033. face = obj_faces[ chunk_faces3[ f ] ];
  13034. // weights
  13035. sw1 = obj_skinWeights[ face.a ];
  13036. sw2 = obj_skinWeights[ face.b ];
  13037. sw3 = obj_skinWeights[ face.c ];
  13038. skinWeightArray[ offset_skin ] = sw1.x;
  13039. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  13040. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  13041. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  13042. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  13043. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  13044. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  13045. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  13046. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  13047. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  13048. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  13049. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  13050. // indices
  13051. si1 = obj_skinIndices[ face.a ];
  13052. si2 = obj_skinIndices[ face.b ];
  13053. si3 = obj_skinIndices[ face.c ];
  13054. skinIndexArray[ offset_skin ] = si1.x;
  13055. skinIndexArray[ offset_skin + 1 ] = si1.y;
  13056. skinIndexArray[ offset_skin + 2 ] = si1.z;
  13057. skinIndexArray[ offset_skin + 3 ] = si1.w;
  13058. skinIndexArray[ offset_skin + 4 ] = si2.x;
  13059. skinIndexArray[ offset_skin + 5 ] = si2.y;
  13060. skinIndexArray[ offset_skin + 6 ] = si2.z;
  13061. skinIndexArray[ offset_skin + 7 ] = si2.w;
  13062. skinIndexArray[ offset_skin + 8 ] = si3.x;
  13063. skinIndexArray[ offset_skin + 9 ] = si3.y;
  13064. skinIndexArray[ offset_skin + 10 ] = si3.z;
  13065. skinIndexArray[ offset_skin + 11 ] = si3.w;
  13066. offset_skin += 12;
  13067. }
  13068. if ( offset_skin > 0 ) {
  13069. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13070. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  13071. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13072. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  13073. }
  13074. }
  13075. if ( dirtyColors && vertexColorType ) {
  13076. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13077. face = obj_faces[ chunk_faces3[ f ] ];
  13078. vertexColors = face.vertexColors;
  13079. faceColor = face.color;
  13080. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  13081. c1 = vertexColors[ 0 ];
  13082. c2 = vertexColors[ 1 ];
  13083. c3 = vertexColors[ 2 ];
  13084. } else {
  13085. c1 = faceColor;
  13086. c2 = faceColor;
  13087. c3 = faceColor;
  13088. }
  13089. colorArray[ offset_color ] = c1.r;
  13090. colorArray[ offset_color + 1 ] = c1.g;
  13091. colorArray[ offset_color + 2 ] = c1.b;
  13092. colorArray[ offset_color + 3 ] = c2.r;
  13093. colorArray[ offset_color + 4 ] = c2.g;
  13094. colorArray[ offset_color + 5 ] = c2.b;
  13095. colorArray[ offset_color + 6 ] = c3.r;
  13096. colorArray[ offset_color + 7 ] = c3.g;
  13097. colorArray[ offset_color + 8 ] = c3.b;
  13098. offset_color += 9;
  13099. }
  13100. if ( offset_color > 0 ) {
  13101. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13102. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  13103. }
  13104. }
  13105. if ( dirtyTangents && geometry.hasTangents ) {
  13106. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13107. face = obj_faces[ chunk_faces3[ f ] ];
  13108. vertexTangents = face.vertexTangents;
  13109. t1 = vertexTangents[ 0 ];
  13110. t2 = vertexTangents[ 1 ];
  13111. t3 = vertexTangents[ 2 ];
  13112. tangentArray[ offset_tangent ] = t1.x;
  13113. tangentArray[ offset_tangent + 1 ] = t1.y;
  13114. tangentArray[ offset_tangent + 2 ] = t1.z;
  13115. tangentArray[ offset_tangent + 3 ] = t1.w;
  13116. tangentArray[ offset_tangent + 4 ] = t2.x;
  13117. tangentArray[ offset_tangent + 5 ] = t2.y;
  13118. tangentArray[ offset_tangent + 6 ] = t2.z;
  13119. tangentArray[ offset_tangent + 7 ] = t2.w;
  13120. tangentArray[ offset_tangent + 8 ] = t3.x;
  13121. tangentArray[ offset_tangent + 9 ] = t3.y;
  13122. tangentArray[ offset_tangent + 10 ] = t3.z;
  13123. tangentArray[ offset_tangent + 11 ] = t3.w;
  13124. offset_tangent += 12;
  13125. }
  13126. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13127. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  13128. }
  13129. if ( dirtyNormals && normalType ) {
  13130. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13131. face = obj_faces[ chunk_faces3[ f ] ];
  13132. vertexNormals = face.vertexNormals;
  13133. faceNormal = face.normal;
  13134. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  13135. for ( i = 0; i < 3; i ++ ) {
  13136. vn = vertexNormals[ i ];
  13137. normalArray[ offset_normal ] = vn.x;
  13138. normalArray[ offset_normal + 1 ] = vn.y;
  13139. normalArray[ offset_normal + 2 ] = vn.z;
  13140. offset_normal += 3;
  13141. }
  13142. } else {
  13143. for ( i = 0; i < 3; i ++ ) {
  13144. normalArray[ offset_normal ] = faceNormal.x;
  13145. normalArray[ offset_normal + 1 ] = faceNormal.y;
  13146. normalArray[ offset_normal + 2 ] = faceNormal.z;
  13147. offset_normal += 3;
  13148. }
  13149. }
  13150. }
  13151. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13152. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  13153. }
  13154. if ( dirtyUvs && obj_uvs && uvType ) {
  13155. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13156. fi = chunk_faces3[ f ];
  13157. uv = obj_uvs[ fi ];
  13158. if ( uv === undefined ) continue;
  13159. for ( i = 0; i < 3; i ++ ) {
  13160. uvi = uv[ i ];
  13161. uvArray[ offset_uv ] = uvi.x;
  13162. uvArray[ offset_uv + 1 ] = uvi.y;
  13163. offset_uv += 2;
  13164. }
  13165. }
  13166. if ( offset_uv > 0 ) {
  13167. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13168. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  13169. }
  13170. }
  13171. if ( dirtyUvs && obj_uvs2 && uvType ) {
  13172. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13173. fi = chunk_faces3[ f ];
  13174. uv2 = obj_uvs2[ fi ];
  13175. if ( uv2 === undefined ) continue;
  13176. for ( i = 0; i < 3; i ++ ) {
  13177. uv2i = uv2[ i ];
  13178. uv2Array[ offset_uv2 ] = uv2i.x;
  13179. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  13180. offset_uv2 += 2;
  13181. }
  13182. }
  13183. if ( offset_uv2 > 0 ) {
  13184. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13185. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  13186. }
  13187. }
  13188. if ( dirtyElements ) {
  13189. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13190. faceArray[ offset_face ] = vertexIndex;
  13191. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  13192. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  13193. offset_face += 3;
  13194. lineArray[ offset_line ] = vertexIndex;
  13195. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  13196. lineArray[ offset_line + 2 ] = vertexIndex;
  13197. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  13198. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  13199. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  13200. offset_line += 6;
  13201. vertexIndex += 3;
  13202. }
  13203. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13204. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  13205. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13206. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  13207. }
  13208. if ( customAttributes ) {
  13209. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13210. customAttribute = customAttributes[ i ];
  13211. if ( ! customAttribute.__original.needsUpdate ) continue;
  13212. offset_custom = 0;
  13213. offset_customSrc = 0;
  13214. if ( customAttribute.size === 1 ) {
  13215. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  13216. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13217. face = obj_faces[ chunk_faces3[ f ] ];
  13218. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  13219. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  13220. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  13221. offset_custom += 3;
  13222. }
  13223. } else if ( customAttribute.boundTo === 'faces' ) {
  13224. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13225. value = customAttribute.value[ chunk_faces3[ f ] ];
  13226. customAttribute.array[ offset_custom ] = value;
  13227. customAttribute.array[ offset_custom + 1 ] = value;
  13228. customAttribute.array[ offset_custom + 2 ] = value;
  13229. offset_custom += 3;
  13230. }
  13231. }
  13232. } else if ( customAttribute.size === 2 ) {
  13233. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  13234. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13235. face = obj_faces[ chunk_faces3[ f ] ];
  13236. v1 = customAttribute.value[ face.a ];
  13237. v2 = customAttribute.value[ face.b ];
  13238. v3 = customAttribute.value[ face.c ];
  13239. customAttribute.array[ offset_custom ] = v1.x;
  13240. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13241. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13242. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13243. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13244. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13245. offset_custom += 6;
  13246. }
  13247. } else if ( customAttribute.boundTo === 'faces' ) {
  13248. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13249. value = customAttribute.value[ chunk_faces3[ f ] ];
  13250. v1 = value;
  13251. v2 = value;
  13252. v3 = value;
  13253. customAttribute.array[ offset_custom ] = v1.x;
  13254. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13255. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13256. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13257. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13258. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13259. offset_custom += 6;
  13260. }
  13261. }
  13262. } else if ( customAttribute.size === 3 ) {
  13263. var pp;
  13264. if ( customAttribute.type === 'c' ) {
  13265. pp = [ 'r', 'g', 'b' ];
  13266. } else {
  13267. pp = [ 'x', 'y', 'z' ];
  13268. }
  13269. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  13270. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13271. face = obj_faces[ chunk_faces3[ f ] ];
  13272. v1 = customAttribute.value[ face.a ];
  13273. v2 = customAttribute.value[ face.b ];
  13274. v3 = customAttribute.value[ face.c ];
  13275. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13276. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13277. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13278. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13279. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13280. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13281. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13282. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13283. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13284. offset_custom += 9;
  13285. }
  13286. } else if ( customAttribute.boundTo === 'faces' ) {
  13287. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13288. value = customAttribute.value[ chunk_faces3[ f ] ];
  13289. v1 = value;
  13290. v2 = value;
  13291. v3 = value;
  13292. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13293. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13294. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13295. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13296. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13297. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13298. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13299. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13300. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13301. offset_custom += 9;
  13302. }
  13303. } else if ( customAttribute.boundTo === 'faceVertices' ) {
  13304. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13305. value = customAttribute.value[ chunk_faces3[ f ] ];
  13306. v1 = value[ 0 ];
  13307. v2 = value[ 1 ];
  13308. v3 = value[ 2 ];
  13309. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13310. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13311. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13312. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13313. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13314. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13315. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13316. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13317. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13318. offset_custom += 9;
  13319. }
  13320. }
  13321. } else if ( customAttribute.size === 4 ) {
  13322. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  13323. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13324. face = obj_faces[ chunk_faces3[ f ] ];
  13325. v1 = customAttribute.value[ face.a ];
  13326. v2 = customAttribute.value[ face.b ];
  13327. v3 = customAttribute.value[ face.c ];
  13328. customAttribute.array[ offset_custom ] = v1.x;
  13329. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13330. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13331. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13332. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13333. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13334. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13335. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13336. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13337. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13338. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13339. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13340. offset_custom += 12;
  13341. }
  13342. } else if ( customAttribute.boundTo === 'faces' ) {
  13343. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13344. value = customAttribute.value[ chunk_faces3[ f ] ];
  13345. v1 = value;
  13346. v2 = value;
  13347. v3 = value;
  13348. customAttribute.array[ offset_custom ] = v1.x;
  13349. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13350. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13351. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13352. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13353. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13354. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13355. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13356. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13357. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13358. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13359. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13360. offset_custom += 12;
  13361. }
  13362. } else if ( customAttribute.boundTo === 'faceVertices' ) {
  13363. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13364. value = customAttribute.value[ chunk_faces3[ f ] ];
  13365. v1 = value[ 0 ];
  13366. v2 = value[ 1 ];
  13367. v3 = value[ 2 ];
  13368. customAttribute.array[ offset_custom ] = v1.x;
  13369. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13370. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13371. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13372. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13373. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13374. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13375. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13376. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13377. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13378. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13379. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13380. offset_custom += 12;
  13381. }
  13382. }
  13383. }
  13384. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  13385. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  13386. }
  13387. }
  13388. if ( dispose ) {
  13389. delete geometryGroup.__inittedArrays;
  13390. delete geometryGroup.__colorArray;
  13391. delete geometryGroup.__normalArray;
  13392. delete geometryGroup.__tangentArray;
  13393. delete geometryGroup.__uvArray;
  13394. delete geometryGroup.__uv2Array;
  13395. delete geometryGroup.__faceArray;
  13396. delete geometryGroup.__vertexArray;
  13397. delete geometryGroup.__lineArray;
  13398. delete geometryGroup.__skinIndexArray;
  13399. delete geometryGroup.__skinWeightArray;
  13400. }
  13401. };
  13402. function setDirectBuffers( geometry, hint ) {
  13403. var attributes = geometry.attributes;
  13404. var attributeName, attributeItem;
  13405. for ( attributeName in attributes ) {
  13406. attributeItem = attributes[ attributeName ];
  13407. if ( attributeItem.needsUpdate ) {
  13408. if ( attributeName === 'index' ) {
  13409. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  13410. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  13411. } else {
  13412. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13413. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  13414. }
  13415. attributeItem.needsUpdate = false;
  13416. }
  13417. }
  13418. }
  13419. // Buffer rendering
  13420. this.renderBufferImmediate = function ( object, program, material ) {
  13421. initAttributes();
  13422. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  13423. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  13424. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  13425. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  13426. if ( object.hasPositions ) {
  13427. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  13428. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  13429. enableAttribute( program.attributes.position );
  13430. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13431. }
  13432. if ( object.hasNormals ) {
  13433. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  13434. if ( material.shading === THREE.FlatShading ) {
  13435. var nx, ny, nz,
  13436. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  13437. normalArray,
  13438. i, il = object.count * 3;
  13439. for ( i = 0; i < il; i += 9 ) {
  13440. normalArray = object.normalArray;
  13441. nax = normalArray[ i ];
  13442. nay = normalArray[ i + 1 ];
  13443. naz = normalArray[ i + 2 ];
  13444. nbx = normalArray[ i + 3 ];
  13445. nby = normalArray[ i + 4 ];
  13446. nbz = normalArray[ i + 5 ];
  13447. ncx = normalArray[ i + 6 ];
  13448. ncy = normalArray[ i + 7 ];
  13449. ncz = normalArray[ i + 8 ];
  13450. nx = ( nax + nbx + ncx ) / 3;
  13451. ny = ( nay + nby + ncy ) / 3;
  13452. nz = ( naz + nbz + ncz ) / 3;
  13453. normalArray[ i ] = nx;
  13454. normalArray[ i + 1 ] = ny;
  13455. normalArray[ i + 2 ] = nz;
  13456. normalArray[ i + 3 ] = nx;
  13457. normalArray[ i + 4 ] = ny;
  13458. normalArray[ i + 5 ] = nz;
  13459. normalArray[ i + 6 ] = nx;
  13460. normalArray[ i + 7 ] = ny;
  13461. normalArray[ i + 8 ] = nz;
  13462. }
  13463. }
  13464. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13465. enableAttribute( program.attributes.normal );
  13466. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13467. }
  13468. if ( object.hasUvs && material.map ) {
  13469. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13470. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13471. enableAttribute( program.attributes.uv );
  13472. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13473. }
  13474. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13475. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13476. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13477. enableAttribute( program.attributes.color );
  13478. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13479. }
  13480. disableUnusedAttributes();
  13481. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13482. object.count = 0;
  13483. };
  13484. function setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex ) {
  13485. for ( var attributeName in programAttributes ) {
  13486. var attributePointer = programAttributes[ attributeName ];
  13487. var attributeItem = geometryAttributes[ attributeName ];
  13488. if ( attributePointer >= 0 ) {
  13489. if ( attributeItem ) {
  13490. var attributeSize = attributeItem.itemSize;
  13491. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13492. enableAttribute( attributePointer );
  13493. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13494. } else if ( material.defaultAttributeValues ) {
  13495. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13496. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13497. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13498. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13499. }
  13500. }
  13501. }
  13502. }
  13503. disableUnusedAttributes();
  13504. }
  13505. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  13506. if ( material.visible === false ) return;
  13507. var linewidth, a, attribute;
  13508. var attributeItem, attributeName, attributePointer, attributeSize;
  13509. var program = setProgram( camera, lights, fog, material, object );
  13510. var programAttributes = program.attributes;
  13511. var geometryAttributes = geometry.attributes;
  13512. var updateBuffers = false,
  13513. wireframeBit = material.wireframe ? 1 : 0,
  13514. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13515. if ( geometryHash !== _currentGeometryGroupHash ) {
  13516. _currentGeometryGroupHash = geometryHash;
  13517. updateBuffers = true;
  13518. }
  13519. if ( updateBuffers ) {
  13520. initAttributes();
  13521. }
  13522. // render mesh
  13523. if ( object instanceof THREE.Mesh ) {
  13524. var index = geometryAttributes[ 'index' ];
  13525. if ( index ) {
  13526. // indexed triangles
  13527. var type, size;
  13528. if ( index.array instanceof Uint32Array ) {
  13529. type = _gl.UNSIGNED_INT;
  13530. size = 4;
  13531. } else {
  13532. type = _gl.UNSIGNED_SHORT;
  13533. size = 2;
  13534. }
  13535. var offsets = geometry.offsets;
  13536. if ( offsets.length === 0 ) {
  13537. if ( updateBuffers ) {
  13538. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13539. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13540. }
  13541. _gl.drawElements( _gl.TRIANGLES, index.array.length, type, 0 );
  13542. _this.info.render.calls ++;
  13543. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  13544. _this.info.render.faces += index.array.length / 3;
  13545. } else {
  13546. // if there is more than 1 chunk
  13547. // must set attribute pointers to use new offsets for each chunk
  13548. // even if geometry and materials didn't change
  13549. updateBuffers = true;
  13550. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13551. var startIndex = offsets[ i ].index;
  13552. if ( updateBuffers ) {
  13553. setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex );
  13554. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13555. }
  13556. // render indexed triangles
  13557. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, type, offsets[ i ].start * size );
  13558. _this.info.render.calls ++;
  13559. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13560. _this.info.render.faces += offsets[ i ].count / 3;
  13561. }
  13562. }
  13563. } else {
  13564. // non-indexed triangles
  13565. if ( updateBuffers ) {
  13566. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13567. }
  13568. var position = geometry.attributes[ 'position' ];
  13569. // render non-indexed triangles
  13570. _gl.drawArrays( _gl.TRIANGLES, 0, position.array.length / 3 );
  13571. _this.info.render.calls ++;
  13572. _this.info.render.vertices += position.array.length / 3;
  13573. _this.info.render.faces += position.array.length / 9;
  13574. }
  13575. } else if ( object instanceof THREE.PointCloud ) {
  13576. // render particles
  13577. if ( updateBuffers ) {
  13578. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13579. }
  13580. var position = geometryAttributes[ 'position' ];
  13581. // render particles
  13582. _gl.drawArrays( _gl.POINTS, 0, position.array.length / 3 );
  13583. _this.info.render.calls ++;
  13584. _this.info.render.points += position.array.length / 3;
  13585. } else if ( object instanceof THREE.Line ) {
  13586. var mode = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13587. setLineWidth( material.linewidth );
  13588. var index = geometryAttributes[ 'index' ];
  13589. if ( index ) {
  13590. // indexed lines
  13591. var type, size;
  13592. if ( index.array instanceof Uint32Array ) {
  13593. type = _gl.UNSIGNED_INT;
  13594. size = 4;
  13595. } else {
  13596. type = _gl.UNSIGNED_SHORT;
  13597. size = 2;
  13598. }
  13599. var offsets = geometry.offsets;
  13600. if ( offsets.length === 0 ) {
  13601. if ( updateBuffers ) {
  13602. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13603. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13604. }
  13605. _gl.drawElements( mode, index.array.length, type, 0 ); // 2 bytes per Uint16Array
  13606. _this.info.render.calls ++;
  13607. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  13608. } else {
  13609. // if there is more than 1 chunk
  13610. // must set attribute pointers to use new offsets for each chunk
  13611. // even if geometry and materials didn't change
  13612. if ( offsets.length > 1 ) updateBuffers = true;
  13613. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13614. var startIndex = offsets[ i ].index;
  13615. if ( updateBuffers ) {
  13616. setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex );
  13617. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13618. }
  13619. // render indexed lines
  13620. _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size ); // 2 bytes per Uint16Array
  13621. _this.info.render.calls ++;
  13622. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13623. }
  13624. }
  13625. } else {
  13626. // non-indexed lines
  13627. if ( updateBuffers ) {
  13628. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13629. }
  13630. var position = geometryAttributes[ 'position' ];
  13631. _gl.drawArrays( mode, 0, position.array.length / 3 );
  13632. _this.info.render.calls ++;
  13633. _this.info.render.points += position.array.length / 3;
  13634. }
  13635. }
  13636. };
  13637. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  13638. if ( material.visible === false ) return;
  13639. var linewidth, a, attribute, i, il;
  13640. var program = setProgram( camera, lights, fog, material, object );
  13641. var attributes = program.attributes;
  13642. var updateBuffers = false,
  13643. wireframeBit = material.wireframe ? 1 : 0,
  13644. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13645. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  13646. _currentGeometryGroupHash = geometryGroupHash;
  13647. updateBuffers = true;
  13648. }
  13649. if ( updateBuffers ) {
  13650. initAttributes();
  13651. }
  13652. // vertices
  13653. if ( ! material.morphTargets && attributes.position >= 0 ) {
  13654. if ( updateBuffers ) {
  13655. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13656. enableAttribute( attributes.position );
  13657. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13658. }
  13659. } else {
  13660. if ( object.morphTargetBase ) {
  13661. setupMorphTargets( material, geometryGroup, object );
  13662. }
  13663. }
  13664. if ( updateBuffers ) {
  13665. // custom attributes
  13666. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  13667. if ( geometryGroup.__webglCustomAttributesList ) {
  13668. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  13669. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  13670. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  13671. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  13672. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  13673. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  13674. }
  13675. }
  13676. }
  13677. // colors
  13678. if ( attributes.color >= 0 ) {
  13679. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  13680. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13681. enableAttribute( attributes.color );
  13682. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13683. } else if ( material.defaultAttributeValues ) {
  13684. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  13685. }
  13686. }
  13687. // normals
  13688. if ( attributes.normal >= 0 ) {
  13689. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13690. enableAttribute( attributes.normal );
  13691. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13692. }
  13693. // tangents
  13694. if ( attributes.tangent >= 0 ) {
  13695. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13696. enableAttribute( attributes.tangent );
  13697. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  13698. }
  13699. // uvs
  13700. if ( attributes.uv >= 0 ) {
  13701. if ( object.geometry.faceVertexUvs[ 0 ] ) {
  13702. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13703. enableAttribute( attributes.uv );
  13704. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13705. } else if ( material.defaultAttributeValues ) {
  13706. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  13707. }
  13708. }
  13709. if ( attributes.uv2 >= 0 ) {
  13710. if ( object.geometry.faceVertexUvs[ 1 ] ) {
  13711. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13712. enableAttribute( attributes.uv2 );
  13713. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  13714. } else if ( material.defaultAttributeValues ) {
  13715. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  13716. }
  13717. }
  13718. if ( material.skinning &&
  13719. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  13720. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13721. enableAttribute( attributes.skinIndex );
  13722. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  13723. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13724. enableAttribute( attributes.skinWeight );
  13725. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  13726. }
  13727. // line distances
  13728. if ( attributes.lineDistance >= 0 ) {
  13729. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  13730. enableAttribute( attributes.lineDistance );
  13731. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  13732. }
  13733. }
  13734. disableUnusedAttributes();
  13735. // render mesh
  13736. if ( object instanceof THREE.Mesh ) {
  13737. var type = geometryGroup.__typeArray === Uint32Array ? _gl.UNSIGNED_INT : _gl.UNSIGNED_SHORT;
  13738. // wireframe
  13739. if ( material.wireframe ) {
  13740. setLineWidth( material.wireframeLinewidth );
  13741. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13742. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, type, 0 );
  13743. // triangles
  13744. } else {
  13745. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13746. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, type, 0 );
  13747. }
  13748. _this.info.render.calls ++;
  13749. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  13750. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  13751. // render lines
  13752. } else if ( object instanceof THREE.Line ) {
  13753. var mode = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13754. setLineWidth( material.linewidth );
  13755. _gl.drawArrays( mode, 0, geometryGroup.__webglLineCount );
  13756. _this.info.render.calls ++;
  13757. // render particles
  13758. } else if ( object instanceof THREE.PointCloud ) {
  13759. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  13760. _this.info.render.calls ++;
  13761. _this.info.render.points += geometryGroup.__webglParticleCount;
  13762. }
  13763. };
  13764. function initAttributes() {
  13765. for ( var i = 0, l = _newAttributes.length; i < l; i ++ ) {
  13766. _newAttributes[ i ] = 0;
  13767. }
  13768. }
  13769. function enableAttribute( attribute ) {
  13770. _newAttributes[ attribute ] = 1;
  13771. if ( _enabledAttributes[ attribute ] === 0 ) {
  13772. _gl.enableVertexAttribArray( attribute );
  13773. _enabledAttributes[ attribute ] = 1;
  13774. }
  13775. }
  13776. function disableUnusedAttributes() {
  13777. for ( var i = 0, l = _enabledAttributes.length; i < l; i ++ ) {
  13778. if ( _enabledAttributes[ i ] !== _newAttributes[ i ] ) {
  13779. _gl.disableVertexAttribArray( i );
  13780. _enabledAttributes[ i ] = 0;
  13781. }
  13782. }
  13783. }
  13784. function setupMorphTargets ( material, geometryGroup, object ) {
  13785. // set base
  13786. var attributes = material.program.attributes;
  13787. if ( object.morphTargetBase !== - 1 && attributes.position >= 0 ) {
  13788. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13789. enableAttribute( attributes.position );
  13790. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13791. } else if ( attributes.position >= 0 ) {
  13792. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13793. enableAttribute( attributes.position );
  13794. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13795. }
  13796. if ( object.morphTargetForcedOrder.length ) {
  13797. // set forced order
  13798. var m = 0;
  13799. var order = object.morphTargetForcedOrder;
  13800. var influences = object.morphTargetInfluences;
  13801. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13802. if ( attributes[ 'morphTarget' + m ] >= 0 ) {
  13803. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13804. enableAttribute( attributes[ 'morphTarget' + m ] );
  13805. _gl.vertexAttribPointer( attributes[ 'morphTarget' + m ], 3, _gl.FLOAT, false, 0, 0 );
  13806. }
  13807. if ( attributes[ 'morphNormal' + m ] >= 0 && material.morphNormals ) {
  13808. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13809. enableAttribute( attributes[ 'morphNormal' + m ] );
  13810. _gl.vertexAttribPointer( attributes[ 'morphNormal' + m ], 3, _gl.FLOAT, false, 0, 0 );
  13811. }
  13812. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13813. m ++;
  13814. }
  13815. } else {
  13816. // find the most influencing
  13817. var influence, activeInfluenceIndices = [];
  13818. var influences = object.morphTargetInfluences;
  13819. var i, il = influences.length;
  13820. for ( i = 0; i < il; i ++ ) {
  13821. influence = influences[ i ];
  13822. if ( influence > 0 ) {
  13823. activeInfluenceIndices.push( [ influence, i ] );
  13824. }
  13825. }
  13826. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13827. activeInfluenceIndices.sort( numericalSort );
  13828. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13829. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13830. activeInfluenceIndices.sort( numericalSort );
  13831. } else if ( activeInfluenceIndices.length === 0 ) {
  13832. activeInfluenceIndices.push( [ 0, 0 ] );
  13833. };
  13834. var influenceIndex, m = 0;
  13835. while ( m < material.numSupportedMorphTargets ) {
  13836. if ( activeInfluenceIndices[ m ] ) {
  13837. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13838. if ( attributes[ 'morphTarget' + m ] >= 0 ) {
  13839. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13840. enableAttribute( attributes[ 'morphTarget' + m ] );
  13841. _gl.vertexAttribPointer( attributes[ 'morphTarget' + m ], 3, _gl.FLOAT, false, 0, 0 );
  13842. }
  13843. if ( attributes[ 'morphNormal' + m ] >= 0 && material.morphNormals ) {
  13844. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13845. enableAttribute( attributes[ 'morphNormal' + m ] );
  13846. _gl.vertexAttribPointer( attributes[ 'morphNormal' + m ], 3, _gl.FLOAT, false, 0, 0 );
  13847. }
  13848. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13849. } else {
  13850. /*
  13851. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13852. if ( material.morphNormals ) {
  13853. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13854. }
  13855. */
  13856. object.__webglMorphTargetInfluences[ m ] = 0;
  13857. }
  13858. m ++;
  13859. }
  13860. }
  13861. // load updated influences uniform
  13862. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13863. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13864. }
  13865. };
  13866. // Sorting
  13867. function painterSortStable ( a, b ) {
  13868. if ( a.z !== b.z ) {
  13869. return b.z - a.z;
  13870. } else {
  13871. return a.id - b.id;
  13872. }
  13873. };
  13874. function reversePainterSortStable ( a, b ) {
  13875. if ( a.z !== b.z ) {
  13876. return a.z - b.z;
  13877. } else {
  13878. return a.id - b.id;
  13879. }
  13880. };
  13881. function numericalSort ( a, b ) {
  13882. return b[ 0 ] - a[ 0 ];
  13883. };
  13884. // Rendering
  13885. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13886. if ( camera instanceof THREE.Camera === false ) {
  13887. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13888. return;
  13889. }
  13890. var i, il,
  13891. webglObject, object,
  13892. renderList,
  13893. lights = scene.__lights,
  13894. fog = scene.fog;
  13895. // reset caching for this frame
  13896. _currentMaterialId = - 1;
  13897. _lightsNeedUpdate = true;
  13898. // update scene graph
  13899. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  13900. // update camera matrices and frustum
  13901. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  13902. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13903. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13904. _frustum.setFromMatrix( _projScreenMatrix );
  13905. // update WebGL objects
  13906. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  13907. // custom render plugins (pre pass)
  13908. renderPlugins( this.renderPluginsPre, scene, camera );
  13909. //
  13910. _this.info.render.calls = 0;
  13911. _this.info.render.vertices = 0;
  13912. _this.info.render.faces = 0;
  13913. _this.info.render.points = 0;
  13914. this.setRenderTarget( renderTarget );
  13915. if ( this.autoClear || forceClear ) {
  13916. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13917. }
  13918. // set matrices for regular objects (frustum culled)
  13919. opaqueObjects.length = 0;
  13920. transparentObjects.length = 0;
  13921. _sortObjects = this.sortObjects;
  13922. projectObject(scene,scene,camera);
  13923. if ( this.sortObjects ) {
  13924. opaqueObjects.sort( painterSortStable );
  13925. transparentObjects.sort( reversePainterSortStable );
  13926. }
  13927. // set matrices for immediate objects
  13928. renderList = scene.__webglObjectsImmediate;
  13929. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13930. webglObject = renderList[ i ];
  13931. object = webglObject.object;
  13932. if ( object.visible ) {
  13933. setupMatrices( object, camera );
  13934. unrollImmediateBufferMaterial( webglObject );
  13935. }
  13936. }
  13937. if ( scene.overrideMaterial ) {
  13938. var material = scene.overrideMaterial;
  13939. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13940. this.setDepthTest( material.depthTest );
  13941. this.setDepthWrite( material.depthWrite );
  13942. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13943. renderObjects( opaqueObjects, camera, lights, fog, true, material );
  13944. renderObjects( transparentObjects, camera, lights, fog, true, material );
  13945. renderObjectsImmediate( scene.__webglObjectsImmediate, '', camera, lights, fog, false, material );
  13946. } else {
  13947. var material = null;
  13948. // opaque pass (front-to-back order)
  13949. this.setBlending( THREE.NoBlending );
  13950. renderObjects( opaqueObjects, camera, lights, fog, false, material );
  13951. renderObjectsImmediate( scene.__webglObjectsImmediate, 'opaque', camera, lights, fog, false, material );
  13952. // transparent pass (back-to-front order)
  13953. renderObjects( transparentObjects, camera, lights, fog, true, material );
  13954. renderObjectsImmediate( scene.__webglObjectsImmediate, 'transparent', camera, lights, fog, true, material );
  13955. }
  13956. // custom render plugins (post pass)
  13957. renderPlugins( this.renderPluginsPost, scene, camera );
  13958. // Generate mipmap if we're using any kind of mipmap filtering
  13959. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  13960. updateRenderTargetMipmap( renderTarget );
  13961. }
  13962. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13963. this.setDepthTest( true );
  13964. this.setDepthWrite( true );
  13965. // _gl.finish();
  13966. };
  13967. function projectObject(scene, object,camera){
  13968. if ( object.visible ) {
  13969. var webglObjects = scene.__webglObjects[object.id];
  13970. if (webglObjects && (object.frustumCulled === false || _frustum.intersectsObject( object ) === true) ) {
  13971. updateObject(scene, object);
  13972. setupMatrices( object, camera );
  13973. for (var i = 0, l = webglObjects.length; i < l; i++){
  13974. var webglObject = webglObjects[i];
  13975. unrollBufferMaterial( webglObject );
  13976. webglObject.render = true;
  13977. if ( _sortObjects === true ) {
  13978. if ( object.renderDepth !== null ) {
  13979. webglObject.z = object.renderDepth;
  13980. } else {
  13981. _vector3.setFromMatrixPosition( object.matrixWorld );
  13982. _vector3.applyProjection( _projScreenMatrix );
  13983. webglObject.z = _vector3.z;
  13984. }
  13985. }
  13986. }
  13987. }
  13988. for(var i = 0, l = object.children.length; i < l; i++) {
  13989. projectObject(scene, object.children[i],camera);
  13990. }
  13991. }
  13992. }
  13993. function renderPlugins( plugins, scene, camera ) {
  13994. if ( ! plugins.length ) return;
  13995. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  13996. // reset state for plugin (to start from clean slate)
  13997. _currentProgram = null;
  13998. _currentCamera = null;
  13999. _oldBlending = - 1;
  14000. _oldDepthTest = - 1;
  14001. _oldDepthWrite = - 1;
  14002. _oldDoubleSided = - 1;
  14003. _oldFlipSided = - 1;
  14004. _currentGeometryGroupHash = - 1;
  14005. _currentMaterialId = - 1;
  14006. _lightsNeedUpdate = true;
  14007. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  14008. // reset state after plugin (anything could have changed)
  14009. _currentProgram = null;
  14010. _currentCamera = null;
  14011. _oldBlending = - 1;
  14012. _oldDepthTest = - 1;
  14013. _oldDepthWrite = - 1;
  14014. _oldDoubleSided = - 1;
  14015. _oldFlipSided = - 1;
  14016. _currentGeometryGroupHash = - 1;
  14017. _currentMaterialId = - 1;
  14018. _lightsNeedUpdate = true;
  14019. }
  14020. };
  14021. function renderObjects( renderList, camera, lights, fog, useBlending, overrideMaterial ) {
  14022. var webglObject, object, buffer, material;
  14023. for ( var i = renderList.length - 1; i !== - 1; i -- ) {
  14024. webglObject = renderList[ i ];
  14025. object = webglObject.object;
  14026. buffer = webglObject.buffer;
  14027. if ( overrideMaterial ) {
  14028. material = overrideMaterial;
  14029. } else {
  14030. material = webglObject.material;
  14031. if ( ! material ) continue;
  14032. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  14033. _this.setDepthTest( material.depthTest );
  14034. _this.setDepthWrite( material.depthWrite );
  14035. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14036. }
  14037. _this.setMaterialFaces( material );
  14038. if ( buffer instanceof THREE.BufferGeometry ) {
  14039. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  14040. } else {
  14041. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  14042. }
  14043. }
  14044. };
  14045. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  14046. var webglObject, object, material, program;
  14047. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  14048. webglObject = renderList[ i ];
  14049. object = webglObject.object;
  14050. if ( object.visible ) {
  14051. if ( overrideMaterial ) {
  14052. material = overrideMaterial;
  14053. } else {
  14054. material = webglObject[ materialType ];
  14055. if ( ! material ) continue;
  14056. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  14057. _this.setDepthTest( material.depthTest );
  14058. _this.setDepthWrite( material.depthWrite );
  14059. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14060. }
  14061. _this.renderImmediateObject( camera, lights, fog, material, object );
  14062. }
  14063. }
  14064. };
  14065. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  14066. var program = setProgram( camera, lights, fog, material, object );
  14067. _currentGeometryGroupHash = - 1;
  14068. _this.setMaterialFaces( material );
  14069. if ( object.immediateRenderCallback ) {
  14070. object.immediateRenderCallback( program, _gl, _frustum );
  14071. } else {
  14072. object.render( function ( object ) { _this.renderBufferImmediate( object, program, material ); } );
  14073. }
  14074. };
  14075. function unrollImmediateBufferMaterial ( globject ) {
  14076. var object = globject.object,
  14077. material = object.material;
  14078. if ( material.transparent ) {
  14079. globject.transparent = material;
  14080. globject.opaque = null;
  14081. } else {
  14082. globject.opaque = material;
  14083. globject.transparent = null;
  14084. }
  14085. };
  14086. function unrollBufferMaterial ( globject ) {
  14087. var object = globject.object;
  14088. var buffer = globject.buffer;
  14089. var geometry = object.geometry;
  14090. var material = object.material;
  14091. if ( material instanceof THREE.MeshFaceMaterial ) {
  14092. var materialIndex = geometry instanceof THREE.BufferGeometry ? 0 : buffer.materialIndex;
  14093. material = material.materials[ materialIndex ];
  14094. if ( material.transparent ) {
  14095. globject.material = material;
  14096. transparentObjects.push(globject);
  14097. } else {
  14098. globject.material = material;
  14099. opaqueObjects.push(globject);
  14100. }
  14101. } else {
  14102. if ( material ) {
  14103. if ( material.transparent ) {
  14104. globject.material = material;
  14105. transparentObjects.push(globject);
  14106. } else {
  14107. globject.material = material;
  14108. opaqueObjects.push(globject);
  14109. }
  14110. }
  14111. }
  14112. };
  14113. // Objects refresh
  14114. this.initWebGLObjects = function ( scene ) {
  14115. if ( ! scene.__webglObjects ) {
  14116. scene.__webglObjects = {};
  14117. scene.__webglObjectsImmediate = [];
  14118. scene.__webglSprites = [];
  14119. scene.__webglFlares = [];
  14120. }
  14121. while ( scene.__objectsAdded.length ) {
  14122. addObject( scene.__objectsAdded[ 0 ], scene );
  14123. scene.__objectsAdded.splice( 0, 1 );
  14124. }
  14125. while ( scene.__objectsRemoved.length ) {
  14126. removeObject( scene.__objectsRemoved[ 0 ], scene );
  14127. scene.__objectsRemoved.splice( 0, 1 );
  14128. }
  14129. };
  14130. // Objects adding
  14131. function addObject( object, scene ) {
  14132. var g, geometry, geometryGroup;
  14133. if ( object.__webglInit === undefined ) {
  14134. object.__webglInit = true;
  14135. object._modelViewMatrix = new THREE.Matrix4();
  14136. object._normalMatrix = new THREE.Matrix3();
  14137. }
  14138. geometry = object.geometry;
  14139. if ( geometry === undefined ) {
  14140. // ImmediateRenderObject
  14141. } else if ( geometry.__webglInit === undefined ) {
  14142. geometry.__webglInit = true;
  14143. geometry.addEventListener( 'dispose', onGeometryDispose );
  14144. if ( geometry instanceof THREE.BufferGeometry ) {
  14145. initDirectBuffers( geometry );
  14146. } else if ( object instanceof THREE.Mesh ) {
  14147. if ( object.__webglActive !== undefined ) {
  14148. removeObject( object, scene );
  14149. }
  14150. initGeometryGroups(scene, object, geometry);
  14151. } else if ( object instanceof THREE.Line ) {
  14152. if ( ! geometry.__webglVertexBuffer ) {
  14153. createLineBuffers( geometry );
  14154. initLineBuffers( geometry, object );
  14155. geometry.verticesNeedUpdate = true;
  14156. geometry.colorsNeedUpdate = true;
  14157. geometry.lineDistancesNeedUpdate = true;
  14158. }
  14159. } else if ( object instanceof THREE.PointCloud ) {
  14160. if ( ! geometry.__webglVertexBuffer ) {
  14161. createParticleBuffers( geometry );
  14162. initParticleBuffers( geometry, object );
  14163. geometry.verticesNeedUpdate = true;
  14164. geometry.colorsNeedUpdate = true;
  14165. }
  14166. }
  14167. }
  14168. if ( object.__webglActive === undefined) {
  14169. if ( object instanceof THREE.Mesh ) {
  14170. geometry = object.geometry;
  14171. if ( geometry instanceof THREE.BufferGeometry ) {
  14172. addBuffer( scene.__webglObjects, geometry, object );
  14173. } else if ( geometry instanceof THREE.Geometry ) {
  14174. for ( var i = 0,l = geometry.geometryGroupsList.length; i<l;i++ ) {
  14175. geometryGroup = geometry.geometryGroupsList[ i ];
  14176. addBuffer( scene.__webglObjects, geometryGroup, object );
  14177. }
  14178. }
  14179. } else if ( object instanceof THREE.Line ||
  14180. object instanceof THREE.PointCloud ) {
  14181. geometry = object.geometry;
  14182. addBuffer( scene.__webglObjects, geometry, object );
  14183. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14184. addBufferImmediate( scene.__webglObjectsImmediate, object );
  14185. } else if ( object instanceof THREE.Sprite ) {
  14186. scene.__webglSprites.push( object );
  14187. } else if ( object instanceof THREE.LensFlare ) {
  14188. scene.__webglFlares.push( object );
  14189. }
  14190. object.__webglActive = true;
  14191. }
  14192. };
  14193. function initGeometryGroups(scene,object,geometry) {
  14194. var g, geometryGroup, material,addBuffers = false;
  14195. material = object.material;
  14196. if ( geometry.geometryGroups === undefined ) {
  14197. delete scene.__webglObjects[object.id];
  14198. geometry.makeGroups( material instanceof THREE.MeshFaceMaterial, _glExtensionElementIndexUint ? 4294967296 : 65535 );
  14199. }
  14200. // create separate VBOs per geometry chunk
  14201. for ( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  14202. geometryGroup = geometry.geometryGroupsList[ i ];
  14203. // initialise VBO on the first access
  14204. if ( ! geometryGroup.__webglVertexBuffer ) {
  14205. createMeshBuffers( geometryGroup );
  14206. initMeshBuffers( geometryGroup, object );
  14207. geometry.verticesNeedUpdate = true;
  14208. geometry.morphTargetsNeedUpdate = true;
  14209. geometry.elementsNeedUpdate = true;
  14210. geometry.uvsNeedUpdate = true;
  14211. geometry.normalsNeedUpdate = true;
  14212. geometry.tangentsNeedUpdate = true;
  14213. geometry.colorsNeedUpdate = true;
  14214. addBuffers = true;
  14215. } else {
  14216. addBuffers = false;
  14217. }
  14218. if ( addBuffers || object.__webglActive === undefined ) {
  14219. addBuffer( scene.__webglObjects, geometryGroup, object );
  14220. }
  14221. }
  14222. object.__webglActive = true;
  14223. }
  14224. function addBuffer( objlist, buffer, object ) {
  14225. var id = object.id;
  14226. objlist[id] = objlist[id] || [];
  14227. objlist[id].push(
  14228. {
  14229. id: null,
  14230. buffer: buffer,
  14231. object: object,
  14232. material: null,
  14233. z: 0
  14234. }
  14235. );
  14236. };
  14237. function addBufferImmediate( objlist, object ) {
  14238. objlist.push(
  14239. {
  14240. id: null,
  14241. object: object,
  14242. opaque: null,
  14243. transparent: null,
  14244. z: 0
  14245. }
  14246. );
  14247. };
  14248. // Objects updates
  14249. function updateObject(scene, object ) {
  14250. var geometry = object.geometry,
  14251. geometryGroup, customAttributesDirty, material;
  14252. if ( geometry instanceof THREE.BufferGeometry ) {
  14253. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW );
  14254. } else if ( object instanceof THREE.Mesh ) {
  14255. // check all geometry groups
  14256. if ( geometry.buffersNeedUpdate ) {
  14257. if ( geometry instanceof THREE.BufferGeometry ) {
  14258. initDirectBuffers( geometry );
  14259. } else if ( object instanceof THREE.Mesh ) {
  14260. initGeometryGroups(scene, object,geometry);
  14261. }
  14262. }
  14263. for ( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  14264. geometryGroup = geometry.geometryGroupsList[ i ];
  14265. material = getBufferMaterial( object, geometryGroup );
  14266. if ( geometry.buffersNeedUpdate ) {
  14267. initMeshBuffers( geometryGroup, object );
  14268. }
  14269. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14270. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  14271. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  14272. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  14273. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, ! geometry.dynamic, material );
  14274. }
  14275. }
  14276. geometry.verticesNeedUpdate = false;
  14277. geometry.morphTargetsNeedUpdate = false;
  14278. geometry.elementsNeedUpdate = false;
  14279. geometry.uvsNeedUpdate = false;
  14280. geometry.normalsNeedUpdate = false;
  14281. geometry.colorsNeedUpdate = false;
  14282. geometry.tangentsNeedUpdate = false;
  14283. geometry.buffersNeedUpdate = false;
  14284. material.attributes && clearCustomAttributes( material );
  14285. } else if ( object instanceof THREE.Line ) {
  14286. material = getBufferMaterial( object, geometry );
  14287. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14288. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  14289. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  14290. }
  14291. geometry.verticesNeedUpdate = false;
  14292. geometry.colorsNeedUpdate = false;
  14293. geometry.lineDistancesNeedUpdate = false;
  14294. material.attributes && clearCustomAttributes( material );
  14295. } else if ( object instanceof THREE.PointCloud ) {
  14296. material = getBufferMaterial( object, geometry );
  14297. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14298. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  14299. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  14300. }
  14301. geometry.verticesNeedUpdate = false;
  14302. geometry.colorsNeedUpdate = false;
  14303. material.attributes && clearCustomAttributes( material );
  14304. }
  14305. };
  14306. // Objects updates - custom attributes check
  14307. function areCustomAttributesDirty( material ) {
  14308. for ( var a in material.attributes ) {
  14309. if ( material.attributes[ a ].needsUpdate ) return true;
  14310. }
  14311. return false;
  14312. };
  14313. function clearCustomAttributes( material ) {
  14314. for ( var a in material.attributes ) {
  14315. material.attributes[ a ].needsUpdate = false;
  14316. }
  14317. };
  14318. // Objects removal
  14319. function removeObject( object, scene ) {
  14320. if ( object instanceof THREE.Mesh ||
  14321. object instanceof THREE.PointCloud ||
  14322. object instanceof THREE.Line ) {
  14323. removeInstancesWebglObjects( scene.__webglObjects, object );
  14324. } else if ( object instanceof THREE.Sprite ) {
  14325. removeInstancesDirect( scene.__webglSprites, object );
  14326. } else if ( object instanceof THREE.LensFlare ) {
  14327. removeInstancesDirect( scene.__webglFlares, object );
  14328. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14329. removeInstances( scene.__webglObjectsImmediate, object );
  14330. }
  14331. delete object.__webglActive;
  14332. };
  14333. function removeInstancesWebglObjects( objlist, object ) {
  14334. delete objlist[object];
  14335. };
  14336. function removeInstances( objlist, object ) {
  14337. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14338. if ( objlist[ o ].object === object ) {
  14339. objlist.splice( o, 1 );
  14340. }
  14341. }
  14342. };
  14343. function removeInstancesDirect( objlist, object ) {
  14344. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14345. if ( objlist[ o ] === object ) {
  14346. objlist.splice( o, 1 );
  14347. }
  14348. }
  14349. };
  14350. // Materials
  14351. this.initMaterial = function ( material, lights, fog, object ) {
  14352. material.addEventListener( 'dispose', onMaterialDispose );
  14353. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  14354. if ( material instanceof THREE.MeshDepthMaterial ) {
  14355. shaderID = 'depth';
  14356. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14357. shaderID = 'normal';
  14358. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  14359. shaderID = 'basic';
  14360. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14361. shaderID = 'lambert';
  14362. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14363. shaderID = 'phong';
  14364. } else if ( material instanceof THREE.LineBasicMaterial ) {
  14365. shaderID = 'basic';
  14366. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14367. shaderID = 'dashed';
  14368. } else if ( material instanceof THREE.PointCloudMaterial ) {
  14369. shaderID = 'particle_basic';
  14370. }
  14371. if ( shaderID ) {
  14372. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  14373. }
  14374. // heuristics to create shader parameters according to lights in the scene
  14375. // (not to blow over maxLights budget)
  14376. maxLightCount = allocateLights( lights );
  14377. maxShadows = allocateShadows( lights );
  14378. maxBones = allocateBones( object );
  14379. parameters = {
  14380. precision: _precision,
  14381. supportsVertexTextures: _supportsVertexTextures,
  14382. map: !! material.map,
  14383. envMap: !! material.envMap,
  14384. lightMap: !! material.lightMap,
  14385. bumpMap: !! material.bumpMap,
  14386. normalMap: !! material.normalMap,
  14387. specularMap: !! material.specularMap,
  14388. vertexColors: material.vertexColors,
  14389. fog: fog,
  14390. useFog: material.fog,
  14391. fogExp: fog instanceof THREE.FogExp2,
  14392. sizeAttenuation: material.sizeAttenuation,
  14393. logarithmicDepthBuffer: _logarithmicDepthBuffer,
  14394. skinning: material.skinning,
  14395. maxBones: maxBones,
  14396. useVertexTexture: _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  14397. morphTargets: material.morphTargets,
  14398. morphNormals: material.morphNormals,
  14399. maxMorphTargets: this.maxMorphTargets,
  14400. maxMorphNormals: this.maxMorphNormals,
  14401. maxDirLights: maxLightCount.directional,
  14402. maxPointLights: maxLightCount.point,
  14403. maxSpotLights: maxLightCount.spot,
  14404. maxHemiLights: maxLightCount.hemi,
  14405. maxShadows: maxShadows,
  14406. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow && maxShadows > 0,
  14407. shadowMapType: this.shadowMapType,
  14408. shadowMapDebug: this.shadowMapDebug,
  14409. shadowMapCascade: this.shadowMapCascade,
  14410. alphaTest: material.alphaTest,
  14411. metal: material.metal,
  14412. wrapAround: material.wrapAround,
  14413. doubleSided: material.side === THREE.DoubleSide,
  14414. flipSided: material.side === THREE.BackSide
  14415. };
  14416. // Generate code
  14417. var chunks = [];
  14418. if ( shaderID ) {
  14419. chunks.push( shaderID );
  14420. } else {
  14421. chunks.push( material.fragmentShader );
  14422. chunks.push( material.vertexShader );
  14423. }
  14424. for ( var d in material.defines ) {
  14425. chunks.push( d );
  14426. chunks.push( material.defines[ d ] );
  14427. }
  14428. for ( var p in parameters ) {
  14429. chunks.push( p );
  14430. chunks.push( parameters[ p ] );
  14431. }
  14432. var code = chunks.join();
  14433. var program;
  14434. // Check if code has been already compiled
  14435. for ( var p = 0, pl = _programs.length; p < pl; p ++ ) {
  14436. var programInfo = _programs[ p ];
  14437. if ( programInfo.code === code ) {
  14438. program = programInfo;
  14439. program.usedTimes ++;
  14440. break;
  14441. }
  14442. }
  14443. if ( program === undefined ) {
  14444. program = new THREE.WebGLProgram( this, code, material, parameters );
  14445. _programs.push( program );
  14446. _this.info.memory.programs = _programs.length;
  14447. }
  14448. material.program = program;
  14449. var attributes = material.program.attributes;
  14450. if ( material.morphTargets ) {
  14451. material.numSupportedMorphTargets = 0;
  14452. var id, base = 'morphTarget';
  14453. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  14454. id = base + i;
  14455. if ( attributes[ id ] >= 0 ) {
  14456. material.numSupportedMorphTargets ++;
  14457. }
  14458. }
  14459. }
  14460. if ( material.morphNormals ) {
  14461. material.numSupportedMorphNormals = 0;
  14462. var id, base = 'morphNormal';
  14463. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  14464. id = base + i;
  14465. if ( attributes[ id ] >= 0 ) {
  14466. material.numSupportedMorphNormals ++;
  14467. }
  14468. }
  14469. }
  14470. material.uniformsList = [];
  14471. for ( u in material.uniforms ) {
  14472. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  14473. }
  14474. };
  14475. function setMaterialShaders( material, shaders ) {
  14476. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  14477. material.vertexShader = shaders.vertexShader;
  14478. material.fragmentShader = shaders.fragmentShader;
  14479. };
  14480. function setProgram( camera, lights, fog, material, object ) {
  14481. _usedTextureUnits = 0;
  14482. if ( material.needsUpdate ) {
  14483. if ( material.program ) deallocateMaterial( material );
  14484. _this.initMaterial( material, lights, fog, object );
  14485. material.needsUpdate = false;
  14486. }
  14487. if ( material.morphTargets ) {
  14488. if ( ! object.__webglMorphTargetInfluences ) {
  14489. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  14490. }
  14491. }
  14492. var refreshMaterial = false;
  14493. var program = material.program,
  14494. p_uniforms = program.uniforms,
  14495. m_uniforms = material.uniforms;
  14496. if ( program.id !== _currentProgram ) {
  14497. _gl.useProgram( program.program );
  14498. _currentProgram = program.id;
  14499. refreshMaterial = true;
  14500. }
  14501. if ( material.id !== _currentMaterialId ) {
  14502. _currentMaterialId = material.id;
  14503. refreshMaterial = true;
  14504. }
  14505. if ( refreshMaterial || camera !== _currentCamera ) {
  14506. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  14507. if ( _logarithmicDepthBuffer ) {
  14508. _gl.uniform1f( p_uniforms.logDepthBufFC, 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  14509. }
  14510. if ( camera !== _currentCamera ) _currentCamera = camera;
  14511. }
  14512. // skinning uniforms must be set even if material didn't change
  14513. // auto-setting of texture unit for bone texture must go before other textures
  14514. // not sure why, but otherwise weird things happen
  14515. if ( material.skinning ) {
  14516. if ( _supportsBoneTextures && object.skeleton.useVertexTexture ) {
  14517. if ( p_uniforms.boneTexture !== null ) {
  14518. var textureUnit = getTextureUnit();
  14519. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  14520. _this.setTexture( object.skeleton.boneTexture, textureUnit );
  14521. }
  14522. if ( p_uniforms.boneTextureWidth !== null ) {
  14523. _gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth );
  14524. }
  14525. if ( p_uniforms.boneTextureHeight !== null ) {
  14526. _gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight );
  14527. }
  14528. } else {
  14529. if ( p_uniforms.boneGlobalMatrices !== null ) {
  14530. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices );
  14531. }
  14532. }
  14533. }
  14534. if ( refreshMaterial ) {
  14535. // refresh uniforms common to several materials
  14536. if ( fog && material.fog ) {
  14537. refreshUniformsFog( m_uniforms, fog );
  14538. }
  14539. if ( material instanceof THREE.MeshPhongMaterial ||
  14540. material instanceof THREE.MeshLambertMaterial ||
  14541. material.lights ) {
  14542. if ( _lightsNeedUpdate ) {
  14543. setupLights( program, lights );
  14544. _lightsNeedUpdate = false;
  14545. }
  14546. refreshUniformsLights( m_uniforms, _lights );
  14547. }
  14548. if ( material instanceof THREE.MeshBasicMaterial ||
  14549. material instanceof THREE.MeshLambertMaterial ||
  14550. material instanceof THREE.MeshPhongMaterial ) {
  14551. refreshUniformsCommon( m_uniforms, material );
  14552. }
  14553. // refresh single material specific uniforms
  14554. if ( material instanceof THREE.LineBasicMaterial ) {
  14555. refreshUniformsLine( m_uniforms, material );
  14556. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14557. refreshUniformsLine( m_uniforms, material );
  14558. refreshUniformsDash( m_uniforms, material );
  14559. } else if ( material instanceof THREE.PointCloudMaterial ) {
  14560. refreshUniformsParticle( m_uniforms, material );
  14561. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14562. refreshUniformsPhong( m_uniforms, material );
  14563. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14564. refreshUniformsLambert( m_uniforms, material );
  14565. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  14566. m_uniforms.mNear.value = camera.near;
  14567. m_uniforms.mFar.value = camera.far;
  14568. m_uniforms.opacity.value = material.opacity;
  14569. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14570. m_uniforms.opacity.value = material.opacity;
  14571. }
  14572. if ( object.receiveShadow && ! material._shadowPass ) {
  14573. refreshUniformsShadow( m_uniforms, lights );
  14574. }
  14575. // load common uniforms
  14576. loadUniformsGeneric( program, material.uniformsList );
  14577. // load material specific uniforms
  14578. // (shader material also gets them for the sake of genericity)
  14579. if ( material instanceof THREE.ShaderMaterial ||
  14580. material instanceof THREE.MeshPhongMaterial ||
  14581. material.envMap ) {
  14582. if ( p_uniforms.cameraPosition !== null ) {
  14583. _vector3.setFromMatrixPosition( camera.matrixWorld );
  14584. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  14585. }
  14586. }
  14587. if ( material instanceof THREE.MeshPhongMaterial ||
  14588. material instanceof THREE.MeshLambertMaterial ||
  14589. material instanceof THREE.ShaderMaterial ||
  14590. material.skinning ) {
  14591. if ( p_uniforms.viewMatrix !== null ) {
  14592. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  14593. }
  14594. }
  14595. }
  14596. loadUniformsMatrices( p_uniforms, object );
  14597. if ( p_uniforms.modelMatrix !== null ) {
  14598. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  14599. }
  14600. return program;
  14601. };
  14602. // Uniforms (refresh uniforms objects)
  14603. function refreshUniformsCommon ( uniforms, material ) {
  14604. uniforms.opacity.value = material.opacity;
  14605. if ( _this.gammaInput ) {
  14606. uniforms.diffuse.value.copyGammaToLinear( material.color );
  14607. } else {
  14608. uniforms.diffuse.value = material.color;
  14609. }
  14610. uniforms.map.value = material.map;
  14611. uniforms.lightMap.value = material.lightMap;
  14612. uniforms.specularMap.value = material.specularMap;
  14613. if ( material.bumpMap ) {
  14614. uniforms.bumpMap.value = material.bumpMap;
  14615. uniforms.bumpScale.value = material.bumpScale;
  14616. }
  14617. if ( material.normalMap ) {
  14618. uniforms.normalMap.value = material.normalMap;
  14619. uniforms.normalScale.value.copy( material.normalScale );
  14620. }
  14621. // uv repeat and offset setting priorities
  14622. // 1. color map
  14623. // 2. specular map
  14624. // 3. normal map
  14625. // 4. bump map
  14626. var uvScaleMap;
  14627. if ( material.map ) {
  14628. uvScaleMap = material.map;
  14629. } else if ( material.specularMap ) {
  14630. uvScaleMap = material.specularMap;
  14631. } else if ( material.normalMap ) {
  14632. uvScaleMap = material.normalMap;
  14633. } else if ( material.bumpMap ) {
  14634. uvScaleMap = material.bumpMap;
  14635. }
  14636. if ( uvScaleMap !== undefined ) {
  14637. var offset = uvScaleMap.offset;
  14638. var repeat = uvScaleMap.repeat;
  14639. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  14640. }
  14641. uniforms.envMap.value = material.envMap;
  14642. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1;
  14643. if ( _this.gammaInput ) {
  14644. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  14645. uniforms.reflectivity.value = material.reflectivity;
  14646. } else {
  14647. uniforms.reflectivity.value = material.reflectivity;
  14648. }
  14649. uniforms.refractionRatio.value = material.refractionRatio;
  14650. uniforms.combine.value = material.combine;
  14651. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  14652. };
  14653. function refreshUniformsLine ( uniforms, material ) {
  14654. uniforms.diffuse.value = material.color;
  14655. uniforms.opacity.value = material.opacity;
  14656. };
  14657. function refreshUniformsDash ( uniforms, material ) {
  14658. uniforms.dashSize.value = material.dashSize;
  14659. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14660. uniforms.scale.value = material.scale;
  14661. };
  14662. function refreshUniformsParticle ( uniforms, material ) {
  14663. uniforms.psColor.value = material.color;
  14664. uniforms.opacity.value = material.opacity;
  14665. uniforms.size.value = material.size;
  14666. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  14667. uniforms.map.value = material.map;
  14668. };
  14669. function refreshUniformsFog ( uniforms, fog ) {
  14670. uniforms.fogColor.value = fog.color;
  14671. if ( fog instanceof THREE.Fog ) {
  14672. uniforms.fogNear.value = fog.near;
  14673. uniforms.fogFar.value = fog.far;
  14674. } else if ( fog instanceof THREE.FogExp2 ) {
  14675. uniforms.fogDensity.value = fog.density;
  14676. }
  14677. };
  14678. function refreshUniformsPhong ( uniforms, material ) {
  14679. uniforms.shininess.value = material.shininess;
  14680. if ( _this.gammaInput ) {
  14681. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14682. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14683. uniforms.specular.value.copyGammaToLinear( material.specular );
  14684. } else {
  14685. uniforms.ambient.value = material.ambient;
  14686. uniforms.emissive.value = material.emissive;
  14687. uniforms.specular.value = material.specular;
  14688. }
  14689. if ( material.wrapAround ) {
  14690. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14691. }
  14692. };
  14693. function refreshUniformsLambert ( uniforms, material ) {
  14694. if ( _this.gammaInput ) {
  14695. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14696. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14697. } else {
  14698. uniforms.ambient.value = material.ambient;
  14699. uniforms.emissive.value = material.emissive;
  14700. }
  14701. if ( material.wrapAround ) {
  14702. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14703. }
  14704. };
  14705. function refreshUniformsLights ( uniforms, lights ) {
  14706. uniforms.ambientLightColor.value = lights.ambient;
  14707. uniforms.directionalLightColor.value = lights.directional.colors;
  14708. uniforms.directionalLightDirection.value = lights.directional.positions;
  14709. uniforms.pointLightColor.value = lights.point.colors;
  14710. uniforms.pointLightPosition.value = lights.point.positions;
  14711. uniforms.pointLightDistance.value = lights.point.distances;
  14712. uniforms.spotLightColor.value = lights.spot.colors;
  14713. uniforms.spotLightPosition.value = lights.spot.positions;
  14714. uniforms.spotLightDistance.value = lights.spot.distances;
  14715. uniforms.spotLightDirection.value = lights.spot.directions;
  14716. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  14717. uniforms.spotLightExponent.value = lights.spot.exponents;
  14718. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  14719. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  14720. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  14721. };
  14722. function refreshUniformsShadow ( uniforms, lights ) {
  14723. if ( uniforms.shadowMatrix ) {
  14724. var j = 0;
  14725. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14726. var light = lights[ i ];
  14727. if ( ! light.castShadow ) continue;
  14728. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  14729. uniforms.shadowMap.value[ j ] = light.shadowMap;
  14730. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  14731. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  14732. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  14733. uniforms.shadowBias.value[ j ] = light.shadowBias;
  14734. j ++;
  14735. }
  14736. }
  14737. }
  14738. };
  14739. // Uniforms (load to GPU)
  14740. function loadUniformsMatrices ( uniforms, object ) {
  14741. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14742. if ( uniforms.normalMatrix ) {
  14743. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14744. }
  14745. };
  14746. function getTextureUnit() {
  14747. var textureUnit = _usedTextureUnits;
  14748. if ( textureUnit >= _maxTextures ) {
  14749. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + _maxTextures );
  14750. }
  14751. _usedTextureUnits += 1;
  14752. return textureUnit;
  14753. };
  14754. function loadUniformsGeneric ( program, uniforms ) {
  14755. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  14756. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14757. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14758. if ( ! location ) continue;
  14759. uniform = uniforms[ j ][ 0 ];
  14760. type = uniform.type;
  14761. value = uniform.value;
  14762. if ( type === 'i' ) { // single integer
  14763. _gl.uniform1i( location, value );
  14764. } else if ( type === 'f' ) { // single float
  14765. _gl.uniform1f( location, value );
  14766. } else if ( type === 'v2' ) { // single THREE.Vector2
  14767. _gl.uniform2f( location, value.x, value.y );
  14768. } else if ( type === 'v3' ) { // single THREE.Vector3
  14769. _gl.uniform3f( location, value.x, value.y, value.z );
  14770. } else if ( type === 'v4' ) { // single THREE.Vector4
  14771. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14772. } else if ( type === 'c' ) { // single THREE.Color
  14773. _gl.uniform3f( location, value.r, value.g, value.b );
  14774. } else if ( type === 'iv1' ) { // flat array of integers (JS or typed array)
  14775. _gl.uniform1iv( location, value );
  14776. } else if ( type === 'iv' ) { // flat array of integers with 3 x N size (JS or typed array)
  14777. _gl.uniform3iv( location, value );
  14778. } else if ( type === 'fv1' ) { // flat array of floats (JS or typed array)
  14779. _gl.uniform1fv( location, value );
  14780. } else if ( type === 'fv' ) { // flat array of floats with 3 x N size (JS or typed array)
  14781. _gl.uniform3fv( location, value );
  14782. } else if ( type === 'v2v' ) { // array of THREE.Vector2
  14783. if ( uniform._array === undefined ) {
  14784. uniform._array = new Float32Array( 2 * value.length );
  14785. }
  14786. for ( i = 0, il = value.length; i < il; i ++ ) {
  14787. offset = i * 2;
  14788. uniform._array[ offset ] = value[ i ].x;
  14789. uniform._array[ offset + 1 ] = value[ i ].y;
  14790. }
  14791. _gl.uniform2fv( location, uniform._array );
  14792. } else if ( type === 'v3v' ) { // array of THREE.Vector3
  14793. if ( uniform._array === undefined ) {
  14794. uniform._array = new Float32Array( 3 * value.length );
  14795. }
  14796. for ( i = 0, il = value.length; i < il; i ++ ) {
  14797. offset = i * 3;
  14798. uniform._array[ offset ] = value[ i ].x;
  14799. uniform._array[ offset + 1 ] = value[ i ].y;
  14800. uniform._array[ offset + 2 ] = value[ i ].z;
  14801. }
  14802. _gl.uniform3fv( location, uniform._array );
  14803. } else if ( type === 'v4v' ) { // array of THREE.Vector4
  14804. if ( uniform._array === undefined ) {
  14805. uniform._array = new Float32Array( 4 * value.length );
  14806. }
  14807. for ( i = 0, il = value.length; i < il; i ++ ) {
  14808. offset = i * 4;
  14809. uniform._array[ offset ] = value[ i ].x;
  14810. uniform._array[ offset + 1 ] = value[ i ].y;
  14811. uniform._array[ offset + 2 ] = value[ i ].z;
  14812. uniform._array[ offset + 3 ] = value[ i ].w;
  14813. }
  14814. _gl.uniform4fv( location, uniform._array );
  14815. } else if ( type === 'm3' ) { // single THREE.Matrix3
  14816. _gl.uniformMatrix3fv( location, false, value.elements );
  14817. } else if ( type === 'm3v' ) { // array of THREE.Matrix3
  14818. if ( uniform._array === undefined ) {
  14819. uniform._array = new Float32Array( 9 * value.length );
  14820. }
  14821. for ( i = 0, il = value.length; i < il; i ++ ) {
  14822. value[ i ].flattenToArrayOffset( uniform._array, i * 9 );
  14823. }
  14824. _gl.uniformMatrix3fv( location, false, uniform._array );
  14825. } else if ( type === 'm4' ) { // single THREE.Matrix4
  14826. _gl.uniformMatrix4fv( location, false, value.elements );
  14827. } else if ( type === 'm4v' ) { // array of THREE.Matrix4
  14828. if ( uniform._array === undefined ) {
  14829. uniform._array = new Float32Array( 16 * value.length );
  14830. }
  14831. for ( i = 0, il = value.length; i < il; i ++ ) {
  14832. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14833. }
  14834. _gl.uniformMatrix4fv( location, false, uniform._array );
  14835. } else if ( type === 't' ) { // single THREE.Texture (2d or cube)
  14836. texture = value;
  14837. textureUnit = getTextureUnit();
  14838. _gl.uniform1i( location, textureUnit );
  14839. if ( ! texture ) continue;
  14840. if ( texture instanceof THREE.CubeTexture ||
  14841. ( texture.image instanceof Array && texture.image.length === 6 ) ) { // CompressedTexture can have Array in image :/
  14842. setCubeTexture( texture, textureUnit );
  14843. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14844. setCubeTextureDynamic( texture, textureUnit );
  14845. } else {
  14846. _this.setTexture( texture, textureUnit );
  14847. }
  14848. } else if ( type === 'tv' ) { // array of THREE.Texture (2d)
  14849. if ( uniform._array === undefined ) {
  14850. uniform._array = [];
  14851. }
  14852. for ( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14853. uniform._array[ i ] = getTextureUnit();
  14854. }
  14855. _gl.uniform1iv( location, uniform._array );
  14856. for ( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14857. texture = uniform.value[ i ];
  14858. textureUnit = uniform._array[ i ];
  14859. if ( ! texture ) continue;
  14860. _this.setTexture( texture, textureUnit );
  14861. }
  14862. } else {
  14863. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  14864. }
  14865. }
  14866. };
  14867. function setupMatrices ( object, camera ) {
  14868. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14869. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  14870. };
  14871. //
  14872. function setColorGamma( array, offset, color, intensitySq ) {
  14873. array[ offset ] = color.r * color.r * intensitySq;
  14874. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14875. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14876. };
  14877. function setColorLinear( array, offset, color, intensity ) {
  14878. array[ offset ] = color.r * intensity;
  14879. array[ offset + 1 ] = color.g * intensity;
  14880. array[ offset + 2 ] = color.b * intensity;
  14881. };
  14882. function setupLights ( program, lights ) {
  14883. var l, ll, light, n,
  14884. r = 0, g = 0, b = 0,
  14885. color, skyColor, groundColor,
  14886. intensity, intensitySq,
  14887. position,
  14888. distance,
  14889. zlights = _lights,
  14890. dirColors = zlights.directional.colors,
  14891. dirPositions = zlights.directional.positions,
  14892. pointColors = zlights.point.colors,
  14893. pointPositions = zlights.point.positions,
  14894. pointDistances = zlights.point.distances,
  14895. spotColors = zlights.spot.colors,
  14896. spotPositions = zlights.spot.positions,
  14897. spotDistances = zlights.spot.distances,
  14898. spotDirections = zlights.spot.directions,
  14899. spotAnglesCos = zlights.spot.anglesCos,
  14900. spotExponents = zlights.spot.exponents,
  14901. hemiSkyColors = zlights.hemi.skyColors,
  14902. hemiGroundColors = zlights.hemi.groundColors,
  14903. hemiPositions = zlights.hemi.positions,
  14904. dirLength = 0,
  14905. pointLength = 0,
  14906. spotLength = 0,
  14907. hemiLength = 0,
  14908. dirCount = 0,
  14909. pointCount = 0,
  14910. spotCount = 0,
  14911. hemiCount = 0,
  14912. dirOffset = 0,
  14913. pointOffset = 0,
  14914. spotOffset = 0,
  14915. hemiOffset = 0;
  14916. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14917. light = lights[ l ];
  14918. if ( light.onlyShadow ) continue;
  14919. color = light.color;
  14920. intensity = light.intensity;
  14921. distance = light.distance;
  14922. if ( light instanceof THREE.AmbientLight ) {
  14923. if ( ! light.visible ) continue;
  14924. if ( _this.gammaInput ) {
  14925. r += color.r * color.r;
  14926. g += color.g * color.g;
  14927. b += color.b * color.b;
  14928. } else {
  14929. r += color.r;
  14930. g += color.g;
  14931. b += color.b;
  14932. }
  14933. } else if ( light instanceof THREE.DirectionalLight ) {
  14934. dirCount += 1;
  14935. if ( ! light.visible ) continue;
  14936. _direction.setFromMatrixPosition( light.matrixWorld );
  14937. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  14938. _direction.sub( _vector3 );
  14939. _direction.normalize();
  14940. // skip lights with undefined direction
  14941. // these create troubles in OpenGL (making pixel black)
  14942. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14943. dirOffset = dirLength * 3;
  14944. dirPositions[ dirOffset ] = _direction.x;
  14945. dirPositions[ dirOffset + 1 ] = _direction.y;
  14946. dirPositions[ dirOffset + 2 ] = _direction.z;
  14947. if ( _this.gammaInput ) {
  14948. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  14949. } else {
  14950. setColorLinear( dirColors, dirOffset, color, intensity );
  14951. }
  14952. dirLength += 1;
  14953. } else if ( light instanceof THREE.PointLight ) {
  14954. pointCount += 1;
  14955. if ( ! light.visible ) continue;
  14956. pointOffset = pointLength * 3;
  14957. if ( _this.gammaInput ) {
  14958. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  14959. } else {
  14960. setColorLinear( pointColors, pointOffset, color, intensity );
  14961. }
  14962. _vector3.setFromMatrixPosition( light.matrixWorld );
  14963. pointPositions[ pointOffset ] = _vector3.x;
  14964. pointPositions[ pointOffset + 1 ] = _vector3.y;
  14965. pointPositions[ pointOffset + 2 ] = _vector3.z;
  14966. pointDistances[ pointLength ] = distance;
  14967. pointLength += 1;
  14968. } else if ( light instanceof THREE.SpotLight ) {
  14969. spotCount += 1;
  14970. if ( ! light.visible ) continue;
  14971. spotOffset = spotLength * 3;
  14972. if ( _this.gammaInput ) {
  14973. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14974. } else {
  14975. setColorLinear( spotColors, spotOffset, color, intensity );
  14976. }
  14977. _vector3.setFromMatrixPosition( light.matrixWorld );
  14978. spotPositions[ spotOffset ] = _vector3.x;
  14979. spotPositions[ spotOffset + 1 ] = _vector3.y;
  14980. spotPositions[ spotOffset + 2 ] = _vector3.z;
  14981. spotDistances[ spotLength ] = distance;
  14982. _direction.copy( _vector3 );
  14983. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  14984. _direction.sub( _vector3 );
  14985. _direction.normalize();
  14986. spotDirections[ spotOffset ] = _direction.x;
  14987. spotDirections[ spotOffset + 1 ] = _direction.y;
  14988. spotDirections[ spotOffset + 2 ] = _direction.z;
  14989. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14990. spotExponents[ spotLength ] = light.exponent;
  14991. spotLength += 1;
  14992. } else if ( light instanceof THREE.HemisphereLight ) {
  14993. hemiCount += 1;
  14994. if ( ! light.visible ) continue;
  14995. _direction.setFromMatrixPosition( light.matrixWorld );
  14996. _direction.normalize();
  14997. // skip lights with undefined direction
  14998. // these create troubles in OpenGL (making pixel black)
  14999. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  15000. hemiOffset = hemiLength * 3;
  15001. hemiPositions[ hemiOffset ] = _direction.x;
  15002. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  15003. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  15004. skyColor = light.color;
  15005. groundColor = light.groundColor;
  15006. if ( _this.gammaInput ) {
  15007. intensitySq = intensity * intensity;
  15008. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  15009. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  15010. } else {
  15011. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  15012. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  15013. }
  15014. hemiLength += 1;
  15015. }
  15016. }
  15017. // null eventual remains from removed lights
  15018. // (this is to avoid if in shader)
  15019. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  15020. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  15021. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  15022. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  15023. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  15024. zlights.directional.length = dirLength;
  15025. zlights.point.length = pointLength;
  15026. zlights.spot.length = spotLength;
  15027. zlights.hemi.length = hemiLength;
  15028. zlights.ambient[ 0 ] = r;
  15029. zlights.ambient[ 1 ] = g;
  15030. zlights.ambient[ 2 ] = b;
  15031. };
  15032. // GL state setting
  15033. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  15034. if ( cullFace === THREE.CullFaceNone ) {
  15035. _gl.disable( _gl.CULL_FACE );
  15036. } else {
  15037. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  15038. _gl.frontFace( _gl.CW );
  15039. } else {
  15040. _gl.frontFace( _gl.CCW );
  15041. }
  15042. if ( cullFace === THREE.CullFaceBack ) {
  15043. _gl.cullFace( _gl.BACK );
  15044. } else if ( cullFace === THREE.CullFaceFront ) {
  15045. _gl.cullFace( _gl.FRONT );
  15046. } else {
  15047. _gl.cullFace( _gl.FRONT_AND_BACK );
  15048. }
  15049. _gl.enable( _gl.CULL_FACE );
  15050. }
  15051. };
  15052. this.setMaterialFaces = function ( material ) {
  15053. var doubleSided = material.side === THREE.DoubleSide;
  15054. var flipSided = material.side === THREE.BackSide;
  15055. if ( _oldDoubleSided !== doubleSided ) {
  15056. if ( doubleSided ) {
  15057. _gl.disable( _gl.CULL_FACE );
  15058. } else {
  15059. _gl.enable( _gl.CULL_FACE );
  15060. }
  15061. _oldDoubleSided = doubleSided;
  15062. }
  15063. if ( _oldFlipSided !== flipSided ) {
  15064. if ( flipSided ) {
  15065. _gl.frontFace( _gl.CW );
  15066. } else {
  15067. _gl.frontFace( _gl.CCW );
  15068. }
  15069. _oldFlipSided = flipSided;
  15070. }
  15071. };
  15072. this.setDepthTest = function ( depthTest ) {
  15073. if ( _oldDepthTest !== depthTest ) {
  15074. if ( depthTest ) {
  15075. _gl.enable( _gl.DEPTH_TEST );
  15076. } else {
  15077. _gl.disable( _gl.DEPTH_TEST );
  15078. }
  15079. _oldDepthTest = depthTest;
  15080. }
  15081. };
  15082. this.setDepthWrite = function ( depthWrite ) {
  15083. if ( _oldDepthWrite !== depthWrite ) {
  15084. _gl.depthMask( depthWrite );
  15085. _oldDepthWrite = depthWrite;
  15086. }
  15087. };
  15088. function setLineWidth ( width ) {
  15089. if ( width !== _oldLineWidth ) {
  15090. _gl.lineWidth( width );
  15091. _oldLineWidth = width;
  15092. }
  15093. };
  15094. function setPolygonOffset ( polygonoffset, factor, units ) {
  15095. if ( _oldPolygonOffset !== polygonoffset ) {
  15096. if ( polygonoffset ) {
  15097. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  15098. } else {
  15099. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  15100. }
  15101. _oldPolygonOffset = polygonoffset;
  15102. }
  15103. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  15104. _gl.polygonOffset( factor, units );
  15105. _oldPolygonOffsetFactor = factor;
  15106. _oldPolygonOffsetUnits = units;
  15107. }
  15108. };
  15109. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  15110. if ( blending !== _oldBlending ) {
  15111. if ( blending === THREE.NoBlending ) {
  15112. _gl.disable( _gl.BLEND );
  15113. } else if ( blending === THREE.AdditiveBlending ) {
  15114. _gl.enable( _gl.BLEND );
  15115. _gl.blendEquation( _gl.FUNC_ADD );
  15116. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  15117. } else if ( blending === THREE.SubtractiveBlending ) {
  15118. // TODO: Find blendFuncSeparate() combination
  15119. _gl.enable( _gl.BLEND );
  15120. _gl.blendEquation( _gl.FUNC_ADD );
  15121. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  15122. } else if ( blending === THREE.MultiplyBlending ) {
  15123. // TODO: Find blendFuncSeparate() combination
  15124. _gl.enable( _gl.BLEND );
  15125. _gl.blendEquation( _gl.FUNC_ADD );
  15126. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  15127. } else if ( blending === THREE.CustomBlending ) {
  15128. _gl.enable( _gl.BLEND );
  15129. } else {
  15130. _gl.enable( _gl.BLEND );
  15131. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  15132. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  15133. }
  15134. _oldBlending = blending;
  15135. }
  15136. if ( blending === THREE.CustomBlending ) {
  15137. if ( blendEquation !== _oldBlendEquation ) {
  15138. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  15139. _oldBlendEquation = blendEquation;
  15140. }
  15141. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  15142. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  15143. _oldBlendSrc = blendSrc;
  15144. _oldBlendDst = blendDst;
  15145. }
  15146. } else {
  15147. _oldBlendEquation = null;
  15148. _oldBlendSrc = null;
  15149. _oldBlendDst = null;
  15150. }
  15151. };
  15152. // Textures
  15153. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  15154. if ( isImagePowerOfTwo ) {
  15155. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  15156. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  15157. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  15158. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  15159. } else {
  15160. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  15161. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  15162. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  15163. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  15164. }
  15165. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  15166. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  15167. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  15168. texture.__oldAnisotropy = texture.anisotropy;
  15169. }
  15170. }
  15171. };
  15172. this.setTexture = function ( texture, slot ) {
  15173. if ( texture.needsUpdate ) {
  15174. if ( ! texture.__webglInit ) {
  15175. texture.__webglInit = true;
  15176. texture.addEventListener( 'dispose', onTextureDispose );
  15177. texture.__webglTexture = _gl.createTexture();
  15178. _this.info.memory.textures ++;
  15179. }
  15180. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15181. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15182. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15183. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  15184. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  15185. var image = texture.image,
  15186. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  15187. glFormat = paramThreeToGL( texture.format ),
  15188. glType = paramThreeToGL( texture.type );
  15189. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  15190. var mipmap, mipmaps = texture.mipmaps;
  15191. if ( texture instanceof THREE.DataTexture ) {
  15192. // use manually created mipmaps if available
  15193. // if there are no manual mipmaps
  15194. // set 0 level mipmap and then use GL to generate other mipmap levels
  15195. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15196. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15197. mipmap = mipmaps[ i ];
  15198. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15199. }
  15200. texture.generateMipmaps = false;
  15201. } else {
  15202. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  15203. }
  15204. } else if ( texture instanceof THREE.CompressedTexture ) {
  15205. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15206. mipmap = mipmaps[ i ];
  15207. if ( texture.format !== THREE.RGBAFormat ) {
  15208. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15209. } else {
  15210. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15211. }
  15212. }
  15213. } else { // regular Texture (image, video, canvas)
  15214. // use manually created mipmaps if available
  15215. // if there are no manual mipmaps
  15216. // set 0 level mipmap and then use GL to generate other mipmap levels
  15217. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15218. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15219. mipmap = mipmaps[ i ];
  15220. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  15221. }
  15222. texture.generateMipmaps = false;
  15223. } else {
  15224. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  15225. }
  15226. }
  15227. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15228. texture.needsUpdate = false;
  15229. if ( texture.onUpdate ) texture.onUpdate();
  15230. } else {
  15231. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15232. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15233. }
  15234. };
  15235. function clampToMaxSize ( image, maxSize ) {
  15236. if ( image.width <= maxSize && image.height <= maxSize ) {
  15237. return image;
  15238. }
  15239. // Warning: Scaling through the canvas will only work with images that use
  15240. // premultiplied alpha.
  15241. var maxDimension = Math.max( image.width, image.height );
  15242. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  15243. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  15244. var canvas = document.createElement( 'canvas' );
  15245. canvas.width = newWidth;
  15246. canvas.height = newHeight;
  15247. var ctx = canvas.getContext( '2d' );
  15248. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  15249. return canvas;
  15250. }
  15251. function setCubeTexture ( texture, slot ) {
  15252. if ( texture.image.length === 6 ) {
  15253. if ( texture.needsUpdate ) {
  15254. if ( ! texture.image.__webglTextureCube ) {
  15255. texture.addEventListener( 'dispose', onTextureDispose );
  15256. texture.image.__webglTextureCube = _gl.createTexture();
  15257. _this.info.memory.textures ++;
  15258. }
  15259. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15260. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15261. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15262. var isCompressed = texture instanceof THREE.CompressedTexture;
  15263. var cubeImage = [];
  15264. for ( var i = 0; i < 6; i ++ ) {
  15265. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  15266. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  15267. } else {
  15268. cubeImage[ i ] = texture.image[ i ];
  15269. }
  15270. }
  15271. var image = cubeImage[ 0 ],
  15272. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  15273. glFormat = paramThreeToGL( texture.format ),
  15274. glType = paramThreeToGL( texture.type );
  15275. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  15276. for ( var i = 0; i < 6; i ++ ) {
  15277. if ( ! isCompressed ) {
  15278. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15279. } else {
  15280. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15281. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15282. mipmap = mipmaps[ j ];
  15283. if ( texture.format !== THREE.RGBAFormat ) {
  15284. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15285. } else {
  15286. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15287. }
  15288. }
  15289. }
  15290. }
  15291. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  15292. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15293. }
  15294. texture.needsUpdate = false;
  15295. if ( texture.onUpdate ) texture.onUpdate();
  15296. } else {
  15297. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15298. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15299. }
  15300. }
  15301. };
  15302. function setCubeTextureDynamic ( texture, slot ) {
  15303. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15304. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  15305. };
  15306. // Render targets
  15307. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  15308. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15309. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  15310. };
  15311. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  15312. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15313. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15314. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15315. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15316. /* For some reason this is not working. Defaulting to RGBA4.
  15317. } else if ( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15318. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  15319. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15320. */
  15321. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15322. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15323. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15324. } else {
  15325. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15326. }
  15327. };
  15328. this.setRenderTarget = function ( renderTarget ) {
  15329. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  15330. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  15331. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  15332. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  15333. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15334. renderTarget.__webglTexture = _gl.createTexture();
  15335. _this.info.memory.textures ++;
  15336. // Setup texture, create render and frame buffers
  15337. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ),
  15338. glFormat = paramThreeToGL( renderTarget.format ),
  15339. glType = paramThreeToGL( renderTarget.type );
  15340. if ( isCube ) {
  15341. renderTarget.__webglFramebuffer = [];
  15342. renderTarget.__webglRenderbuffer = [];
  15343. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15344. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  15345. for ( var i = 0; i < 6; i ++ ) {
  15346. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15347. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  15348. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15349. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15350. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  15351. }
  15352. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15353. } else {
  15354. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  15355. if ( renderTarget.shareDepthFrom ) {
  15356. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  15357. } else {
  15358. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  15359. }
  15360. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15361. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  15362. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15363. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  15364. if ( renderTarget.shareDepthFrom ) {
  15365. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15366. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15367. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15368. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15369. }
  15370. } else {
  15371. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15372. }
  15373. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15374. }
  15375. // Release everything
  15376. if ( isCube ) {
  15377. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15378. } else {
  15379. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15380. }
  15381. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15382. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15383. }
  15384. var framebuffer, width, height, vx, vy;
  15385. if ( renderTarget ) {
  15386. if ( isCube ) {
  15387. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15388. } else {
  15389. framebuffer = renderTarget.__webglFramebuffer;
  15390. }
  15391. width = renderTarget.width;
  15392. height = renderTarget.height;
  15393. vx = 0;
  15394. vy = 0;
  15395. } else {
  15396. framebuffer = null;
  15397. width = _viewportWidth;
  15398. height = _viewportHeight;
  15399. vx = _viewportX;
  15400. vy = _viewportY;
  15401. }
  15402. if ( framebuffer !== _currentFramebuffer ) {
  15403. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15404. _gl.viewport( vx, vy, width, height );
  15405. _currentFramebuffer = framebuffer;
  15406. }
  15407. _currentWidth = width;
  15408. _currentHeight = height;
  15409. };
  15410. function updateRenderTargetMipmap ( renderTarget ) {
  15411. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15412. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15413. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15414. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15415. } else {
  15416. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15417. _gl.generateMipmap( _gl.TEXTURE_2D );
  15418. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15419. }
  15420. };
  15421. // Fallback filters for non-power-of-2 textures
  15422. function filterFallback ( f ) {
  15423. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15424. return _gl.NEAREST;
  15425. }
  15426. return _gl.LINEAR;
  15427. };
  15428. // Map three.js constants to WebGL constants
  15429. function paramThreeToGL ( p ) {
  15430. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15431. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15432. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15433. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15434. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15435. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15436. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15437. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15438. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15439. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15440. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15441. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15442. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15443. if ( p === THREE.ByteType ) return _gl.BYTE;
  15444. if ( p === THREE.ShortType ) return _gl.SHORT;
  15445. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15446. if ( p === THREE.IntType ) return _gl.INT;
  15447. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15448. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15449. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15450. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15451. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15452. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15453. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15454. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15455. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15456. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15457. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15458. if ( p === THREE.OneFactor ) return _gl.ONE;
  15459. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15460. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15461. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15462. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15463. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15464. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15465. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15466. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15467. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15468. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15469. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15470. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15471. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15472. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15473. }
  15474. return 0;
  15475. };
  15476. // Allocations
  15477. function allocateBones ( object ) {
  15478. if ( _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  15479. return 1024;
  15480. } else {
  15481. // default for when object is not specified
  15482. // ( for example when prebuilding shader
  15483. // to be used with multiple objects )
  15484. //
  15485. // - leave some extra space for other uniforms
  15486. // - limit here is ANGLE's 254 max uniform vectors
  15487. // (up to 54 should be safe)
  15488. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15489. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15490. var maxBones = nVertexMatrices;
  15491. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15492. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  15493. if ( maxBones < object.skeleton.bones.length ) {
  15494. console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  15495. }
  15496. }
  15497. return maxBones;
  15498. }
  15499. };
  15500. function allocateLights( lights ) {
  15501. var dirLights = 0;
  15502. var pointLights = 0;
  15503. var spotLights = 0;
  15504. var hemiLights = 0;
  15505. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15506. var light = lights[ l ];
  15507. if ( light.onlyShadow || light.visible === false ) continue;
  15508. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15509. if ( light instanceof THREE.PointLight ) pointLights ++;
  15510. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15511. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15512. }
  15513. return { 'directional': dirLights, 'point': pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15514. };
  15515. function allocateShadows( lights ) {
  15516. var maxShadows = 0;
  15517. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15518. var light = lights[ l ];
  15519. if ( ! light.castShadow ) continue;
  15520. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15521. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15522. }
  15523. return maxShadows;
  15524. };
  15525. // Initialization
  15526. function initGL() {
  15527. try {
  15528. var attributes = {
  15529. alpha: _alpha,
  15530. depth: _depth,
  15531. stencil: _stencil,
  15532. antialias: _antialias,
  15533. premultipliedAlpha: _premultipliedAlpha,
  15534. preserveDrawingBuffer: _preserveDrawingBuffer
  15535. };
  15536. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  15537. if ( _gl === null ) {
  15538. throw 'Error creating WebGL context.';
  15539. }
  15540. } catch ( error ) {
  15541. console.error( error );
  15542. }
  15543. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15544. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  15545. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15546. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15547. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15548. _glExtensionElementIndexUint = _gl.getExtension( 'OES_element_index_uint' );
  15549. if ( _glExtensionTextureFloat === null ) {
  15550. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15551. }
  15552. if ( _glExtensionStandardDerivatives === null ) {
  15553. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15554. }
  15555. if ( _glExtensionTextureFilterAnisotropic === null ) {
  15556. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15557. }
  15558. if ( _glExtensionCompressedTextureS3TC === null ) {
  15559. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15560. }
  15561. if ( _glExtensionElementIndexUint === null ) {
  15562. console.log( 'THREE.WebGLRenderer: elementindex as unsigned integer not supported.' );
  15563. }
  15564. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15565. _gl.getShaderPrecisionFormat = function () {
  15566. return {
  15567. 'rangeMin': 1,
  15568. 'rangeMax': 1,
  15569. 'precision': 1
  15570. };
  15571. }
  15572. }
  15573. if ( _logarithmicDepthBuffer ) {
  15574. _glExtensionFragDepth = _gl.getExtension( 'EXT_frag_depth' );
  15575. }
  15576. };
  15577. function setDefaultGLState () {
  15578. _gl.clearColor( 0, 0, 0, 1 );
  15579. _gl.clearDepth( 1 );
  15580. _gl.clearStencil( 0 );
  15581. _gl.enable( _gl.DEPTH_TEST );
  15582. _gl.depthFunc( _gl.LEQUAL );
  15583. _gl.frontFace( _gl.CCW );
  15584. _gl.cullFace( _gl.BACK );
  15585. _gl.enable( _gl.CULL_FACE );
  15586. _gl.enable( _gl.BLEND );
  15587. _gl.blendEquation( _gl.FUNC_ADD );
  15588. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15589. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  15590. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15591. };
  15592. // default plugins (order is important)
  15593. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15594. this.addPrePlugin( this.shadowMapPlugin );
  15595. this.addPostPlugin( new THREE.SpritePlugin() );
  15596. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15597. };
  15598. // File:src/renderers/WebGLRenderTarget.js
  15599. /**
  15600. * @author szimek / https://github.com/szimek/
  15601. * @author alteredq / http://alteredqualia.com/
  15602. */
  15603. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15604. this.width = width;
  15605. this.height = height;
  15606. options = options || {};
  15607. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15608. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15609. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15610. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15611. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15612. this.offset = new THREE.Vector2( 0, 0 );
  15613. this.repeat = new THREE.Vector2( 1, 1 );
  15614. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15615. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15616. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15617. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15618. this.generateMipmaps = true;
  15619. this.shareDepthFrom = null;
  15620. };
  15621. THREE.WebGLRenderTarget.prototype = {
  15622. constructor: THREE.WebGLRenderTarget,
  15623. setSize: function ( width, height ) {
  15624. this.width = width;
  15625. this.height = height;
  15626. },
  15627. clone: function () {
  15628. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15629. tmp.wrapS = this.wrapS;
  15630. tmp.wrapT = this.wrapT;
  15631. tmp.magFilter = this.magFilter;
  15632. tmp.minFilter = this.minFilter;
  15633. tmp.anisotropy = this.anisotropy;
  15634. tmp.offset.copy( this.offset );
  15635. tmp.repeat.copy( this.repeat );
  15636. tmp.format = this.format;
  15637. tmp.type = this.type;
  15638. tmp.depthBuffer = this.depthBuffer;
  15639. tmp.stencilBuffer = this.stencilBuffer;
  15640. tmp.generateMipmaps = this.generateMipmaps;
  15641. tmp.shareDepthFrom = this.shareDepthFrom;
  15642. return tmp;
  15643. },
  15644. dispose: function () {
  15645. this.dispatchEvent( { type: 'dispose' } );
  15646. }
  15647. };
  15648. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  15649. // File:src/renderers/WebGLRenderTargetCube.js
  15650. /**
  15651. * @author alteredq / http://alteredqualia.com
  15652. */
  15653. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15654. THREE.WebGLRenderTarget.call( this, width, height, options );
  15655. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15656. };
  15657. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15658. // File:src/renderers/webgl/WebGLProgram.js
  15659. THREE.WebGLProgram = ( function () {
  15660. var programIdCount = 0;
  15661. var generateDefines = function ( defines ) {
  15662. var value, chunk, chunks = [];
  15663. for ( var d in defines ) {
  15664. value = defines[ d ];
  15665. if ( value === false ) continue;
  15666. chunk = "#define " + d + " " + value;
  15667. chunks.push( chunk );
  15668. }
  15669. return chunks.join( "\n" );
  15670. };
  15671. var cacheUniformLocations = function ( gl, program, identifiers ) {
  15672. var uniforms = {};
  15673. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  15674. var id = identifiers[ i ];
  15675. uniforms[ id ] = gl.getUniformLocation( program, id );
  15676. }
  15677. return uniforms;
  15678. };
  15679. var cacheAttributeLocations = function ( gl, program, identifiers ) {
  15680. var attributes = {};
  15681. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  15682. var id = identifiers[ i ];
  15683. attributes[ id ] = gl.getAttribLocation( program, id );
  15684. }
  15685. return attributes;
  15686. };
  15687. return function ( renderer, code, material, parameters ) {
  15688. var _this = renderer;
  15689. var _gl = _this.context;
  15690. var fragmentShader = material.fragmentShader;
  15691. var vertexShader = material.vertexShader;
  15692. var uniforms = material.uniforms;
  15693. var attributes = material.attributes;
  15694. var defines = material.defines;
  15695. var index0AttributeName = material.index0AttributeName;
  15696. if ( index0AttributeName === undefined && parameters.morphTargets === true ) {
  15697. // programs with morphTargets displace position out of attribute 0
  15698. index0AttributeName = 'position';
  15699. }
  15700. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  15701. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  15702. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  15703. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  15704. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  15705. }
  15706. // console.log( "building new program " );
  15707. //
  15708. var customDefines = generateDefines( defines );
  15709. //
  15710. var program = _gl.createProgram();
  15711. var prefix_vertex, prefix_fragment;
  15712. if ( material instanceof THREE.RawShaderMaterial ) {
  15713. prefix_vertex = '';
  15714. prefix_fragment = '';
  15715. } else {
  15716. prefix_vertex = [
  15717. "precision " + parameters.precision + " float;",
  15718. "precision " + parameters.precision + " int;",
  15719. customDefines,
  15720. parameters.supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  15721. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15722. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15723. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15724. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15725. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15726. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15727. "#define MAX_SHADOWS " + parameters.maxShadows,
  15728. "#define MAX_BONES " + parameters.maxBones,
  15729. parameters.map ? "#define USE_MAP" : "",
  15730. parameters.envMap ? "#define USE_ENVMAP" : "",
  15731. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15732. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15733. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15734. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15735. parameters.vertexColors ? "#define USE_COLOR" : "",
  15736. parameters.skinning ? "#define USE_SKINNING" : "",
  15737. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  15738. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  15739. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  15740. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15741. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15742. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15743. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15744. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15745. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15746. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15747. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  15748. parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "",
  15749. //_this._glExtensionFragDepth ? "#define USE_LOGDEPTHBUF_EXT" : "",
  15750. "uniform mat4 modelMatrix;",
  15751. "uniform mat4 modelViewMatrix;",
  15752. "uniform mat4 projectionMatrix;",
  15753. "uniform mat4 viewMatrix;",
  15754. "uniform mat3 normalMatrix;",
  15755. "uniform vec3 cameraPosition;",
  15756. "attribute vec3 position;",
  15757. "attribute vec3 normal;",
  15758. "attribute vec2 uv;",
  15759. "attribute vec2 uv2;",
  15760. "#ifdef USE_COLOR",
  15761. " attribute vec3 color;",
  15762. "#endif",
  15763. "#ifdef USE_MORPHTARGETS",
  15764. " attribute vec3 morphTarget0;",
  15765. " attribute vec3 morphTarget1;",
  15766. " attribute vec3 morphTarget2;",
  15767. " attribute vec3 morphTarget3;",
  15768. " #ifdef USE_MORPHNORMALS",
  15769. " attribute vec3 morphNormal0;",
  15770. " attribute vec3 morphNormal1;",
  15771. " attribute vec3 morphNormal2;",
  15772. " attribute vec3 morphNormal3;",
  15773. " #else",
  15774. " attribute vec3 morphTarget4;",
  15775. " attribute vec3 morphTarget5;",
  15776. " attribute vec3 morphTarget6;",
  15777. " attribute vec3 morphTarget7;",
  15778. " #endif",
  15779. "#endif",
  15780. "#ifdef USE_SKINNING",
  15781. " attribute vec4 skinIndex;",
  15782. " attribute vec4 skinWeight;",
  15783. "#endif",
  15784. ""
  15785. ].join( '\n' );
  15786. prefix_fragment = [
  15787. "precision " + parameters.precision + " float;",
  15788. "precision " + parameters.precision + " int;",
  15789. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  15790. customDefines,
  15791. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15792. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15793. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15794. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15795. "#define MAX_SHADOWS " + parameters.maxShadows,
  15796. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  15797. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15798. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15799. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  15800. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  15801. parameters.map ? "#define USE_MAP" : "",
  15802. parameters.envMap ? "#define USE_ENVMAP" : "",
  15803. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15804. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15805. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15806. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15807. parameters.vertexColors ? "#define USE_COLOR" : "",
  15808. parameters.metal ? "#define METAL" : "",
  15809. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15810. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15811. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15812. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15813. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15814. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15815. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15816. parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "",
  15817. //_this._glExtensionFragDepth ? "#define USE_LOGDEPTHBUF_EXT" : "",
  15818. "uniform mat4 viewMatrix;",
  15819. "uniform vec3 cameraPosition;",
  15820. ""
  15821. ].join( '\n' );
  15822. }
  15823. var glVertexShader = new THREE.WebGLShader( _gl, _gl.VERTEX_SHADER, prefix_vertex + vertexShader );
  15824. var glFragmentShader = new THREE.WebGLShader( _gl, _gl.FRAGMENT_SHADER, prefix_fragment + fragmentShader );
  15825. _gl.attachShader( program, glVertexShader );
  15826. _gl.attachShader( program, glFragmentShader );
  15827. if ( index0AttributeName !== undefined ) {
  15828. // Force a particular attribute to index 0.
  15829. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  15830. // And, color, for example is often automatically bound to index 0 so disabling it
  15831. _gl.bindAttribLocation( program, 0, index0AttributeName );
  15832. }
  15833. _gl.linkProgram( program );
  15834. if ( _gl.getProgramParameter( program, _gl.LINK_STATUS ) === false ) {
  15835. console.error( 'THREE.WebGLProgram: Could not initialise shader.' );
  15836. console.error( 'gl.VALIDATE_STATUS', _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) );
  15837. console.error( 'gl.getError()', _gl.getError() );
  15838. }
  15839. if ( _gl.getProgramInfoLog( program ) !== '' ) {
  15840. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', _gl.getProgramInfoLog( program ) );
  15841. }
  15842. // clean up
  15843. _gl.deleteShader( glVertexShader );
  15844. _gl.deleteShader( glFragmentShader );
  15845. // cache uniform locations
  15846. var identifiers = [
  15847. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  15848. 'morphTargetInfluences'
  15849. ];
  15850. if ( parameters.useVertexTexture ) {
  15851. identifiers.push( 'boneTexture' );
  15852. identifiers.push( 'boneTextureWidth' );
  15853. identifiers.push( 'boneTextureHeight' );
  15854. } else {
  15855. identifiers.push( 'boneGlobalMatrices' );
  15856. }
  15857. if ( parameters.logarithmicDepthBuffer ) {
  15858. identifiers.push('logDepthBufFC');
  15859. }
  15860. for ( var u in uniforms ) {
  15861. identifiers.push( u );
  15862. }
  15863. this.uniforms = cacheUniformLocations( _gl, program, identifiers );
  15864. // cache attributes locations
  15865. identifiers = [
  15866. "position", "normal", "uv", "uv2", "tangent", "color",
  15867. "skinIndex", "skinWeight", "lineDistance"
  15868. ];
  15869. for ( var i = 0; i < parameters.maxMorphTargets; i ++ ) {
  15870. identifiers.push( "morphTarget" + i );
  15871. }
  15872. for ( var i = 0; i < parameters.maxMorphNormals; i ++ ) {
  15873. identifiers.push( "morphNormal" + i );
  15874. }
  15875. for ( var a in attributes ) {
  15876. identifiers.push( a );
  15877. }
  15878. this.attributes = cacheAttributeLocations( _gl, program, identifiers );
  15879. //
  15880. this.id = programIdCount ++;
  15881. this.code = code;
  15882. this.usedTimes = 1;
  15883. this.program = program;
  15884. this.vertexShader = glVertexShader;
  15885. this.fragmentShader = glFragmentShader;
  15886. return this;
  15887. };
  15888. } )();
  15889. // File:src/renderers/webgl/WebGLShader.js
  15890. THREE.WebGLShader = ( function () {
  15891. var addLineNumbers = function ( string ) {
  15892. var lines = string.split( '\n' );
  15893. for ( var i = 0; i < lines.length; i ++ ) {
  15894. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  15895. }
  15896. return lines.join( '\n' );
  15897. };
  15898. return function ( gl, type, string ) {
  15899. var shader = gl.createShader( type );
  15900. gl.shaderSource( shader, string );
  15901. gl.compileShader( shader );
  15902. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  15903. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  15904. }
  15905. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  15906. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', gl.getShaderInfoLog( shader ) );
  15907. console.warn( addLineNumbers( string ) );
  15908. }
  15909. // --enable-privileged-webgl-extension
  15910. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  15911. return shader;
  15912. };
  15913. } )();
  15914. // File:src/renderers/renderables/RenderableVertex.js
  15915. /**
  15916. * @author mrdoob / http://mrdoob.com/
  15917. */
  15918. THREE.RenderableVertex = function () {
  15919. this.position = new THREE.Vector3();
  15920. this.positionWorld = new THREE.Vector3();
  15921. this.positionScreen = new THREE.Vector4();
  15922. this.visible = true;
  15923. };
  15924. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15925. this.positionWorld.copy( vertex.positionWorld );
  15926. this.positionScreen.copy( vertex.positionScreen );
  15927. };
  15928. // File:src/renderers/renderables/RenderableFace.js
  15929. /**
  15930. * @author mrdoob / http://mrdoob.com/
  15931. */
  15932. THREE.RenderableFace = function () {
  15933. this.id = 0;
  15934. this.v1 = new THREE.RenderableVertex();
  15935. this.v2 = new THREE.RenderableVertex();
  15936. this.v3 = new THREE.RenderableVertex();
  15937. this.normalModel = new THREE.Vector3();
  15938. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15939. this.vertexNormalsLength = 0;
  15940. this.color = new THREE.Color();
  15941. this.material = null;
  15942. this.uvs = [ new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() ];
  15943. this.z = 0;
  15944. };
  15945. // File:src/renderers/renderables/RenderableObject.js
  15946. /**
  15947. * @author mrdoob / http://mrdoob.com/
  15948. */
  15949. THREE.RenderableObject = function () {
  15950. this.id = 0;
  15951. this.object = null;
  15952. this.z = 0;
  15953. };
  15954. // File:src/renderers/renderables/RenderableSprite.js
  15955. /**
  15956. * @author mrdoob / http://mrdoob.com/
  15957. */
  15958. THREE.RenderableSprite = function () {
  15959. this.id = 0;
  15960. this.object = null;
  15961. this.x = 0;
  15962. this.y = 0;
  15963. this.z = 0;
  15964. this.rotation = 0;
  15965. this.scale = new THREE.Vector2();
  15966. this.material = null;
  15967. };
  15968. // File:src/renderers/renderables/RenderableLine.js
  15969. /**
  15970. * @author mrdoob / http://mrdoob.com/
  15971. */
  15972. THREE.RenderableLine = function () {
  15973. this.id = 0;
  15974. this.v1 = new THREE.RenderableVertex();
  15975. this.v2 = new THREE.RenderableVertex();
  15976. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  15977. this.material = null;
  15978. this.z = 0;
  15979. };
  15980. // File:src/extras/GeometryUtils.js
  15981. /**
  15982. * @author mrdoob / http://mrdoob.com/
  15983. */
  15984. THREE.GeometryUtils = {
  15985. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  15986. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  15987. var matrix;
  15988. if ( geometry2 instanceof THREE.Mesh ) {
  15989. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  15990. matrix = geometry2.matrix;
  15991. geometry2 = geometry2.geometry;
  15992. }
  15993. geometry1.merge( geometry2, matrix, materialIndexOffset );
  15994. },
  15995. center: function ( geometry ) {
  15996. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  15997. return geometry.center();
  15998. }
  15999. };
  16000. // File:src/extras/ImageUtils.js
  16001. /**
  16002. * @author alteredq / http://alteredqualia.com/
  16003. * @author mrdoob / http://mrdoob.com/
  16004. * @author Daosheng Mu / https://github.com/DaoshengMu/
  16005. */
  16006. THREE.ImageUtils = {
  16007. crossOrigin: undefined,
  16008. loadTexture: function ( url, mapping, onLoad, onError ) {
  16009. var loader = new THREE.ImageLoader();
  16010. loader.crossOrigin = this.crossOrigin;
  16011. var texture = new THREE.Texture( undefined, mapping );
  16012. loader.load( url, function ( image ) {
  16013. texture.image = image;
  16014. texture.needsUpdate = true;
  16015. if ( onLoad ) onLoad( texture );
  16016. }, undefined, function ( event ) {
  16017. if ( onError ) onError( event );
  16018. } );
  16019. texture.sourceFile = url;
  16020. return texture;
  16021. },
  16022. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  16023. var images = [];
  16024. var loader = new THREE.ImageLoader();
  16025. loader.crossOrigin = this.crossOrigin;
  16026. var texture = new THREE.CubeTexture( images, mapping );
  16027. // no flipping needed for cube textures
  16028. texture.flipY = false;
  16029. var loaded = 0;
  16030. var loadTexture = function ( i ) {
  16031. loader.load( array[ i ], function ( image ) {
  16032. texture.images[ i ] = image;
  16033. loaded += 1;
  16034. if ( loaded === 6 ) {
  16035. texture.needsUpdate = true;
  16036. if ( onLoad ) onLoad( texture );
  16037. }
  16038. } );
  16039. }
  16040. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16041. loadTexture( i );
  16042. }
  16043. return texture;
  16044. },
  16045. loadCompressedTexture: function () {
  16046. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' )
  16047. },
  16048. loadCompressedTextureCube: function () {
  16049. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' )
  16050. },
  16051. getNormalMap: function ( image, depth ) {
  16052. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  16053. var cross = function ( a, b ) {
  16054. 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 ] ];
  16055. }
  16056. var subtract = function ( a, b ) {
  16057. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  16058. }
  16059. var normalize = function ( a ) {
  16060. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  16061. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  16062. }
  16063. depth = depth | 1;
  16064. var width = image.width;
  16065. var height = image.height;
  16066. var canvas = document.createElement( 'canvas' );
  16067. canvas.width = width;
  16068. canvas.height = height;
  16069. var context = canvas.getContext( '2d' );
  16070. context.drawImage( image, 0, 0 );
  16071. var data = context.getImageData( 0, 0, width, height ).data;
  16072. var imageData = context.createImageData( width, height );
  16073. var output = imageData.data;
  16074. for ( var x = 0; x < width; x ++ ) {
  16075. for ( var y = 0; y < height; y ++ ) {
  16076. var ly = y - 1 < 0 ? 0 : y - 1;
  16077. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  16078. var lx = x - 1 < 0 ? 0 : x - 1;
  16079. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  16080. var points = [];
  16081. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  16082. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  16083. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  16084. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  16085. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  16086. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  16087. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  16088. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  16089. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  16090. var normals = [];
  16091. var num_points = points.length;
  16092. for ( var i = 0; i < num_points; i ++ ) {
  16093. var v1 = points[ i ];
  16094. var v2 = points[ ( i + 1 ) % num_points ];
  16095. v1 = subtract( v1, origin );
  16096. v2 = subtract( v2, origin );
  16097. normals.push( normalize( cross( v1, v2 ) ) );
  16098. }
  16099. var normal = [ 0, 0, 0 ];
  16100. for ( var i = 0; i < normals.length; i ++ ) {
  16101. normal[ 0 ] += normals[ i ][ 0 ];
  16102. normal[ 1 ] += normals[ i ][ 1 ];
  16103. normal[ 2 ] += normals[ i ][ 2 ];
  16104. }
  16105. normal[ 0 ] /= normals.length;
  16106. normal[ 1 ] /= normals.length;
  16107. normal[ 2 ] /= normals.length;
  16108. var idx = ( y * width + x ) * 4;
  16109. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16110. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16111. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  16112. output[ idx + 3 ] = 255;
  16113. }
  16114. }
  16115. context.putImageData( imageData, 0, 0 );
  16116. return canvas;
  16117. },
  16118. generateDataTexture: function ( width, height, color ) {
  16119. var size = width * height;
  16120. var data = new Uint8Array( 3 * size );
  16121. var r = Math.floor( color.r * 255 );
  16122. var g = Math.floor( color.g * 255 );
  16123. var b = Math.floor( color.b * 255 );
  16124. for ( var i = 0; i < size; i ++ ) {
  16125. data[ i * 3 ] = r;
  16126. data[ i * 3 + 1 ] = g;
  16127. data[ i * 3 + 2 ] = b;
  16128. }
  16129. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16130. texture.needsUpdate = true;
  16131. return texture;
  16132. }
  16133. };
  16134. // File:src/extras/SceneUtils.js
  16135. /**
  16136. * @author alteredq / http://alteredqualia.com/
  16137. */
  16138. THREE.SceneUtils = {
  16139. createMultiMaterialObject: function ( geometry, materials ) {
  16140. var group = new THREE.Object3D();
  16141. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16142. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16143. }
  16144. return group;
  16145. },
  16146. detach: function ( child, parent, scene ) {
  16147. child.applyMatrix( parent.matrixWorld );
  16148. parent.remove( child );
  16149. scene.add( child );
  16150. },
  16151. attach: function ( child, scene, parent ) {
  16152. var matrixWorldInverse = new THREE.Matrix4();
  16153. matrixWorldInverse.getInverse( parent.matrixWorld );
  16154. child.applyMatrix( matrixWorldInverse );
  16155. scene.remove( child );
  16156. parent.add( child );
  16157. }
  16158. };
  16159. // File:src/extras/FontUtils.js
  16160. /**
  16161. * @author zz85 / http://www.lab4games.net/zz85/blog
  16162. * @author alteredq / http://alteredqualia.com/
  16163. *
  16164. * For Text operations in three.js (See TextGeometry)
  16165. *
  16166. * It uses techniques used in:
  16167. *
  16168. * typeface.js and canvastext
  16169. * For converting fonts and rendering with javascript
  16170. * http://typeface.neocracy.org
  16171. *
  16172. * Triangulation ported from AS3
  16173. * Simple Polygon Triangulation
  16174. * http://actionsnippet.com/?p=1462
  16175. *
  16176. * A Method to triangulate shapes with holes
  16177. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16178. *
  16179. */
  16180. THREE.FontUtils = {
  16181. faces: {},
  16182. // Just for now. face[weight][style]
  16183. face: 'helvetiker',
  16184. weight: 'normal',
  16185. style: 'normal',
  16186. size: 150,
  16187. divisions: 10,
  16188. getFace: function () {
  16189. try {
  16190. return this.faces[ this.face ][ this.weight ][ this.style ];
  16191. } catch (e) {
  16192. throw "The font " + this.face + " with " + this.weight + " weight and " + this.style + " style is missing."
  16193. };
  16194. },
  16195. loadFace: function ( data ) {
  16196. var family = data.familyName.toLowerCase();
  16197. var ThreeFont = this;
  16198. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16199. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16200. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16201. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16202. return data;
  16203. },
  16204. drawText: function ( text ) {
  16205. var characterPts = [], allPts = [];
  16206. // RenderText
  16207. var i, p,
  16208. face = this.getFace(),
  16209. scale = this.size / face.resolution,
  16210. offset = 0,
  16211. chars = String( text ).split( '' ),
  16212. length = chars.length;
  16213. var fontPaths = [];
  16214. for ( i = 0; i < length; i ++ ) {
  16215. var path = new THREE.Path();
  16216. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16217. offset += ret.offset;
  16218. fontPaths.push( ret.path );
  16219. }
  16220. // get the width
  16221. var width = offset / 2;
  16222. //
  16223. // for ( p = 0; p < allPts.length; p++ ) {
  16224. //
  16225. // allPts[ p ].x -= width;
  16226. //
  16227. // }
  16228. //var extract = this.extractPoints( allPts, characterPts );
  16229. //extract.contour = allPts;
  16230. //extract.paths = fontPaths;
  16231. //extract.offset = width;
  16232. return { paths: fontPaths, offset: width };
  16233. },
  16234. extractGlyphPoints: function ( c, face, scale, offset, path ) {
  16235. var pts = [];
  16236. var i, i2, divisions,
  16237. outline, action, length,
  16238. scaleX, scaleY,
  16239. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16240. laste,
  16241. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16242. if ( ! glyph ) return;
  16243. if ( glyph.o ) {
  16244. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16245. length = outline.length;
  16246. scaleX = scale;
  16247. scaleY = scale;
  16248. for ( i = 0; i < length; ) {
  16249. action = outline[ i ++ ];
  16250. //console.log( action );
  16251. switch ( action ) {
  16252. case 'm':
  16253. // Move To
  16254. x = outline[ i ++ ] * scaleX + offset;
  16255. y = outline[ i ++ ] * scaleY;
  16256. path.moveTo( x, y );
  16257. break;
  16258. case 'l':
  16259. // Line To
  16260. x = outline[ i ++ ] * scaleX + offset;
  16261. y = outline[ i ++ ] * scaleY;
  16262. path.lineTo( x,y );
  16263. break;
  16264. case 'q':
  16265. // QuadraticCurveTo
  16266. cpx = outline[ i ++ ] * scaleX + offset;
  16267. cpy = outline[ i ++ ] * scaleY;
  16268. cpx1 = outline[ i ++ ] * scaleX + offset;
  16269. cpy1 = outline[ i ++ ] * scaleY;
  16270. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  16271. laste = pts[ pts.length - 1 ];
  16272. if ( laste ) {
  16273. cpx0 = laste.x;
  16274. cpy0 = laste.y;
  16275. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16276. var t = i2 / divisions;
  16277. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16278. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16279. }
  16280. }
  16281. break;
  16282. case 'b':
  16283. // Cubic Bezier Curve
  16284. cpx = outline[ i ++ ] * scaleX + offset;
  16285. cpy = outline[ i ++ ] * scaleY;
  16286. cpx1 = outline[ i ++ ] * scaleX + offset;
  16287. cpy1 = outline[ i ++ ] * scaleY;
  16288. cpx2 = outline[ i ++ ] * scaleX + offset;
  16289. cpy2 = outline[ i ++ ] * scaleY;
  16290. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  16291. laste = pts[ pts.length - 1 ];
  16292. if ( laste ) {
  16293. cpx0 = laste.x;
  16294. cpy0 = laste.y;
  16295. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16296. var t = i2 / divisions;
  16297. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16298. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16299. }
  16300. }
  16301. break;
  16302. }
  16303. }
  16304. }
  16305. return { offset: glyph.ha * scale, path:path };
  16306. }
  16307. };
  16308. THREE.FontUtils.generateShapes = function ( text, parameters ) {
  16309. // Parameters
  16310. parameters = parameters || {};
  16311. var size = parameters.size !== undefined ? parameters.size : 100;
  16312. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments : 4;
  16313. var font = parameters.font !== undefined ? parameters.font : 'helvetiker';
  16314. var weight = parameters.weight !== undefined ? parameters.weight : 'normal';
  16315. var style = parameters.style !== undefined ? parameters.style : 'normal';
  16316. THREE.FontUtils.size = size;
  16317. THREE.FontUtils.divisions = curveSegments;
  16318. THREE.FontUtils.face = font;
  16319. THREE.FontUtils.weight = weight;
  16320. THREE.FontUtils.style = style;
  16321. // Get a Font data json object
  16322. var data = THREE.FontUtils.drawText( text );
  16323. var paths = data.paths;
  16324. var shapes = [];
  16325. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16326. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16327. }
  16328. return shapes;
  16329. };
  16330. /**
  16331. * This code is a quick port of code written in C++ which was submitted to
  16332. * flipcode.com by John W. Ratcliff // July 22, 2000
  16333. * See original code and more information here:
  16334. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16335. *
  16336. * ported to actionscript by Zevan Rosser
  16337. * www.actionsnippet.com
  16338. *
  16339. * ported to javascript by Joshua Koo
  16340. * http://www.lab4games.net/zz85/blog
  16341. *
  16342. */
  16343. ( function ( namespace ) {
  16344. var EPSILON = 0.0000000001;
  16345. // takes in an contour array and returns
  16346. var process = function ( contour, indices ) {
  16347. var n = contour.length;
  16348. if ( n < 3 ) return null;
  16349. var result = [],
  16350. verts = [],
  16351. vertIndices = [];
  16352. /* we want a counter-clockwise polygon in verts */
  16353. var u, v, w;
  16354. if ( area( contour ) > 0.0 ) {
  16355. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  16356. } else {
  16357. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  16358. }
  16359. var nv = n;
  16360. /* remove nv - 2 vertices, creating 1 triangle every time */
  16361. var count = 2 * nv; /* error detection */
  16362. for ( v = nv - 1; nv > 2; ) {
  16363. /* if we loop, it is probably a non-simple polygon */
  16364. if ( ( count -- ) <= 0 ) {
  16365. //** Triangulate: ERROR - probable bad polygon!
  16366. //throw ( "Warning, unable to triangulate polygon!" );
  16367. //return null;
  16368. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16369. console.log( 'Warning, unable to triangulate polygon!' );
  16370. if ( indices ) return vertIndices;
  16371. return result;
  16372. }
  16373. /* three consecutive vertices in current polygon, <u,v,w> */
  16374. u = v; if ( nv <= u ) u = 0; /* previous */
  16375. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16376. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16377. if ( snip( contour, u, v, w, nv, verts ) ) {
  16378. var a, b, c, s, t;
  16379. /* true names of the vertices */
  16380. a = verts[ u ];
  16381. b = verts[ v ];
  16382. c = verts[ w ];
  16383. /* output Triangle */
  16384. result.push( [ contour[ a ],
  16385. contour[ b ],
  16386. contour[ c ] ] );
  16387. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16388. /* remove v from the remaining polygon */
  16389. for ( s = v, t = v + 1; t < nv; s++, t++ ) {
  16390. verts[ s ] = verts[ t ];
  16391. }
  16392. nv --;
  16393. /* reset error detection counter */
  16394. count = 2 * nv;
  16395. }
  16396. }
  16397. if ( indices ) return vertIndices;
  16398. return result;
  16399. };
  16400. // calculate area of the contour polygon
  16401. var area = function ( contour ) {
  16402. var n = contour.length;
  16403. var a = 0.0;
  16404. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  16405. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16406. }
  16407. return a * 0.5;
  16408. };
  16409. var snip = function ( contour, u, v, w, n, verts ) {
  16410. var p;
  16411. var ax, ay, bx, by;
  16412. var cx, cy, px, py;
  16413. ax = contour[ verts[ u ] ].x;
  16414. ay = contour[ verts[ u ] ].y;
  16415. bx = contour[ verts[ v ] ].x;
  16416. by = contour[ verts[ v ] ].y;
  16417. cx = contour[ verts[ w ] ].x;
  16418. cy = contour[ verts[ w ] ].y;
  16419. if ( EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false;
  16420. var aX, aY, bX, bY, cX, cY;
  16421. var apx, apy, bpx, bpy, cpx, cpy;
  16422. var cCROSSap, bCROSScp, aCROSSbp;
  16423. aX = cx - bx; aY = cy - by;
  16424. bX = ax - cx; bY = ay - cy;
  16425. cX = bx - ax; cY = by - ay;
  16426. for ( p = 0; p < n; p ++ ) {
  16427. px = contour[ verts[ p ] ].x
  16428. py = contour[ verts[ p ] ].y
  16429. if ( ( ( px === ax ) && ( py === ay ) ) ||
  16430. ( ( px === bx ) && ( py === by ) ) ||
  16431. ( ( px === cx ) && ( py === cy ) ) ) continue;
  16432. apx = px - ax; apy = py - ay;
  16433. bpx = px - bx; bpy = py - by;
  16434. cpx = px - cx; cpy = py - cy;
  16435. // see if p is inside triangle abc
  16436. aCROSSbp = aX * bpy - aY * bpx;
  16437. cCROSSap = cX * apy - cY * apx;
  16438. bCROSScp = bX * cpy - bY * cpx;
  16439. if ( ( aCROSSbp >= - EPSILON ) && ( bCROSScp >= - EPSILON ) && ( cCROSSap >= - EPSILON ) ) return false;
  16440. }
  16441. return true;
  16442. };
  16443. namespace.Triangulate = process;
  16444. namespace.Triangulate.area = area;
  16445. return namespace;
  16446. } )( THREE.FontUtils );
  16447. // To use the typeface.js face files, hook up the API
  16448. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  16449. THREE.typeface_js = self._typeface_js;
  16450. // File:src/extras/core/Curve.js
  16451. /**
  16452. * @author zz85 / http://www.lab4games.net/zz85/blog
  16453. * Extensible curve object
  16454. *
  16455. * Some common of Curve methods
  16456. * .getPoint(t), getTangent(t)
  16457. * .getPointAt(u), getTagentAt(u)
  16458. * .getPoints(), .getSpacedPoints()
  16459. * .getLength()
  16460. * .updateArcLengths()
  16461. *
  16462. * This following classes subclasses THREE.Curve:
  16463. *
  16464. * -- 2d classes --
  16465. * THREE.LineCurve
  16466. * THREE.QuadraticBezierCurve
  16467. * THREE.CubicBezierCurve
  16468. * THREE.SplineCurve
  16469. * THREE.ArcCurve
  16470. * THREE.EllipseCurve
  16471. *
  16472. * -- 3d classes --
  16473. * THREE.LineCurve3
  16474. * THREE.QuadraticBezierCurve3
  16475. * THREE.CubicBezierCurve3
  16476. * THREE.SplineCurve3
  16477. * THREE.ClosedSplineCurve3
  16478. *
  16479. * A series of curves can be represented as a THREE.CurvePath
  16480. *
  16481. **/
  16482. /**************************************************************
  16483. * Abstract Curve base class
  16484. **************************************************************/
  16485. THREE.Curve = function () {
  16486. };
  16487. // Virtual base class method to overwrite and implement in subclasses
  16488. // - t [0 .. 1]
  16489. THREE.Curve.prototype.getPoint = function ( t ) {
  16490. console.log( "Warning, getPoint() not implemented!" );
  16491. return null;
  16492. };
  16493. // Get point at relative position in curve according to arc length
  16494. // - u [0 .. 1]
  16495. THREE.Curve.prototype.getPointAt = function ( u ) {
  16496. var t = this.getUtoTmapping( u );
  16497. return this.getPoint( t );
  16498. };
  16499. // Get sequence of points using getPoint( t )
  16500. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16501. if ( ! divisions ) divisions = 5;
  16502. var d, pts = [];
  16503. for ( d = 0; d <= divisions; d ++ ) {
  16504. pts.push( this.getPoint( d / divisions ) );
  16505. }
  16506. return pts;
  16507. };
  16508. // Get sequence of points using getPointAt( u )
  16509. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16510. if ( ! divisions ) divisions = 5;
  16511. var d, pts = [];
  16512. for ( d = 0; d <= divisions; d ++ ) {
  16513. pts.push( this.getPointAt( d / divisions ) );
  16514. }
  16515. return pts;
  16516. };
  16517. // Get total curve arc length
  16518. THREE.Curve.prototype.getLength = function () {
  16519. var lengths = this.getLengths();
  16520. return lengths[ lengths.length - 1 ];
  16521. };
  16522. // Get list of cumulative segment lengths
  16523. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16524. if ( ! divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16525. if ( this.cacheArcLengths
  16526. && ( this.cacheArcLengths.length == divisions + 1 )
  16527. && ! this.needsUpdate) {
  16528. //console.log( "cached", this.cacheArcLengths );
  16529. return this.cacheArcLengths;
  16530. }
  16531. this.needsUpdate = false;
  16532. var cache = [];
  16533. var current, last = this.getPoint( 0 );
  16534. var p, sum = 0;
  16535. cache.push( 0 );
  16536. for ( p = 1; p <= divisions; p ++ ) {
  16537. current = this.getPoint ( p / divisions );
  16538. sum += current.distanceTo( last );
  16539. cache.push( sum );
  16540. last = current;
  16541. }
  16542. this.cacheArcLengths = cache;
  16543. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16544. };
  16545. THREE.Curve.prototype.updateArcLengths = function() {
  16546. this.needsUpdate = true;
  16547. this.getLengths();
  16548. };
  16549. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16550. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16551. var arcLengths = this.getLengths();
  16552. var i = 0, il = arcLengths.length;
  16553. var targetArcLength; // The targeted u distance value to get
  16554. if ( distance ) {
  16555. targetArcLength = distance;
  16556. } else {
  16557. targetArcLength = u * arcLengths[ il - 1 ];
  16558. }
  16559. //var time = Date.now();
  16560. // binary search for the index with largest value smaller than target u distance
  16561. var low = 0, high = il - 1, comparison;
  16562. while ( low <= high ) {
  16563. 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
  16564. comparison = arcLengths[ i ] - targetArcLength;
  16565. if ( comparison < 0 ) {
  16566. low = i + 1;
  16567. continue;
  16568. } else if ( comparison > 0 ) {
  16569. high = i - 1;
  16570. continue;
  16571. } else {
  16572. high = i;
  16573. break;
  16574. // DONE
  16575. }
  16576. }
  16577. i = high;
  16578. //console.log('b' , i, low, high, Date.now()- time);
  16579. if ( arcLengths[ i ] == targetArcLength ) {
  16580. var t = i / ( il - 1 );
  16581. return t;
  16582. }
  16583. // we could get finer grain at lengths, or use simple interpolatation between two points
  16584. var lengthBefore = arcLengths[ i ];
  16585. var lengthAfter = arcLengths[ i + 1 ];
  16586. var segmentLength = lengthAfter - lengthBefore;
  16587. // determine where we are between the 'before' and 'after' points
  16588. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16589. // add that fractional amount to t
  16590. var t = ( i + segmentFraction ) / ( il -1 );
  16591. return t;
  16592. };
  16593. // Returns a unit vector tangent at t
  16594. // In case any sub curve does not implement its tangent derivation,
  16595. // 2 points a small delta apart will be used to find its gradient
  16596. // which seems to give a reasonable approximation
  16597. THREE.Curve.prototype.getTangent = function( t ) {
  16598. var delta = 0.0001;
  16599. var t1 = t - delta;
  16600. var t2 = t + delta;
  16601. // Capping in case of danger
  16602. if ( t1 < 0 ) t1 = 0;
  16603. if ( t2 > 1 ) t2 = 1;
  16604. var pt1 = this.getPoint( t1 );
  16605. var pt2 = this.getPoint( t2 );
  16606. var vec = pt2.clone().sub(pt1);
  16607. return vec.normalize();
  16608. };
  16609. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16610. var t = this.getUtoTmapping( u );
  16611. return this.getTangent( t );
  16612. };
  16613. /**************************************************************
  16614. * Utils
  16615. **************************************************************/
  16616. THREE.Curve.Utils = {
  16617. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16618. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16619. },
  16620. // Puay Bing, thanks for helping with this derivative!
  16621. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16622. return - 3 * p0 * (1 - t) * (1 - t) +
  16623. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16624. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16625. 3 * t * t * p3;
  16626. },
  16627. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16628. // To check if my formulas are correct
  16629. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16630. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16631. var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2
  16632. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16633. return h00 + h10 + h01 + h11;
  16634. },
  16635. // Catmull-Rom
  16636. interpolate: function( p0, p1, p2, p3, t ) {
  16637. var v0 = ( p2 - p0 ) * 0.5;
  16638. var v1 = ( p3 - p1 ) * 0.5;
  16639. var t2 = t * t;
  16640. var t3 = t * t2;
  16641. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16642. }
  16643. };
  16644. // TODO: Transformation for Curves?
  16645. /**************************************************************
  16646. * 3D Curves
  16647. **************************************************************/
  16648. // A Factory method for creating new curve subclasses
  16649. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16650. constructor.prototype = Object.create( THREE.Curve.prototype );
  16651. constructor.prototype.getPoint = getPointFunc;
  16652. return constructor;
  16653. };
  16654. // File:src/extras/core/CurvePath.js
  16655. /**
  16656. * @author zz85 / http://www.lab4games.net/zz85/blog
  16657. *
  16658. **/
  16659. /**************************************************************
  16660. * Curved Path - a curve path is simply a array of connected
  16661. * curves, but retains the api of a curve
  16662. **************************************************************/
  16663. THREE.CurvePath = function () {
  16664. this.curves = [];
  16665. this.bends = [];
  16666. this.autoClose = false; // Automatically closes the path
  16667. };
  16668. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16669. THREE.CurvePath.prototype.add = function ( curve ) {
  16670. this.curves.push( curve );
  16671. };
  16672. THREE.CurvePath.prototype.checkConnection = function() {
  16673. // TODO
  16674. // If the ending of curve is not connected to the starting
  16675. // or the next curve, then, this is not a real path
  16676. };
  16677. THREE.CurvePath.prototype.closePath = function() {
  16678. // TODO Test
  16679. // and verify for vector3 (needs to implement equals)
  16680. // Add a line curve if start and end of lines are not connected
  16681. var startPoint = this.curves[0].getPoint(0);
  16682. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16683. if (! startPoint.equals(endPoint)) {
  16684. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16685. }
  16686. };
  16687. // To get accurate point with reference to
  16688. // entire path distance at time t,
  16689. // following has to be done:
  16690. // 1. Length of each sub path have to be known
  16691. // 2. Locate and identify type of curve
  16692. // 3. Get t for the curve
  16693. // 4. Return curve.getPointAt(t')
  16694. THREE.CurvePath.prototype.getPoint = function( t ) {
  16695. var d = t * this.getLength();
  16696. var curveLengths = this.getCurveLengths();
  16697. var i = 0, diff, curve;
  16698. // To think about boundaries points.
  16699. while ( i < curveLengths.length ) {
  16700. if ( curveLengths[ i ] >= d ) {
  16701. diff = curveLengths[ i ] - d;
  16702. curve = this.curves[ i ];
  16703. var u = 1 - diff / curve.getLength();
  16704. return curve.getPointAt( u );
  16705. break;
  16706. }
  16707. i ++;
  16708. }
  16709. return null;
  16710. // loop where sum != 0, sum > d , sum+1 <d
  16711. };
  16712. /*
  16713. THREE.CurvePath.prototype.getTangent = function( t ) {
  16714. };*/
  16715. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16716. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16717. // getPoint() depends on getLength
  16718. THREE.CurvePath.prototype.getLength = function() {
  16719. var lens = this.getCurveLengths();
  16720. return lens[ lens.length - 1 ];
  16721. };
  16722. // Compute lengths and cache them
  16723. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16724. THREE.CurvePath.prototype.getCurveLengths = function() {
  16725. // We use cache values if curves and cache array are same length
  16726. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16727. return this.cacheLengths;
  16728. };
  16729. // Get length of subsurve
  16730. // Push sums into cached array
  16731. var lengths = [], sums = 0;
  16732. var i, il = this.curves.length;
  16733. for ( i = 0; i < il; i ++ ) {
  16734. sums += this.curves[ i ].getLength();
  16735. lengths.push( sums );
  16736. }
  16737. this.cacheLengths = lengths;
  16738. return lengths;
  16739. };
  16740. // Returns min and max coordinates
  16741. THREE.CurvePath.prototype.getBoundingBox = function () {
  16742. var points = this.getPoints();
  16743. var maxX, maxY, maxZ;
  16744. var minX, minY, minZ;
  16745. maxX = maxY = Number.NEGATIVE_INFINITY;
  16746. minX = minY = Number.POSITIVE_INFINITY;
  16747. var p, i, il, sum;
  16748. var v3 = points[0] instanceof THREE.Vector3;
  16749. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16750. for ( i = 0, il = points.length; i < il; i ++ ) {
  16751. p = points[ i ];
  16752. if ( p.x > maxX ) maxX = p.x;
  16753. else if ( p.x < minX ) minX = p.x;
  16754. if ( p.y > maxY ) maxY = p.y;
  16755. else if ( p.y < minY ) minY = p.y;
  16756. if ( v3 ) {
  16757. if ( p.z > maxZ ) maxZ = p.z;
  16758. else if ( p.z < minZ ) minZ = p.z;
  16759. }
  16760. sum.add( p );
  16761. }
  16762. var ret = {
  16763. minX: minX,
  16764. minY: minY,
  16765. maxX: maxX,
  16766. maxY: maxY
  16767. };
  16768. if ( v3 ) {
  16769. ret.maxZ = maxZ;
  16770. ret.minZ = minZ;
  16771. }
  16772. return ret;
  16773. };
  16774. /**************************************************************
  16775. * Create Geometries Helpers
  16776. **************************************************************/
  16777. /// Generate geometry from path points (for Line or Points objects)
  16778. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16779. var pts = this.getPoints( divisions, true );
  16780. return this.createGeometry( pts );
  16781. };
  16782. // Generate geometry from equidistance sampling along the path
  16783. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16784. var pts = this.getSpacedPoints( divisions, true );
  16785. return this.createGeometry( pts );
  16786. };
  16787. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16788. var geometry = new THREE.Geometry();
  16789. for ( var i = 0; i < points.length; i ++ ) {
  16790. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16791. }
  16792. return geometry;
  16793. };
  16794. /**************************************************************
  16795. * Bend / Wrap Helper Methods
  16796. **************************************************************/
  16797. // Wrap path / Bend modifiers?
  16798. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16799. this.bends.push( bendpath );
  16800. };
  16801. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16802. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16803. var i, il;
  16804. if ( ! bends ) {
  16805. bends = this.bends;
  16806. }
  16807. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16808. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16809. }
  16810. return oldPts;
  16811. };
  16812. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16813. var oldPts = this.getSpacedPoints( segments );
  16814. var i, il;
  16815. if ( ! bends ) {
  16816. bends = this.bends;
  16817. }
  16818. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16819. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16820. }
  16821. return oldPts;
  16822. };
  16823. // This returns getPoints() bend/wrapped around the contour of a path.
  16824. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16825. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16826. var bounds = this.getBoundingBox();
  16827. var i, il, p, oldX, oldY, xNorm;
  16828. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16829. p = oldPts[ i ];
  16830. oldX = p.x;
  16831. oldY = p.y;
  16832. xNorm = oldX / bounds.maxX;
  16833. // If using actual distance, for length > path, requires line extrusions
  16834. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16835. xNorm = path.getUtoTmapping( xNorm, oldX );
  16836. // check for out of bounds?
  16837. var pathPt = path.getPoint( xNorm );
  16838. var normal = path.getTangent( xNorm );
  16839. normal.set( - normal.y, normal.x ).multiplyScalar( oldY );
  16840. p.x = pathPt.x + normal.x;
  16841. p.y = pathPt.y + normal.y;
  16842. }
  16843. return oldPts;
  16844. };
  16845. // File:src/extras/core/Gyroscope.js
  16846. /**
  16847. * @author alteredq / http://alteredqualia.com/
  16848. */
  16849. THREE.Gyroscope = function () {
  16850. THREE.Object3D.call( this );
  16851. };
  16852. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16853. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16854. this.matrixAutoUpdate && this.updateMatrix();
  16855. // update matrixWorld
  16856. if ( this.matrixWorldNeedsUpdate || force ) {
  16857. if ( this.parent ) {
  16858. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  16859. this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld );
  16860. this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject );
  16861. this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld );
  16862. } else {
  16863. this.matrixWorld.copy( this.matrix );
  16864. }
  16865. this.matrixWorldNeedsUpdate = false;
  16866. force = true;
  16867. }
  16868. // update children
  16869. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16870. this.children[ i ].updateMatrixWorld( force );
  16871. }
  16872. };
  16873. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16874. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16875. THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion();
  16876. THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion();
  16877. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16878. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16879. // File:src/extras/core/Path.js
  16880. /**
  16881. * @author zz85 / http://www.lab4games.net/zz85/blog
  16882. * Creates free form 2d path using series of points, lines or curves.
  16883. *
  16884. **/
  16885. THREE.Path = function ( points ) {
  16886. THREE.CurvePath.call(this);
  16887. this.actions = [];
  16888. if ( points ) {
  16889. this.fromPoints( points );
  16890. }
  16891. };
  16892. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16893. THREE.PathActions = {
  16894. MOVE_TO: 'moveTo',
  16895. LINE_TO: 'lineTo',
  16896. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16897. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16898. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16899. ARC: 'arc', // Circle
  16900. ELLIPSE: 'ellipse'
  16901. };
  16902. // TODO Clean up PATH API
  16903. // Create path using straight lines to connect all points
  16904. // - vectors: array of Vector2
  16905. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16906. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16907. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16908. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16909. };
  16910. };
  16911. // startPath() endPath()?
  16912. THREE.Path.prototype.moveTo = function ( x, y ) {
  16913. var args = Array.prototype.slice.call( arguments );
  16914. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16915. };
  16916. THREE.Path.prototype.lineTo = function ( x, y ) {
  16917. var args = Array.prototype.slice.call( arguments );
  16918. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16919. var x0 = lastargs[ lastargs.length - 2 ];
  16920. var y0 = lastargs[ lastargs.length - 1 ];
  16921. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16922. this.curves.push( curve );
  16923. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16924. };
  16925. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16926. var args = Array.prototype.slice.call( arguments );
  16927. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16928. var x0 = lastargs[ lastargs.length - 2 ];
  16929. var y0 = lastargs[ lastargs.length - 1 ];
  16930. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16931. new THREE.Vector2( aCPx, aCPy ),
  16932. new THREE.Vector2( aX, aY ) );
  16933. this.curves.push( curve );
  16934. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16935. };
  16936. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16937. aCP2x, aCP2y,
  16938. aX, aY ) {
  16939. var args = Array.prototype.slice.call( arguments );
  16940. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16941. var x0 = lastargs[ lastargs.length - 2 ];
  16942. var y0 = lastargs[ lastargs.length - 1 ];
  16943. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16944. new THREE.Vector2( aCP1x, aCP1y ),
  16945. new THREE.Vector2( aCP2x, aCP2y ),
  16946. new THREE.Vector2( aX, aY ) );
  16947. this.curves.push( curve );
  16948. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16949. };
  16950. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16951. var args = Array.prototype.slice.call( arguments );
  16952. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16953. var x0 = lastargs[ lastargs.length - 2 ];
  16954. var y0 = lastargs[ lastargs.length - 1 ];
  16955. //---
  16956. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16957. Array.prototype.push.apply( npts, pts );
  16958. var curve = new THREE.SplineCurve( npts );
  16959. this.curves.push( curve );
  16960. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16961. };
  16962. // FUTURE: Change the API or follow canvas API?
  16963. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16964. aStartAngle, aEndAngle, aClockwise ) {
  16965. var lastargs = this.actions[ this.actions.length - 1].args;
  16966. var x0 = lastargs[ lastargs.length - 2 ];
  16967. var y0 = lastargs[ lastargs.length - 1 ];
  16968. this.absarc(aX + x0, aY + y0, aRadius,
  16969. aStartAngle, aEndAngle, aClockwise );
  16970. };
  16971. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16972. aStartAngle, aEndAngle, aClockwise ) {
  16973. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16974. };
  16975. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16976. aStartAngle, aEndAngle, aClockwise ) {
  16977. var lastargs = this.actions[ this.actions.length - 1].args;
  16978. var x0 = lastargs[ lastargs.length - 2 ];
  16979. var y0 = lastargs[ lastargs.length - 1 ];
  16980. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16981. aStartAngle, aEndAngle, aClockwise );
  16982. };
  16983. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16984. aStartAngle, aEndAngle, aClockwise ) {
  16985. var args = Array.prototype.slice.call( arguments );
  16986. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16987. aStartAngle, aEndAngle, aClockwise );
  16988. this.curves.push( curve );
  16989. var lastPoint = curve.getPoint(1);
  16990. args.push(lastPoint.x);
  16991. args.push(lastPoint.y);
  16992. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16993. };
  16994. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16995. if ( ! divisions ) divisions = 40;
  16996. var points = [];
  16997. for ( var i = 0; i < divisions; i ++ ) {
  16998. points.push( this.getPoint( i / divisions ) );
  16999. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17000. }
  17001. // if ( closedPath ) {
  17002. //
  17003. // points.push( points[ 0 ] );
  17004. //
  17005. // }
  17006. return points;
  17007. };
  17008. /* Return an array of vectors based on contour of the path */
  17009. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17010. if (this.useSpacedPoints) {
  17011. console.log('tata');
  17012. return this.getSpacedPoints( divisions, closedPath );
  17013. }
  17014. divisions = divisions || 12;
  17015. var points = [];
  17016. var i, il, item, action, args;
  17017. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17018. laste, j,
  17019. t, tx, ty;
  17020. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17021. item = this.actions[ i ];
  17022. action = item.action;
  17023. args = item.args;
  17024. switch( action ) {
  17025. case THREE.PathActions.MOVE_TO:
  17026. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17027. break;
  17028. case THREE.PathActions.LINE_TO:
  17029. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17030. break;
  17031. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17032. cpx = args[ 2 ];
  17033. cpy = args[ 3 ];
  17034. cpx1 = args[ 0 ];
  17035. cpy1 = args[ 1 ];
  17036. if ( points.length > 0 ) {
  17037. laste = points[ points.length - 1 ];
  17038. cpx0 = laste.x;
  17039. cpy0 = laste.y;
  17040. } else {
  17041. laste = this.actions[ i - 1 ].args;
  17042. cpx0 = laste[ laste.length - 2 ];
  17043. cpy0 = laste[ laste.length - 1 ];
  17044. }
  17045. for ( j = 1; j <= divisions; j ++ ) {
  17046. t = j / divisions;
  17047. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17048. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17049. points.push( new THREE.Vector2( tx, ty ) );
  17050. }
  17051. break;
  17052. case THREE.PathActions.BEZIER_CURVE_TO:
  17053. cpx = args[ 4 ];
  17054. cpy = args[ 5 ];
  17055. cpx1 = args[ 0 ];
  17056. cpy1 = args[ 1 ];
  17057. cpx2 = args[ 2 ];
  17058. cpy2 = args[ 3 ];
  17059. if ( points.length > 0 ) {
  17060. laste = points[ points.length - 1 ];
  17061. cpx0 = laste.x;
  17062. cpy0 = laste.y;
  17063. } else {
  17064. laste = this.actions[ i - 1 ].args;
  17065. cpx0 = laste[ laste.length - 2 ];
  17066. cpy0 = laste[ laste.length - 1 ];
  17067. }
  17068. for ( j = 1; j <= divisions; j ++ ) {
  17069. t = j / divisions;
  17070. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17071. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17072. points.push( new THREE.Vector2( tx, ty ) );
  17073. }
  17074. break;
  17075. case THREE.PathActions.CSPLINE_THRU:
  17076. laste = this.actions[ i - 1 ].args;
  17077. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17078. var spts = [ last ];
  17079. var n = divisions * args[ 0 ].length;
  17080. spts = spts.concat( args[ 0 ] );
  17081. var spline = new THREE.SplineCurve( spts );
  17082. for ( j = 1; j <= n; j ++ ) {
  17083. points.push( spline.getPointAt( j / n ) ) ;
  17084. }
  17085. break;
  17086. case THREE.PathActions.ARC:
  17087. var aX = args[ 0 ], aY = args[ 1 ],
  17088. aRadius = args[ 2 ],
  17089. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17090. aClockwise = !! args[ 5 ];
  17091. var deltaAngle = aEndAngle - aStartAngle;
  17092. var angle;
  17093. var tdivisions = divisions * 2;
  17094. for ( j = 1; j <= tdivisions; j ++ ) {
  17095. t = j / tdivisions;
  17096. if ( ! aClockwise ) {
  17097. t = 1 - t;
  17098. }
  17099. angle = aStartAngle + t * deltaAngle;
  17100. tx = aX + aRadius * Math.cos( angle );
  17101. ty = aY + aRadius * Math.sin( angle );
  17102. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17103. points.push( new THREE.Vector2( tx, ty ) );
  17104. }
  17105. //console.log(points);
  17106. break;
  17107. case THREE.PathActions.ELLIPSE:
  17108. var aX = args[ 0 ], aY = args[ 1 ],
  17109. xRadius = args[ 2 ],
  17110. yRadius = args[ 3 ],
  17111. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17112. aClockwise = !! args[ 6 ];
  17113. var deltaAngle = aEndAngle - aStartAngle;
  17114. var angle;
  17115. var tdivisions = divisions * 2;
  17116. for ( j = 1; j <= tdivisions; j ++ ) {
  17117. t = j / tdivisions;
  17118. if ( ! aClockwise ) {
  17119. t = 1 - t;
  17120. }
  17121. angle = aStartAngle + t * deltaAngle;
  17122. tx = aX + xRadius * Math.cos( angle );
  17123. ty = aY + yRadius * Math.sin( angle );
  17124. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17125. points.push( new THREE.Vector2( tx, ty ) );
  17126. }
  17127. //console.log(points);
  17128. break;
  17129. } // end switch
  17130. }
  17131. // Normalize to remove the closing point by default.
  17132. var lastPoint = points[ points.length - 1];
  17133. var EPSILON = 0.0000000001;
  17134. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17135. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17136. points.splice( points.length - 1, 1);
  17137. if ( closedPath ) {
  17138. points.push( points[ 0 ] );
  17139. }
  17140. return points;
  17141. };
  17142. //
  17143. // Breaks path into shapes
  17144. //
  17145. // Assumptions (if parameter isCCW==true the opposite holds):
  17146. // - solid shapes are defined clockwise (CW)
  17147. // - holes are defined counterclockwise (CCW)
  17148. //
  17149. // If parameter noHoles==true:
  17150. // - all subPaths are regarded as solid shapes
  17151. // - definition order CW/CCW has no relevance
  17152. //
  17153. THREE.Path.prototype.toShapes = function( isCCW, noHoles ) {
  17154. function extractSubpaths( inActions ) {
  17155. var i, il, item, action, args;
  17156. var subPaths = [], lastPath = new THREE.Path();
  17157. for ( i = 0, il = inActions.length; i < il; i ++ ) {
  17158. item = inActions[ i ];
  17159. args = item.args;
  17160. action = item.action;
  17161. if ( action == THREE.PathActions.MOVE_TO ) {
  17162. if ( lastPath.actions.length != 0 ) {
  17163. subPaths.push( lastPath );
  17164. lastPath = new THREE.Path();
  17165. }
  17166. }
  17167. lastPath[ action ].apply( lastPath, args );
  17168. }
  17169. if ( lastPath.actions.length != 0 ) {
  17170. subPaths.push( lastPath );
  17171. }
  17172. // console.log(subPaths);
  17173. return subPaths;
  17174. }
  17175. function toShapesNoHoles( inSubpaths ) {
  17176. var shapes = [];
  17177. for ( var i = 0, il = inSubpaths.length; i < il; i ++ ) {
  17178. var tmpPath = inSubpaths[ i ];
  17179. var tmpShape = new THREE.Shape();
  17180. tmpShape.actions = tmpPath.actions;
  17181. tmpShape.curves = tmpPath.curves;
  17182. shapes.push( tmpShape );
  17183. }
  17184. //console.log("shape", shapes);
  17185. return shapes;
  17186. };
  17187. function isPointInsidePolygon( inPt, inPolygon ) {
  17188. var EPSILON = 0.0000000001;
  17189. var polyLen = inPolygon.length;
  17190. // inPt on polygon contour => immediate success or
  17191. // toggling of inside/outside at every single! intersection point of an edge
  17192. // with the horizontal line through inPt, left of inPt
  17193. // not counting lowerY endpoints of edges and whole edges on that line
  17194. var inside = false;
  17195. for( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  17196. var edgeLowPt = inPolygon[ p ];
  17197. var edgeHighPt = inPolygon[ q ];
  17198. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  17199. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  17200. if ( Math.abs(edgeDy) > EPSILON ) { // not parallel
  17201. if ( edgeDy < 0 ) {
  17202. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  17203. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  17204. }
  17205. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  17206. if ( inPt.y == edgeLowPt.y ) {
  17207. if ( inPt.x == edgeLowPt.x ) return true; // inPt is on contour ?
  17208. // continue; // no intersection or edgeLowPt => doesn't count !!!
  17209. } else {
  17210. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  17211. if ( perpEdge == 0 ) return true; // inPt is on contour ?
  17212. if ( perpEdge < 0 ) continue;
  17213. inside = ! inside; // true intersection left of inPt
  17214. }
  17215. } else { // parallel or colinear
  17216. if ( inPt.y != edgeLowPt.y ) continue; // parallel
  17217. // egde lies on the same horizontal line as inPt
  17218. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  17219. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  17220. // continue;
  17221. }
  17222. }
  17223. return inside;
  17224. }
  17225. var subPaths = extractSubpaths( this.actions );
  17226. if ( subPaths.length == 0 ) return [];
  17227. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  17228. var solid, tmpPath, tmpShape, shapes = [];
  17229. if ( subPaths.length == 1) {
  17230. tmpPath = subPaths[0];
  17231. tmpShape = new THREE.Shape();
  17232. tmpShape.actions = tmpPath.actions;
  17233. tmpShape.curves = tmpPath.curves;
  17234. shapes.push( tmpShape );
  17235. return shapes;
  17236. }
  17237. var holesFirst = ! THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17238. holesFirst = isCCW ? ! holesFirst : holesFirst;
  17239. // console.log("Holes first", holesFirst);
  17240. var betterShapeHoles = [];
  17241. var newShapes = [];
  17242. var newShapeHoles = [];
  17243. var mainIdx = 0;
  17244. var tmpPoints;
  17245. newShapes[mainIdx] = undefined;
  17246. newShapeHoles[mainIdx] = [];
  17247. var i, il;
  17248. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17249. tmpPath = subPaths[ i ];
  17250. tmpPoints = tmpPath.getPoints();
  17251. solid = THREE.Shape.Utils.isClockWise( tmpPoints );
  17252. solid = isCCW ? ! solid : solid;
  17253. if ( solid ) {
  17254. if ( (! holesFirst ) && ( newShapes[mainIdx] ) ) mainIdx ++;
  17255. newShapes[mainIdx] = { s: new THREE.Shape(), p: tmpPoints };
  17256. newShapes[mainIdx].s.actions = tmpPath.actions;
  17257. newShapes[mainIdx].s.curves = tmpPath.curves;
  17258. if ( holesFirst ) mainIdx ++;
  17259. newShapeHoles[mainIdx] = [];
  17260. //console.log('cw', i);
  17261. } else {
  17262. newShapeHoles[mainIdx].push( { h: tmpPath, p: tmpPoints[0] } );
  17263. //console.log('ccw', i);
  17264. }
  17265. }
  17266. // only Holes? -> probably all Shapes with wrong orientation
  17267. if ( ! newShapes[0] ) return toShapesNoHoles( subPaths );
  17268. if ( newShapes.length > 1 ) {
  17269. var ambigious = false;
  17270. var toChange = [];
  17271. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  17272. betterShapeHoles[sIdx] = [];
  17273. }
  17274. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  17275. var sh = newShapes[sIdx];
  17276. var sho = newShapeHoles[sIdx];
  17277. for (var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  17278. var ho = sho[hIdx];
  17279. var hole_unassigned = true;
  17280. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  17281. if ( isPointInsidePolygon( ho.p, newShapes[s2Idx].p ) ) {
  17282. if ( sIdx != s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  17283. if ( hole_unassigned ) {
  17284. hole_unassigned = false;
  17285. betterShapeHoles[s2Idx].push( ho );
  17286. } else {
  17287. ambigious = true;
  17288. }
  17289. }
  17290. }
  17291. if ( hole_unassigned ) { betterShapeHoles[sIdx].push( ho ); }
  17292. }
  17293. }
  17294. // console.log("ambigious: ", ambigious);
  17295. if ( toChange.length > 0 ) {
  17296. // console.log("to change: ", toChange);
  17297. if (! ambigious) newShapeHoles = betterShapeHoles;
  17298. }
  17299. }
  17300. var tmpHoles, j, jl;
  17301. for ( i = 0, il = newShapes.length; i < il; i ++ ) {
  17302. tmpShape = newShapes[i].s;
  17303. shapes.push( tmpShape );
  17304. tmpHoles = newShapeHoles[i];
  17305. for ( j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  17306. tmpShape.holes.push( tmpHoles[j].h );
  17307. }
  17308. }
  17309. //console.log("shape", shapes);
  17310. return shapes;
  17311. };
  17312. // File:src/extras/core/Shape.js
  17313. /**
  17314. * @author zz85 / http://www.lab4games.net/zz85/blog
  17315. * Defines a 2d shape plane using paths.
  17316. **/
  17317. // STEP 1 Create a path.
  17318. // STEP 2 Turn path into shape.
  17319. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17320. // STEP 3a - Extract points from each shape, turn to vertices
  17321. // STEP 3b - Triangulate each shape, add faces.
  17322. THREE.Shape = function () {
  17323. THREE.Path.apply( this, arguments );
  17324. this.holes = [];
  17325. };
  17326. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17327. // Convenience method to return ExtrudeGeometry
  17328. THREE.Shape.prototype.extrude = function ( options ) {
  17329. var extruded = new THREE.ExtrudeGeometry( this, options );
  17330. return extruded;
  17331. };
  17332. // Convenience method to return ShapeGeometry
  17333. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17334. var geometry = new THREE.ShapeGeometry( this, options );
  17335. return geometry;
  17336. };
  17337. // Get points of holes
  17338. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17339. var i, il = this.holes.length, holesPts = [];
  17340. for ( i = 0; i < il; i ++ ) {
  17341. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17342. }
  17343. return holesPts;
  17344. };
  17345. // Get points of holes (spaced by regular distance)
  17346. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17347. var i, il = this.holes.length, holesPts = [];
  17348. for ( i = 0; i < il; i ++ ) {
  17349. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17350. }
  17351. return holesPts;
  17352. };
  17353. // Get points of shape and holes (keypoints based on segments parameter)
  17354. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17355. return {
  17356. shape: this.getTransformedPoints( divisions ),
  17357. holes: this.getPointsHoles( divisions )
  17358. };
  17359. };
  17360. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17361. if (this.useSpacedPoints) {
  17362. return this.extractAllSpacedPoints(divisions);
  17363. }
  17364. return this.extractAllPoints(divisions);
  17365. };
  17366. //
  17367. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17368. //
  17369. // return {
  17370. //
  17371. // shape: this.transform( bend, divisions ),
  17372. // holes: this.getPointsHoles( divisions, bend )
  17373. //
  17374. // };
  17375. //
  17376. // };
  17377. // Get points of shape and holes (spaced by regular distance)
  17378. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17379. return {
  17380. shape: this.getTransformedSpacedPoints( divisions ),
  17381. holes: this.getSpacedPointsHoles( divisions )
  17382. };
  17383. };
  17384. /**************************************************************
  17385. * Utils
  17386. **************************************************************/
  17387. THREE.Shape.Utils = {
  17388. triangulateShape: function ( contour, holes ) {
  17389. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  17390. // inOtherPt needs to be colinear to the inSegment
  17391. if ( inSegPt1.x != inSegPt2.x ) {
  17392. if ( inSegPt1.x < inSegPt2.x ) {
  17393. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  17394. } else {
  17395. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  17396. }
  17397. } else {
  17398. if ( inSegPt1.y < inSegPt2.y ) {
  17399. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  17400. } else {
  17401. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  17402. }
  17403. }
  17404. }
  17405. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  17406. var EPSILON = 0.0000000001;
  17407. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  17408. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  17409. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  17410. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  17411. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  17412. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  17413. if ( Math.abs(limit) > EPSILON ) { // not parallel
  17414. var perpSeg2;
  17415. if ( limit > 0 ) {
  17416. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  17417. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17418. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  17419. } else {
  17420. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  17421. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17422. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  17423. }
  17424. // i.e. to reduce rounding errors
  17425. // intersection at endpoint of segment#1?
  17426. if ( perpSeg2 == 0 ) {
  17427. if ( ( inExcludeAdjacentSegs ) &&
  17428. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17429. return [ inSeg1Pt1 ];
  17430. }
  17431. if ( perpSeg2 == limit ) {
  17432. if ( ( inExcludeAdjacentSegs ) &&
  17433. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17434. return [ inSeg1Pt2 ];
  17435. }
  17436. // intersection at endpoint of segment#2?
  17437. if ( perpSeg1 == 0 ) return [ inSeg2Pt1 ];
  17438. if ( perpSeg1 == limit ) return [ inSeg2Pt2 ];
  17439. // return real intersection point
  17440. var factorSeg1 = perpSeg2 / limit;
  17441. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  17442. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  17443. } else { // parallel or colinear
  17444. if ( ( perpSeg1 != 0 ) ||
  17445. ( seg2dy * seg1seg2dx != seg2dx * seg1seg2dy ) ) return [];
  17446. // they are collinear or degenerate
  17447. var seg1Pt = ( (seg1dx == 0) && (seg1dy == 0) ); // segment1 ist just a point?
  17448. var seg2Pt = ( (seg2dx == 0) && (seg2dy == 0) ); // segment2 ist just a point?
  17449. // both segments are points
  17450. if ( seg1Pt && seg2Pt ) {
  17451. if ( (inSeg1Pt1.x != inSeg2Pt1.x) ||
  17452. (inSeg1Pt1.y != inSeg2Pt1.y) ) return []; // they are distinct points
  17453. return [ inSeg1Pt1 ]; // they are the same point
  17454. }
  17455. // segment#1 is a single point
  17456. if ( seg1Pt ) {
  17457. if (! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  17458. return [ inSeg1Pt1 ];
  17459. }
  17460. // segment#2 is a single point
  17461. if ( seg2Pt ) {
  17462. if (! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  17463. return [ inSeg2Pt1 ];
  17464. }
  17465. // they are collinear segments, which might overlap
  17466. var seg1min, seg1max, seg1minVal, seg1maxVal;
  17467. var seg2min, seg2max, seg2minVal, seg2maxVal;
  17468. if (seg1dx != 0) { // the segments are NOT on a vertical line
  17469. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  17470. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  17471. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  17472. } else {
  17473. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  17474. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  17475. }
  17476. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  17477. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  17478. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  17479. } else {
  17480. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  17481. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  17482. }
  17483. } else { // the segments are on a vertical line
  17484. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  17485. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  17486. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  17487. } else {
  17488. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  17489. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  17490. }
  17491. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  17492. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  17493. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  17494. } else {
  17495. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  17496. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  17497. }
  17498. }
  17499. if ( seg1minVal <= seg2minVal ) {
  17500. if ( seg1maxVal < seg2minVal ) return [];
  17501. if ( seg1maxVal == seg2minVal ) {
  17502. if ( inExcludeAdjacentSegs ) return [];
  17503. return [ seg2min ];
  17504. }
  17505. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  17506. return [ seg2min, seg2max ];
  17507. } else {
  17508. if ( seg1minVal > seg2maxVal ) return [];
  17509. if ( seg1minVal == seg2maxVal ) {
  17510. if ( inExcludeAdjacentSegs ) return [];
  17511. return [ seg1min ];
  17512. }
  17513. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  17514. return [ seg1min, seg2max ];
  17515. }
  17516. }
  17517. }
  17518. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  17519. // The order of legs is important
  17520. var EPSILON = 0.0000000001;
  17521. // translation of all points, so that Vertex is at (0,0)
  17522. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  17523. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  17524. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  17525. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  17526. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  17527. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  17528. if ( Math.abs(from2toAngle) > EPSILON ) { // angle != 180 deg.
  17529. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  17530. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  17531. if ( from2toAngle > 0 ) { // main angle < 180 deg.
  17532. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  17533. } else { // main angle > 180 deg.
  17534. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  17535. }
  17536. } else { // angle == 180 deg.
  17537. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  17538. return ( from2otherAngle > 0 );
  17539. }
  17540. }
  17541. function removeHoles( contour, holes ) {
  17542. var shape = contour.concat(); // work on this shape
  17543. var hole;
  17544. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  17545. // Check if hole point lies within angle around shape point
  17546. var lastShapeIdx = shape.length - 1;
  17547. var prevShapeIdx = inShapeIdx - 1;
  17548. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  17549. var nextShapeIdx = inShapeIdx + 1;
  17550. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  17551. var insideAngle = isPointInsideAngle( shape[inShapeIdx], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[inHoleIdx] );
  17552. if (! insideAngle ) {
  17553. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  17554. return false;
  17555. }
  17556. // Check if shape point lies within angle around hole point
  17557. var lastHoleIdx = hole.length - 1;
  17558. var prevHoleIdx = inHoleIdx - 1;
  17559. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  17560. var nextHoleIdx = inHoleIdx + 1;
  17561. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  17562. insideAngle = isPointInsideAngle( hole[inHoleIdx], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[inShapeIdx] );
  17563. if (! insideAngle ) {
  17564. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  17565. return false;
  17566. }
  17567. return true;
  17568. }
  17569. function intersectsShapeEdge( inShapePt, inHolePt ) {
  17570. // checks for intersections with shape edges
  17571. var sIdx, nextIdx, intersection;
  17572. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  17573. nextIdx = sIdx+1; nextIdx %= shape.length;
  17574. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[sIdx], shape[nextIdx], true );
  17575. if ( intersection.length > 0 ) return true;
  17576. }
  17577. return false;
  17578. }
  17579. var indepHoles = [];
  17580. function intersectsHoleEdge( inShapePt, inHolePt ) {
  17581. // checks for intersections with hole edges
  17582. var ihIdx, chkHole,
  17583. hIdx, nextIdx, intersection;
  17584. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  17585. chkHole = holes[indepHoles[ihIdx]];
  17586. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  17587. nextIdx = hIdx+1; nextIdx %= chkHole.length;
  17588. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[hIdx], chkHole[nextIdx], true );
  17589. if ( intersection.length > 0 ) return true;
  17590. }
  17591. }
  17592. return false;
  17593. }
  17594. var holeIndex, shapeIndex,
  17595. shapePt, holePt,
  17596. holeIdx, cutKey, failedCuts = [],
  17597. tmpShape1, tmpShape2,
  17598. tmpHole1, tmpHole2;
  17599. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17600. indepHoles.push( h );
  17601. }
  17602. var minShapeIndex = 0;
  17603. var counter = indepHoles.length * 2;
  17604. while ( indepHoles.length > 0 ) {
  17605. counter --;
  17606. if ( counter < 0 ) {
  17607. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  17608. break;
  17609. }
  17610. // search for shape-vertex and hole-vertex,
  17611. // which can be connected without intersections
  17612. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  17613. shapePt = shape[ shapeIndex ];
  17614. holeIndex = - 1;
  17615. // search for hole which can be reached without intersections
  17616. for ( var h = 0; h < indepHoles.length; h ++ ) {
  17617. holeIdx = indepHoles[h];
  17618. // prevent multiple checks
  17619. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  17620. if ( failedCuts[cutKey] !== undefined ) continue;
  17621. hole = holes[holeIdx];
  17622. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  17623. holePt = hole[ h2 ];
  17624. if (! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  17625. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  17626. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  17627. holeIndex = h2;
  17628. indepHoles.splice(h,1);
  17629. tmpShape1 = shape.slice( 0, shapeIndex+1 );
  17630. tmpShape2 = shape.slice( shapeIndex );
  17631. tmpHole1 = hole.slice( holeIndex );
  17632. tmpHole2 = hole.slice( 0, holeIndex+1 );
  17633. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17634. minShapeIndex = shapeIndex;
  17635. // Debug only, to show the selected cuts
  17636. // glob_CutLines.push( [ shapePt, holePt ] );
  17637. break;
  17638. }
  17639. if ( holeIndex >= 0 ) break; // hole-vertex found
  17640. failedCuts[cutKey] = true; // remember failure
  17641. }
  17642. if ( holeIndex >= 0 ) break; // hole-vertex found
  17643. }
  17644. }
  17645. return shape; /* shape with no holes */
  17646. }
  17647. var i, il, f, face,
  17648. key, index,
  17649. allPointsMap = {};
  17650. // 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.
  17651. var allpoints = contour.concat();
  17652. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17653. Array.prototype.push.apply( allpoints, holes[h] );
  17654. }
  17655. //console.log( "allpoints",allpoints, allpoints.length );
  17656. // prepare all points map
  17657. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17658. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17659. if ( allPointsMap[ key ] !== undefined ) {
  17660. console.log( "Duplicate point", key );
  17661. }
  17662. allPointsMap[ key ] = i;
  17663. }
  17664. // remove holes by cutting paths to holes and adding them to the shape
  17665. var shapeWithoutHoles = removeHoles( contour, holes );
  17666. var triangles = THREE.FontUtils.Triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  17667. //console.log( "triangles",triangles, triangles.length );
  17668. // check all face vertices against all points map
  17669. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17670. face = triangles[ i ];
  17671. for ( f = 0; f < 3; f ++ ) {
  17672. key = face[ f ].x + ":" + face[ f ].y;
  17673. index = allPointsMap[ key ];
  17674. if ( index !== undefined ) {
  17675. face[ f ] = index;
  17676. }
  17677. }
  17678. }
  17679. return triangles.concat();
  17680. },
  17681. isClockWise: function ( pts ) {
  17682. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17683. },
  17684. // Bezier Curves formulas obtained from
  17685. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17686. // Quad Bezier Functions
  17687. b2p0: function ( t, p ) {
  17688. var k = 1 - t;
  17689. return k * k * p;
  17690. },
  17691. b2p1: function ( t, p ) {
  17692. return 2 * ( 1 - t ) * t * p;
  17693. },
  17694. b2p2: function ( t, p ) {
  17695. return t * t * p;
  17696. },
  17697. b2: function ( t, p0, p1, p2 ) {
  17698. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17699. },
  17700. // Cubic Bezier Functions
  17701. b3p0: function ( t, p ) {
  17702. var k = 1 - t;
  17703. return k * k * k * p;
  17704. },
  17705. b3p1: function ( t, p ) {
  17706. var k = 1 - t;
  17707. return 3 * k * k * t * p;
  17708. },
  17709. b3p2: function ( t, p ) {
  17710. var k = 1 - t;
  17711. return 3 * k * t * t * p;
  17712. },
  17713. b3p3: function ( t, p ) {
  17714. return t * t * t * p;
  17715. },
  17716. b3: function ( t, p0, p1, p2, p3 ) {
  17717. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17718. }
  17719. };
  17720. // File:src/extras/curves/LineCurve.js
  17721. /**************************************************************
  17722. * Line
  17723. **************************************************************/
  17724. THREE.LineCurve = function ( v1, v2 ) {
  17725. this.v1 = v1;
  17726. this.v2 = v2;
  17727. };
  17728. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  17729. THREE.LineCurve.prototype.getPoint = function ( t ) {
  17730. var point = this.v2.clone().sub(this.v1);
  17731. point.multiplyScalar( t ).add( this.v1 );
  17732. return point;
  17733. };
  17734. // Line curve is linear, so we can overwrite default getPointAt
  17735. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  17736. return this.getPoint( u );
  17737. };
  17738. THREE.LineCurve.prototype.getTangent = function( t ) {
  17739. var tangent = this.v2.clone().sub(this.v1);
  17740. return tangent.normalize();
  17741. };
  17742. // File:src/extras/curves/QuadraticBezierCurve.js
  17743. /**************************************************************
  17744. * Quadratic Bezier curve
  17745. **************************************************************/
  17746. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  17747. this.v0 = v0;
  17748. this.v1 = v1;
  17749. this.v2 = v2;
  17750. };
  17751. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17752. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  17753. var tx, ty;
  17754. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17755. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17756. return new THREE.Vector2( tx, ty );
  17757. };
  17758. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  17759. var tx, ty;
  17760. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  17761. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  17762. // returns unit vector
  17763. var tangent = new THREE.Vector2( tx, ty );
  17764. tangent.normalize();
  17765. return tangent;
  17766. };
  17767. // File:src/extras/curves/CubicBezierCurve.js
  17768. /**************************************************************
  17769. * Cubic Bezier curve
  17770. **************************************************************/
  17771. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  17772. this.v0 = v0;
  17773. this.v1 = v1;
  17774. this.v2 = v2;
  17775. this.v3 = v3;
  17776. };
  17777. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17778. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  17779. var tx, ty;
  17780. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17781. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17782. return new THREE.Vector2( tx, ty );
  17783. };
  17784. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  17785. var tx, ty;
  17786. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17787. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17788. var tangent = new THREE.Vector2( tx, ty );
  17789. tangent.normalize();
  17790. return tangent;
  17791. };
  17792. // File:src/extras/curves/SplineCurve.js
  17793. /**************************************************************
  17794. * Spline curve
  17795. **************************************************************/
  17796. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  17797. this.points = (points == undefined) ? [] : points;
  17798. };
  17799. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  17800. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  17801. var v = new THREE.Vector2();
  17802. var c = [];
  17803. var points = this.points, point, intPoint, weight;
  17804. point = ( points.length - 1 ) * t;
  17805. intPoint = Math.floor( point );
  17806. weight = point - intPoint;
  17807. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17808. c[ 1 ] = intPoint;
  17809. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  17810. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  17811. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  17812. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  17813. return v;
  17814. };
  17815. // File:src/extras/curves/EllipseCurve.js
  17816. /**************************************************************
  17817. * Ellipse curve
  17818. **************************************************************/
  17819. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) {
  17820. this.aX = aX;
  17821. this.aY = aY;
  17822. this.xRadius = xRadius;
  17823. this.yRadius = yRadius;
  17824. this.aStartAngle = aStartAngle;
  17825. this.aEndAngle = aEndAngle;
  17826. this.aClockwise = aClockwise;
  17827. };
  17828. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  17829. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  17830. var angle;
  17831. var deltaAngle = this.aEndAngle - this.aStartAngle;
  17832. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  17833. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  17834. if ( this.aClockwise === true ) {
  17835. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  17836. } else {
  17837. angle = this.aStartAngle + t * deltaAngle;
  17838. }
  17839. var tx = this.aX + this.xRadius * Math.cos( angle );
  17840. var ty = this.aY + this.yRadius * Math.sin( angle );
  17841. return new THREE.Vector2( tx, ty );
  17842. };
  17843. // File:src/extras/curves/ArcCurve.js
  17844. /**************************************************************
  17845. * Arc curve
  17846. **************************************************************/
  17847. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  17848. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  17849. };
  17850. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  17851. // File:src/extras/curves/LineCurve3.js
  17852. /**************************************************************
  17853. * Line3D
  17854. **************************************************************/
  17855. THREE.LineCurve3 = THREE.Curve.create(
  17856. function ( v1, v2 ) {
  17857. this.v1 = v1;
  17858. this.v2 = v2;
  17859. },
  17860. function ( t ) {
  17861. var r = new THREE.Vector3();
  17862. r.subVectors( this.v2, this.v1 ); // diff
  17863. r.multiplyScalar( t );
  17864. r.add( this.v1 );
  17865. return r;
  17866. }
  17867. );
  17868. // File:src/extras/curves/QuadraticBezierCurve3.js
  17869. /**************************************************************
  17870. * Quadratic Bezier 3D curve
  17871. **************************************************************/
  17872. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  17873. function ( v0, v1, v2 ) {
  17874. this.v0 = v0;
  17875. this.v1 = v1;
  17876. this.v2 = v2;
  17877. },
  17878. function ( t ) {
  17879. var tx, ty, tz;
  17880. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17881. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17882. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  17883. return new THREE.Vector3( tx, ty, tz );
  17884. }
  17885. );
  17886. // File:src/extras/curves/CubicBezierCurve3.js
  17887. /**************************************************************
  17888. * Cubic Bezier 3D curve
  17889. **************************************************************/
  17890. THREE.CubicBezierCurve3 = THREE.Curve.create(
  17891. function ( v0, v1, v2, v3 ) {
  17892. this.v0 = v0;
  17893. this.v1 = v1;
  17894. this.v2 = v2;
  17895. this.v3 = v3;
  17896. },
  17897. function ( t ) {
  17898. var tx, ty, tz;
  17899. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17900. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17901. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  17902. return new THREE.Vector3( tx, ty, tz );
  17903. }
  17904. );
  17905. // File:src/extras/curves/SplineCurve3.js
  17906. /**************************************************************
  17907. * Spline 3D curve
  17908. **************************************************************/
  17909. THREE.SplineCurve3 = THREE.Curve.create(
  17910. function ( points /* array of Vector3 */) {
  17911. this.points = (points == undefined) ? [] : points;
  17912. },
  17913. function ( t ) {
  17914. var v = new THREE.Vector3();
  17915. var c = [];
  17916. var points = this.points, point, intPoint, weight;
  17917. point = ( points.length - 1 ) * t;
  17918. intPoint = Math.floor( point );
  17919. weight = point - intPoint;
  17920. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17921. c[ 1 ] = intPoint;
  17922. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17923. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17924. var pt0 = points[ c[0] ],
  17925. pt1 = points[ c[1] ],
  17926. pt2 = points[ c[2] ],
  17927. pt3 = points[ c[3] ];
  17928. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  17929. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  17930. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  17931. return v;
  17932. }
  17933. );
  17934. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  17935. // var v = new THREE.Vector3();
  17936. // var c = [];
  17937. // var points = this.points, point, intPoint, weight;
  17938. // point = ( points.length - 1 ) * t;
  17939. // intPoint = Math.floor( point );
  17940. // weight = point - intPoint;
  17941. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17942. // c[ 1 ] = intPoint;
  17943. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17944. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17945. // var pt0 = points[ c[0] ],
  17946. // pt1 = points[ c[1] ],
  17947. // pt2 = points[ c[2] ],
  17948. // pt3 = points[ c[3] ];
  17949. // // t = weight;
  17950. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  17951. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  17952. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  17953. // return v;
  17954. // }
  17955. // File:src/extras/curves/ClosedSplineCurve3.js
  17956. /**************************************************************
  17957. * Closed Spline 3D curve
  17958. **************************************************************/
  17959. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  17960. function ( points /* array of Vector3 */) {
  17961. this.points = (points == undefined) ? [] : points;
  17962. },
  17963. function ( t ) {
  17964. var v = new THREE.Vector3();
  17965. var c = [];
  17966. var points = this.points, point, intPoint, weight;
  17967. point = ( points.length - 0 ) * t;
  17968. // This needs to be from 0-length +1
  17969. intPoint = Math.floor( point );
  17970. weight = point - intPoint;
  17971. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  17972. c[ 0 ] = ( intPoint - 1 ) % points.length;
  17973. c[ 1 ] = ( intPoint ) % points.length;
  17974. c[ 2 ] = ( intPoint + 1 ) % points.length;
  17975. c[ 3 ] = ( intPoint + 2 ) % points.length;
  17976. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  17977. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  17978. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  17979. return v;
  17980. }
  17981. );
  17982. // File:src/extras/animation/AnimationHandler.js
  17983. /**
  17984. * @author mikael emtinger / http://gomo.se/
  17985. */
  17986. THREE.AnimationHandler = {
  17987. LINEAR: 0,
  17988. CATMULLROM: 1,
  17989. CATMULLROM_FORWARD: 2,
  17990. //
  17991. add: function () { console.warn( 'THREE.AnimationHandler.add() has been deprecated.' ); },
  17992. get: function () { console.warn( 'THREE.AnimationHandler.get() has been deprecated.' ); },
  17993. remove: function () { console.warn( 'THREE.AnimationHandler.remove() has been deprecated.' ); },
  17994. //
  17995. animations: [],
  17996. init: function ( data ) {
  17997. if ( data.initialized === true ) return;
  17998. // loop through all keys
  17999. for ( var h = 0; h < data.hierarchy.length; h ++ ) {
  18000. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18001. // remove minus times
  18002. if ( data.hierarchy[ h ].keys[ k ].time < 0 ) {
  18003. data.hierarchy[ h ].keys[ k ].time = 0;
  18004. }
  18005. // create quaternions
  18006. if ( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  18007. ! ( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  18008. var quat = data.hierarchy[ h ].keys[ k ].rot;
  18009. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion().fromArray( quat );
  18010. }
  18011. }
  18012. // prepare morph target keys
  18013. if ( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  18014. // get all used
  18015. var usedMorphTargets = {};
  18016. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18017. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18018. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  18019. usedMorphTargets[ morphTargetName ] = - 1;
  18020. }
  18021. }
  18022. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  18023. // set all used on all frames
  18024. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18025. var influences = {};
  18026. for ( var morphTargetName in usedMorphTargets ) {
  18027. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18028. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  18029. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  18030. break;
  18031. }
  18032. }
  18033. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  18034. influences[ morphTargetName ] = 0;
  18035. }
  18036. }
  18037. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  18038. }
  18039. }
  18040. // remove all keys that are on the same time
  18041. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18042. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  18043. data.hierarchy[ h ].keys.splice( k, 1 );
  18044. k --;
  18045. }
  18046. }
  18047. // set index
  18048. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18049. data.hierarchy[ h ].keys[ k ].index = k;
  18050. }
  18051. }
  18052. data.initialized = true;
  18053. return data;
  18054. },
  18055. parse: function ( root ) {
  18056. var parseRecurseHierarchy = function ( root, hierarchy ) {
  18057. hierarchy.push( root );
  18058. for ( var c = 0; c < root.children.length; c ++ )
  18059. parseRecurseHierarchy( root.children[ c ], hierarchy );
  18060. };
  18061. // setup hierarchy
  18062. var hierarchy = [];
  18063. if ( root instanceof THREE.SkinnedMesh ) {
  18064. for ( var b = 0; b < root.skeleton.bones.length; b ++ ) {
  18065. hierarchy.push( root.skeleton.bones[ b ] );
  18066. }
  18067. } else {
  18068. parseRecurseHierarchy( root, hierarchy );
  18069. }
  18070. return hierarchy;
  18071. },
  18072. play: function ( animation ) {
  18073. if ( this.animations.indexOf( animation ) === - 1 ) {
  18074. this.animations.push( animation );
  18075. }
  18076. },
  18077. stop: function ( animation ) {
  18078. var index = this.animations.indexOf( animation );
  18079. if ( index !== - 1 ) {
  18080. this.animations.splice( index, 1 );
  18081. }
  18082. },
  18083. update: function ( deltaTimeMS ) {
  18084. for ( var i = 0; i < this.animations.length; i ++ ) {
  18085. this.animations[ i ].update( deltaTimeMS );
  18086. }
  18087. }
  18088. };
  18089. // File:src/extras/animation/Animation.js
  18090. /**
  18091. * @author mikael emtinger / http://gomo.se/
  18092. * @author mrdoob / http://mrdoob.com/
  18093. * @author alteredq / http://alteredqualia.com/
  18094. */
  18095. THREE.Animation = function ( root, data ) {
  18096. this.root = root;
  18097. this.data = THREE.AnimationHandler.init( data );
  18098. this.hierarchy = THREE.AnimationHandler.parse( root );
  18099. this.currentTime = 0;
  18100. this.timeScale = 1;
  18101. this.isPlaying = false;
  18102. this.loop = true;
  18103. this.weight = 0;
  18104. this.interpolationType = THREE.AnimationHandler.LINEAR;
  18105. };
  18106. THREE.Animation.prototype.keyTypes = [ "pos", "rot", "scl" ];
  18107. THREE.Animation.prototype.play = function ( startTime, weight ) {
  18108. this.currentTime = startTime !== undefined ? startTime : 0;
  18109. this.weight = weight !== undefined ? weight: 1;
  18110. this.isPlaying = true;
  18111. this.reset();
  18112. THREE.AnimationHandler.play( this );
  18113. };
  18114. THREE.Animation.prototype.stop = function() {
  18115. this.isPlaying = false;
  18116. THREE.AnimationHandler.stop( this );
  18117. };
  18118. THREE.Animation.prototype.reset = function () {
  18119. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18120. var object = this.hierarchy[ h ];
  18121. object.matrixAutoUpdate = true;
  18122. if ( object.animationCache === undefined ) {
  18123. object.animationCache = {};
  18124. }
  18125. if ( object.animationCache[this.data.name] === undefined ) {
  18126. object.animationCache[this.data.name] = {};
  18127. object.animationCache[this.data.name].prevKey = { pos: 0, rot: 0, scl: 0 };
  18128. object.animationCache[this.data.name].nextKey = { pos: 0, rot: 0, scl: 0 };
  18129. object.animationCache[this.data.name].originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18130. }
  18131. var animationCache = object.animationCache[this.data.name];
  18132. // Get keys to match our current time
  18133. for ( var t = 0; t < 3; t ++ ) {
  18134. var type = this.keyTypes[ t ];
  18135. var prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18136. var nextKey = this.getNextKeyWith( type, h, 1 );
  18137. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18138. prevKey = nextKey;
  18139. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18140. }
  18141. animationCache.prevKey[ type ] = prevKey;
  18142. animationCache.nextKey[ type ] = nextKey;
  18143. }
  18144. }
  18145. };
  18146. THREE.Animation.prototype.update = (function(){
  18147. var points = [];
  18148. var target = new THREE.Vector3();
  18149. var newVector = new THREE.Vector3();
  18150. var newQuat = new THREE.Quaternion();
  18151. // Catmull-Rom spline
  18152. var interpolateCatmullRom = function ( points, scale ) {
  18153. var c = [], v3 = [],
  18154. point, intPoint, weight, w2, w3,
  18155. pa, pb, pc, pd;
  18156. point = ( points.length - 1 ) * scale;
  18157. intPoint = Math.floor( point );
  18158. weight = point - intPoint;
  18159. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18160. c[ 1 ] = intPoint;
  18161. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18162. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18163. pa = points[ c[ 0 ] ];
  18164. pb = points[ c[ 1 ] ];
  18165. pc = points[ c[ 2 ] ];
  18166. pd = points[ c[ 3 ] ];
  18167. w2 = weight * weight;
  18168. w3 = weight * w2;
  18169. v3[ 0 ] = interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18170. v3[ 1 ] = interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18171. v3[ 2 ] = interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18172. return v3;
  18173. };
  18174. var interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18175. var v0 = ( p2 - p0 ) * 0.5,
  18176. v1 = ( p3 - p1 ) * 0.5;
  18177. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18178. };
  18179. return function ( delta ) {
  18180. if ( this.isPlaying === false ) return;
  18181. this.currentTime += delta * this.timeScale;
  18182. if ( this.weight === 0 )
  18183. return;
  18184. //
  18185. var duration = this.data.length;
  18186. if ( this.loop === true && this.currentTime > duration ) {
  18187. this.currentTime %= duration;
  18188. this.reset();
  18189. } else if ( this.loop === false && this.currentTime > duration ) {
  18190. this.stop();
  18191. return;
  18192. }
  18193. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18194. var object = this.hierarchy[ h ];
  18195. var animationCache = object.animationCache[this.data.name];
  18196. // loop through pos/rot/scl
  18197. for ( var t = 0; t < 3; t ++ ) {
  18198. // get keys
  18199. var type = this.keyTypes[ t ];
  18200. var prevKey = animationCache.prevKey[ type ];
  18201. var nextKey = animationCache.nextKey[ type ];
  18202. if ( nextKey.time <= this.currentTime ) {
  18203. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18204. nextKey = this.getNextKeyWith( type, h, 1 );
  18205. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18206. prevKey = nextKey;
  18207. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18208. }
  18209. animationCache.prevKey[ type ] = prevKey;
  18210. animationCache.nextKey[ type ] = nextKey;
  18211. }
  18212. object.matrixAutoUpdate = true;
  18213. object.matrixWorldNeedsUpdate = true;
  18214. var scale = ( this.currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18215. var prevXYZ = prevKey[ type ];
  18216. var nextXYZ = nextKey[ type ];
  18217. if ( scale < 0 ) scale = 0;
  18218. if ( scale > 1 ) scale = 1;
  18219. // interpolate
  18220. if ( type === "pos" ) {
  18221. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18222. newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18223. newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18224. newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18225. // blend
  18226. if ( object instanceof THREE.Bone ) {
  18227. var proportionalWeight = this.weight / ( this.weight + object.accumulatedPosWeight );
  18228. object.position.lerp( newVector, proportionalWeight );
  18229. object.accumulatedPosWeight += this.weight;
  18230. } else {
  18231. object.position.copy( newVector );
  18232. }
  18233. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18234. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18235. points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18236. points[ 1 ] = prevXYZ;
  18237. points[ 2 ] = nextXYZ;
  18238. points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18239. scale = scale * 0.33 + 0.33;
  18240. var currentPoint = interpolateCatmullRom( points, scale );
  18241. var proportionalWeight = 1;
  18242. if ( object instanceof THREE.Bone ) {
  18243. proportionalWeight = this.weight / ( this.weight + object.accumulatedPosWeight );
  18244. object.accumulatedPosWeight += this.weight;
  18245. }
  18246. // blend
  18247. var vector = object.position;
  18248. vector.x = vector.x + ( currentPoint[ 0 ] - vector.x ) * proportionalWeight;
  18249. vector.y = vector.y + ( currentPoint[ 1 ] - vector.y ) * proportionalWeight;
  18250. vector.z = vector.z + ( currentPoint[ 2 ] - vector.z ) * proportionalWeight;
  18251. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18252. var forwardPoint = interpolateCatmullRom( points, scale * 1.01 );
  18253. target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18254. target.sub( vector );
  18255. target.y = 0;
  18256. target.normalize();
  18257. var angle = Math.atan2( target.x, target.z );
  18258. object.rotation.set( 0, angle, 0 );
  18259. }
  18260. }
  18261. } else if ( type === "rot" ) {
  18262. THREE.Quaternion.slerp( prevXYZ, nextXYZ, newQuat, scale );
  18263. // Avoid paying the cost of an additional slerp if we don't have to
  18264. if ( ! ( object instanceof THREE.Bone ) ) {
  18265. object.quaternion.copy(newQuat);
  18266. } else if ( object.accumulatedRotWeight === 0 ) {
  18267. object.quaternion.copy(newQuat);
  18268. object.accumulatedRotWeight = this.weight;
  18269. } else {
  18270. var proportionalWeight = this.weight / ( this.weight + object.accumulatedRotWeight );
  18271. THREE.Quaternion.slerp( object.quaternion, newQuat, object.quaternion, proportionalWeight );
  18272. object.accumulatedRotWeight += this.weight;
  18273. }
  18274. } else if ( type === "scl" ) {
  18275. newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18276. newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18277. newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18278. if ( object instanceof THREE.Bone ) {
  18279. var proportionalWeight = this.weight / ( this.weight + object.accumulatedSclWeight);
  18280. object.scale.lerp( newVector, proportionalWeight );
  18281. object.accumulatedSclWeight += this.weight;
  18282. } else {
  18283. object.scale.copy( newVector );
  18284. }
  18285. }
  18286. }
  18287. }
  18288. return true;
  18289. };
  18290. })();
  18291. // Get next key with
  18292. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18293. var keys = this.data.hierarchy[ h ].keys;
  18294. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18295. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18296. key = key < keys.length - 1 ? key : keys.length - 1;
  18297. } else {
  18298. key = key % keys.length;
  18299. }
  18300. for ( ; key < keys.length; key ++ ) {
  18301. if ( keys[ key ][ type ] !== undefined ) {
  18302. return keys[ key ];
  18303. }
  18304. }
  18305. return this.data.hierarchy[ h ].keys[ 0 ];
  18306. };
  18307. // Get previous key with
  18308. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18309. var keys = this.data.hierarchy[ h ].keys;
  18310. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18311. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18312. key = key > 0 ? key : 0;
  18313. } else {
  18314. key = key >= 0 ? key : key + keys.length;
  18315. }
  18316. for ( ; key >= 0; key -- ) {
  18317. if ( keys[ key ][ type ] !== undefined ) {
  18318. return keys[ key ];
  18319. }
  18320. }
  18321. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18322. };
  18323. // File:src/extras/animation/KeyFrameAnimation.js
  18324. /**
  18325. * @author mikael emtinger / http://gomo.se/
  18326. * @author mrdoob / http://mrdoob.com/
  18327. * @author alteredq / http://alteredqualia.com/
  18328. * @author khang duong
  18329. * @author erik kitson
  18330. */
  18331. THREE.KeyFrameAnimation = function ( data ) {
  18332. this.root = data.node;
  18333. this.data = THREE.AnimationHandler.init( data );
  18334. this.hierarchy = THREE.AnimationHandler.parse( this.root );
  18335. this.currentTime = 0;
  18336. this.timeScale = 0.001;
  18337. this.isPlaying = false;
  18338. this.isPaused = true;
  18339. this.loop = true;
  18340. // initialize to first keyframes
  18341. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18342. var keys = this.data.hierarchy[h].keys,
  18343. sids = this.data.hierarchy[h].sids,
  18344. obj = this.hierarchy[h];
  18345. if ( keys.length && sids ) {
  18346. for ( var s = 0; s < sids.length; s ++ ) {
  18347. var sid = sids[ s ],
  18348. next = this.getNextKeyWith( sid, h, 0 );
  18349. if ( next ) {
  18350. next.apply( sid );
  18351. }
  18352. }
  18353. obj.matrixAutoUpdate = false;
  18354. this.data.hierarchy[h].node.updateMatrix();
  18355. obj.matrixWorldNeedsUpdate = true;
  18356. }
  18357. }
  18358. };
  18359. THREE.KeyFrameAnimation.prototype.play = function ( startTime ) {
  18360. this.currentTime = startTime !== undefined ? startTime : 0;
  18361. if ( this.isPlaying === false ) {
  18362. this.isPlaying = true;
  18363. // reset key cache
  18364. var h, hl = this.hierarchy.length,
  18365. object,
  18366. node;
  18367. for ( h = 0; h < hl; h ++ ) {
  18368. object = this.hierarchy[ h ];
  18369. node = this.data.hierarchy[ h ];
  18370. if ( node.animationCache === undefined ) {
  18371. node.animationCache = {};
  18372. node.animationCache.prevKey = null;
  18373. node.animationCache.nextKey = null;
  18374. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18375. }
  18376. var keys = this.data.hierarchy[h].keys;
  18377. if (keys.length) {
  18378. node.animationCache.prevKey = keys[ 0 ];
  18379. node.animationCache.nextKey = keys[ 1 ];
  18380. this.startTime = Math.min( keys[0].time, this.startTime );
  18381. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18382. }
  18383. }
  18384. this.update( 0 );
  18385. }
  18386. this.isPaused = false;
  18387. THREE.AnimationHandler.play( this );
  18388. };
  18389. THREE.KeyFrameAnimation.prototype.stop = function() {
  18390. this.isPlaying = false;
  18391. this.isPaused = false;
  18392. THREE.AnimationHandler.stop( this );
  18393. // reset JIT matrix and remove cache
  18394. for ( var h = 0; h < this.data.hierarchy.length; h ++ ) {
  18395. var obj = this.hierarchy[ h ];
  18396. var node = this.data.hierarchy[ h ];
  18397. if ( node.animationCache !== undefined ) {
  18398. var original = node.animationCache.originalMatrix;
  18399. if( obj instanceof THREE.Bone ) {
  18400. original.copy( obj.skinMatrix );
  18401. obj.skinMatrix = original;
  18402. } else {
  18403. original.copy( obj.matrix );
  18404. obj.matrix = original;
  18405. }
  18406. delete node.animationCache;
  18407. }
  18408. }
  18409. };
  18410. // Update
  18411. THREE.KeyFrameAnimation.prototype.update = function ( delta ) {
  18412. if ( this.isPlaying === false ) return;
  18413. this.currentTime += delta * this.timeScale;
  18414. //
  18415. var duration = this.data.length;
  18416. if ( this.loop === true && this.currentTime > duration ) {
  18417. this.currentTime %= duration;
  18418. }
  18419. this.currentTime = Math.min( this.currentTime, duration );
  18420. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18421. var object = this.hierarchy[ h ];
  18422. var node = this.data.hierarchy[ h ];
  18423. var keys = node.keys,
  18424. animationCache = node.animationCache;
  18425. if ( keys.length ) {
  18426. var prevKey = animationCache.prevKey;
  18427. var nextKey = animationCache.nextKey;
  18428. if ( nextKey.time <= this.currentTime ) {
  18429. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18430. prevKey = nextKey;
  18431. nextKey = keys[ prevKey.index + 1 ];
  18432. }
  18433. animationCache.prevKey = prevKey;
  18434. animationCache.nextKey = nextKey;
  18435. }
  18436. if ( nextKey.time >= this.currentTime ) {
  18437. prevKey.interpolate( nextKey, this.currentTime );
  18438. } else {
  18439. prevKey.interpolate( nextKey, nextKey.time );
  18440. }
  18441. this.data.hierarchy[ h ].node.updateMatrix();
  18442. object.matrixWorldNeedsUpdate = true;
  18443. }
  18444. }
  18445. };
  18446. // Get next key with
  18447. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18448. var keys = this.data.hierarchy[ h ].keys;
  18449. key = key % keys.length;
  18450. for ( ; key < keys.length; key ++ ) {
  18451. if ( keys[ key ].hasTarget( sid ) ) {
  18452. return keys[ key ];
  18453. }
  18454. }
  18455. return keys[ 0 ];
  18456. };
  18457. // Get previous key with
  18458. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18459. var keys = this.data.hierarchy[ h ].keys;
  18460. key = key >= 0 ? key : key + keys.length;
  18461. for ( ; key >= 0; key -- ) {
  18462. if ( keys[ key ].hasTarget( sid ) ) {
  18463. return keys[ key ];
  18464. }
  18465. }
  18466. return keys[ keys.length - 1 ];
  18467. };
  18468. // File:src/extras/animation/MorphAnimation.js
  18469. /**
  18470. * @author mrdoob / http://mrdoob.com
  18471. */
  18472. THREE.MorphAnimation = function ( mesh ) {
  18473. this.mesh = mesh;
  18474. this.frames = mesh.morphTargetInfluences.length;
  18475. this.currentTime = 0;
  18476. this.duration = 1000;
  18477. this.loop = true;
  18478. this.isPlaying = false;
  18479. };
  18480. THREE.MorphAnimation.prototype = {
  18481. play: function () {
  18482. this.isPlaying = true;
  18483. },
  18484. pause: function () {
  18485. this.isPlaying = false;
  18486. },
  18487. update: ( function () {
  18488. var lastFrame = 0;
  18489. var currentFrame = 0;
  18490. return function ( delta ) {
  18491. if ( this.isPlaying === false ) return;
  18492. this.currentTime += delta;
  18493. if ( this.loop === true && this.currentTime > this.duration ) {
  18494. this.currentTime %= this.duration;
  18495. }
  18496. this.currentTime = Math.min( this.currentTime, this.duration );
  18497. var interpolation = this.duration / this.frames;
  18498. var frame = Math.floor( this.currentTime / interpolation );
  18499. if ( frame != currentFrame ) {
  18500. this.mesh.morphTargetInfluences[ lastFrame ] = 0;
  18501. this.mesh.morphTargetInfluences[ currentFrame ] = 1;
  18502. this.mesh.morphTargetInfluences[ frame ] = 0;
  18503. lastFrame = currentFrame;
  18504. currentFrame = frame;
  18505. }
  18506. this.mesh.morphTargetInfluences[ frame ] = ( this.currentTime % interpolation ) / interpolation;
  18507. this.mesh.morphTargetInfluences[ lastFrame ] = 1 - this.mesh.morphTargetInfluences[ frame ];
  18508. }
  18509. } )()
  18510. };
  18511. // File:src/extras/geometries/BoxGeometry.js
  18512. /**
  18513. * @author mrdoob / http://mrdoob.com/
  18514. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18515. */
  18516. THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18517. THREE.Geometry.call( this );
  18518. this.parameters = {
  18519. width: width,
  18520. height: height,
  18521. depth: depth,
  18522. widthSegments: widthSegments,
  18523. heightSegments: heightSegments,
  18524. depthSegments: depthSegments
  18525. };
  18526. this.widthSegments = widthSegments || 1;
  18527. this.heightSegments = heightSegments || 1;
  18528. this.depthSegments = depthSegments || 1;
  18529. var scope = this;
  18530. var width_half = width / 2;
  18531. var height_half = height / 2;
  18532. var depth_half = depth / 2;
  18533. buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, 0 ); // px
  18534. buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, 1 ); // nx
  18535. buildPlane( 'x', 'z', 1, 1, width, depth, height_half, 2 ); // py
  18536. buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, 3 ); // ny
  18537. buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, 4 ); // pz
  18538. buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, 5 ); // nz
  18539. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18540. var w, ix, iy,
  18541. gridX = scope.widthSegments,
  18542. gridY = scope.heightSegments,
  18543. width_half = width / 2,
  18544. height_half = height / 2,
  18545. offset = scope.vertices.length;
  18546. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18547. w = 'z';
  18548. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18549. w = 'y';
  18550. gridY = scope.depthSegments;
  18551. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18552. w = 'x';
  18553. gridX = scope.depthSegments;
  18554. }
  18555. var gridX1 = gridX + 1,
  18556. gridY1 = gridY + 1,
  18557. segment_width = width / gridX,
  18558. segment_height = height / gridY,
  18559. normal = new THREE.Vector3();
  18560. normal[ w ] = depth > 0 ? 1 : - 1;
  18561. for ( iy = 0; iy < gridY1; iy ++ ) {
  18562. for ( ix = 0; ix < gridX1; ix ++ ) {
  18563. var vector = new THREE.Vector3();
  18564. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18565. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18566. vector[ w ] = depth;
  18567. scope.vertices.push( vector );
  18568. }
  18569. }
  18570. for ( iy = 0; iy < gridY; iy ++ ) {
  18571. for ( ix = 0; ix < gridX; ix ++ ) {
  18572. var a = ix + gridX1 * iy;
  18573. var b = ix + gridX1 * ( iy + 1 );
  18574. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18575. var d = ( ix + 1 ) + gridX1 * iy;
  18576. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  18577. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  18578. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  18579. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  18580. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  18581. face.normal.copy( normal );
  18582. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18583. face.materialIndex = materialIndex;
  18584. scope.faces.push( face );
  18585. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  18586. face = new THREE.Face3( b + offset, c + offset, d + offset );
  18587. face.normal.copy( normal );
  18588. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18589. face.materialIndex = materialIndex;
  18590. scope.faces.push( face );
  18591. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  18592. }
  18593. }
  18594. }
  18595. this.mergeVertices();
  18596. };
  18597. THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18598. // File:src/extras/geometries/CircleGeometry.js
  18599. /**
  18600. * @author hughes
  18601. */
  18602. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18603. THREE.Geometry.call( this );
  18604. this.parameters = {
  18605. radius: radius,
  18606. segments: segments,
  18607. thetaStart: thetaStart,
  18608. thetaLength: thetaLength
  18609. };
  18610. radius = radius || 50;
  18611. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18612. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18613. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18614. var i, uvs = [],
  18615. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18616. this.vertices.push(center);
  18617. uvs.push( centerUV );
  18618. for ( i = 0; i <= segments; i ++ ) {
  18619. var vertex = new THREE.Vector3();
  18620. var segment = thetaStart + i / segments * thetaLength;
  18621. vertex.x = radius * Math.cos( segment );
  18622. vertex.y = radius * Math.sin( segment );
  18623. this.vertices.push( vertex );
  18624. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  18625. }
  18626. var n = new THREE.Vector3( 0, 0, 1 );
  18627. for ( i = 1; i <= segments; i ++ ) {
  18628. this.faces.push( new THREE.Face3( i, i + 1, 0, [ n.clone(), n.clone(), n.clone() ] ) );
  18629. this.faceVertexUvs[ 0 ].push( [ uvs[ i ].clone(), uvs[ i + 1 ].clone(), centerUV.clone() ] );
  18630. }
  18631. this.computeFaceNormals();
  18632. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18633. };
  18634. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18635. // File:src/extras/geometries/CubeGeometry.js
  18636. /**
  18637. * @author mrdoob / http://mrdoob.com/
  18638. */
  18639. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18640. console.warn( 'THEE.CubeGeometry has been renamed to THREE.BoxGeometry.' );
  18641. return new THREE.BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments );
  18642. };
  18643. // File:src/extras/geometries/CylinderGeometry.js
  18644. /**
  18645. * @author mrdoob / http://mrdoob.com/
  18646. */
  18647. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
  18648. THREE.Geometry.call( this );
  18649. this.parameters = {
  18650. radiusTop: radiusTop,
  18651. radiusBottom: radiusBottom,
  18652. height: height,
  18653. radialSegments: radialSegments,
  18654. heightSegments: heightSegments,
  18655. openEnded: openEnded
  18656. };
  18657. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18658. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18659. height = height !== undefined ? height : 100;
  18660. radialSegments = radialSegments || 8;
  18661. heightSegments = heightSegments || 1;
  18662. openEnded = openEnded !== undefined ? openEnded : false;
  18663. var heightHalf = height / 2;
  18664. var x, y, vertices = [], uvs = [];
  18665. for ( y = 0; y <= heightSegments; y ++ ) {
  18666. var verticesRow = [];
  18667. var uvsRow = [];
  18668. var v = y / heightSegments;
  18669. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18670. for ( x = 0; x <= radialSegments; x ++ ) {
  18671. var u = x / radialSegments;
  18672. var vertex = new THREE.Vector3();
  18673. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18674. vertex.y = - v * height + heightHalf;
  18675. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18676. this.vertices.push( vertex );
  18677. verticesRow.push( this.vertices.length - 1 );
  18678. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18679. }
  18680. vertices.push( verticesRow );
  18681. uvs.push( uvsRow );
  18682. }
  18683. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18684. var na, nb;
  18685. for ( x = 0; x < radialSegments; x ++ ) {
  18686. if ( radiusTop !== 0 ) {
  18687. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18688. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18689. } else {
  18690. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18691. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18692. }
  18693. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18694. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18695. for ( y = 0; y < heightSegments; y ++ ) {
  18696. var v1 = vertices[ y ][ x ];
  18697. var v2 = vertices[ y + 1 ][ x ];
  18698. var v3 = vertices[ y + 1 ][ x + 1 ];
  18699. var v4 = vertices[ y ][ x + 1 ];
  18700. var n1 = na.clone();
  18701. var n2 = na.clone();
  18702. var n3 = nb.clone();
  18703. var n4 = nb.clone();
  18704. var uv1 = uvs[ y ][ x ].clone();
  18705. var uv2 = uvs[ y + 1 ][ x ].clone();
  18706. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18707. var uv4 = uvs[ y ][ x + 1 ].clone();
  18708. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  18709. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  18710. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  18711. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  18712. }
  18713. }
  18714. // top cap
  18715. if ( openEnded === false && radiusTop > 0 ) {
  18716. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18717. for ( x = 0; x < radialSegments; x ++ ) {
  18718. var v1 = vertices[ 0 ][ x ];
  18719. var v2 = vertices[ 0 ][ x + 1 ];
  18720. var v3 = this.vertices.length - 1;
  18721. var n1 = new THREE.Vector3( 0, 1, 0 );
  18722. var n2 = new THREE.Vector3( 0, 1, 0 );
  18723. var n3 = new THREE.Vector3( 0, 1, 0 );
  18724. var uv1 = uvs[ 0 ][ x ].clone();
  18725. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18726. var uv3 = new THREE.Vector2( uv2.x, 0 );
  18727. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18728. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18729. }
  18730. }
  18731. // bottom cap
  18732. if ( openEnded === false && radiusBottom > 0 ) {
  18733. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18734. for ( x = 0; x < radialSegments; x ++ ) {
  18735. var v1 = vertices[ y ][ x + 1 ];
  18736. var v2 = vertices[ y ][ x ];
  18737. var v3 = this.vertices.length - 1;
  18738. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18739. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18740. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18741. var uv1 = uvs[ y ][ x + 1 ].clone();
  18742. var uv2 = uvs[ y ][ x ].clone();
  18743. var uv3 = new THREE.Vector2( uv2.x, 1 );
  18744. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18745. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18746. }
  18747. }
  18748. this.computeFaceNormals();
  18749. }
  18750. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18751. // File:src/extras/geometries/ExtrudeGeometry.js
  18752. /**
  18753. * @author zz85 / http://www.lab4games.net/zz85/blog
  18754. *
  18755. * Creates extruded geometry from a path shape.
  18756. *
  18757. * parameters = {
  18758. *
  18759. * curveSegments: <int>, // number of points on the curves
  18760. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18761. * amount: <int>, // Depth to extrude the shape
  18762. *
  18763. * bevelEnabled: <bool>, // turn on bevel
  18764. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18765. * bevelSize: <float>, // how far from shape outline is bevel
  18766. * bevelSegments: <int>, // number of bevel layers
  18767. *
  18768. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18769. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18770. *
  18771. * material: <int> // material index for front and back faces
  18772. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18773. * uvGenerator: <Object> // object that provides UV generator functions
  18774. *
  18775. * }
  18776. **/
  18777. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18778. if ( typeof( shapes ) === "undefined" ) {
  18779. shapes = [];
  18780. return;
  18781. }
  18782. THREE.Geometry.call( this );
  18783. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18784. this.addShapeList( shapes, options );
  18785. this.computeFaceNormals();
  18786. // can't really use automatic vertex normals
  18787. // as then front and back sides get smoothed too
  18788. // should do separate smoothing just for sides
  18789. //this.computeVertexNormals();
  18790. //console.log( "took", ( Date.now() - startTime ) );
  18791. };
  18792. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18793. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18794. var sl = shapes.length;
  18795. for ( var s = 0; s < sl; s ++ ) {
  18796. var shape = shapes[ s ];
  18797. this.addShape( shape, options );
  18798. }
  18799. };
  18800. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18801. var amount = options.amount !== undefined ? options.amount : 100;
  18802. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18803. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18804. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18805. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18806. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18807. var steps = options.steps !== undefined ? options.steps : 1;
  18808. var extrudePath = options.extrudePath;
  18809. var extrudePts, extrudeByPath = false;
  18810. var material = options.material;
  18811. var extrudeMaterial = options.extrudeMaterial;
  18812. // Use default WorldUVGenerator if no UV generators are specified.
  18813. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18814. var splineTube, binormal, normal, position2;
  18815. if ( extrudePath ) {
  18816. extrudePts = extrudePath.getSpacedPoints( steps );
  18817. extrudeByPath = true;
  18818. bevelEnabled = false; // bevels not supported for path extrusion
  18819. // SETUP TNB variables
  18820. // Reuse TNB from TubeGeomtry for now.
  18821. // TODO1 - have a .isClosed in spline?
  18822. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18823. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18824. binormal = new THREE.Vector3();
  18825. normal = new THREE.Vector3();
  18826. position2 = new THREE.Vector3();
  18827. }
  18828. // Safeguards if bevels are not enabled
  18829. if ( ! bevelEnabled ) {
  18830. bevelSegments = 0;
  18831. bevelThickness = 0;
  18832. bevelSize = 0;
  18833. }
  18834. // Variables initalization
  18835. var ahole, h, hl; // looping of holes
  18836. var scope = this;
  18837. var bevelPoints = [];
  18838. var shapesOffset = this.vertices.length;
  18839. var shapePoints = shape.extractPoints( curveSegments );
  18840. var vertices = shapePoints.shape;
  18841. var holes = shapePoints.holes;
  18842. var reverse = ! THREE.Shape.Utils.isClockWise( vertices ) ;
  18843. if ( reverse ) {
  18844. vertices = vertices.reverse();
  18845. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18846. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18847. ahole = holes[ h ];
  18848. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18849. holes[ h ] = ahole.reverse();
  18850. }
  18851. }
  18852. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18853. }
  18854. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18855. /* Vertices */
  18856. var contour = vertices; // vertices has all points but contour has only points of circumference
  18857. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18858. ahole = holes[ h ];
  18859. vertices = vertices.concat( ahole );
  18860. }
  18861. function scalePt2 ( pt, vec, size ) {
  18862. if ( ! vec ) console.log( "die" );
  18863. return vec.clone().multiplyScalar( size ).add( pt );
  18864. }
  18865. var b, bs, t, z,
  18866. vert, vlen = vertices.length,
  18867. face, flen = faces.length,
  18868. cont, clen = contour.length;
  18869. // Find directions for point movement
  18870. var RAD_TO_DEGREES = 180 / Math.PI;
  18871. function getBevelVec( inPt, inPrev, inNext ) {
  18872. var EPSILON = 0.0000000001;
  18873. var sign = THREE.Math.sign;
  18874. // computes for inPt the corresponding point inPt' on a new contour
  18875. // shiftet by 1 unit (length of normalized vector) to the left
  18876. // if we walk along contour clockwise, this new contour is outside the old one
  18877. //
  18878. // inPt' is the intersection of the two lines parallel to the two
  18879. // adjacent edges of inPt at a distance of 1 unit on the left side.
  18880. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  18881. // good reading for geometry algorithms (here: line-line intersection)
  18882. // http://geomalgorithms.com/a05-_intersect-1.html
  18883. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  18884. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  18885. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  18886. // check for colinear edges
  18887. var colinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18888. if ( Math.abs( colinear0 ) > EPSILON ) { // not colinear
  18889. // length of vectors for normalizing
  18890. var v_prev_len = Math.sqrt( v_prev_lensq );
  18891. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  18892. // shift adjacent points by unit vectors to the left
  18893. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  18894. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  18895. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  18896. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  18897. // scaling factor for v_prev to intersection point
  18898. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  18899. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  18900. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18901. // vector from inPt to intersection point
  18902. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  18903. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  18904. // Don't normalize!, otherwise sharp corners become ugly
  18905. // but prevent crazy spikes
  18906. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y )
  18907. if ( v_trans_lensq <= 2 ) {
  18908. return new THREE.Vector2( v_trans_x, v_trans_y );
  18909. } else {
  18910. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  18911. }
  18912. } else { // handle special case of colinear edges
  18913. var direction_eq = false; // assumes: opposite
  18914. if ( v_prev_x > EPSILON ) {
  18915. if ( v_next_x > EPSILON ) { direction_eq = true; }
  18916. } else {
  18917. if ( v_prev_x < - EPSILON ) {
  18918. if ( v_next_x < - EPSILON ) { direction_eq = true; }
  18919. } else {
  18920. if ( sign(v_prev_y) == sign(v_next_y) ) { direction_eq = true; }
  18921. }
  18922. }
  18923. if ( direction_eq ) {
  18924. // console.log("Warning: lines are a straight sequence");
  18925. v_trans_x = - v_prev_y;
  18926. v_trans_y = v_prev_x;
  18927. shrink_by = Math.sqrt( v_prev_lensq );
  18928. } else {
  18929. // console.log("Warning: lines are a straight spike");
  18930. v_trans_x = v_prev_x;
  18931. v_trans_y = v_prev_y;
  18932. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  18933. }
  18934. }
  18935. return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  18936. }
  18937. var contourMovements = [];
  18938. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18939. if ( j === il ) j = 0;
  18940. if ( k === il ) k = 0;
  18941. // (j)---(i)---(k)
  18942. // console.log('i,j,k', i, j , k)
  18943. var pt_i = contour[ i ];
  18944. var pt_j = contour[ j ];
  18945. var pt_k = contour[ k ];
  18946. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18947. }
  18948. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18949. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18950. ahole = holes[ h ];
  18951. oneHoleMovements = [];
  18952. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18953. if ( j === il ) j = 0;
  18954. if ( k === il ) k = 0;
  18955. // (j)---(i)---(k)
  18956. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18957. }
  18958. holesMovements.push( oneHoleMovements );
  18959. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18960. }
  18961. // Loop bevelSegments, 1 for the front, 1 for the back
  18962. for ( b = 0; b < bevelSegments; b ++ ) {
  18963. //for ( b = bevelSegments; b > 0; b -- ) {
  18964. t = b / bevelSegments;
  18965. z = bevelThickness * ( 1 - t );
  18966. //z = bevelThickness * t;
  18967. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18968. //bs = bevelSize * t ; // linear
  18969. // contract shape
  18970. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18971. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18972. v( vert.x, vert.y, - z );
  18973. }
  18974. // expand holes
  18975. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18976. ahole = holes[ h ];
  18977. oneHoleMovements = holesMovements[ h ];
  18978. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18979. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18980. v( vert.x, vert.y, - z );
  18981. }
  18982. }
  18983. }
  18984. bs = bevelSize;
  18985. // Back facing vertices
  18986. for ( i = 0; i < vlen; i ++ ) {
  18987. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18988. if ( ! extrudeByPath ) {
  18989. v( vert.x, vert.y, 0 );
  18990. } else {
  18991. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18992. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18993. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18994. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  18995. v( position2.x, position2.y, position2.z );
  18996. }
  18997. }
  18998. // Add stepped vertices...
  18999. // Including front facing vertices
  19000. var s;
  19001. for ( s = 1; s <= steps; s ++ ) {
  19002. for ( i = 0; i < vlen; i ++ ) {
  19003. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19004. if ( ! extrudeByPath ) {
  19005. v( vert.x, vert.y, amount / steps * s );
  19006. } else {
  19007. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19008. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19009. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19010. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  19011. v( position2.x, position2.y, position2.z );
  19012. }
  19013. }
  19014. }
  19015. // Add bevel segments planes
  19016. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19017. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19018. t = b / bevelSegments;
  19019. z = bevelThickness * ( 1 - t );
  19020. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19021. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19022. // contract shape
  19023. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19024. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19025. v( vert.x, vert.y, amount + z );
  19026. }
  19027. // expand holes
  19028. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19029. ahole = holes[ h ];
  19030. oneHoleMovements = holesMovements[ h ];
  19031. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19032. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19033. if ( ! extrudeByPath ) {
  19034. v( vert.x, vert.y, amount + z );
  19035. } else {
  19036. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19037. }
  19038. }
  19039. }
  19040. }
  19041. /* Faces */
  19042. // Top and bottom faces
  19043. buildLidFaces();
  19044. // Sides faces
  19045. buildSideFaces();
  19046. ///// Internal functions
  19047. function buildLidFaces() {
  19048. if ( bevelEnabled ) {
  19049. var layer = 0 ; // steps + 1
  19050. var offset = vlen * layer;
  19051. // Bottom faces
  19052. for ( i = 0; i < flen; i ++ ) {
  19053. face = faces[ i ];
  19054. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19055. }
  19056. layer = steps + bevelSegments * 2;
  19057. offset = vlen * layer;
  19058. // Top faces
  19059. for ( i = 0; i < flen; i ++ ) {
  19060. face = faces[ i ];
  19061. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19062. }
  19063. } else {
  19064. // Bottom faces
  19065. for ( i = 0; i < flen; i ++ ) {
  19066. face = faces[ i ];
  19067. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19068. }
  19069. // Top faces
  19070. for ( i = 0; i < flen; i ++ ) {
  19071. face = faces[ i ];
  19072. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19073. }
  19074. }
  19075. }
  19076. // Create faces for the z-sides of the shape
  19077. function buildSideFaces() {
  19078. var layeroffset = 0;
  19079. sidewalls( contour, layeroffset );
  19080. layeroffset += contour.length;
  19081. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19082. ahole = holes[ h ];
  19083. sidewalls( ahole, layeroffset );
  19084. //, true
  19085. layeroffset += ahole.length;
  19086. }
  19087. }
  19088. function sidewalls( contour, layeroffset ) {
  19089. var j, k;
  19090. i = contour.length;
  19091. while ( --i >= 0 ) {
  19092. j = i;
  19093. k = i - 1;
  19094. if ( k < 0 ) k = contour.length - 1;
  19095. //console.log('b', i,j, i-1, k,vertices.length);
  19096. var s = 0, sl = steps + bevelSegments * 2;
  19097. for ( s = 0; s < sl; s ++ ) {
  19098. var slen1 = vlen * s;
  19099. var slen2 = vlen * ( s + 1 );
  19100. var a = layeroffset + j + slen1,
  19101. b = layeroffset + k + slen1,
  19102. c = layeroffset + k + slen2,
  19103. d = layeroffset + j + slen2;
  19104. f4( a, b, c, d, contour, s, sl, j, k );
  19105. }
  19106. }
  19107. }
  19108. function v( x, y, z ) {
  19109. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19110. }
  19111. function f3( a, b, c, isBottom ) {
  19112. a += shapesOffset;
  19113. b += shapesOffset;
  19114. c += shapesOffset;
  19115. // normal, color, material
  19116. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19117. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19118. scope.faceVertexUvs[ 0 ].push( uvs );
  19119. }
  19120. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19121. a += shapesOffset;
  19122. b += shapesOffset;
  19123. c += shapesOffset;
  19124. d += shapesOffset;
  19125. scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) );
  19126. scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) );
  19127. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19128. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19129. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  19130. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  19131. }
  19132. };
  19133. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19134. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19135. var ax = geometry.vertices[ indexA ].x,
  19136. ay = geometry.vertices[ indexA ].y,
  19137. bx = geometry.vertices[ indexB ].x,
  19138. by = geometry.vertices[ indexB ].y,
  19139. cx = geometry.vertices[ indexC ].x,
  19140. cy = geometry.vertices[ indexC ].y;
  19141. return [
  19142. new THREE.Vector2( ax, ay ),
  19143. new THREE.Vector2( bx, by ),
  19144. new THREE.Vector2( cx, cy )
  19145. ];
  19146. },
  19147. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19148. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19149. },
  19150. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19151. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19152. contourIndex1, contourIndex2 ) {
  19153. var ax = geometry.vertices[ indexA ].x,
  19154. ay = geometry.vertices[ indexA ].y,
  19155. az = geometry.vertices[ indexA ].z,
  19156. bx = geometry.vertices[ indexB ].x,
  19157. by = geometry.vertices[ indexB ].y,
  19158. bz = geometry.vertices[ indexB ].z,
  19159. cx = geometry.vertices[ indexC ].x,
  19160. cy = geometry.vertices[ indexC ].y,
  19161. cz = geometry.vertices[ indexC ].z,
  19162. dx = geometry.vertices[ indexD ].x,
  19163. dy = geometry.vertices[ indexD ].y,
  19164. dz = geometry.vertices[ indexD ].z;
  19165. if ( Math.abs( ay - by ) < 0.01 ) {
  19166. return [
  19167. new THREE.Vector2( ax, 1 - az ),
  19168. new THREE.Vector2( bx, 1 - bz ),
  19169. new THREE.Vector2( cx, 1 - cz ),
  19170. new THREE.Vector2( dx, 1 - dz )
  19171. ];
  19172. } else {
  19173. return [
  19174. new THREE.Vector2( ay, 1 - az ),
  19175. new THREE.Vector2( by, 1 - bz ),
  19176. new THREE.Vector2( cy, 1 - cz ),
  19177. new THREE.Vector2( dy, 1 - dz )
  19178. ];
  19179. }
  19180. }
  19181. };
  19182. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19183. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19184. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19185. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19186. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19187. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19188. // File:src/extras/geometries/ShapeGeometry.js
  19189. /**
  19190. * @author jonobr1 / http://jonobr1.com
  19191. *
  19192. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19193. * ExtrudeGeometry.
  19194. *
  19195. * parameters = {
  19196. *
  19197. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19198. *
  19199. * material: <int> // material index for front and back faces
  19200. * uvGenerator: <Object> // object that provides UV generator functions
  19201. *
  19202. * }
  19203. **/
  19204. THREE.ShapeGeometry = function ( shapes, options ) {
  19205. THREE.Geometry.call( this );
  19206. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19207. this.addShapeList( shapes, options );
  19208. this.computeFaceNormals();
  19209. };
  19210. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19211. /**
  19212. * Add an array of shapes to THREE.ShapeGeometry.
  19213. */
  19214. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19215. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  19216. this.addShape( shapes[ i ], options );
  19217. }
  19218. return this;
  19219. };
  19220. /**
  19221. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19222. */
  19223. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19224. if ( options === undefined ) options = {};
  19225. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19226. var material = options.material;
  19227. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19228. //
  19229. var i, l, hole, s;
  19230. var shapesOffset = this.vertices.length;
  19231. var shapePoints = shape.extractPoints( curveSegments );
  19232. var vertices = shapePoints.shape;
  19233. var holes = shapePoints.holes;
  19234. var reverse = ! THREE.Shape.Utils.isClockWise( vertices );
  19235. if ( reverse ) {
  19236. vertices = vertices.reverse();
  19237. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19238. for ( i = 0, l = holes.length; i < l; i ++ ) {
  19239. hole = holes[ i ];
  19240. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19241. holes[ i ] = hole.reverse();
  19242. }
  19243. }
  19244. reverse = false;
  19245. }
  19246. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19247. // Vertices
  19248. var contour = vertices;
  19249. for ( i = 0, l = holes.length; i < l; i ++ ) {
  19250. hole = holes[ i ];
  19251. vertices = vertices.concat( hole );
  19252. }
  19253. //
  19254. var vert, vlen = vertices.length;
  19255. var face, flen = faces.length;
  19256. var cont, clen = contour.length;
  19257. for ( i = 0; i < vlen; i ++ ) {
  19258. vert = vertices[ i ];
  19259. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19260. }
  19261. for ( i = 0; i < flen; i ++ ) {
  19262. face = faces[ i ];
  19263. var a = face[ 0 ] + shapesOffset;
  19264. var b = face[ 1 ] + shapesOffset;
  19265. var c = face[ 2 ] + shapesOffset;
  19266. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19267. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19268. }
  19269. };
  19270. // File:src/extras/geometries/LatheGeometry.js
  19271. /**
  19272. * @author astrodud / http://astrodud.isgreat.org/
  19273. * @author zz85 / https://github.com/zz85
  19274. * @author bhouston / http://exocortex.com
  19275. */
  19276. // points - to create a closed torus, one must use a set of points
  19277. // like so: [ a, b, c, d, a ], see first is the same as last.
  19278. // segments - the number of circumference segments to create
  19279. // phiStart - the starting radian
  19280. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19281. // 2*pi is a closed lathe, less than 2PI is a portion.
  19282. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19283. THREE.Geometry.call( this );
  19284. segments = segments || 12;
  19285. phiStart = phiStart || 0;
  19286. phiLength = phiLength || 2 * Math.PI;
  19287. var inversePointLength = 1.0 / ( points.length - 1 );
  19288. var inverseSegments = 1.0 / segments;
  19289. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19290. var phi = phiStart + i * inverseSegments * phiLength;
  19291. var c = Math.cos( phi ),
  19292. s = Math.sin( phi );
  19293. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19294. var pt = points[ j ];
  19295. var vertex = new THREE.Vector3();
  19296. vertex.x = c * pt.x - s * pt.y;
  19297. vertex.y = s * pt.x + c * pt.y;
  19298. vertex.z = pt.z;
  19299. this.vertices.push( vertex );
  19300. }
  19301. }
  19302. var np = points.length;
  19303. for ( var i = 0, il = segments; i < il; i ++ ) {
  19304. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19305. var base = j + np * i;
  19306. var a = base;
  19307. var b = base + np;
  19308. var c = base + 1 + np;
  19309. var d = base + 1;
  19310. var u0 = i * inverseSegments;
  19311. var v0 = j * inversePointLength;
  19312. var u1 = u0 + inverseSegments;
  19313. var v1 = v0 + inversePointLength;
  19314. this.faces.push( new THREE.Face3( a, b, d ) );
  19315. this.faceVertexUvs[ 0 ].push( [
  19316. new THREE.Vector2( u0, v0 ),
  19317. new THREE.Vector2( u1, v0 ),
  19318. new THREE.Vector2( u0, v1 )
  19319. ] );
  19320. this.faces.push( new THREE.Face3( b, c, d ) );
  19321. this.faceVertexUvs[ 0 ].push( [
  19322. new THREE.Vector2( u1, v0 ),
  19323. new THREE.Vector2( u1, v1 ),
  19324. new THREE.Vector2( u0, v1 )
  19325. ] );
  19326. }
  19327. }
  19328. this.mergeVertices();
  19329. this.computeFaceNormals();
  19330. this.computeVertexNormals();
  19331. };
  19332. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19333. // File:src/extras/geometries/PlaneGeometry.js
  19334. /**
  19335. * @author mrdoob / http://mrdoob.com/
  19336. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19337. */
  19338. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19339. THREE.Geometry.call( this );
  19340. this.parameters = {
  19341. width: width,
  19342. height: height,
  19343. widthSegments: widthSegments,
  19344. heightSegments: heightSegments
  19345. };
  19346. var ix, iz;
  19347. var width_half = width / 2;
  19348. var height_half = height / 2;
  19349. var gridX = widthSegments || 1;
  19350. var gridZ = heightSegments || 1;
  19351. var gridX1 = gridX + 1;
  19352. var gridZ1 = gridZ + 1;
  19353. var segment_width = width / gridX;
  19354. var segment_height = height / gridZ;
  19355. var normal = new THREE.Vector3( 0, 0, 1 );
  19356. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19357. var y = iz * segment_height - height_half;
  19358. for ( ix = 0; ix < gridX1; ix ++ ) {
  19359. var x = ix * segment_width - width_half;
  19360. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19361. }
  19362. }
  19363. for ( iz = 0; iz < gridZ; iz ++ ) {
  19364. for ( ix = 0; ix < gridX; ix ++ ) {
  19365. var a = ix + gridX1 * iz;
  19366. var b = ix + gridX1 * ( iz + 1 );
  19367. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19368. var d = ( ix + 1 ) + gridX1 * iz;
  19369. var uva = new THREE.Vector2( ix / gridX, 1 - iz / gridZ );
  19370. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ );
  19371. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ );
  19372. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ );
  19373. var face = new THREE.Face3( a, b, d );
  19374. face.normal.copy( normal );
  19375. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19376. this.faces.push( face );
  19377. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19378. face = new THREE.Face3( b, c, d );
  19379. face.normal.copy( normal );
  19380. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19381. this.faces.push( face );
  19382. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19383. }
  19384. }
  19385. };
  19386. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19387. // File:src/extras/geometries/RingGeometry.js
  19388. /**
  19389. * @author Kaleb Murphy
  19390. */
  19391. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19392. THREE.Geometry.call( this );
  19393. innerRadius = innerRadius || 0;
  19394. outerRadius = outerRadius || 50;
  19395. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19396. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19397. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19398. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 8;
  19399. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19400. for ( i = 0; i < phiSegments + 1; i ++ ) { // concentric circles inside ring
  19401. for ( o = 0; o < thetaSegments + 1; o ++ ) { // number of segments per circle
  19402. var vertex = new THREE.Vector3();
  19403. var segment = thetaStart + o / thetaSegments * thetaLength;
  19404. vertex.x = radius * Math.cos( segment );
  19405. vertex.y = radius * Math.sin( segment );
  19406. this.vertices.push( vertex );
  19407. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  19408. }
  19409. radius += radiusStep;
  19410. }
  19411. var n = new THREE.Vector3( 0, 0, 1 );
  19412. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19413. var thetaSegment = i * (thetaSegments + 1);
  19414. for ( o = 0; o < thetaSegments ; o ++ ) { // number of segments per circle
  19415. var segment = o + thetaSegment;
  19416. var v1 = segment;
  19417. var v2 = segment + thetaSegments + 1;
  19418. var v3 = segment + thetaSegments + 2;
  19419. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19420. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19421. v1 = segment;
  19422. v2 = segment + thetaSegments + 2;
  19423. v3 = segment + 1;
  19424. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19425. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19426. }
  19427. }
  19428. this.computeFaceNormals();
  19429. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19430. };
  19431. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19432. // File:src/extras/geometries/SphereGeometry.js
  19433. /**
  19434. * @author mrdoob / http://mrdoob.com/
  19435. */
  19436. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19437. THREE.Geometry.call( this );
  19438. this.parameters = {
  19439. radius: radius,
  19440. widthSegments: widthSegments,
  19441. heightSegments: heightSegments,
  19442. phiStart: phiStart,
  19443. phiLength: phiLength,
  19444. thetaStart: thetaStart,
  19445. thetaLength: thetaLength
  19446. };
  19447. radius = radius || 50;
  19448. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19449. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19450. phiStart = phiStart !== undefined ? phiStart : 0;
  19451. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19452. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19453. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19454. var x, y, vertices = [], uvs = [];
  19455. for ( y = 0; y <= heightSegments; y ++ ) {
  19456. var verticesRow = [];
  19457. var uvsRow = [];
  19458. for ( x = 0; x <= widthSegments; x ++ ) {
  19459. var u = x / widthSegments;
  19460. var v = y / heightSegments;
  19461. var vertex = new THREE.Vector3();
  19462. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19463. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19464. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19465. this.vertices.push( vertex );
  19466. verticesRow.push( this.vertices.length - 1 );
  19467. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19468. }
  19469. vertices.push( verticesRow );
  19470. uvs.push( uvsRow );
  19471. }
  19472. for ( y = 0; y < heightSegments; y ++ ) {
  19473. for ( x = 0; x < widthSegments; x ++ ) {
  19474. var v1 = vertices[ y ][ x + 1 ];
  19475. var v2 = vertices[ y ][ x ];
  19476. var v3 = vertices[ y + 1 ][ x ];
  19477. var v4 = vertices[ y + 1 ][ x + 1 ];
  19478. var n1 = this.vertices[ v1 ].clone().normalize();
  19479. var n2 = this.vertices[ v2 ].clone().normalize();
  19480. var n3 = this.vertices[ v3 ].clone().normalize();
  19481. var n4 = this.vertices[ v4 ].clone().normalize();
  19482. var uv1 = uvs[ y ][ x + 1 ].clone();
  19483. var uv2 = uvs[ y ][ x ].clone();
  19484. var uv3 = uvs[ y + 1 ][ x ].clone();
  19485. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19486. if ( Math.abs( this.vertices[ v1 ].y ) === radius ) {
  19487. uv1.x = ( uv1.x + uv2.x ) / 2;
  19488. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19489. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19490. } else if ( Math.abs( this.vertices[ v3 ].y ) === radius ) {
  19491. uv3.x = ( uv3.x + uv4.x ) / 2;
  19492. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19493. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19494. } else {
  19495. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19496. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19497. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  19498. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  19499. }
  19500. }
  19501. }
  19502. this.computeFaceNormals();
  19503. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19504. };
  19505. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19506. // File:src/extras/geometries/TextGeometry.js
  19507. /**
  19508. * @author zz85 / http://www.lab4games.net/zz85/blog
  19509. * @author alteredq / http://alteredqualia.com/
  19510. *
  19511. * For creating 3D text geometry in three.js
  19512. *
  19513. * Text = 3D Text
  19514. *
  19515. * parameters = {
  19516. * size: <float>, // size of the text
  19517. * height: <float>, // thickness to extrude text
  19518. * curveSegments: <int>, // number of points on the curves
  19519. *
  19520. * font: <string>, // font name
  19521. * weight: <string>, // font weight (normal, bold)
  19522. * style: <string>, // font style (normal, italics)
  19523. *
  19524. * bevelEnabled: <bool>, // turn on bevel
  19525. * bevelThickness: <float>, // how deep into text bevel goes
  19526. * bevelSize: <float>, // how far from text outline is bevel
  19527. * }
  19528. *
  19529. */
  19530. /* Usage Examples
  19531. // TextGeometry wrapper
  19532. var text3d = new TextGeometry( text, options );
  19533. // Complete manner
  19534. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19535. var text3d = new ExtrudeGeometry( textShapes, options );
  19536. */
  19537. THREE.TextGeometry = function ( text, parameters ) {
  19538. parameters = parameters || {};
  19539. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19540. // translate parameters to ExtrudeGeometry API
  19541. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19542. // defaults
  19543. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19544. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19545. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19546. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19547. };
  19548. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19549. // File:src/extras/geometries/TorusGeometry.js
  19550. /**
  19551. * @author oosmoxiecode
  19552. * @author mrdoob / http://mrdoob.com/
  19553. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19554. */
  19555. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19556. THREE.Geometry.call( this );
  19557. this.parameters = {
  19558. radius: radius,
  19559. tube: tube,
  19560. radialSegments: radialSegments,
  19561. tubularSegments: tubularSegments,
  19562. arc: arc
  19563. };
  19564. radius = radius || 100;
  19565. tube = tube || 40;
  19566. radialSegments = radialSegments || 8;
  19567. tubularSegments = tubularSegments || 6;
  19568. arc = arc || Math.PI * 2;
  19569. var center = new THREE.Vector3(), uvs = [], normals = [];
  19570. for ( var j = 0; j <= radialSegments; j ++ ) {
  19571. for ( var i = 0; i <= tubularSegments; i ++ ) {
  19572. var u = i / tubularSegments * arc;
  19573. var v = j / radialSegments * Math.PI * 2;
  19574. center.x = radius * Math.cos( u );
  19575. center.y = radius * Math.sin( u );
  19576. var vertex = new THREE.Vector3();
  19577. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  19578. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  19579. vertex.z = tube * Math.sin( v );
  19580. this.vertices.push( vertex );
  19581. uvs.push( new THREE.Vector2( i / tubularSegments, j / radialSegments ) );
  19582. normals.push( vertex.clone().sub( center ).normalize() );
  19583. }
  19584. }
  19585. for ( var j = 1; j <= radialSegments; j ++ ) {
  19586. for ( var i = 1; i <= tubularSegments; i ++ ) {
  19587. var a = ( tubularSegments + 1 ) * j + i - 1;
  19588. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19589. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  19590. var d = ( tubularSegments + 1 ) * j + i;
  19591. var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
  19592. this.faces.push( face );
  19593. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  19594. face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
  19595. this.faces.push( face );
  19596. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19597. }
  19598. }
  19599. this.computeFaceNormals();
  19600. };
  19601. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19602. // File:src/extras/geometries/TorusKnotGeometry.js
  19603. /**
  19604. * @author oosmoxiecode
  19605. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19606. */
  19607. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19608. THREE.Geometry.call( this );
  19609. this.parameters = {
  19610. radius: radius,
  19611. tube: tube,
  19612. radialSegments: radialSegments,
  19613. tubularSegments: tubularSegments,
  19614. p: p,
  19615. q: q,
  19616. heightScale: heightScale
  19617. };
  19618. radius = radius || 100;
  19619. tube = tube || 40;
  19620. radialSegments = radialSegments || 64;
  19621. tubularSegments = tubularSegments || 8;
  19622. p = p || 2;
  19623. q = q || 3;
  19624. heightScale = heightScale || 1;
  19625. var grid = new Array( radialSegments );
  19626. var tang = new THREE.Vector3();
  19627. var n = new THREE.Vector3();
  19628. var bitan = new THREE.Vector3();
  19629. for ( var i = 0; i < radialSegments; ++ i ) {
  19630. grid[ i ] = new Array( tubularSegments );
  19631. var u = i / radialSegments * 2 * p * Math.PI;
  19632. var p1 = getPos( u, q, p, radius, heightScale );
  19633. var p2 = getPos( u + 0.01, q, p, radius, heightScale );
  19634. tang.subVectors( p2, p1 );
  19635. n.addVectors( p2, p1 );
  19636. bitan.crossVectors( tang, n );
  19637. n.crossVectors( bitan, tang );
  19638. bitan.normalize();
  19639. n.normalize();
  19640. for ( var j = 0; j < tubularSegments; ++ j ) {
  19641. var v = j / tubularSegments * 2 * Math.PI;
  19642. var cx = - tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19643. var cy = tube * Math.sin( v );
  19644. var pos = new THREE.Vector3();
  19645. pos.x = p1.x + cx * n.x + cy * bitan.x;
  19646. pos.y = p1.y + cx * n.y + cy * bitan.y;
  19647. pos.z = p1.z + cx * n.z + cy * bitan.z;
  19648. grid[ i ][ j ] = this.vertices.push( pos ) - 1;
  19649. }
  19650. }
  19651. for ( var i = 0; i < radialSegments; ++ i ) {
  19652. for ( var j = 0; j < tubularSegments; ++ j ) {
  19653. var ip = ( i + 1 ) % radialSegments;
  19654. var jp = ( j + 1 ) % tubularSegments;
  19655. var a = grid[ i ][ j ];
  19656. var b = grid[ ip ][ j ];
  19657. var c = grid[ ip ][ jp ];
  19658. var d = grid[ i ][ jp ];
  19659. var uva = new THREE.Vector2( i / radialSegments, j / tubularSegments );
  19660. var uvb = new THREE.Vector2( ( i + 1 ) / radialSegments, j / tubularSegments );
  19661. var uvc = new THREE.Vector2( ( i + 1 ) / radialSegments, ( j + 1 ) / tubularSegments );
  19662. var uvd = new THREE.Vector2( i / radialSegments, ( j + 1 ) / tubularSegments );
  19663. this.faces.push( new THREE.Face3( a, b, d ) );
  19664. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19665. this.faces.push( new THREE.Face3( b, c, d ) );
  19666. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19667. }
  19668. }
  19669. this.computeFaceNormals();
  19670. this.computeVertexNormals();
  19671. function getPos( u, in_q, in_p, radius, heightScale ) {
  19672. var cu = Math.cos( u );
  19673. var su = Math.sin( u );
  19674. var quOverP = in_q / in_p * u;
  19675. var cs = Math.cos( quOverP );
  19676. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19677. var ty = radius * ( 2 + cs ) * su * 0.5;
  19678. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19679. return new THREE.Vector3( tx, ty, tz );
  19680. }
  19681. };
  19682. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19683. // File:src/extras/geometries/TubeGeometry.js
  19684. /**
  19685. * @author WestLangley / https://github.com/WestLangley
  19686. * @author zz85 / https://github.com/zz85
  19687. * @author miningold / https://github.com/miningold
  19688. *
  19689. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19690. *
  19691. * Creates a tube which extrudes along a 3d spline
  19692. *
  19693. * Uses parallel transport frames as described in
  19694. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19695. */
  19696. THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed ) {
  19697. THREE.Geometry.call( this );
  19698. this.parameters = {
  19699. path: path,
  19700. segments: segments,
  19701. radius: radius,
  19702. radialSegments: radialSegments,
  19703. closed: closed
  19704. };
  19705. segments = segments || 64;
  19706. radius = radius || 1;
  19707. radialSegments = radialSegments || 8;
  19708. closed = closed || false;
  19709. var grid = [];
  19710. var scope = this,
  19711. tangent,
  19712. normal,
  19713. binormal,
  19714. numpoints = segments + 1,
  19715. x, y, z,
  19716. tx, ty, tz,
  19717. u, v,
  19718. cx, cy,
  19719. pos, pos2 = new THREE.Vector3(),
  19720. i, j,
  19721. ip, jp,
  19722. a, b, c, d,
  19723. uva, uvb, uvc, uvd;
  19724. var frames = new THREE.TubeGeometry.FrenetFrames( path, segments, closed ),
  19725. tangents = frames.tangents,
  19726. normals = frames.normals,
  19727. binormals = frames.binormals;
  19728. // proxy internals
  19729. this.tangents = tangents;
  19730. this.normals = normals;
  19731. this.binormals = binormals;
  19732. function vert( x, y, z ) {
  19733. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19734. }
  19735. // consruct the grid
  19736. for ( i = 0; i < numpoints; i ++ ) {
  19737. grid[ i ] = [];
  19738. u = i / ( numpoints - 1 );
  19739. pos = path.getPointAt( u );
  19740. tangent = tangents[ i ];
  19741. normal = normals[ i ];
  19742. binormal = binormals[ i ];
  19743. for ( j = 0; j < radialSegments; j ++ ) {
  19744. v = j / radialSegments * 2 * Math.PI;
  19745. cx = - radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19746. cy = radius * Math.sin( v );
  19747. pos2.copy( pos );
  19748. pos2.x += cx * normal.x + cy * binormal.x;
  19749. pos2.y += cx * normal.y + cy * binormal.y;
  19750. pos2.z += cx * normal.z + cy * binormal.z;
  19751. grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19752. }
  19753. }
  19754. // construct the mesh
  19755. for ( i = 0; i < segments; i ++ ) {
  19756. for ( j = 0; j < radialSegments; j ++ ) {
  19757. ip = ( closed ) ? (i + 1) % segments : i + 1;
  19758. jp = (j + 1) % radialSegments;
  19759. a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19760. b = grid[ ip ][ j ];
  19761. c = grid[ ip ][ jp ];
  19762. d = grid[ i ][ jp ];
  19763. uva = new THREE.Vector2( i / segments, j / radialSegments );
  19764. uvb = new THREE.Vector2( ( i + 1 ) / segments, j / radialSegments );
  19765. uvc = new THREE.Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments );
  19766. uvd = new THREE.Vector2( i / segments, ( j + 1 ) / radialSegments );
  19767. this.faces.push( new THREE.Face3( a, b, d ) );
  19768. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19769. this.faces.push( new THREE.Face3( b, c, d ) );
  19770. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19771. }
  19772. }
  19773. this.computeFaceNormals();
  19774. this.computeVertexNormals();
  19775. };
  19776. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19777. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19778. THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) {
  19779. var tangent = new THREE.Vector3(),
  19780. normal = new THREE.Vector3(),
  19781. binormal = new THREE.Vector3(),
  19782. tangents = [],
  19783. normals = [],
  19784. binormals = [],
  19785. vec = new THREE.Vector3(),
  19786. mat = new THREE.Matrix4(),
  19787. numpoints = segments + 1,
  19788. theta,
  19789. epsilon = 0.0001,
  19790. smallest,
  19791. tx, ty, tz,
  19792. i, u, v;
  19793. // expose internals
  19794. this.tangents = tangents;
  19795. this.normals = normals;
  19796. this.binormals = binormals;
  19797. // compute the tangent vectors for each segment on the path
  19798. for ( i = 0; i < numpoints; i ++ ) {
  19799. u = i / ( numpoints - 1 );
  19800. tangents[ i ] = path.getTangentAt( u );
  19801. tangents[ i ].normalize();
  19802. }
  19803. initialNormal3();
  19804. /*
  19805. function initialNormal1(lastBinormal) {
  19806. // fixed start binormal. Has dangers of 0 vectors
  19807. normals[ 0 ] = new THREE.Vector3();
  19808. binormals[ 0 ] = new THREE.Vector3();
  19809. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19810. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19811. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19812. }
  19813. function initialNormal2() {
  19814. // This uses the Frenet-Serret formula for deriving binormal
  19815. var t2 = path.getTangentAt( epsilon );
  19816. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  19817. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  19818. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19819. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19820. }
  19821. */
  19822. function initialNormal3() {
  19823. // select an initial normal vector perpenicular to the first tangent vector,
  19824. // and in the direction of the smallest tangent xyz component
  19825. normals[ 0 ] = new THREE.Vector3();
  19826. binormals[ 0 ] = new THREE.Vector3();
  19827. smallest = Number.MAX_VALUE;
  19828. tx = Math.abs( tangents[ 0 ].x );
  19829. ty = Math.abs( tangents[ 0 ].y );
  19830. tz = Math.abs( tangents[ 0 ].z );
  19831. if ( tx <= smallest ) {
  19832. smallest = tx;
  19833. normal.set( 1, 0, 0 );
  19834. }
  19835. if ( ty <= smallest ) {
  19836. smallest = ty;
  19837. normal.set( 0, 1, 0 );
  19838. }
  19839. if ( tz <= smallest ) {
  19840. normal.set( 0, 0, 1 );
  19841. }
  19842. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19843. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19844. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19845. }
  19846. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19847. for ( i = 1; i < numpoints; i ++ ) {
  19848. normals[ i ] = normals[ i-1 ].clone();
  19849. binormals[ i ] = binormals[ i-1 ].clone();
  19850. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  19851. if ( vec.length() > epsilon ) {
  19852. vec.normalize();
  19853. theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  19854. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19855. }
  19856. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19857. }
  19858. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19859. if ( closed ) {
  19860. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), - 1, 1 ) );
  19861. theta /= ( numpoints - 1 );
  19862. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19863. theta = - theta;
  19864. }
  19865. for ( i = 1; i < numpoints; i ++ ) {
  19866. // twist a little...
  19867. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19868. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19869. }
  19870. }
  19871. };
  19872. // File:src/extras/geometries/PolyhedronGeometry.js
  19873. /**
  19874. * @author clockworkgeek / https://github.com/clockworkgeek
  19875. * @author timothypratley / https://github.com/timothypratley
  19876. * @author WestLangley / http://github.com/WestLangley
  19877. */
  19878. THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) {
  19879. THREE.Geometry.call( this );
  19880. radius = radius || 1;
  19881. detail = detail || 0;
  19882. var that = this;
  19883. for ( var i = 0, l = vertices.length; i < l; i += 3 ) {
  19884. prepare( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  19885. }
  19886. var midpoints = [], p = this.vertices;
  19887. var faces = [];
  19888. for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) {
  19889. var v1 = p[ indices[ i ] ];
  19890. var v2 = p[ indices[ i + 1 ] ];
  19891. var v3 = p[ indices[ i + 2 ] ];
  19892. faces[ j ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19893. }
  19894. var centroid = new THREE.Vector3();
  19895. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19896. subdivide( faces[ i ], detail );
  19897. }
  19898. // Handle case when face straddles the seam
  19899. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  19900. var uvs = this.faceVertexUvs[ 0 ][ i ];
  19901. var x0 = uvs[ 0 ].x;
  19902. var x1 = uvs[ 1 ].x;
  19903. var x2 = uvs[ 2 ].x;
  19904. var max = Math.max( x0, Math.max( x1, x2 ) );
  19905. var min = Math.min( x0, Math.min( x1, x2 ) );
  19906. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  19907. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  19908. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  19909. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  19910. }
  19911. }
  19912. // Apply radius
  19913. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19914. this.vertices[ i ].multiplyScalar( radius );
  19915. }
  19916. // Merge vertices
  19917. this.mergeVertices();
  19918. this.computeFaceNormals();
  19919. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19920. // Project vector onto sphere's surface
  19921. function prepare( vector ) {
  19922. var vertex = vector.normalize().clone();
  19923. vertex.index = that.vertices.push( vertex ) - 1;
  19924. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19925. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19926. var v = inclination( vector ) / Math.PI + 0.5;
  19927. vertex.uv = new THREE.Vector2( u, 1 - v );
  19928. return vertex;
  19929. }
  19930. // Approximate a curved face with recursively sub-divided triangles.
  19931. function make( v1, v2, v3 ) {
  19932. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19933. that.faces.push( face );
  19934. centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  19935. var azi = azimuth( centroid );
  19936. that.faceVertexUvs[ 0 ].push( [
  19937. correctUV( v1.uv, v1, azi ),
  19938. correctUV( v2.uv, v2, azi ),
  19939. correctUV( v3.uv, v3, azi )
  19940. ] );
  19941. }
  19942. // Analytically subdivide a face to the required detail level.
  19943. function subdivide( face, detail ) {
  19944. var cols = Math.pow(2, detail);
  19945. var cells = Math.pow(4, detail);
  19946. var a = prepare( that.vertices[ face.a ] );
  19947. var b = prepare( that.vertices[ face.b ] );
  19948. var c = prepare( that.vertices[ face.c ] );
  19949. var v = [];
  19950. // Construct all of the vertices for this subdivision.
  19951. for ( var i = 0 ; i <= cols; i ++ ) {
  19952. v[ i ] = [];
  19953. var aj = prepare( a.clone().lerp( c, i / cols ) );
  19954. var bj = prepare( b.clone().lerp( c, i / cols ) );
  19955. var rows = cols - i;
  19956. for ( var j = 0; j <= rows; j ++) {
  19957. if ( j == 0 && i == cols ) {
  19958. v[ i ][ j ] = aj;
  19959. } else {
  19960. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  19961. }
  19962. }
  19963. }
  19964. // Construct all of the faces.
  19965. for ( var i = 0; i < cols ; i ++ ) {
  19966. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  19967. var k = Math.floor( j / 2 );
  19968. if ( j % 2 == 0 ) {
  19969. make(
  19970. v[ i ][ k + 1],
  19971. v[ i + 1 ][ k ],
  19972. v[ i ][ k ]
  19973. );
  19974. } else {
  19975. make(
  19976. v[ i ][ k + 1 ],
  19977. v[ i + 1][ k + 1],
  19978. v[ i + 1 ][ k ]
  19979. );
  19980. }
  19981. }
  19982. }
  19983. }
  19984. // Angle around the Y axis, counter-clockwise when looking from above.
  19985. function azimuth( vector ) {
  19986. return Math.atan2( vector.z, - vector.x );
  19987. }
  19988. // Angle above the XZ plane.
  19989. function inclination( vector ) {
  19990. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19991. }
  19992. // Texture fixing helper. Spheres have some odd behaviours.
  19993. function correctUV( uv, vector, azimuth ) {
  19994. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  19995. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  19996. return uv.clone();
  19997. }
  19998. };
  19999. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20000. // File:src/extras/geometries/IcosahedronGeometry.js
  20001. /**
  20002. * @author timothypratley / https://github.com/timothypratley
  20003. */
  20004. THREE.IcosahedronGeometry = function ( radius, detail ) {
  20005. this.parameters = {
  20006. radius: radius,
  20007. detail: detail
  20008. };
  20009. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20010. var vertices = [
  20011. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  20012. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  20013. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  20014. ];
  20015. var indices = [
  20016. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  20017. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  20018. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  20019. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  20020. ];
  20021. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  20022. };
  20023. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20024. // File:src/extras/geometries/OctahedronGeometry.js
  20025. /**
  20026. * @author timothypratley / https://github.com/timothypratley
  20027. */
  20028. THREE.OctahedronGeometry = function ( radius, detail ) {
  20029. this.parameters = {
  20030. radius: radius,
  20031. detail: detail
  20032. };
  20033. var vertices = [
  20034. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0,- 1, 0, 0, 0, 1, 0, 0,- 1
  20035. ];
  20036. var indices = [
  20037. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  20038. ];
  20039. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  20040. };
  20041. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20042. // File:src/extras/geometries/TetrahedronGeometry.js
  20043. /**
  20044. * @author timothypratley / https://github.com/timothypratley
  20045. */
  20046. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20047. var vertices = [
  20048. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  20049. ];
  20050. var indices = [
  20051. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  20052. ];
  20053. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  20054. };
  20055. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20056. // File:src/extras/geometries/ParametricGeometry.js
  20057. /**
  20058. * @author zz85 / https://github.com/zz85
  20059. * Parametric Surfaces Geometry
  20060. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20061. *
  20062. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  20063. *
  20064. */
  20065. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  20066. THREE.Geometry.call( this );
  20067. var verts = this.vertices;
  20068. var faces = this.faces;
  20069. var uvs = this.faceVertexUvs[ 0 ];
  20070. var i, il, j, p;
  20071. var u, v;
  20072. var stackCount = stacks + 1;
  20073. var sliceCount = slices + 1;
  20074. for ( i = 0; i <= stacks; i ++ ) {
  20075. v = i / stacks;
  20076. for ( j = 0; j <= slices; j ++ ) {
  20077. u = j / slices;
  20078. p = func( u, v );
  20079. verts.push( p );
  20080. }
  20081. }
  20082. var a, b, c, d;
  20083. var uva, uvb, uvc, uvd;
  20084. for ( i = 0; i < stacks; i ++ ) {
  20085. for ( j = 0; j < slices; j ++ ) {
  20086. a = i * sliceCount + j;
  20087. b = i * sliceCount + j + 1;
  20088. c = (i + 1) * sliceCount + j + 1;
  20089. d = (i + 1) * sliceCount + j;
  20090. uva = new THREE.Vector2( j / slices, i / stacks );
  20091. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20092. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20093. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20094. faces.push( new THREE.Face3( a, b, d ) );
  20095. uvs.push( [ uva, uvb, uvd ] );
  20096. faces.push( new THREE.Face3( b, c, d ) );
  20097. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  20098. }
  20099. }
  20100. // console.log(this);
  20101. // magic bullet
  20102. // var diff = this.mergeVertices();
  20103. // console.log('removed ', diff, ' vertices by merging');
  20104. this.computeFaceNormals();
  20105. this.computeVertexNormals();
  20106. };
  20107. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20108. // File:src/extras/helpers/AxisHelper.js
  20109. /**
  20110. * @author sroucheray / http://sroucheray.org/
  20111. * @author mrdoob / http://mrdoob.com/
  20112. */
  20113. THREE.AxisHelper = function ( size ) {
  20114. size = size || 1;
  20115. var vertices = new Float32Array( [
  20116. 0, 0, 0, size, 0, 0,
  20117. 0, 0, 0, 0, size, 0,
  20118. 0, 0, 0, 0, 0, size
  20119. ] );
  20120. var colors = new Float32Array( [
  20121. 1, 0, 0, 1, 0.6, 0,
  20122. 0, 1, 0, 0.6, 1, 0,
  20123. 0, 0, 1, 0, 0.6, 1
  20124. ] );
  20125. var geometry = new THREE.BufferGeometry();
  20126. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  20127. geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
  20128. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20129. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20130. };
  20131. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20132. // File:src/extras/helpers/ArrowHelper.js
  20133. /**
  20134. * @author WestLangley / http://github.com/WestLangley
  20135. * @author zz85 / http://github.com/zz85
  20136. * @author bhouston / http://exocortex.com
  20137. *
  20138. * Creates an arrow for visualizing directions
  20139. *
  20140. * Parameters:
  20141. * dir - Vector3
  20142. * origin - Vector3
  20143. * length - Number
  20144. * color - color in hex value
  20145. * headLength - Number
  20146. * headWidth - Number
  20147. */
  20148. THREE.ArrowHelper = ( function () {
  20149. var lineGeometry = new THREE.Geometry();
  20150. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) );
  20151. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  20152. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  20153. return function ( dir, origin, length, color, headLength, headWidth ) {
  20154. // dir is assumed to be normalized
  20155. THREE.Object3D.call( this );
  20156. if ( color === undefined ) color = 0xffff00;
  20157. if ( length === undefined ) length = 1;
  20158. if ( headLength === undefined ) headLength = 0.2 * length;
  20159. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20160. this.position.copy( origin );
  20161. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: color } ) );
  20162. this.line.matrixAutoUpdate = false;
  20163. this.add( this.line );
  20164. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: color } ) );
  20165. this.cone.matrixAutoUpdate = false;
  20166. this.add( this.cone );
  20167. this.setDirection( dir );
  20168. this.setLength( length, headLength, headWidth );
  20169. }
  20170. }() );
  20171. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20172. THREE.ArrowHelper.prototype.setDirection = ( function () {
  20173. var axis = new THREE.Vector3();
  20174. var radians;
  20175. return function ( dir ) {
  20176. // dir is assumed to be normalized
  20177. if ( dir.y > 0.99999 ) {
  20178. this.quaternion.set( 0, 0, 0, 1 );
  20179. } else if ( dir.y < - 0.99999 ) {
  20180. this.quaternion.set( 1, 0, 0, 0 );
  20181. } else {
  20182. axis.set( dir.z, 0, - dir.x ).normalize();
  20183. radians = Math.acos( dir.y );
  20184. this.quaternion.setFromAxisAngle( axis, radians );
  20185. }
  20186. };
  20187. }() );
  20188. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  20189. if ( headLength === undefined ) headLength = 0.2 * length;
  20190. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20191. this.line.scale.set( 1, length, 1 );
  20192. this.line.updateMatrix();
  20193. this.cone.scale.set( headWidth, headLength, headWidth );
  20194. this.cone.position.y = length;
  20195. this.cone.updateMatrix();
  20196. };
  20197. THREE.ArrowHelper.prototype.setColor = function ( color ) {
  20198. this.line.material.color.set( color );
  20199. this.cone.material.color.set( color );
  20200. };
  20201. // File:src/extras/helpers/BoxHelper.js
  20202. /**
  20203. * @author mrdoob / http://mrdoob.com/
  20204. */
  20205. THREE.BoxHelper = function ( object ) {
  20206. var geometry = new THREE.BufferGeometry();
  20207. geometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( 72 ), 3 ) );
  20208. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  20209. if ( object !== undefined ) {
  20210. this.update( object );
  20211. }
  20212. };
  20213. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20214. THREE.BoxHelper.prototype.update = function ( object ) {
  20215. var geometry = object.geometry;
  20216. if ( geometry.boundingBox === null ) {
  20217. geometry.computeBoundingBox();
  20218. }
  20219. var min = geometry.boundingBox.min;
  20220. var max = geometry.boundingBox.max;
  20221. /*
  20222. 5____4
  20223. 1/___0/|
  20224. | 6__|_7
  20225. 2/___3/
  20226. 0: max.x, max.y, max.z
  20227. 1: min.x, max.y, max.z
  20228. 2: min.x, min.y, max.z
  20229. 3: max.x, min.y, max.z
  20230. 4: max.x, max.y, min.z
  20231. 5: min.x, max.y, min.z
  20232. 6: min.x, min.y, min.z
  20233. 7: max.x, min.y, min.z
  20234. */
  20235. var vertices = this.geometry.attributes.position.array;
  20236. vertices[ 0 ] = max.x; vertices[ 1 ] = max.y; vertices[ 2 ] = max.z;
  20237. vertices[ 3 ] = min.x; vertices[ 4 ] = max.y; vertices[ 5 ] = max.z;
  20238. vertices[ 6 ] = min.x; vertices[ 7 ] = max.y; vertices[ 8 ] = max.z;
  20239. vertices[ 9 ] = min.x; vertices[ 10 ] = min.y; vertices[ 11 ] = max.z;
  20240. vertices[ 12 ] = min.x; vertices[ 13 ] = min.y; vertices[ 14 ] = max.z;
  20241. vertices[ 15 ] = max.x; vertices[ 16 ] = min.y; vertices[ 17 ] = max.z;
  20242. vertices[ 18 ] = max.x; vertices[ 19 ] = min.y; vertices[ 20 ] = max.z;
  20243. vertices[ 21 ] = max.x; vertices[ 22 ] = max.y; vertices[ 23 ] = max.z;
  20244. //
  20245. vertices[ 24 ] = max.x; vertices[ 25 ] = max.y; vertices[ 26 ] = min.z;
  20246. vertices[ 27 ] = min.x; vertices[ 28 ] = max.y; vertices[ 29 ] = min.z;
  20247. vertices[ 30 ] = min.x; vertices[ 31 ] = max.y; vertices[ 32 ] = min.z;
  20248. vertices[ 33 ] = min.x; vertices[ 34 ] = min.y; vertices[ 35 ] = min.z;
  20249. vertices[ 36 ] = min.x; vertices[ 37 ] = min.y; vertices[ 38 ] = min.z;
  20250. vertices[ 39 ] = max.x; vertices[ 40 ] = min.y; vertices[ 41 ] = min.z;
  20251. vertices[ 42 ] = max.x; vertices[ 43 ] = min.y; vertices[ 44 ] = min.z;
  20252. vertices[ 45 ] = max.x; vertices[ 46 ] = max.y; vertices[ 47 ] = min.z;
  20253. //
  20254. vertices[ 48 ] = max.x; vertices[ 49 ] = max.y; vertices[ 50 ] = max.z;
  20255. vertices[ 51 ] = max.x; vertices[ 52 ] = max.y; vertices[ 53 ] = min.z;
  20256. vertices[ 54 ] = min.x; vertices[ 55 ] = max.y; vertices[ 56 ] = max.z;
  20257. vertices[ 57 ] = min.x; vertices[ 58 ] = max.y; vertices[ 59 ] = min.z;
  20258. vertices[ 60 ] = min.x; vertices[ 61 ] = min.y; vertices[ 62 ] = max.z;
  20259. vertices[ 63 ] = min.x; vertices[ 64 ] = min.y; vertices[ 65 ] = min.z;
  20260. vertices[ 66 ] = max.x; vertices[ 67 ] = min.y; vertices[ 68 ] = max.z;
  20261. vertices[ 69 ] = max.x; vertices[ 70 ] = min.y; vertices[ 71 ] = min.z;
  20262. this.geometry.attributes.position.needsUpdate = true;
  20263. this.geometry.computeBoundingSphere();
  20264. this.matrixAutoUpdate = false;
  20265. this.matrixWorld = object.matrixWorld;
  20266. };
  20267. // File:src/extras/helpers/BoundingBoxHelper.js
  20268. /**
  20269. * @author WestLangley / http://github.com/WestLangley
  20270. */
  20271. // a helper to show the world-axis-aligned bounding box for an object
  20272. THREE.BoundingBoxHelper = function ( object, hex ) {
  20273. var color = ( hex !== undefined ) ? hex : 0x888888;
  20274. this.object = object;
  20275. this.box = new THREE.Box3();
  20276. THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20277. };
  20278. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20279. THREE.BoundingBoxHelper.prototype.update = function () {
  20280. this.box.setFromObject( this.object );
  20281. this.box.size( this.scale );
  20282. this.box.center( this.position );
  20283. };
  20284. // File:src/extras/helpers/CameraHelper.js
  20285. /**
  20286. * @author alteredq / http://alteredqualia.com/
  20287. *
  20288. * - shows frustum, line of sight and up of the camera
  20289. * - suitable for fast updates
  20290. * - based on frustum visualization in lightgl.js shadowmap example
  20291. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20292. */
  20293. THREE.CameraHelper = function ( camera ) {
  20294. var geometry = new THREE.Geometry();
  20295. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20296. var pointMap = {};
  20297. // colors
  20298. var hexFrustum = 0xffaa00;
  20299. var hexCone = 0xff0000;
  20300. var hexUp = 0x00aaff;
  20301. var hexTarget = 0xffffff;
  20302. var hexCross = 0x333333;
  20303. // near
  20304. addLine( "n1", "n2", hexFrustum );
  20305. addLine( "n2", "n4", hexFrustum );
  20306. addLine( "n4", "n3", hexFrustum );
  20307. addLine( "n3", "n1", hexFrustum );
  20308. // far
  20309. addLine( "f1", "f2", hexFrustum );
  20310. addLine( "f2", "f4", hexFrustum );
  20311. addLine( "f4", "f3", hexFrustum );
  20312. addLine( "f3", "f1", hexFrustum );
  20313. // sides
  20314. addLine( "n1", "f1", hexFrustum );
  20315. addLine( "n2", "f2", hexFrustum );
  20316. addLine( "n3", "f3", hexFrustum );
  20317. addLine( "n4", "f4", hexFrustum );
  20318. // cone
  20319. addLine( "p", "n1", hexCone );
  20320. addLine( "p", "n2", hexCone );
  20321. addLine( "p", "n3", hexCone );
  20322. addLine( "p", "n4", hexCone );
  20323. // up
  20324. addLine( "u1", "u2", hexUp );
  20325. addLine( "u2", "u3", hexUp );
  20326. addLine( "u3", "u1", hexUp );
  20327. // target
  20328. addLine( "c", "t", hexTarget );
  20329. addLine( "p", "c", hexCross );
  20330. // cross
  20331. addLine( "cn1", "cn2", hexCross );
  20332. addLine( "cn3", "cn4", hexCross );
  20333. addLine( "cf1", "cf2", hexCross );
  20334. addLine( "cf3", "cf4", hexCross );
  20335. function addLine( a, b, hex ) {
  20336. addPoint( a, hex );
  20337. addPoint( b, hex );
  20338. }
  20339. function addPoint( id, hex ) {
  20340. geometry.vertices.push( new THREE.Vector3() );
  20341. geometry.colors.push( new THREE.Color( hex ) );
  20342. if ( pointMap[ id ] === undefined ) {
  20343. pointMap[ id ] = [];
  20344. }
  20345. pointMap[ id ].push( geometry.vertices.length - 1 );
  20346. }
  20347. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20348. this.camera = camera;
  20349. this.matrixWorld = camera.matrixWorld;
  20350. this.matrixAutoUpdate = false;
  20351. this.pointMap = pointMap;
  20352. this.update();
  20353. };
  20354. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20355. THREE.CameraHelper.prototype.update = function () {
  20356. var vector = new THREE.Vector3();
  20357. var camera = new THREE.Camera();
  20358. var projector = new THREE.Projector();
  20359. return function () {
  20360. var scope = this;
  20361. var w = 1, h = 1;
  20362. // we need just camera projection matrix
  20363. // world matrix must be identity
  20364. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20365. // center / target
  20366. setPoint( "c", 0, 0, - 1 );
  20367. setPoint( "t", 0, 0, 1 );
  20368. // near
  20369. setPoint( "n1", - w, - h, - 1 );
  20370. setPoint( "n2", w, - h, - 1 );
  20371. setPoint( "n3", - w, h, - 1 );
  20372. setPoint( "n4", w, h, - 1 );
  20373. // far
  20374. setPoint( "f1", - w, - h, 1 );
  20375. setPoint( "f2", w, - h, 1 );
  20376. setPoint( "f3", - w, h, 1 );
  20377. setPoint( "f4", w, h, 1 );
  20378. // up
  20379. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  20380. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  20381. setPoint( "u3", 0, h * 2, - 1 );
  20382. // cross
  20383. setPoint( "cf1", - w, 0, 1 );
  20384. setPoint( "cf2", w, 0, 1 );
  20385. setPoint( "cf3", 0, - h, 1 );
  20386. setPoint( "cf4", 0, h, 1 );
  20387. setPoint( "cn1", - w, 0, - 1 );
  20388. setPoint( "cn2", w, 0, - 1 );
  20389. setPoint( "cn3", 0, - h, - 1 );
  20390. setPoint( "cn4", 0, h, - 1 );
  20391. function setPoint( point, x, y, z ) {
  20392. vector.set( x, y, z );
  20393. projector.unprojectVector( vector, camera );
  20394. var points = scope.pointMap[ point ];
  20395. if ( points !== undefined ) {
  20396. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20397. scope.geometry.vertices[ points[ i ] ].copy( vector );
  20398. }
  20399. }
  20400. }
  20401. this.geometry.verticesNeedUpdate = true;
  20402. };
  20403. }();
  20404. // File:src/extras/helpers/DirectionalLightHelper.js
  20405. /**
  20406. * @author alteredq / http://alteredqualia.com/
  20407. * @author mrdoob / http://mrdoob.com/
  20408. * @author WestLangley / http://github.com/WestLangley
  20409. */
  20410. THREE.DirectionalLightHelper = function ( light, size ) {
  20411. THREE.Object3D.call( this );
  20412. this.light = light;
  20413. this.light.updateMatrixWorld();
  20414. this.matrixWorld = light.matrixWorld;
  20415. this.matrixAutoUpdate = false;
  20416. size = size || 1;
  20417. var geometry = new THREE.Geometry();
  20418. geometry.vertices.push(
  20419. new THREE.Vector3( - size, size, 0 ),
  20420. new THREE.Vector3( size, size, 0 ),
  20421. new THREE.Vector3( size, - size, 0 ),
  20422. new THREE.Vector3( - size, - size, 0 ),
  20423. new THREE.Vector3( - size, size, 0 )
  20424. );
  20425. var material = new THREE.LineBasicMaterial( { fog: false } );
  20426. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20427. this.lightPlane = new THREE.Line( geometry, material );
  20428. this.add( this.lightPlane );
  20429. geometry = new THREE.Geometry();
  20430. geometry.vertices.push(
  20431. new THREE.Vector3(),
  20432. new THREE.Vector3()
  20433. );
  20434. material = new THREE.LineBasicMaterial( { fog: false } );
  20435. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20436. this.targetLine = new THREE.Line( geometry, material );
  20437. this.add( this.targetLine );
  20438. this.update();
  20439. };
  20440. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20441. THREE.DirectionalLightHelper.prototype.dispose = function () {
  20442. this.lightPlane.geometry.dispose();
  20443. this.lightPlane.material.dispose();
  20444. this.targetLine.geometry.dispose();
  20445. this.targetLine.material.dispose();
  20446. };
  20447. THREE.DirectionalLightHelper.prototype.update = function () {
  20448. var v1 = new THREE.Vector3();
  20449. var v2 = new THREE.Vector3();
  20450. var v3 = new THREE.Vector3();
  20451. return function () {
  20452. v1.setFromMatrixPosition( this.light.matrixWorld );
  20453. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20454. v3.subVectors( v2, v1 );
  20455. this.lightPlane.lookAt( v3 );
  20456. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20457. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  20458. this.targetLine.geometry.verticesNeedUpdate = true;
  20459. this.targetLine.material.color.copy( this.lightPlane.material.color );
  20460. }
  20461. }();
  20462. // File:src/extras/helpers/EdgesHelper.js
  20463. /**
  20464. * @author WestLangley / http://github.com/WestLangley
  20465. */
  20466. THREE.EdgesHelper = function ( object, hex ) {
  20467. var color = ( hex !== undefined ) ? hex : 0xffffff;
  20468. var edge = [ 0, 0 ], hash = {};
  20469. var sortFunction = function ( a, b ) { return a - b };
  20470. var keys = [ 'a', 'b', 'c' ];
  20471. var geometry = new THREE.BufferGeometry();
  20472. var geometry2 = object.geometry.clone();
  20473. geometry2.mergeVertices();
  20474. geometry2.computeFaceNormals();
  20475. var vertices = geometry2.vertices;
  20476. var faces = geometry2.faces;
  20477. var numEdges = 0;
  20478. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20479. var face = faces[ i ];
  20480. for ( var j = 0; j < 3; j ++ ) {
  20481. edge[ 0 ] = face[ keys[ j ] ];
  20482. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20483. edge.sort( sortFunction );
  20484. var key = edge.toString();
  20485. if ( hash[ key ] === undefined ) {
  20486. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  20487. numEdges ++;
  20488. } else {
  20489. hash[ key ].face2 = i;
  20490. }
  20491. }
  20492. }
  20493. geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2 * 3, 3 ) );
  20494. var coords = geometry.attributes.position.array;
  20495. var index = 0;
  20496. for ( var key in hash ) {
  20497. var h = hash[ key ];
  20498. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) < 0.9999 ) { // hardwired const OK
  20499. var vertex = vertices[ h.vert1 ];
  20500. coords[ index ++ ] = vertex.x;
  20501. coords[ index ++ ] = vertex.y;
  20502. coords[ index ++ ] = vertex.z;
  20503. vertex = vertices[ h.vert2 ];
  20504. coords[ index ++ ] = vertex.x;
  20505. coords[ index ++ ] = vertex.y;
  20506. coords[ index ++ ] = vertex.z;
  20507. }
  20508. }
  20509. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  20510. this.matrixAutoUpdate = false;
  20511. this.matrixWorld = object.matrixWorld;
  20512. };
  20513. THREE.EdgesHelper.prototype = Object.create( THREE.Line.prototype );
  20514. // File:src/extras/helpers/FaceNormalsHelper.js
  20515. /**
  20516. * @author mrdoob / http://mrdoob.com/
  20517. * @author WestLangley / http://github.com/WestLangley
  20518. */
  20519. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  20520. this.object = object;
  20521. this.size = ( size !== undefined ) ? size : 1;
  20522. var color = ( hex !== undefined ) ? hex : 0xffff00;
  20523. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20524. var geometry = new THREE.Geometry();
  20525. var faces = this.object.geometry.faces;
  20526. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20527. geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() );
  20528. }
  20529. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20530. this.matrixAutoUpdate = false;
  20531. this.normalMatrix = new THREE.Matrix3();
  20532. this.update();
  20533. };
  20534. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20535. THREE.FaceNormalsHelper.prototype.update = function () {
  20536. var vertices = this.geometry.vertices;
  20537. var object = this.object;
  20538. var objectVertices = object.geometry.vertices;
  20539. var objectFaces = object.geometry.faces;
  20540. var objectWorldMatrix = object.matrixWorld;
  20541. object.updateMatrixWorld( true );
  20542. this.normalMatrix.getNormalMatrix( objectWorldMatrix );
  20543. for ( var i = 0, i2 = 0, l = objectFaces.length; i < l; i ++, i2 += 2 ) {
  20544. var face = objectFaces[ i ];
  20545. vertices[ i2 ].copy( objectVertices[ face.a ] )
  20546. .add( objectVertices[ face.b ] )
  20547. .add( objectVertices[ face.c ] )
  20548. .divideScalar( 3 )
  20549. .applyMatrix4( objectWorldMatrix );
  20550. vertices[ i2 + 1 ].copy( face.normal )
  20551. .applyMatrix3( this.normalMatrix )
  20552. .normalize()
  20553. .multiplyScalar( this.size )
  20554. .add( vertices[ i2 ] );
  20555. }
  20556. this.geometry.verticesNeedUpdate = true;
  20557. return this;
  20558. };
  20559. // File:src/extras/helpers/GridHelper.js
  20560. /**
  20561. * @author mrdoob / http://mrdoob.com/
  20562. */
  20563. THREE.GridHelper = function ( size, step ) {
  20564. var geometry = new THREE.Geometry();
  20565. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20566. this.color1 = new THREE.Color( 0x444444 );
  20567. this.color2 = new THREE.Color( 0x888888 );
  20568. for ( var i = - size; i <= size; i += step ) {
  20569. geometry.vertices.push(
  20570. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  20571. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  20572. );
  20573. var color = i === 0 ? this.color1 : this.color2;
  20574. geometry.colors.push( color, color, color, color );
  20575. }
  20576. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20577. };
  20578. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  20579. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  20580. this.color1.set( colorCenterLine );
  20581. this.color2.set( colorGrid );
  20582. this.geometry.colorsNeedUpdate = true;
  20583. }
  20584. // File:src/extras/helpers/HemisphereLightHelper.js
  20585. /**
  20586. * @author alteredq / http://alteredqualia.com/
  20587. * @author mrdoob / http://mrdoob.com/
  20588. */
  20589. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20590. THREE.Object3D.call( this );
  20591. this.light = light;
  20592. this.light.updateMatrixWorld();
  20593. this.matrixWorld = light.matrixWorld;
  20594. this.matrixAutoUpdate = false;
  20595. this.colors = [ new THREE.Color(), new THREE.Color() ];
  20596. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20597. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20598. for ( var i = 0, il = 8; i < il; i ++ ) {
  20599. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  20600. }
  20601. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  20602. this.lightSphere = new THREE.Mesh( geometry, material );
  20603. this.add( this.lightSphere );
  20604. this.update();
  20605. };
  20606. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20607. THREE.HemisphereLightHelper.prototype.dispose = function () {
  20608. this.lightSphere.geometry.dispose();
  20609. this.lightSphere.material.dispose();
  20610. };
  20611. THREE.HemisphereLightHelper.prototype.update = function () {
  20612. var vector = new THREE.Vector3();
  20613. return function () {
  20614. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  20615. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  20616. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20617. this.lightSphere.geometry.colorsNeedUpdate = true;
  20618. }
  20619. }();
  20620. // File:src/extras/helpers/PointLightHelper.js
  20621. /**
  20622. * @author alteredq / http://alteredqualia.com/
  20623. * @author mrdoob / http://mrdoob.com/
  20624. */
  20625. THREE.PointLightHelper = function ( light, sphereSize ) {
  20626. this.light = light;
  20627. this.light.updateMatrixWorld();
  20628. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20629. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20630. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20631. THREE.Mesh.call( this, geometry, material );
  20632. this.matrixWorld = this.light.matrixWorld;
  20633. this.matrixAutoUpdate = false;
  20634. /*
  20635. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20636. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20637. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20638. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20639. var d = light.distance;
  20640. if ( d === 0.0 ) {
  20641. this.lightDistance.visible = false;
  20642. } else {
  20643. this.lightDistance.scale.set( d, d, d );
  20644. }
  20645. this.add( this.lightDistance );
  20646. */
  20647. };
  20648. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  20649. THREE.PointLightHelper.prototype.dispose = function () {
  20650. this.geometry.dispose();
  20651. this.material.dispose();
  20652. };
  20653. THREE.PointLightHelper.prototype.update = function () {
  20654. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20655. /*
  20656. var d = this.light.distance;
  20657. if ( d === 0.0 ) {
  20658. this.lightDistance.visible = false;
  20659. } else {
  20660. this.lightDistance.visible = true;
  20661. this.lightDistance.scale.set( d, d, d );
  20662. }
  20663. */
  20664. };
  20665. // File:src/extras/helpers/SkeletonHelper.js
  20666. /**
  20667. * @author Sean Griffin / http://twitter.com/sgrif
  20668. * @author Michael Guerrero / http://realitymeltdown.com
  20669. * @author mrdoob / http://mrdoob.com/
  20670. */
  20671. THREE.SkeletonHelper = function ( object ) {
  20672. var skeleton = object.skeleton;
  20673. var geometry = new THREE.Geometry();
  20674. for ( var i = 0; i < skeleton.bones.length; i ++ ) {
  20675. var bone = skeleton.bones[ i ];
  20676. if ( bone.parent instanceof THREE.Bone ) {
  20677. geometry.vertices.push( new THREE.Vector3() );
  20678. geometry.vertices.push( new THREE.Vector3() );
  20679. geometry.colors.push( new THREE.Color( 0, 0, 1 ) );
  20680. geometry.colors.push( new THREE.Color( 0, 1, 0 ) );
  20681. }
  20682. }
  20683. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  20684. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20685. this.skeleton = skeleton;
  20686. this.matrixWorld = object.matrixWorld;
  20687. this.matrixAutoUpdate = false;
  20688. this.update();
  20689. };
  20690. THREE.SkeletonHelper.prototype = Object.create( THREE.Line.prototype );
  20691. THREE.SkeletonHelper.prototype.update = function () {
  20692. var geometry = this.geometry;
  20693. var j = 0;
  20694. for ( var i = 0; i < this.skeleton.bones.length; i ++ ) {
  20695. var bone = this.skeleton.bones[ i ];
  20696. if ( bone.parent instanceof THREE.Bone ) {
  20697. geometry.vertices[ j ].setFromMatrixPosition( bone.skinMatrix );
  20698. geometry.vertices[ j + 1 ].setFromMatrixPosition( bone.parent.skinMatrix );
  20699. j += 2;
  20700. }
  20701. }
  20702. geometry.verticesNeedUpdate = true;
  20703. geometry.computeBoundingSphere();
  20704. };
  20705. // File:src/extras/helpers/SpotLightHelper.js
  20706. /**
  20707. * @author alteredq / http://alteredqualia.com/
  20708. * @author mrdoob / http://mrdoob.com/
  20709. * @author WestLangley / http://github.com/WestLangley
  20710. */
  20711. THREE.SpotLightHelper = function ( light ) {
  20712. THREE.Object3D.call( this );
  20713. this.light = light;
  20714. this.light.updateMatrixWorld();
  20715. this.matrixWorld = light.matrixWorld;
  20716. this.matrixAutoUpdate = false;
  20717. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  20718. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  20719. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20720. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20721. this.cone = new THREE.Mesh( geometry, material );
  20722. this.add( this.cone );
  20723. this.update();
  20724. };
  20725. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20726. THREE.SpotLightHelper.prototype.dispose = function () {
  20727. this.cone.geometry.dispose();
  20728. this.cone.material.dispose();
  20729. };
  20730. THREE.SpotLightHelper.prototype.update = function () {
  20731. var vector = new THREE.Vector3();
  20732. var vector2 = new THREE.Vector3();
  20733. return function () {
  20734. var coneLength = this.light.distance ? this.light.distance : 10000;
  20735. var coneWidth = coneLength * Math.tan( this.light.angle );
  20736. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20737. vector.setFromMatrixPosition( this.light.matrixWorld );
  20738. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  20739. this.cone.lookAt( vector2.sub( vector ) );
  20740. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20741. };
  20742. }();
  20743. // File:src/extras/helpers/VertexNormalsHelper.js
  20744. /**
  20745. * @author mrdoob / http://mrdoob.com/
  20746. * @author WestLangley / http://github.com/WestLangley
  20747. */
  20748. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  20749. this.object = object;
  20750. this.size = ( size !== undefined ) ? size : 1;
  20751. var color = ( hex !== undefined ) ? hex : 0xff0000;
  20752. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20753. var geometry = new THREE.Geometry();
  20754. var vertices = object.geometry.vertices;
  20755. var faces = object.geometry.faces;
  20756. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20757. var face = faces[ i ];
  20758. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20759. geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() );
  20760. }
  20761. }
  20762. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20763. this.matrixAutoUpdate = false;
  20764. this.normalMatrix = new THREE.Matrix3();
  20765. this.update();
  20766. };
  20767. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20768. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  20769. var v1 = new THREE.Vector3();
  20770. return function( object ) {
  20771. var keys = [ 'a', 'b', 'c', 'd' ];
  20772. this.object.updateMatrixWorld( true );
  20773. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20774. var vertices = this.geometry.vertices;
  20775. var verts = this.object.geometry.vertices;
  20776. var faces = this.object.geometry.faces;
  20777. var worldMatrix = this.object.matrixWorld;
  20778. var idx = 0;
  20779. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20780. var face = faces[ i ];
  20781. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20782. var vertexId = face[ keys[ j ] ];
  20783. var vertex = verts[ vertexId ];
  20784. var normal = face.vertexNormals[ j ];
  20785. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20786. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20787. v1.add( vertices[ idx ] );
  20788. idx = idx + 1;
  20789. vertices[ idx ].copy( v1 );
  20790. idx = idx + 1;
  20791. }
  20792. }
  20793. this.geometry.verticesNeedUpdate = true;
  20794. return this;
  20795. }
  20796. }());
  20797. // File:src/extras/helpers/VertexTangentsHelper.js
  20798. /**
  20799. * @author mrdoob / http://mrdoob.com/
  20800. * @author WestLangley / http://github.com/WestLangley
  20801. */
  20802. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  20803. this.object = object;
  20804. this.size = ( size !== undefined ) ? size : 1;
  20805. var color = ( hex !== undefined ) ? hex : 0x0000ff;
  20806. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20807. var geometry = new THREE.Geometry();
  20808. var vertices = object.geometry.vertices;
  20809. var faces = object.geometry.faces;
  20810. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20811. var face = faces[ i ];
  20812. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20813. geometry.vertices.push( new THREE.Vector3() );
  20814. geometry.vertices.push( new THREE.Vector3() );
  20815. }
  20816. }
  20817. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20818. this.matrixAutoUpdate = false;
  20819. this.update();
  20820. };
  20821. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  20822. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  20823. var v1 = new THREE.Vector3();
  20824. return function( object ) {
  20825. var keys = [ 'a', 'b', 'c', 'd' ];
  20826. this.object.updateMatrixWorld( true );
  20827. var vertices = this.geometry.vertices;
  20828. var verts = this.object.geometry.vertices;
  20829. var faces = this.object.geometry.faces;
  20830. var worldMatrix = this.object.matrixWorld;
  20831. var idx = 0;
  20832. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20833. var face = faces[ i ];
  20834. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20835. var vertexId = face[ keys[ j ] ];
  20836. var vertex = verts[ vertexId ];
  20837. var tangent = face.vertexTangents[ j ];
  20838. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20839. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  20840. v1.add( vertices[ idx ] );
  20841. idx = idx + 1;
  20842. vertices[ idx ].copy( v1 );
  20843. idx = idx + 1;
  20844. }
  20845. }
  20846. this.geometry.verticesNeedUpdate = true;
  20847. return this;
  20848. }
  20849. }());
  20850. // File:src/extras/helpers/WireframeHelper.js
  20851. /**
  20852. * @author mrdoob / http://mrdoob.com/
  20853. */
  20854. THREE.WireframeHelper = function ( object, hex ) {
  20855. var color = ( hex !== undefined ) ? hex : 0xffffff;
  20856. var edge = [ 0, 0 ], hash = {};
  20857. var sortFunction = function ( a, b ) { return a - b };
  20858. var keys = [ 'a', 'b', 'c' ];
  20859. var geometry = new THREE.BufferGeometry();
  20860. if ( object.geometry instanceof THREE.Geometry ) {
  20861. var vertices = object.geometry.vertices;
  20862. var faces = object.geometry.faces;
  20863. var numEdges = 0;
  20864. // allocate maximal size
  20865. var edges = new Uint32Array( 6 * faces.length );
  20866. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20867. var face = faces[ i ];
  20868. for ( var j = 0; j < 3; j ++ ) {
  20869. edge[ 0 ] = face[ keys[ j ] ];
  20870. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20871. edge.sort( sortFunction );
  20872. var key = edge.toString();
  20873. if ( hash[ key ] === undefined ) {
  20874. edges[ 2 * numEdges ] = edge[ 0 ];
  20875. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  20876. hash[ key ] = true;
  20877. numEdges ++;
  20878. }
  20879. }
  20880. }
  20881. var coords = new Float32Array( numEdges * 2 * 3 );
  20882. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  20883. for ( var j = 0; j < 2; j ++ ) {
  20884. var vertex = vertices[ edges [ 2 * i + j] ];
  20885. var index = 6 * i + 3 * j;
  20886. coords[ index + 0 ] = vertex.x;
  20887. coords[ index + 1 ] = vertex.y;
  20888. coords[ index + 2 ] = vertex.z;
  20889. }
  20890. }
  20891. geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20892. } else if ( object.geometry instanceof THREE.BufferGeometry ) {
  20893. if ( object.geometry.attributes.index !== undefined ) { // Indexed BufferGeometry
  20894. var vertices = object.geometry.attributes.position.array;
  20895. var indices = object.geometry.attributes.index.array;
  20896. var offsets = object.geometry.offsets;
  20897. var numEdges = 0;
  20898. // allocate maximal size
  20899. var edges = new Uint32Array( 2 * indices.length );
  20900. for ( var o = 0, ol = offsets.length; o < ol; ++ o ) {
  20901. var start = offsets[ o ].start;
  20902. var count = offsets[ o ].count;
  20903. var index = offsets[ o ].index;
  20904. for ( var i = start, il = start + count; i < il; i += 3 ) {
  20905. for ( var j = 0; j < 3; j ++ ) {
  20906. edge[ 0 ] = index + indices[ i + j ];
  20907. edge[ 1 ] = index + indices[ i + ( j + 1 ) % 3 ];
  20908. edge.sort( sortFunction );
  20909. var key = edge.toString();
  20910. if ( hash[ key ] === undefined ) {
  20911. edges[ 2 * numEdges ] = edge[ 0 ];
  20912. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  20913. hash[ key ] = true;
  20914. numEdges ++;
  20915. }
  20916. }
  20917. }
  20918. }
  20919. var coords = new Float32Array( numEdges * 2 * 3 );
  20920. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  20921. for ( var j = 0; j < 2; j ++ ) {
  20922. var index = 6 * i + 3 * j;
  20923. var index2 = 3 * edges[ 2 * i + j];
  20924. coords[ index + 0 ] = vertices[ index2 ];
  20925. coords[ index + 1 ] = vertices[ index2 + 1 ];
  20926. coords[ index + 2 ] = vertices[ index2 + 2 ];
  20927. }
  20928. }
  20929. geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20930. } else { // non-indexed BufferGeometry
  20931. var vertices = object.geometry.attributes.position.array;
  20932. var numEdges = vertices.length / 3;
  20933. var numTris = numEdges / 3;
  20934. var coords = new Float32Array( numEdges * 2 * 3 );
  20935. for ( var i = 0, l = numTris; i < l; i ++ ) {
  20936. for ( var j = 0; j < 3; j ++ ) {
  20937. var index = 18 * i + 6 * j;
  20938. var index1 = 9 * i + 3 * j;
  20939. coords[ index + 0 ] = vertices[ index1 ];
  20940. coords[ index + 1 ] = vertices[ index1 + 1 ];
  20941. coords[ index + 2 ] = vertices[ index1 + 2 ];
  20942. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  20943. coords[ index + 3 ] = vertices[ index2 ];
  20944. coords[ index + 4 ] = vertices[ index2 + 1 ];
  20945. coords[ index + 5 ] = vertices[ index2 + 2 ];
  20946. }
  20947. }
  20948. geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20949. }
  20950. }
  20951. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  20952. this.matrixAutoUpdate = false;
  20953. this.matrixWorld = object.matrixWorld;
  20954. };
  20955. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  20956. // File:src/extras/objects/ImmediateRenderObject.js
  20957. /**
  20958. * @author alteredq / http://alteredqualia.com/
  20959. */
  20960. THREE.ImmediateRenderObject = function () {
  20961. THREE.Object3D.call( this );
  20962. this.render = function ( renderCallback ) {};
  20963. };
  20964. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20965. // File:src/extras/objects/LensFlare.js
  20966. /**
  20967. * @author mikael emtinger / http://gomo.se/
  20968. * @author alteredq / http://alteredqualia.com/
  20969. */
  20970. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20971. THREE.Object3D.call( this );
  20972. this.lensFlares = [];
  20973. this.positionScreen = new THREE.Vector3();
  20974. this.customUpdateCallback = undefined;
  20975. if( texture !== undefined ) {
  20976. this.add( texture, size, distance, blending, color );
  20977. }
  20978. };
  20979. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20980. /*
  20981. * Add: adds another flare
  20982. */
  20983. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20984. if( size === undefined ) size = - 1;
  20985. if( distance === undefined ) distance = 0;
  20986. if( opacity === undefined ) opacity = 1;
  20987. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20988. if( blending === undefined ) blending = THREE.NormalBlending;
  20989. distance = Math.min( distance, Math.max( 0, distance ) );
  20990. this.lensFlares.push( { texture: texture, // THREE.Texture
  20991. size: size, // size in pixels (-1 = use texture.width)
  20992. distance: distance, // distance (0-1) from light source (0=at light source)
  20993. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20994. scale: 1, // scale
  20995. rotation: 1, // rotation
  20996. opacity: opacity, // opacity
  20997. color: color, // color
  20998. blending: blending } ); // blending
  20999. };
  21000. /*
  21001. * Update lens flares update positions on all flares based on the screen position
  21002. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  21003. */
  21004. THREE.LensFlare.prototype.updateLensFlares = function () {
  21005. var f, fl = this.lensFlares.length;
  21006. var flare;
  21007. var vecX = - this.positionScreen.x * 2;
  21008. var vecY = - this.positionScreen.y * 2;
  21009. for( f = 0; f < fl; f ++ ) {
  21010. flare = this.lensFlares[ f ];
  21011. flare.x = this.positionScreen.x + vecX * flare.distance;
  21012. flare.y = this.positionScreen.y + vecY * flare.distance;
  21013. flare.wantedRotation = flare.x * Math.PI * 0.25;
  21014. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  21015. }
  21016. };
  21017. // File:src/extras/objects/MorphBlendMesh.js
  21018. /**
  21019. * @author alteredq / http://alteredqualia.com/
  21020. */
  21021. THREE.MorphBlendMesh = function( geometry, material ) {
  21022. THREE.Mesh.call( this, geometry, material );
  21023. this.animationsMap = {};
  21024. this.animationsList = [];
  21025. // prepare default animation
  21026. // (all frames played together in 1 second)
  21027. var numFrames = this.geometry.morphTargets.length;
  21028. var name = "__default";
  21029. var startFrame = 0;
  21030. var endFrame = numFrames - 1;
  21031. var fps = numFrames / 1;
  21032. this.createAnimation( name, startFrame, endFrame, fps );
  21033. this.setAnimationWeight( name, 1 );
  21034. };
  21035. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  21036. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  21037. var animation = {
  21038. startFrame: start,
  21039. endFrame: end,
  21040. length: end - start + 1,
  21041. fps: fps,
  21042. duration: ( end - start ) / fps,
  21043. lastFrame: 0,
  21044. currentFrame: 0,
  21045. active: false,
  21046. time: 0,
  21047. direction: 1,
  21048. weight: 1,
  21049. directionBackwards: false,
  21050. mirroredLoop: false
  21051. };
  21052. this.animationsMap[ name ] = animation;
  21053. this.animationsList.push( animation );
  21054. };
  21055. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21056. var pattern = /([a-z]+)_?(\d+)/;
  21057. var firstAnimation, frameRanges = {};
  21058. var geometry = this.geometry;
  21059. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21060. var morph = geometry.morphTargets[ i ];
  21061. var chunks = morph.name.match( pattern );
  21062. if ( chunks && chunks.length > 1 ) {
  21063. var name = chunks[ 1 ];
  21064. var num = chunks[ 2 ];
  21065. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  21066. var range = frameRanges[ name ];
  21067. if ( i < range.start ) range.start = i;
  21068. if ( i > range.end ) range.end = i;
  21069. if ( ! firstAnimation ) firstAnimation = name;
  21070. }
  21071. }
  21072. for ( var name in frameRanges ) {
  21073. var range = frameRanges[ name ];
  21074. this.createAnimation( name, range.start, range.end, fps );
  21075. }
  21076. this.firstAnimation = firstAnimation;
  21077. };
  21078. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  21079. var animation = this.animationsMap[ name ];
  21080. if ( animation ) {
  21081. animation.direction = 1;
  21082. animation.directionBackwards = false;
  21083. }
  21084. };
  21085. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  21086. var animation = this.animationsMap[ name ];
  21087. if ( animation ) {
  21088. animation.direction = - 1;
  21089. animation.directionBackwards = true;
  21090. }
  21091. };
  21092. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  21093. var animation = this.animationsMap[ name ];
  21094. if ( animation ) {
  21095. animation.fps = fps;
  21096. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21097. }
  21098. };
  21099. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21100. var animation = this.animationsMap[ name ];
  21101. if ( animation ) {
  21102. animation.duration = duration;
  21103. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21104. }
  21105. };
  21106. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21107. var animation = this.animationsMap[ name ];
  21108. if ( animation ) {
  21109. animation.weight = weight;
  21110. }
  21111. };
  21112. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21113. var animation = this.animationsMap[ name ];
  21114. if ( animation ) {
  21115. animation.time = time;
  21116. }
  21117. };
  21118. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21119. var time = 0;
  21120. var animation = this.animationsMap[ name ];
  21121. if ( animation ) {
  21122. time = animation.time;
  21123. }
  21124. return time;
  21125. };
  21126. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21127. var duration = - 1;
  21128. var animation = this.animationsMap[ name ];
  21129. if ( animation ) {
  21130. duration = animation.duration;
  21131. }
  21132. return duration;
  21133. };
  21134. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21135. var animation = this.animationsMap[ name ];
  21136. if ( animation ) {
  21137. animation.time = 0;
  21138. animation.active = true;
  21139. } else {
  21140. console.warn( "animation[" + name + "] undefined" );
  21141. }
  21142. };
  21143. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21144. var animation = this.animationsMap[ name ];
  21145. if ( animation ) {
  21146. animation.active = false;
  21147. }
  21148. };
  21149. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  21150. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21151. var animation = this.animationsList[ i ];
  21152. if ( ! animation.active ) continue;
  21153. var frameTime = animation.duration / animation.length;
  21154. animation.time += animation.direction * delta;
  21155. if ( animation.mirroredLoop ) {
  21156. if ( animation.time > animation.duration || animation.time < 0 ) {
  21157. animation.direction *= - 1;
  21158. if ( animation.time > animation.duration ) {
  21159. animation.time = animation.duration;
  21160. animation.directionBackwards = true;
  21161. }
  21162. if ( animation.time < 0 ) {
  21163. animation.time = 0;
  21164. animation.directionBackwards = false;
  21165. }
  21166. }
  21167. } else {
  21168. animation.time = animation.time % animation.duration;
  21169. if ( animation.time < 0 ) animation.time += animation.duration;
  21170. }
  21171. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21172. var weight = animation.weight;
  21173. if ( keyframe !== animation.currentFrame ) {
  21174. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21175. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21176. this.morphTargetInfluences[ keyframe ] = 0;
  21177. animation.lastFrame = animation.currentFrame;
  21178. animation.currentFrame = keyframe;
  21179. }
  21180. var mix = ( animation.time % frameTime ) / frameTime;
  21181. if ( animation.directionBackwards ) mix = 1 - mix;
  21182. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21183. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21184. }
  21185. };
  21186. // File:src/extras/renderers/plugins/LensFlarePlugin.js
  21187. /**
  21188. * @author mikael emtinger / http://gomo.se/
  21189. * @author alteredq / http://alteredqualia.com/
  21190. */
  21191. THREE.LensFlarePlugin = function () {
  21192. var _gl, _renderer, _precision, _lensFlare = {};
  21193. this.init = function ( renderer ) {
  21194. _gl = renderer.context;
  21195. _renderer = renderer;
  21196. _precision = renderer.getPrecision();
  21197. _lensFlare.vertices = new Float32Array( 8 + 8 );
  21198. _lensFlare.faces = new Uint16Array( 6 );
  21199. var i = 0;
  21200. _lensFlare.vertices[ i ++ ] = - 1; _lensFlare.vertices[ i ++ ] = - 1; // vertex
  21201. _lensFlare.vertices[ i ++ ] = 0; _lensFlare.vertices[ i ++ ] = 0; // uv... etc.
  21202. _lensFlare.vertices[ i ++ ] = 1; _lensFlare.vertices[ i ++ ] = - 1;
  21203. _lensFlare.vertices[ i ++ ] = 1; _lensFlare.vertices[ i ++ ] = 0;
  21204. _lensFlare.vertices[ i ++ ] = 1; _lensFlare.vertices[ i ++ ] = 1;
  21205. _lensFlare.vertices[ i ++ ] = 1; _lensFlare.vertices[ i ++ ] = 1;
  21206. _lensFlare.vertices[ i ++ ] = - 1; _lensFlare.vertices[ i ++ ] = 1;
  21207. _lensFlare.vertices[ i ++ ] = 0; _lensFlare.vertices[ i ++ ] = 1;
  21208. i = 0;
  21209. _lensFlare.faces[ i ++ ] = 0; _lensFlare.faces[ i ++ ] = 1; _lensFlare.faces[ i ++ ] = 2;
  21210. _lensFlare.faces[ i ++ ] = 0; _lensFlare.faces[ i ++ ] = 2; _lensFlare.faces[ i ++ ] = 3;
  21211. // buffers
  21212. _lensFlare.vertexBuffer = _gl.createBuffer();
  21213. _lensFlare.elementBuffer = _gl.createBuffer();
  21214. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21215. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  21216. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21217. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  21218. // textures
  21219. _lensFlare.tempTexture = _gl.createTexture();
  21220. _lensFlare.occlusionTexture = _gl.createTexture();
  21221. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21222. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21223. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21224. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21225. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21226. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21227. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21228. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21229. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21230. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21231. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21232. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21233. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21234. _lensFlare.hasVertexTexture = false;
  21235. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  21236. } else {
  21237. _lensFlare.hasVertexTexture = true;
  21238. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  21239. }
  21240. _lensFlare.attributes = {};
  21241. _lensFlare.uniforms = {};
  21242. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21243. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21244. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21245. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21246. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21247. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21248. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21249. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21250. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21251. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21252. };
  21253. /*
  21254. * Render lens flares
  21255. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21256. * reads these back and calculates occlusion.
  21257. * Then _lensFlare.update_lensFlares() is called to re-position and
  21258. * update transparency of flares. Then they are rendered.
  21259. *
  21260. */
  21261. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21262. var flares = scene.__webglFlares,
  21263. nFlares = flares.length;
  21264. if ( ! nFlares ) return;
  21265. var tempPosition = new THREE.Vector3();
  21266. var invAspect = viewportHeight / viewportWidth,
  21267. halfViewportWidth = viewportWidth * 0.5,
  21268. halfViewportHeight = viewportHeight * 0.5;
  21269. var size = 16 / viewportHeight,
  21270. scale = new THREE.Vector2( size * invAspect, size );
  21271. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21272. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21273. var uniforms = _lensFlare.uniforms,
  21274. attributes = _lensFlare.attributes;
  21275. // set _lensFlare program and reset blending
  21276. _gl.useProgram( _lensFlare.program );
  21277. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21278. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21279. // loop through all lens flares to update their occlusion and positions
  21280. // setup gl and common used attribs/unforms
  21281. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21282. _gl.uniform1i( uniforms.map, 1 );
  21283. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21284. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21285. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21286. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21287. _gl.disable( _gl.CULL_FACE );
  21288. _gl.depthMask( false );
  21289. var i, j, jl, flare, sprite;
  21290. for ( i = 0; i < nFlares; i ++ ) {
  21291. size = 16 / viewportHeight;
  21292. scale.set( size * invAspect, size );
  21293. // calc object screen position
  21294. flare = flares[ i ];
  21295. if ( flare.visible === false ) continue;
  21296. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21297. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  21298. tempPosition.applyProjection( camera.projectionMatrix );
  21299. // setup arrays for gl programs
  21300. screenPosition.copy( tempPosition )
  21301. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21302. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21303. // screen cull
  21304. if ( _lensFlare.hasVertexTexture || (
  21305. screenPositionPixels.x > 0 &&
  21306. screenPositionPixels.x < viewportWidth &&
  21307. screenPositionPixels.y > 0 &&
  21308. screenPositionPixels.y < viewportHeight ) ) {
  21309. // save current RGB to temp texture
  21310. _gl.activeTexture( _gl.TEXTURE1 );
  21311. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21312. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21313. // render pink quad
  21314. _gl.uniform1i( uniforms.renderType, 0 );
  21315. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21316. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21317. _gl.disable( _gl.BLEND );
  21318. _gl.enable( _gl.DEPTH_TEST );
  21319. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21320. // copy result to occlusionMap
  21321. _gl.activeTexture( _gl.TEXTURE0 );
  21322. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21323. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21324. // restore graphics
  21325. _gl.uniform1i( uniforms.renderType, 1 );
  21326. _gl.disable( _gl.DEPTH_TEST );
  21327. _gl.activeTexture( _gl.TEXTURE1 );
  21328. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21329. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21330. // update object positions
  21331. flare.positionScreen.copy( screenPosition )
  21332. if ( flare.customUpdateCallback ) {
  21333. flare.customUpdateCallback( flare );
  21334. } else {
  21335. flare.updateLensFlares();
  21336. }
  21337. // render flares
  21338. _gl.uniform1i( uniforms.renderType, 2 );
  21339. _gl.enable( _gl.BLEND );
  21340. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21341. sprite = flare.lensFlares[ j ];
  21342. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21343. screenPosition.x = sprite.x;
  21344. screenPosition.y = sprite.y;
  21345. screenPosition.z = sprite.z;
  21346. size = sprite.size * sprite.scale / viewportHeight;
  21347. scale.x = size * invAspect;
  21348. scale.y = size;
  21349. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21350. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21351. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21352. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21353. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21354. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21355. _renderer.setTexture( sprite.texture, 1 );
  21356. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21357. }
  21358. }
  21359. }
  21360. }
  21361. // restore gl
  21362. _gl.enable( _gl.CULL_FACE );
  21363. _gl.enable( _gl.DEPTH_TEST );
  21364. _gl.depthMask( true );
  21365. };
  21366. function createProgram ( shader, precision ) {
  21367. var program = _gl.createProgram();
  21368. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21369. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21370. var prefix = "precision " + precision + " float;\n";
  21371. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21372. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21373. _gl.compileShader( fragmentShader );
  21374. _gl.compileShader( vertexShader );
  21375. _gl.attachShader( program, fragmentShader );
  21376. _gl.attachShader( program, vertexShader );
  21377. _gl.linkProgram( program );
  21378. return program;
  21379. };
  21380. };
  21381. // File:src/extras/renderers/plugins/ShadowMapPlugin.js
  21382. /**
  21383. * @author alteredq / http://alteredqualia.com/
  21384. */
  21385. THREE.ShadowMapPlugin = function () {
  21386. var _gl,
  21387. _renderer,
  21388. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21389. _frustum = new THREE.Frustum(),
  21390. _projScreenMatrix = new THREE.Matrix4(),
  21391. _min = new THREE.Vector3(),
  21392. _max = new THREE.Vector3(),
  21393. _matrixPosition = new THREE.Vector3(),
  21394. _renderList = [];
  21395. this.init = function ( renderer ) {
  21396. _gl = renderer.context;
  21397. _renderer = renderer;
  21398. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21399. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21400. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21401. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21402. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21403. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21404. _depthMaterial._shadowPass = true;
  21405. _depthMaterialMorph._shadowPass = true;
  21406. _depthMaterialSkin._shadowPass = true;
  21407. _depthMaterialMorphSkin._shadowPass = true;
  21408. };
  21409. this.render = function ( scene, camera ) {
  21410. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21411. this.update( scene, camera );
  21412. };
  21413. this.update = function ( scene, camera ) {
  21414. var i, il, j, jl, n,
  21415. shadowMap, shadowMatrix, shadowCamera,
  21416. program, buffer, material,
  21417. webglObject, object, light,
  21418. lights = [],
  21419. k = 0,
  21420. fog = null;
  21421. // set GL state for depth map
  21422. _gl.clearColor( 1, 1, 1, 1 );
  21423. _gl.disable( _gl.BLEND );
  21424. _gl.enable( _gl.CULL_FACE );
  21425. _gl.frontFace( _gl.CCW );
  21426. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21427. _gl.cullFace( _gl.FRONT );
  21428. } else {
  21429. _gl.cullFace( _gl.BACK );
  21430. }
  21431. _renderer.setDepthTest( true );
  21432. // preprocess lights
  21433. // - skip lights that are not casting shadows
  21434. // - create virtual lights for cascaded shadow maps
  21435. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21436. light = scene.__lights[ i ];
  21437. if ( ! light.castShadow ) continue;
  21438. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21439. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21440. var virtualLight;
  21441. if ( ! light.shadowCascadeArray[ n ] ) {
  21442. virtualLight = createVirtualLight( light, n );
  21443. virtualLight.originalCamera = camera;
  21444. var gyro = new THREE.Gyroscope();
  21445. gyro.position.copy( light.shadowCascadeOffset );
  21446. gyro.add( virtualLight );
  21447. gyro.add( virtualLight.target );
  21448. camera.add( gyro );
  21449. light.shadowCascadeArray[ n ] = virtualLight;
  21450. console.log( "Created virtualLight", virtualLight );
  21451. } else {
  21452. virtualLight = light.shadowCascadeArray[ n ];
  21453. }
  21454. updateVirtualLight( light, n );
  21455. lights[ k ] = virtualLight;
  21456. k ++;
  21457. }
  21458. } else {
  21459. lights[ k ] = light;
  21460. k ++;
  21461. }
  21462. }
  21463. // render depth map
  21464. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21465. light = lights[ i ];
  21466. if ( ! light.shadowMap ) {
  21467. var shadowFilter = THREE.LinearFilter;
  21468. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21469. shadowFilter = THREE.NearestFilter;
  21470. }
  21471. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21472. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21473. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21474. light.shadowMatrix = new THREE.Matrix4();
  21475. }
  21476. if ( ! light.shadowCamera ) {
  21477. if ( light instanceof THREE.SpotLight ) {
  21478. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21479. } else if ( light instanceof THREE.DirectionalLight ) {
  21480. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21481. } else {
  21482. console.error( "Unsupported light type for shadow" );
  21483. continue;
  21484. }
  21485. scene.add( light.shadowCamera );
  21486. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21487. }
  21488. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21489. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21490. light.shadowCamera.add( light.cameraHelper );
  21491. }
  21492. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21493. updateShadowCamera( camera, light );
  21494. }
  21495. shadowMap = light.shadowMap;
  21496. shadowMatrix = light.shadowMatrix;
  21497. shadowCamera = light.shadowCamera;
  21498. shadowCamera.position.setFromMatrixPosition( light.matrixWorld );
  21499. _matrixPosition.setFromMatrixPosition( light.target.matrixWorld );
  21500. shadowCamera.lookAt( _matrixPosition );
  21501. shadowCamera.updateMatrixWorld();
  21502. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21503. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21504. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21505. // compute shadow matrix
  21506. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21507. 0.0, 0.5, 0.0, 0.5,
  21508. 0.0, 0.0, 0.5, 0.5,
  21509. 0.0, 0.0, 0.0, 1.0 );
  21510. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  21511. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  21512. // update camera matrices and frustum
  21513. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21514. _frustum.setFromMatrix( _projScreenMatrix );
  21515. // render shadow map
  21516. _renderer.setRenderTarget( shadowMap );
  21517. _renderer.clear();
  21518. // set object matrices & frustum culling
  21519. _renderList.length = 0;
  21520. projectObject(scene,scene,shadowCamera);
  21521. // render regular objects
  21522. var objectMaterial, useMorphing, useSkinning;
  21523. for ( j = 0, jl = _renderList.length; j < jl; j ++ ) {
  21524. webglObject = _renderList[ j ];
  21525. object = webglObject.object;
  21526. buffer = webglObject.buffer;
  21527. // culling is overriden globally for all objects
  21528. // while rendering depth map
  21529. // need to deal with MeshFaceMaterial somehow
  21530. // in that case just use the first of material.materials for now
  21531. // (proper solution would require to break objects by materials
  21532. // similarly to regular rendering and then set corresponding
  21533. // depth materials per each chunk instead of just once per object)
  21534. objectMaterial = getObjectMaterial( object );
  21535. useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21536. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21537. if ( object.customDepthMaterial ) {
  21538. material = object.customDepthMaterial;
  21539. } else if ( useSkinning ) {
  21540. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21541. } else if ( useMorphing ) {
  21542. material = _depthMaterialMorph;
  21543. } else {
  21544. material = _depthMaterial;
  21545. }
  21546. _renderer.setMaterialFaces( objectMaterial );
  21547. if ( buffer instanceof THREE.BufferGeometry ) {
  21548. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21549. } else {
  21550. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21551. }
  21552. }
  21553. // set matrices and render immediate objects
  21554. var renderList = scene.__webglObjectsImmediate;
  21555. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21556. webglObject = renderList[ j ];
  21557. object = webglObject.object;
  21558. if ( object.visible && object.castShadow ) {
  21559. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21560. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21561. }
  21562. }
  21563. }
  21564. // restore GL state
  21565. var clearColor = _renderer.getClearColor(),
  21566. clearAlpha = _renderer.getClearAlpha();
  21567. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21568. _gl.enable( _gl.BLEND );
  21569. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21570. _gl.cullFace( _gl.BACK );
  21571. }
  21572. };
  21573. function projectObject(scene, object,shadowCamera){
  21574. if ( object.visible ) {
  21575. var webglObjects = scene.__webglObjects[object.id];
  21576. if (webglObjects && object.castShadow && (object.frustumCulled === false || _frustum.intersectsObject( object ) === true) ) {
  21577. for (var i = 0, l = webglObjects.length; i < l; i++){
  21578. var webglObject = webglObjects[i];
  21579. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21580. _renderList.push(webglObject);
  21581. }
  21582. }
  21583. for(var i = 0, l = object.children.length; i < l; i++) {
  21584. projectObject(scene, object.children[i],shadowCamera);
  21585. }
  21586. }
  21587. }
  21588. function createVirtualLight( light, cascade ) {
  21589. var virtualLight = new THREE.DirectionalLight();
  21590. virtualLight.isVirtual = true;
  21591. virtualLight.onlyShadow = true;
  21592. virtualLight.castShadow = true;
  21593. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21594. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21595. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21596. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21597. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21598. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21599. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21600. virtualLight.shadowDarkness = light.shadowDarkness;
  21601. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21602. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21603. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21604. virtualLight.pointsWorld = [];
  21605. virtualLight.pointsFrustum = [];
  21606. var pointsWorld = virtualLight.pointsWorld,
  21607. pointsFrustum = virtualLight.pointsFrustum;
  21608. for ( var i = 0; i < 8; i ++ ) {
  21609. pointsWorld[ i ] = new THREE.Vector3();
  21610. pointsFrustum[ i ] = new THREE.Vector3();
  21611. }
  21612. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21613. var farZ = light.shadowCascadeFarZ[ cascade ];
  21614. pointsFrustum[ 0 ].set( - 1, - 1, nearZ );
  21615. pointsFrustum[ 1 ].set( 1, - 1, nearZ );
  21616. pointsFrustum[ 2 ].set( - 1, 1, nearZ );
  21617. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21618. pointsFrustum[ 4 ].set( - 1, - 1, farZ );
  21619. pointsFrustum[ 5 ].set( 1, - 1, farZ );
  21620. pointsFrustum[ 6 ].set( - 1, 1, farZ );
  21621. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21622. return virtualLight;
  21623. }
  21624. // Synchronize virtual light with the original light
  21625. function updateVirtualLight( light, cascade ) {
  21626. var virtualLight = light.shadowCascadeArray[ cascade ];
  21627. virtualLight.position.copy( light.position );
  21628. virtualLight.target.position.copy( light.target.position );
  21629. virtualLight.lookAt( virtualLight.target );
  21630. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21631. virtualLight.shadowDarkness = light.shadowDarkness;
  21632. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21633. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21634. var farZ = light.shadowCascadeFarZ[ cascade ];
  21635. var pointsFrustum = virtualLight.pointsFrustum;
  21636. pointsFrustum[ 0 ].z = nearZ;
  21637. pointsFrustum[ 1 ].z = nearZ;
  21638. pointsFrustum[ 2 ].z = nearZ;
  21639. pointsFrustum[ 3 ].z = nearZ;
  21640. pointsFrustum[ 4 ].z = farZ;
  21641. pointsFrustum[ 5 ].z = farZ;
  21642. pointsFrustum[ 6 ].z = farZ;
  21643. pointsFrustum[ 7 ].z = farZ;
  21644. }
  21645. // Fit shadow camera's ortho frustum to camera frustum
  21646. function updateShadowCamera( camera, light ) {
  21647. var shadowCamera = light.shadowCamera,
  21648. pointsFrustum = light.pointsFrustum,
  21649. pointsWorld = light.pointsWorld;
  21650. _min.set( Infinity, Infinity, Infinity );
  21651. _max.set( - Infinity, - Infinity, - Infinity );
  21652. for ( var i = 0; i < 8; i ++ ) {
  21653. var p = pointsWorld[ i ];
  21654. p.copy( pointsFrustum[ i ] );
  21655. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21656. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21657. if ( p.x < _min.x ) _min.x = p.x;
  21658. if ( p.x > _max.x ) _max.x = p.x;
  21659. if ( p.y < _min.y ) _min.y = p.y;
  21660. if ( p.y > _max.y ) _max.y = p.y;
  21661. if ( p.z < _min.z ) _min.z = p.z;
  21662. if ( p.z > _max.z ) _max.z = p.z;
  21663. }
  21664. shadowCamera.left = _min.x;
  21665. shadowCamera.right = _max.x;
  21666. shadowCamera.top = _max.y;
  21667. shadowCamera.bottom = _min.y;
  21668. // can't really fit near/far
  21669. //shadowCamera.near = _min.z;
  21670. //shadowCamera.far = _max.z;
  21671. shadowCamera.updateProjectionMatrix();
  21672. }
  21673. // For the moment just ignore objects that have multiple materials with different animation methods
  21674. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21675. function getObjectMaterial( object ) {
  21676. return object.material instanceof THREE.MeshFaceMaterial
  21677. ? object.material.materials[ 0 ]
  21678. : object.material;
  21679. };
  21680. };
  21681. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21682. // File:src/extras/renderers/plugins/SpritePlugin.js
  21683. /**
  21684. * @author mikael emtinger / http://gomo.se/
  21685. * @author alteredq / http://alteredqualia.com/
  21686. */
  21687. THREE.SpritePlugin = function () {
  21688. var _gl, _renderer, _texture;
  21689. var vertices, faces, vertexBuffer, elementBuffer;
  21690. var program, attributes, uniforms;
  21691. this.init = function ( renderer ) {
  21692. _gl = renderer.context;
  21693. _renderer = renderer;
  21694. vertices = new Float32Array( [
  21695. - 0.5, - 0.5, 0, 0,
  21696. 0.5, - 0.5, 1, 0,
  21697. 0.5, 0.5, 1, 1,
  21698. - 0.5, 0.5, 0, 1
  21699. ] );
  21700. faces = new Uint16Array( [
  21701. 0, 1, 2,
  21702. 0, 2, 3
  21703. ] );
  21704. vertexBuffer = _gl.createBuffer();
  21705. elementBuffer = _gl.createBuffer();
  21706. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  21707. _gl.bufferData( _gl.ARRAY_BUFFER, vertices, _gl.STATIC_DRAW );
  21708. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  21709. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faces, _gl.STATIC_DRAW );
  21710. program = createProgram();
  21711. attributes = {
  21712. position: _gl.getAttribLocation ( program, 'position' ),
  21713. uv: _gl.getAttribLocation ( program, 'uv' )
  21714. };
  21715. uniforms = {
  21716. uvOffset: _gl.getUniformLocation( program, 'uvOffset' ),
  21717. uvScale: _gl.getUniformLocation( program, 'uvScale' ),
  21718. rotation: _gl.getUniformLocation( program, 'rotation' ),
  21719. scale: _gl.getUniformLocation( program, 'scale' ),
  21720. color: _gl.getUniformLocation( program, 'color' ),
  21721. map: _gl.getUniformLocation( program, 'map' ),
  21722. opacity: _gl.getUniformLocation( program, 'opacity' ),
  21723. modelViewMatrix: _gl.getUniformLocation( program, 'modelViewMatrix' ),
  21724. projectionMatrix: _gl.getUniformLocation( program, 'projectionMatrix' ),
  21725. fogType: _gl.getUniformLocation( program, 'fogType' ),
  21726. fogDensity: _gl.getUniformLocation( program, 'fogDensity' ),
  21727. fogNear: _gl.getUniformLocation( program, 'fogNear' ),
  21728. fogFar: _gl.getUniformLocation( program, 'fogFar' ),
  21729. fogColor: _gl.getUniformLocation( program, 'fogColor' ),
  21730. alphaTest: _gl.getUniformLocation( program, 'alphaTest' )
  21731. };
  21732. var canvas = document.createElement( 'canvas' );
  21733. canvas.width = 8;
  21734. canvas.height = 8;
  21735. var context = canvas.getContext( '2d' );
  21736. context.fillStyle = 'white';
  21737. context.fillRect( 0, 0, 8, 8 );
  21738. _texture = new THREE.Texture( canvas );
  21739. _texture.needsUpdate = true;
  21740. };
  21741. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21742. var sprites = scene.__webglSprites,
  21743. nSprites = sprites.length;
  21744. if ( ! nSprites ) return;
  21745. // setup gl
  21746. _gl.useProgram( program );
  21747. _gl.enableVertexAttribArray( attributes.position );
  21748. _gl.enableVertexAttribArray( attributes.uv );
  21749. _gl.disable( _gl.CULL_FACE );
  21750. _gl.enable( _gl.BLEND );
  21751. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  21752. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21753. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21754. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  21755. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21756. _gl.activeTexture( _gl.TEXTURE0 );
  21757. _gl.uniform1i( uniforms.map, 0 );
  21758. var oldFogType = 0;
  21759. var sceneFogType = 0;
  21760. var fog = scene.fog;
  21761. if ( fog ) {
  21762. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21763. if ( fog instanceof THREE.Fog ) {
  21764. _gl.uniform1f( uniforms.fogNear, fog.near );
  21765. _gl.uniform1f( uniforms.fogFar, fog.far );
  21766. _gl.uniform1i( uniforms.fogType, 1 );
  21767. oldFogType = 1;
  21768. sceneFogType = 1;
  21769. } else if ( fog instanceof THREE.FogExp2 ) {
  21770. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21771. _gl.uniform1i( uniforms.fogType, 2 );
  21772. oldFogType = 2;
  21773. sceneFogType = 2;
  21774. }
  21775. } else {
  21776. _gl.uniform1i( uniforms.fogType, 0 );
  21777. oldFogType = 0;
  21778. sceneFogType = 0;
  21779. }
  21780. // update positions and sort
  21781. var i, sprite, material, fogType, scale = [];
  21782. for( i = 0; i < nSprites; i ++ ) {
  21783. sprite = sprites[ i ];
  21784. material = sprite.material;
  21785. if ( sprite.visible === false ) continue;
  21786. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  21787. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21788. }
  21789. sprites.sort( painterSortStable );
  21790. // render all sprites
  21791. for( i = 0; i < nSprites; i ++ ) {
  21792. sprite = sprites[ i ];
  21793. if ( sprite.visible === false ) continue;
  21794. material = sprite.material;
  21795. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21796. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21797. scale[ 0 ] = sprite.scale.x;
  21798. scale[ 1 ] = sprite.scale.y;
  21799. if ( scene.fog && material.fog ) {
  21800. fogType = sceneFogType;
  21801. } else {
  21802. fogType = 0;
  21803. }
  21804. if ( oldFogType !== fogType ) {
  21805. _gl.uniform1i( uniforms.fogType, fogType );
  21806. oldFogType = fogType;
  21807. }
  21808. if ( material.map !== null ) {
  21809. _gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  21810. _gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  21811. } else {
  21812. _gl.uniform2f( uniforms.uvOffset, 0, 0 );
  21813. _gl.uniform2f( uniforms.uvScale, 1, 1 );
  21814. }
  21815. _gl.uniform1f( uniforms.opacity, material.opacity );
  21816. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21817. _gl.uniform1f( uniforms.rotation, material.rotation );
  21818. _gl.uniform2fv( uniforms.scale, scale );
  21819. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21820. _renderer.setDepthTest( material.depthTest );
  21821. _renderer.setDepthWrite( material.depthWrite );
  21822. if ( material.map && material.map.image && material.map.image.width ) {
  21823. _renderer.setTexture( material.map, 0 );
  21824. } else {
  21825. _renderer.setTexture( _texture, 0 );
  21826. }
  21827. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21828. }
  21829. // restore gl
  21830. _gl.enable( _gl.CULL_FACE );
  21831. };
  21832. function createProgram () {
  21833. var program = _gl.createProgram();
  21834. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21835. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21836. _gl.shaderSource( vertexShader, [
  21837. 'precision ' + _renderer.getPrecision() + ' float;',
  21838. 'uniform mat4 modelViewMatrix;',
  21839. 'uniform mat4 projectionMatrix;',
  21840. 'uniform float rotation;',
  21841. 'uniform vec2 scale;',
  21842. 'uniform vec2 uvOffset;',
  21843. 'uniform vec2 uvScale;',
  21844. 'attribute vec2 position;',
  21845. 'attribute vec2 uv;',
  21846. 'varying vec2 vUV;',
  21847. 'void main() {',
  21848. 'vUV = uvOffset + uv * uvScale;',
  21849. 'vec2 alignedPosition = position * scale;',
  21850. 'vec2 rotatedPosition;',
  21851. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  21852. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  21853. 'vec4 finalPosition;',
  21854. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  21855. 'finalPosition.xy += rotatedPosition;',
  21856. 'finalPosition = projectionMatrix * finalPosition;',
  21857. 'gl_Position = finalPosition;',
  21858. '}'
  21859. ].join( '\n' ) );
  21860. _gl.shaderSource( fragmentShader, [
  21861. 'precision ' + _renderer.getPrecision() + ' float;',
  21862. 'uniform vec3 color;',
  21863. 'uniform sampler2D map;',
  21864. 'uniform float opacity;',
  21865. 'uniform int fogType;',
  21866. 'uniform vec3 fogColor;',
  21867. 'uniform float fogDensity;',
  21868. 'uniform float fogNear;',
  21869. 'uniform float fogFar;',
  21870. 'uniform float alphaTest;',
  21871. 'varying vec2 vUV;',
  21872. 'void main() {',
  21873. 'vec4 texture = texture2D( map, vUV );',
  21874. 'if ( texture.a < alphaTest ) discard;',
  21875. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  21876. 'if ( fogType > 0 ) {',
  21877. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  21878. 'float fogFactor = 0.0;',
  21879. 'if ( fogType == 1 ) {',
  21880. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  21881. '} else {',
  21882. 'const float LOG2 = 1.442695;',
  21883. 'float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  21884. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  21885. '}',
  21886. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  21887. '}',
  21888. '}'
  21889. ].join( '\n' ) );
  21890. _gl.compileShader( vertexShader );
  21891. _gl.compileShader( fragmentShader );
  21892. _gl.attachShader( program, vertexShader );
  21893. _gl.attachShader( program, fragmentShader );
  21894. _gl.linkProgram( program );
  21895. return program;
  21896. };
  21897. function painterSortStable ( a, b ) {
  21898. if ( a.z !== b.z ) {
  21899. return b.z - a.z;
  21900. } else {
  21901. return b.id - a.id;
  21902. }
  21903. };
  21904. };
  21905. // File:src/extras/renderers/plugins/DepthPassPlugin.js
  21906. /**
  21907. * @author alteredq / http://alteredqualia.com/
  21908. */
  21909. THREE.DepthPassPlugin = function () {
  21910. this.enabled = false;
  21911. this.renderTarget = null;
  21912. var _gl,
  21913. _renderer,
  21914. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21915. _frustum = new THREE.Frustum(),
  21916. _projScreenMatrix = new THREE.Matrix4(),
  21917. _renderList = [];
  21918. this.init = function ( renderer ) {
  21919. _gl = renderer.context;
  21920. _renderer = renderer;
  21921. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21922. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21923. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21924. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21925. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21926. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21927. _depthMaterial._shadowPass = true;
  21928. _depthMaterialMorph._shadowPass = true;
  21929. _depthMaterialSkin._shadowPass = true;
  21930. _depthMaterialMorphSkin._shadowPass = true;
  21931. };
  21932. this.render = function ( scene, camera ) {
  21933. if ( ! this.enabled ) return;
  21934. this.update( scene, camera );
  21935. };
  21936. this.update = function ( scene, camera ) {
  21937. var i, il, j, jl, n,
  21938. program, buffer, material,
  21939. webglObject, object, light,
  21940. renderList,
  21941. fog = null;
  21942. // set GL state for depth map
  21943. _gl.clearColor( 1, 1, 1, 1 );
  21944. _gl.disable( _gl.BLEND );
  21945. _renderer.setDepthTest( true );
  21946. // update scene
  21947. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21948. // update camera matrices and frustum
  21949. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21950. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  21951. _frustum.setFromMatrix( _projScreenMatrix );
  21952. // render depth map
  21953. _renderer.setRenderTarget( this.renderTarget );
  21954. _renderer.clear();
  21955. // set object matrices & frustum culling
  21956. _renderList.length = 0;
  21957. projectObject(scene,scene,camera);
  21958. /*_renderList = scene.__webglObjects;
  21959. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21960. webglObject = renderList[ j ];
  21961. object = webglObject.object;
  21962. webglObject.render = false;
  21963. if ( object.visible ) {
  21964. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  21965. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21966. webglObject.render = true;
  21967. }
  21968. }
  21969. }*/
  21970. // render regular objects
  21971. var objectMaterial, useMorphing, useSkinning;
  21972. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21973. webglObject = _renderList[ j ];
  21974. object = webglObject.object;
  21975. buffer = webglObject.buffer;
  21976. // todo: create proper depth material for particles
  21977. if ( object instanceof THREE.PointCloud && ! object.customDepthMaterial ) continue;
  21978. objectMaterial = getObjectMaterial( object );
  21979. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21980. useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21981. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21982. if ( object.customDepthMaterial ) {
  21983. material = object.customDepthMaterial;
  21984. } else if ( useSkinning ) {
  21985. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21986. } else if ( useMorphing ) {
  21987. material = _depthMaterialMorph;
  21988. } else {
  21989. material = _depthMaterial;
  21990. }
  21991. if ( buffer instanceof THREE.BufferGeometry ) {
  21992. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21993. } else {
  21994. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21995. }
  21996. }
  21997. // set matrices and render immediate objects
  21998. renderList = scene.__webglObjectsImmediate;
  21999. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22000. webglObject = renderList[ j ];
  22001. object = webglObject.object;
  22002. if ( object.visible ) {
  22003. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22004. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  22005. }
  22006. }
  22007. // restore GL state
  22008. var clearColor = _renderer.getClearColor(),
  22009. clearAlpha = _renderer.getClearAlpha();
  22010. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  22011. _gl.enable( _gl.BLEND );
  22012. };
  22013. function projectObject(scene, object,camera){
  22014. if ( object.visible ) {
  22015. var webglObjects = scene.__webglObjects[object.id];
  22016. if (webglObjects && (object.frustumCulled === false || _frustum.intersectsObject( object ) === true) ) {
  22017. for (var i = 0, l = webglObjects.length; i < l; i++){
  22018. var webglObject = webglObjects[i];
  22019. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22020. _renderList.push(webglObject);
  22021. }
  22022. }
  22023. for(var i = 0, l = object.children.length; i < l; i++) {
  22024. projectObject(scene, object.children[i], camera);
  22025. }
  22026. }
  22027. }
  22028. // For the moment just ignore objects that have multiple materials with different animation methods
  22029. // Only the first material will be taken into account for deciding which depth material to use
  22030. function getObjectMaterial( object ) {
  22031. return object.material instanceof THREE.MeshFaceMaterial
  22032. ? object.material.materials[ 0 ]
  22033. : object.material;
  22034. };
  22035. };
  22036. // File:src/extras/shaders/ShaderFlares.js
  22037. /**
  22038. * @author mikael emtinger / http://gomo.se/
  22039. */
  22040. THREE.ShaderFlares = {
  22041. 'lensFlareVertexTexture': {
  22042. vertexShader: [
  22043. "uniform lowp int renderType;",
  22044. "uniform vec3 screenPosition;",
  22045. "uniform vec2 scale;",
  22046. "uniform float rotation;",
  22047. "uniform sampler2D occlusionMap;",
  22048. "attribute vec2 position;",
  22049. "attribute vec2 uv;",
  22050. "varying vec2 vUV;",
  22051. "varying float vVisibility;",
  22052. "void main() {",
  22053. "vUV = uv;",
  22054. "vec2 pos = position;",
  22055. "if( renderType == 2 ) {",
  22056. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  22057. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  22058. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  22059. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  22060. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  22061. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  22062. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  22063. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  22064. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  22065. "vVisibility = visibility.r / 9.0;",
  22066. "vVisibility *= 1.0 - visibility.g / 9.0;",
  22067. "vVisibility *= visibility.b / 9.0;",
  22068. "vVisibility *= 1.0 - visibility.a / 9.0;",
  22069. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22070. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22071. "}",
  22072. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22073. "}"
  22074. ].join( "\n" ),
  22075. fragmentShader: [
  22076. "uniform lowp int renderType;",
  22077. "uniform sampler2D map;",
  22078. "uniform float opacity;",
  22079. "uniform vec3 color;",
  22080. "varying vec2 vUV;",
  22081. "varying float vVisibility;",
  22082. "void main() {",
  22083. // pink square
  22084. "if( renderType == 0 ) {",
  22085. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  22086. // restore
  22087. "} else if( renderType == 1 ) {",
  22088. "gl_FragColor = texture2D( map, vUV );",
  22089. // flare
  22090. "} else {",
  22091. "vec4 texture = texture2D( map, vUV );",
  22092. "texture.a *= opacity * vVisibility;",
  22093. "gl_FragColor = texture;",
  22094. "gl_FragColor.rgb *= color;",
  22095. "}",
  22096. "}"
  22097. ].join( "\n" )
  22098. },
  22099. 'lensFlare': {
  22100. vertexShader: [
  22101. "uniform lowp int renderType;",
  22102. "uniform vec3 screenPosition;",
  22103. "uniform vec2 scale;",
  22104. "uniform float rotation;",
  22105. "attribute vec2 position;",
  22106. "attribute vec2 uv;",
  22107. "varying vec2 vUV;",
  22108. "void main() {",
  22109. "vUV = uv;",
  22110. "vec2 pos = position;",
  22111. "if( renderType == 2 ) {",
  22112. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22113. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22114. "}",
  22115. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22116. "}"
  22117. ].join( "\n" ),
  22118. fragmentShader: [
  22119. "precision mediump float;",
  22120. "uniform lowp int renderType;",
  22121. "uniform sampler2D map;",
  22122. "uniform sampler2D occlusionMap;",
  22123. "uniform float opacity;",
  22124. "uniform vec3 color;",
  22125. "varying vec2 vUV;",
  22126. "void main() {",
  22127. // pink square
  22128. "if( renderType == 0 ) {",
  22129. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  22130. // restore
  22131. "} else if( renderType == 1 ) {",
  22132. "gl_FragColor = texture2D( map, vUV );",
  22133. // flare
  22134. "} else {",
  22135. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  22136. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  22137. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  22138. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  22139. "visibility = ( 1.0 - visibility / 4.0 );",
  22140. "vec4 texture = texture2D( map, vUV );",
  22141. "texture.a *= opacity * visibility;",
  22142. "gl_FragColor = texture;",
  22143. "gl_FragColor.rgb *= color;",
  22144. "}",
  22145. "}"
  22146. ].join( "\n" )
  22147. }
  22148. };
粤ICP备19079148号