three.js 794 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350
  1. // File:src/Three.js
  2. /**
  3. * @author mrdoob / http://mrdoob.com/
  4. */
  5. var THREE = { REVISION: '72dev' };
  6. // browserify support
  7. if ( typeof module === 'object' ) {
  8. module.exports = THREE;
  9. }
  10. // polyfills
  11. if ( Math.sign === undefined ) {
  12. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  13. Math.sign = function ( x ) {
  14. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : +x;
  15. };
  16. }
  17. // set the default log handlers
  18. THREE.log = function() { console.log.apply( console, arguments ); }
  19. THREE.warn = function() { console.warn.apply( console, arguments ); }
  20. THREE.error = function() { console.error.apply( console, arguments ); }
  21. // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.button
  22. THREE.MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  23. // GL STATE CONSTANTS
  24. THREE.CullFaceNone = 0;
  25. THREE.CullFaceBack = 1;
  26. THREE.CullFaceFront = 2;
  27. THREE.CullFaceFrontBack = 3;
  28. THREE.FrontFaceDirectionCW = 0;
  29. THREE.FrontFaceDirectionCCW = 1;
  30. // SHADOWING TYPES
  31. THREE.BasicShadowMap = 0;
  32. THREE.PCFShadowMap = 1;
  33. THREE.PCFSoftShadowMap = 2;
  34. // MATERIAL CONSTANTS
  35. // side
  36. THREE.FrontSide = 0;
  37. THREE.BackSide = 1;
  38. THREE.DoubleSide = 2;
  39. // shading
  40. THREE.NoShading = 0;
  41. THREE.FlatShading = 1;
  42. THREE.SmoothShading = 2;
  43. // colors
  44. THREE.NoColors = 0;
  45. THREE.FaceColors = 1;
  46. THREE.VertexColors = 2;
  47. // blending modes
  48. THREE.NoBlending = 0;
  49. THREE.NormalBlending = 1;
  50. THREE.AdditiveBlending = 2;
  51. THREE.SubtractiveBlending = 3;
  52. THREE.MultiplyBlending = 4;
  53. THREE.CustomBlending = 5;
  54. // custom blending equations
  55. // (numbers start from 100 not to clash with other
  56. // mappings to OpenGL constants defined in Texture.js)
  57. THREE.AddEquation = 100;
  58. THREE.SubtractEquation = 101;
  59. THREE.ReverseSubtractEquation = 102;
  60. THREE.MinEquation = 103;
  61. THREE.MaxEquation = 104;
  62. // custom blending destination factors
  63. THREE.ZeroFactor = 200;
  64. THREE.OneFactor = 201;
  65. THREE.SrcColorFactor = 202;
  66. THREE.OneMinusSrcColorFactor = 203;
  67. THREE.SrcAlphaFactor = 204;
  68. THREE.OneMinusSrcAlphaFactor = 205;
  69. THREE.DstAlphaFactor = 206;
  70. THREE.OneMinusDstAlphaFactor = 207;
  71. // custom blending source factors
  72. //THREE.ZeroFactor = 200;
  73. //THREE.OneFactor = 201;
  74. //THREE.SrcAlphaFactor = 204;
  75. //THREE.OneMinusSrcAlphaFactor = 205;
  76. //THREE.DstAlphaFactor = 206;
  77. //THREE.OneMinusDstAlphaFactor = 207;
  78. THREE.DstColorFactor = 208;
  79. THREE.OneMinusDstColorFactor = 209;
  80. THREE.SrcAlphaSaturateFactor = 210;
  81. // TEXTURE CONSTANTS
  82. THREE.MultiplyOperation = 0;
  83. THREE.MixOperation = 1;
  84. THREE.AddOperation = 2;
  85. // Mapping modes
  86. THREE.UVMapping = 300;
  87. THREE.CubeReflectionMapping = 301;
  88. THREE.CubeRefractionMapping = 302;
  89. THREE.EquirectangularReflectionMapping = 303;
  90. THREE.EquirectangularRefractionMapping = 304;
  91. THREE.SphericalReflectionMapping = 305;
  92. // Wrapping modes
  93. THREE.RepeatWrapping = 1000;
  94. THREE.ClampToEdgeWrapping = 1001;
  95. THREE.MirroredRepeatWrapping = 1002;
  96. // Filters
  97. THREE.NearestFilter = 1003;
  98. THREE.NearestMipMapNearestFilter = 1004;
  99. THREE.NearestMipMapLinearFilter = 1005;
  100. THREE.LinearFilter = 1006;
  101. THREE.LinearMipMapNearestFilter = 1007;
  102. THREE.LinearMipMapLinearFilter = 1008;
  103. // Data types
  104. THREE.UnsignedByteType = 1009;
  105. THREE.ByteType = 1010;
  106. THREE.ShortType = 1011;
  107. THREE.UnsignedShortType = 1012;
  108. THREE.IntType = 1013;
  109. THREE.UnsignedIntType = 1014;
  110. THREE.FloatType = 1015;
  111. THREE.HalfFloatType = 1025;
  112. // Pixel types
  113. //THREE.UnsignedByteType = 1009;
  114. THREE.UnsignedShort4444Type = 1016;
  115. THREE.UnsignedShort5551Type = 1017;
  116. THREE.UnsignedShort565Type = 1018;
  117. // Pixel formats
  118. THREE.AlphaFormat = 1019;
  119. THREE.RGBFormat = 1020;
  120. THREE.RGBAFormat = 1021;
  121. THREE.LuminanceFormat = 1022;
  122. THREE.LuminanceAlphaFormat = 1023;
  123. // THREE.RGBEFormat handled as THREE.RGBAFormat in shaders
  124. THREE.RGBEFormat = THREE.RGBAFormat; //1024;
  125. // DDS / ST3C Compressed texture formats
  126. THREE.RGB_S3TC_DXT1_Format = 2001;
  127. THREE.RGBA_S3TC_DXT1_Format = 2002;
  128. THREE.RGBA_S3TC_DXT3_Format = 2003;
  129. THREE.RGBA_S3TC_DXT5_Format = 2004;
  130. // PVRTC compressed texture formats
  131. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  132. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  133. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  134. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  135. // DEPRECATED
  136. THREE.Projector = function () {
  137. THREE.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  138. this.projectVector = function ( vector, camera ) {
  139. THREE.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  140. vector.project( camera );
  141. };
  142. this.unprojectVector = function ( vector, camera ) {
  143. THREE.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  144. vector.unproject( camera );
  145. };
  146. this.pickingRay = function ( vector, camera ) {
  147. THREE.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  148. };
  149. };
  150. THREE.CanvasRenderer = function () {
  151. THREE.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  152. this.domElement = document.createElement( 'canvas' );
  153. this.clear = function () {};
  154. this.render = function () {};
  155. this.setClearColor = function () {};
  156. this.setSize = function () {};
  157. };
  158. // File:src/math/Color.js
  159. /**
  160. * @author mrdoob / http://mrdoob.com/
  161. */
  162. THREE.Color = function ( color ) {
  163. if ( arguments.length === 3 ) {
  164. return this.setRGB( arguments[ 0 ], arguments[ 1 ], arguments[ 2 ] );
  165. }
  166. return this.set( color )
  167. };
  168. THREE.Color.prototype = {
  169. constructor: THREE.Color,
  170. r: 1, g: 1, b: 1,
  171. set: function ( value ) {
  172. if ( value instanceof THREE.Color ) {
  173. this.copy( value );
  174. } else if ( typeof value === 'number' ) {
  175. this.setHex( value );
  176. } else if ( typeof value === 'string' ) {
  177. this.setStyle( value );
  178. }
  179. return this;
  180. },
  181. setHex: function ( hex ) {
  182. hex = Math.floor( hex );
  183. this.r = ( hex >> 16 & 255 ) / 255;
  184. this.g = ( hex >> 8 & 255 ) / 255;
  185. this.b = ( hex & 255 ) / 255;
  186. return this;
  187. },
  188. setRGB: function ( r, g, b ) {
  189. this.r = r;
  190. this.g = g;
  191. this.b = b;
  192. return this;
  193. },
  194. setHSL: function ( h, s, l ) {
  195. // h,s,l ranges are in 0.0 - 1.0
  196. if ( s === 0 ) {
  197. this.r = this.g = this.b = l;
  198. } else {
  199. var hue2rgb = function ( p, q, t ) {
  200. if ( t < 0 ) t += 1;
  201. if ( t > 1 ) t -= 1;
  202. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  203. if ( t < 1 / 2 ) return q;
  204. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  205. return p;
  206. };
  207. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  208. var q = ( 2 * l ) - p;
  209. this.r = hue2rgb( q, p, h + 1 / 3 );
  210. this.g = hue2rgb( q, p, h );
  211. this.b = hue2rgb( q, p, h - 1 / 3 );
  212. }
  213. return this;
  214. },
  215. setStyle: function ( style ) {
  216. // rgb(255,0,0)
  217. if ( /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.test( style ) ) {
  218. var color = /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.exec( style );
  219. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  220. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  221. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  222. return this;
  223. }
  224. // rgb(100%,0%,0%)
  225. if ( /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.test( style ) ) {
  226. var color = /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.exec( style );
  227. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  228. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  229. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  230. return this;
  231. }
  232. // #ff0000
  233. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  234. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  235. this.setHex( parseInt( color[ 1 ], 16 ) );
  236. return this;
  237. }
  238. // #f00
  239. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  240. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  241. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  242. return this;
  243. }
  244. // red
  245. if ( /^(\w+)$/i.test( style ) ) {
  246. this.setHex( THREE.ColorKeywords[ style ] );
  247. return this;
  248. }
  249. },
  250. copy: function ( color ) {
  251. this.r = color.r;
  252. this.g = color.g;
  253. this.b = color.b;
  254. return this;
  255. },
  256. copyGammaToLinear: function ( color, gammaFactor ) {
  257. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  258. this.r = Math.pow( color.r, gammaFactor );
  259. this.g = Math.pow( color.g, gammaFactor );
  260. this.b = Math.pow( color.b, gammaFactor );
  261. return this;
  262. },
  263. copyLinearToGamma: function ( color, gammaFactor ) {
  264. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  265. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  266. this.r = Math.pow( color.r, safeInverse );
  267. this.g = Math.pow( color.g, safeInverse );
  268. this.b = Math.pow( color.b, safeInverse );
  269. return this;
  270. },
  271. convertGammaToLinear: function () {
  272. var r = this.r, g = this.g, b = this.b;
  273. this.r = r * r;
  274. this.g = g * g;
  275. this.b = b * b;
  276. return this;
  277. },
  278. convertLinearToGamma: function () {
  279. this.r = Math.sqrt( this.r );
  280. this.g = Math.sqrt( this.g );
  281. this.b = Math.sqrt( this.b );
  282. return this;
  283. },
  284. getHex: function () {
  285. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  286. },
  287. getHexString: function () {
  288. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  289. },
  290. getHSL: function ( optionalTarget ) {
  291. // h,s,l ranges are in 0.0 - 1.0
  292. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  293. var r = this.r, g = this.g, b = this.b;
  294. var max = Math.max( r, g, b );
  295. var min = Math.min( r, g, b );
  296. var hue, saturation;
  297. var lightness = ( min + max ) / 2.0;
  298. if ( min === max ) {
  299. hue = 0;
  300. saturation = 0;
  301. } else {
  302. var delta = max - min;
  303. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  304. switch ( max ) {
  305. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  306. case g: hue = ( b - r ) / delta + 2; break;
  307. case b: hue = ( r - g ) / delta + 4; break;
  308. }
  309. hue /= 6;
  310. }
  311. hsl.h = hue;
  312. hsl.s = saturation;
  313. hsl.l = lightness;
  314. return hsl;
  315. },
  316. getStyle: function () {
  317. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  318. },
  319. offsetHSL: function ( h, s, l ) {
  320. var hsl = this.getHSL();
  321. hsl.h += h; hsl.s += s; hsl.l += l;
  322. this.setHSL( hsl.h, hsl.s, hsl.l );
  323. return this;
  324. },
  325. add: function ( color ) {
  326. this.r += color.r;
  327. this.g += color.g;
  328. this.b += color.b;
  329. return this;
  330. },
  331. addColors: function ( color1, color2 ) {
  332. this.r = color1.r + color2.r;
  333. this.g = color1.g + color2.g;
  334. this.b = color1.b + color2.b;
  335. return this;
  336. },
  337. addScalar: function ( s ) {
  338. this.r += s;
  339. this.g += s;
  340. this.b += s;
  341. return this;
  342. },
  343. multiply: function ( color ) {
  344. this.r *= color.r;
  345. this.g *= color.g;
  346. this.b *= color.b;
  347. return this;
  348. },
  349. multiplyScalar: function ( s ) {
  350. this.r *= s;
  351. this.g *= s;
  352. this.b *= s;
  353. return this;
  354. },
  355. lerp: function ( color, alpha ) {
  356. this.r += ( color.r - this.r ) * alpha;
  357. this.g += ( color.g - this.g ) * alpha;
  358. this.b += ( color.b - this.b ) * alpha;
  359. return this;
  360. },
  361. equals: function ( c ) {
  362. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  363. },
  364. fromArray: function ( array ) {
  365. this.r = array[ 0 ];
  366. this.g = array[ 1 ];
  367. this.b = array[ 2 ];
  368. return this;
  369. },
  370. toArray: function ( array, offset ) {
  371. if ( array === undefined ) array = [];
  372. if ( offset === undefined ) offset = 0;
  373. array[ offset ] = this.r;
  374. array[ offset + 1 ] = this.g;
  375. array[ offset + 2 ] = this.b;
  376. return array;
  377. },
  378. clone: function () {
  379. return new THREE.Color().setRGB( this.r, this.g, this.b );
  380. }
  381. };
  382. THREE.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  383. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  384. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  385. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  386. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  387. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  388. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  389. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  390. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  391. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  392. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  393. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  394. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  395. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  396. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  397. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  398. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  399. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  400. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  401. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  402. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  403. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  404. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  405. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  406. // File:src/math/Quaternion.js
  407. /**
  408. * @author mikael emtinger / http://gomo.se/
  409. * @author alteredq / http://alteredqualia.com/
  410. * @author WestLangley / http://github.com/WestLangley
  411. * @author bhouston / http://exocortex.com
  412. */
  413. THREE.Quaternion = function ( x, y, z, w ) {
  414. this._x = x || 0;
  415. this._y = y || 0;
  416. this._z = z || 0;
  417. this._w = ( w !== undefined ) ? w : 1;
  418. };
  419. THREE.Quaternion.prototype = {
  420. constructor: THREE.Quaternion,
  421. _x: 0,_y: 0, _z: 0, _w: 0,
  422. get x () {
  423. return this._x;
  424. },
  425. set x ( value ) {
  426. this._x = value;
  427. this.onChangeCallback();
  428. },
  429. get y () {
  430. return this._y;
  431. },
  432. set y ( value ) {
  433. this._y = value;
  434. this.onChangeCallback();
  435. },
  436. get z () {
  437. return this._z;
  438. },
  439. set z ( value ) {
  440. this._z = value;
  441. this.onChangeCallback();
  442. },
  443. get w () {
  444. return this._w;
  445. },
  446. set w ( value ) {
  447. this._w = value;
  448. this.onChangeCallback();
  449. },
  450. set: function ( x, y, z, w ) {
  451. this._x = x;
  452. this._y = y;
  453. this._z = z;
  454. this._w = w;
  455. this.onChangeCallback();
  456. return this;
  457. },
  458. copy: function ( quaternion ) {
  459. this._x = quaternion.x;
  460. this._y = quaternion.y;
  461. this._z = quaternion.z;
  462. this._w = quaternion.w;
  463. this.onChangeCallback();
  464. return this;
  465. },
  466. setFromEuler: function ( euler, update ) {
  467. if ( euler instanceof THREE.Euler === false ) {
  468. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  469. }
  470. // http://www.mathworks.com/matlabcentral/fileexchange/
  471. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  472. // content/SpinCalc.m
  473. var c1 = Math.cos( euler._x / 2 );
  474. var c2 = Math.cos( euler._y / 2 );
  475. var c3 = Math.cos( euler._z / 2 );
  476. var s1 = Math.sin( euler._x / 2 );
  477. var s2 = Math.sin( euler._y / 2 );
  478. var s3 = Math.sin( euler._z / 2 );
  479. if ( euler.order === 'XYZ' ) {
  480. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  481. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  482. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  483. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  484. } else if ( euler.order === 'YXZ' ) {
  485. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  486. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  487. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  488. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  489. } else if ( euler.order === 'ZXY' ) {
  490. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  491. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  492. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  493. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  494. } else if ( euler.order === 'ZYX' ) {
  495. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  496. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  497. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  498. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  499. } else if ( euler.order === 'YZX' ) {
  500. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  501. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  502. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  503. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  504. } else if ( euler.order === 'XZY' ) {
  505. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  506. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  507. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  508. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  509. }
  510. if ( update !== false ) this.onChangeCallback();
  511. return this;
  512. },
  513. setFromAxisAngle: function ( axis, angle ) {
  514. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  515. // assumes axis is normalized
  516. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  517. this._x = axis.x * s;
  518. this._y = axis.y * s;
  519. this._z = axis.z * s;
  520. this._w = Math.cos( halfAngle );
  521. this.onChangeCallback();
  522. return this;
  523. },
  524. setFromRotationMatrix: function ( m ) {
  525. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  526. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  527. var te = m.elements,
  528. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  529. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  530. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  531. trace = m11 + m22 + m33,
  532. s;
  533. if ( trace > 0 ) {
  534. s = 0.5 / Math.sqrt( trace + 1.0 );
  535. this._w = 0.25 / s;
  536. this._x = ( m32 - m23 ) * s;
  537. this._y = ( m13 - m31 ) * s;
  538. this._z = ( m21 - m12 ) * s;
  539. } else if ( m11 > m22 && m11 > m33 ) {
  540. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  541. this._w = ( m32 - m23 ) / s;
  542. this._x = 0.25 * s;
  543. this._y = ( m12 + m21 ) / s;
  544. this._z = ( m13 + m31 ) / s;
  545. } else if ( m22 > m33 ) {
  546. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  547. this._w = ( m13 - m31 ) / s;
  548. this._x = ( m12 + m21 ) / s;
  549. this._y = 0.25 * s;
  550. this._z = ( m23 + m32 ) / s;
  551. } else {
  552. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  553. this._w = ( m21 - m12 ) / s;
  554. this._x = ( m13 + m31 ) / s;
  555. this._y = ( m23 + m32 ) / s;
  556. this._z = 0.25 * s;
  557. }
  558. this.onChangeCallback();
  559. return this;
  560. },
  561. setFromUnitVectors: function () {
  562. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  563. // assumes direction vectors vFrom and vTo are normalized
  564. var v1, r;
  565. var EPS = 0.000001;
  566. return function ( vFrom, vTo ) {
  567. if ( v1 === undefined ) v1 = new THREE.Vector3();
  568. r = vFrom.dot( vTo ) + 1;
  569. if ( r < EPS ) {
  570. r = 0;
  571. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  572. v1.set( - vFrom.y, vFrom.x, 0 );
  573. } else {
  574. v1.set( 0, - vFrom.z, vFrom.y );
  575. }
  576. } else {
  577. v1.crossVectors( vFrom, vTo );
  578. }
  579. this._x = v1.x;
  580. this._y = v1.y;
  581. this._z = v1.z;
  582. this._w = r;
  583. this.normalize();
  584. return this;
  585. }
  586. }(),
  587. inverse: function () {
  588. this.conjugate().normalize();
  589. return this;
  590. },
  591. conjugate: function () {
  592. this._x *= - 1;
  593. this._y *= - 1;
  594. this._z *= - 1;
  595. this.onChangeCallback();
  596. return this;
  597. },
  598. dot: function ( v ) {
  599. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  600. },
  601. lengthSq: function () {
  602. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  603. },
  604. length: function () {
  605. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  606. },
  607. normalize: function () {
  608. var l = this.length();
  609. if ( l === 0 ) {
  610. this._x = 0;
  611. this._y = 0;
  612. this._z = 0;
  613. this._w = 1;
  614. } else {
  615. l = 1 / l;
  616. this._x = this._x * l;
  617. this._y = this._y * l;
  618. this._z = this._z * l;
  619. this._w = this._w * l;
  620. }
  621. this.onChangeCallback();
  622. return this;
  623. },
  624. multiply: function ( q, p ) {
  625. if ( p !== undefined ) {
  626. THREE.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  627. return this.multiplyQuaternions( q, p );
  628. }
  629. return this.multiplyQuaternions( this, q );
  630. },
  631. multiplyQuaternions: function ( a, b ) {
  632. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  633. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  634. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  635. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  636. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  637. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  638. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  639. this.onChangeCallback();
  640. return this;
  641. },
  642. multiplyVector3: function ( vector ) {
  643. THREE.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  644. return vector.applyQuaternion( this );
  645. },
  646. slerp: function ( qb, t ) {
  647. if ( t === 0 ) return this;
  648. if ( t === 1 ) return this.copy( qb );
  649. var x = this._x, y = this._y, z = this._z, w = this._w;
  650. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  651. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  652. if ( cosHalfTheta < 0 ) {
  653. this._w = - qb._w;
  654. this._x = - qb._x;
  655. this._y = - qb._y;
  656. this._z = - qb._z;
  657. cosHalfTheta = - cosHalfTheta;
  658. } else {
  659. this.copy( qb );
  660. }
  661. if ( cosHalfTheta >= 1.0 ) {
  662. this._w = w;
  663. this._x = x;
  664. this._y = y;
  665. this._z = z;
  666. return this;
  667. }
  668. var halfTheta = Math.acos( cosHalfTheta );
  669. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  670. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  671. this._w = 0.5 * ( w + this._w );
  672. this._x = 0.5 * ( x + this._x );
  673. this._y = 0.5 * ( y + this._y );
  674. this._z = 0.5 * ( z + this._z );
  675. return this;
  676. }
  677. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  678. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  679. this._w = ( w * ratioA + this._w * ratioB );
  680. this._x = ( x * ratioA + this._x * ratioB );
  681. this._y = ( y * ratioA + this._y * ratioB );
  682. this._z = ( z * ratioA + this._z * ratioB );
  683. this.onChangeCallback();
  684. return this;
  685. },
  686. equals: function ( quaternion ) {
  687. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  688. },
  689. fromArray: function ( array, offset ) {
  690. if ( offset === undefined ) offset = 0;
  691. this._x = array[ offset ];
  692. this._y = array[ offset + 1 ];
  693. this._z = array[ offset + 2 ];
  694. this._w = array[ offset + 3 ];
  695. this.onChangeCallback();
  696. return this;
  697. },
  698. toArray: function ( array, offset ) {
  699. if ( array === undefined ) array = [];
  700. if ( offset === undefined ) offset = 0;
  701. array[ offset ] = this._x;
  702. array[ offset + 1 ] = this._y;
  703. array[ offset + 2 ] = this._z;
  704. array[ offset + 3 ] = this._w;
  705. return array;
  706. },
  707. onChange: function ( callback ) {
  708. this.onChangeCallback = callback;
  709. return this;
  710. },
  711. onChangeCallback: function () {},
  712. clone: function () {
  713. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  714. }
  715. };
  716. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  717. return qm.copy( qa ).slerp( qb, t );
  718. }
  719. // File:src/math/Vector2.js
  720. /**
  721. * @author mrdoob / http://mrdoob.com/
  722. * @author philogb / http://blog.thejit.org/
  723. * @author egraether / http://egraether.com/
  724. * @author zz85 / http://www.lab4games.net/zz85/blog
  725. */
  726. THREE.Vector2 = function ( x, y ) {
  727. this.x = x || 0;
  728. this.y = y || 0;
  729. };
  730. THREE.Vector2.prototype = {
  731. constructor: THREE.Vector2,
  732. set: function ( x, y ) {
  733. this.x = x;
  734. this.y = y;
  735. return this;
  736. },
  737. setX: function ( x ) {
  738. this.x = x;
  739. return this;
  740. },
  741. setY: function ( y ) {
  742. this.y = y;
  743. return this;
  744. },
  745. setComponent: function ( index, value ) {
  746. switch ( index ) {
  747. case 0: this.x = value; break;
  748. case 1: this.y = value; break;
  749. default: throw new Error( 'index is out of range: ' + index );
  750. }
  751. },
  752. getComponent: function ( index ) {
  753. switch ( index ) {
  754. case 0: return this.x;
  755. case 1: return this.y;
  756. default: throw new Error( 'index is out of range: ' + index );
  757. }
  758. },
  759. copy: function ( v ) {
  760. this.x = v.x;
  761. this.y = v.y;
  762. return this;
  763. },
  764. add: function ( v, w ) {
  765. if ( w !== undefined ) {
  766. THREE.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  767. return this.addVectors( v, w );
  768. }
  769. this.x += v.x;
  770. this.y += v.y;
  771. return this;
  772. },
  773. addScalar: function ( s ) {
  774. this.x += s;
  775. this.y += s;
  776. return this;
  777. },
  778. addVectors: function ( a, b ) {
  779. this.x = a.x + b.x;
  780. this.y = a.y + b.y;
  781. return this;
  782. },
  783. sub: function ( v, w ) {
  784. if ( w !== undefined ) {
  785. THREE.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  786. return this.subVectors( v, w );
  787. }
  788. this.x -= v.x;
  789. this.y -= v.y;
  790. return this;
  791. },
  792. subScalar: function ( s ) {
  793. this.x -= s;
  794. this.y -= s;
  795. return this;
  796. },
  797. subVectors: function ( a, b ) {
  798. this.x = a.x - b.x;
  799. this.y = a.y - b.y;
  800. return this;
  801. },
  802. multiply: function ( v ) {
  803. this.x *= v.x;
  804. this.y *= v.y;
  805. return this;
  806. },
  807. multiplyScalar: function ( s ) {
  808. this.x *= s;
  809. this.y *= s;
  810. return this;
  811. },
  812. divide: function ( v ) {
  813. this.x /= v.x;
  814. this.y /= v.y;
  815. return this;
  816. },
  817. divideScalar: function ( scalar ) {
  818. if ( scalar !== 0 ) {
  819. var invScalar = 1 / scalar;
  820. this.x *= invScalar;
  821. this.y *= invScalar;
  822. } else {
  823. this.x = 0;
  824. this.y = 0;
  825. }
  826. return this;
  827. },
  828. min: function ( v ) {
  829. if ( this.x > v.x ) {
  830. this.x = v.x;
  831. }
  832. if ( this.y > v.y ) {
  833. this.y = v.y;
  834. }
  835. return this;
  836. },
  837. max: function ( v ) {
  838. if ( this.x < v.x ) {
  839. this.x = v.x;
  840. }
  841. if ( this.y < v.y ) {
  842. this.y = v.y;
  843. }
  844. return this;
  845. },
  846. clamp: function ( min, max ) {
  847. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  848. if ( this.x < min.x ) {
  849. this.x = min.x;
  850. } else if ( this.x > max.x ) {
  851. this.x = max.x;
  852. }
  853. if ( this.y < min.y ) {
  854. this.y = min.y;
  855. } else if ( this.y > max.y ) {
  856. this.y = max.y;
  857. }
  858. return this;
  859. },
  860. clampScalar: ( function () {
  861. var min, max;
  862. return function ( minVal, maxVal ) {
  863. if ( min === undefined ) {
  864. min = new THREE.Vector2();
  865. max = new THREE.Vector2();
  866. }
  867. min.set( minVal, minVal );
  868. max.set( maxVal, maxVal );
  869. return this.clamp( min, max );
  870. };
  871. } )(),
  872. floor: function () {
  873. this.x = Math.floor( this.x );
  874. this.y = Math.floor( this.y );
  875. return this;
  876. },
  877. ceil: function () {
  878. this.x = Math.ceil( this.x );
  879. this.y = Math.ceil( this.y );
  880. return this;
  881. },
  882. round: function () {
  883. this.x = Math.round( this.x );
  884. this.y = Math.round( this.y );
  885. return this;
  886. },
  887. roundToZero: function () {
  888. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  889. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  890. return this;
  891. },
  892. negate: function () {
  893. this.x = - this.x;
  894. this.y = - this.y;
  895. return this;
  896. },
  897. dot: function ( v ) {
  898. return this.x * v.x + this.y * v.y;
  899. },
  900. lengthSq: function () {
  901. return this.x * this.x + this.y * this.y;
  902. },
  903. length: function () {
  904. return Math.sqrt( this.x * this.x + this.y * this.y );
  905. },
  906. normalize: function () {
  907. return this.divideScalar( this.length() );
  908. },
  909. distanceTo: function ( v ) {
  910. return Math.sqrt( this.distanceToSquared( v ) );
  911. },
  912. distanceToSquared: function ( v ) {
  913. var dx = this.x - v.x, dy = this.y - v.y;
  914. return dx * dx + dy * dy;
  915. },
  916. setLength: function ( l ) {
  917. var oldLength = this.length();
  918. if ( oldLength !== 0 && l !== oldLength ) {
  919. this.multiplyScalar( l / oldLength );
  920. }
  921. return this;
  922. },
  923. lerp: function ( v, alpha ) {
  924. this.x += ( v.x - this.x ) * alpha;
  925. this.y += ( v.y - this.y ) * alpha;
  926. return this;
  927. },
  928. lerpVectors: function ( v1, v2, alpha ) {
  929. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  930. return this;
  931. },
  932. equals: function ( v ) {
  933. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  934. },
  935. fromArray: function ( array, offset ) {
  936. if ( offset === undefined ) offset = 0;
  937. this.x = array[ offset ];
  938. this.y = array[ offset + 1 ];
  939. return this;
  940. },
  941. toArray: function ( array, offset ) {
  942. if ( array === undefined ) array = [];
  943. if ( offset === undefined ) offset = 0;
  944. array[ offset ] = this.x;
  945. array[ offset + 1 ] = this.y;
  946. return array;
  947. },
  948. fromAttribute: function ( attribute, index, offset ) {
  949. if ( offset === undefined ) offset = 0;
  950. index = index * attribute.itemSize + offset;
  951. this.x = attribute.array[ index ];
  952. this.y = attribute.array[ index + 1 ];
  953. return this;
  954. },
  955. clone: function () {
  956. return new THREE.Vector2( this.x, this.y );
  957. }
  958. };
  959. // File:src/math/Vector3.js
  960. /**
  961. * @author mrdoob / http://mrdoob.com/
  962. * @author *kile / http://kile.stravaganza.org/
  963. * @author philogb / http://blog.thejit.org/
  964. * @author mikael emtinger / http://gomo.se/
  965. * @author egraether / http://egraether.com/
  966. * @author WestLangley / http://github.com/WestLangley
  967. */
  968. THREE.Vector3 = function ( x, y, z ) {
  969. this.x = x || 0;
  970. this.y = y || 0;
  971. this.z = z || 0;
  972. };
  973. THREE.Vector3.prototype = {
  974. constructor: THREE.Vector3,
  975. set: function ( x, y, z ) {
  976. this.x = x;
  977. this.y = y;
  978. this.z = z;
  979. return this;
  980. },
  981. setX: function ( x ) {
  982. this.x = x;
  983. return this;
  984. },
  985. setY: function ( y ) {
  986. this.y = y;
  987. return this;
  988. },
  989. setZ: function ( z ) {
  990. this.z = z;
  991. return this;
  992. },
  993. setComponent: function ( index, value ) {
  994. switch ( index ) {
  995. case 0: this.x = value; break;
  996. case 1: this.y = value; break;
  997. case 2: this.z = value; break;
  998. default: throw new Error( 'index is out of range: ' + index );
  999. }
  1000. },
  1001. getComponent: function ( index ) {
  1002. switch ( index ) {
  1003. case 0: return this.x;
  1004. case 1: return this.y;
  1005. case 2: return this.z;
  1006. default: throw new Error( 'index is out of range: ' + index );
  1007. }
  1008. },
  1009. copy: function ( v ) {
  1010. this.x = v.x;
  1011. this.y = v.y;
  1012. this.z = v.z;
  1013. return this;
  1014. },
  1015. add: function ( v, w ) {
  1016. if ( w !== undefined ) {
  1017. THREE.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1018. return this.addVectors( v, w );
  1019. }
  1020. this.x += v.x;
  1021. this.y += v.y;
  1022. this.z += v.z;
  1023. return this;
  1024. },
  1025. addScalar: function ( s ) {
  1026. this.x += s;
  1027. this.y += s;
  1028. this.z += s;
  1029. return this;
  1030. },
  1031. addVectors: function ( a, b ) {
  1032. this.x = a.x + b.x;
  1033. this.y = a.y + b.y;
  1034. this.z = a.z + b.z;
  1035. return this;
  1036. },
  1037. sub: function ( v, w ) {
  1038. if ( w !== undefined ) {
  1039. THREE.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1040. return this.subVectors( v, w );
  1041. }
  1042. this.x -= v.x;
  1043. this.y -= v.y;
  1044. this.z -= v.z;
  1045. return this;
  1046. },
  1047. subScalar: function ( s ) {
  1048. this.x -= s;
  1049. this.y -= s;
  1050. this.z -= s;
  1051. return this;
  1052. },
  1053. subVectors: function ( a, b ) {
  1054. this.x = a.x - b.x;
  1055. this.y = a.y - b.y;
  1056. this.z = a.z - b.z;
  1057. return this;
  1058. },
  1059. multiply: function ( v, w ) {
  1060. if ( w !== undefined ) {
  1061. THREE.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  1062. return this.multiplyVectors( v, w );
  1063. }
  1064. this.x *= v.x;
  1065. this.y *= v.y;
  1066. this.z *= v.z;
  1067. return this;
  1068. },
  1069. multiplyScalar: function ( scalar ) {
  1070. this.x *= scalar;
  1071. this.y *= scalar;
  1072. this.z *= scalar;
  1073. return this;
  1074. },
  1075. multiplyVectors: function ( a, b ) {
  1076. this.x = a.x * b.x;
  1077. this.y = a.y * b.y;
  1078. this.z = a.z * b.z;
  1079. return this;
  1080. },
  1081. applyEuler: function () {
  1082. var quaternion;
  1083. return function ( euler ) {
  1084. if ( euler instanceof THREE.Euler === false ) {
  1085. THREE.error( 'THREE.Vector3: .applyEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  1086. }
  1087. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1088. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1089. return this;
  1090. };
  1091. }(),
  1092. applyAxisAngle: function () {
  1093. var quaternion;
  1094. return function ( axis, angle ) {
  1095. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1096. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1097. return this;
  1098. };
  1099. }(),
  1100. applyMatrix3: function ( m ) {
  1101. var x = this.x;
  1102. var y = this.y;
  1103. var z = this.z;
  1104. var e = m.elements;
  1105. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1106. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1107. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1108. return this;
  1109. },
  1110. applyMatrix4: function ( m ) {
  1111. // input: THREE.Matrix4 affine matrix
  1112. var x = this.x, y = this.y, z = this.z;
  1113. var e = m.elements;
  1114. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  1115. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  1116. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  1117. return this;
  1118. },
  1119. applyProjection: function ( m ) {
  1120. // input: THREE.Matrix4 projection matrix
  1121. var x = this.x, y = this.y, z = this.z;
  1122. var e = m.elements;
  1123. var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide
  1124. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d;
  1125. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d;
  1126. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d;
  1127. return this;
  1128. },
  1129. applyQuaternion: function ( q ) {
  1130. var x = this.x;
  1131. var y = this.y;
  1132. var z = this.z;
  1133. var qx = q.x;
  1134. var qy = q.y;
  1135. var qz = q.z;
  1136. var qw = q.w;
  1137. // calculate quat * vector
  1138. var ix = qw * x + qy * z - qz * y;
  1139. var iy = qw * y + qz * x - qx * z;
  1140. var iz = qw * z + qx * y - qy * x;
  1141. var iw = - qx * x - qy * y - qz * z;
  1142. // calculate result * inverse quat
  1143. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1144. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1145. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1146. return this;
  1147. },
  1148. project: function () {
  1149. var matrix;
  1150. return function ( camera ) {
  1151. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1152. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1153. return this.applyProjection( matrix );
  1154. };
  1155. }(),
  1156. unproject: function () {
  1157. var matrix;
  1158. return function ( camera ) {
  1159. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1160. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1161. return this.applyProjection( matrix );
  1162. };
  1163. }(),
  1164. transformDirection: function ( m ) {
  1165. // input: THREE.Matrix4 affine matrix
  1166. // vector interpreted as a direction
  1167. var x = this.x, y = this.y, z = this.z;
  1168. var e = m.elements;
  1169. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1170. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1171. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1172. this.normalize();
  1173. return this;
  1174. },
  1175. divide: function ( v ) {
  1176. this.x /= v.x;
  1177. this.y /= v.y;
  1178. this.z /= v.z;
  1179. return this;
  1180. },
  1181. divideScalar: function ( scalar ) {
  1182. if ( scalar !== 0 ) {
  1183. var invScalar = 1 / scalar;
  1184. this.x *= invScalar;
  1185. this.y *= invScalar;
  1186. this.z *= invScalar;
  1187. } else {
  1188. this.x = 0;
  1189. this.y = 0;
  1190. this.z = 0;
  1191. }
  1192. return this;
  1193. },
  1194. min: function ( v ) {
  1195. if ( this.x > v.x ) {
  1196. this.x = v.x;
  1197. }
  1198. if ( this.y > v.y ) {
  1199. this.y = v.y;
  1200. }
  1201. if ( this.z > v.z ) {
  1202. this.z = v.z;
  1203. }
  1204. return this;
  1205. },
  1206. max: function ( v ) {
  1207. if ( this.x < v.x ) {
  1208. this.x = v.x;
  1209. }
  1210. if ( this.y < v.y ) {
  1211. this.y = v.y;
  1212. }
  1213. if ( this.z < v.z ) {
  1214. this.z = v.z;
  1215. }
  1216. return this;
  1217. },
  1218. clamp: function ( min, max ) {
  1219. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1220. if ( this.x < min.x ) {
  1221. this.x = min.x;
  1222. } else if ( this.x > max.x ) {
  1223. this.x = max.x;
  1224. }
  1225. if ( this.y < min.y ) {
  1226. this.y = min.y;
  1227. } else if ( this.y > max.y ) {
  1228. this.y = max.y;
  1229. }
  1230. if ( this.z < min.z ) {
  1231. this.z = min.z;
  1232. } else if ( this.z > max.z ) {
  1233. this.z = max.z;
  1234. }
  1235. return this;
  1236. },
  1237. clampScalar: ( function () {
  1238. var min, max;
  1239. return function ( minVal, maxVal ) {
  1240. if ( min === undefined ) {
  1241. min = new THREE.Vector3();
  1242. max = new THREE.Vector3();
  1243. }
  1244. min.set( minVal, minVal, minVal );
  1245. max.set( maxVal, maxVal, maxVal );
  1246. return this.clamp( min, max );
  1247. };
  1248. } )(),
  1249. floor: function () {
  1250. this.x = Math.floor( this.x );
  1251. this.y = Math.floor( this.y );
  1252. this.z = Math.floor( this.z );
  1253. return this;
  1254. },
  1255. ceil: function () {
  1256. this.x = Math.ceil( this.x );
  1257. this.y = Math.ceil( this.y );
  1258. this.z = Math.ceil( this.z );
  1259. return this;
  1260. },
  1261. round: function () {
  1262. this.x = Math.round( this.x );
  1263. this.y = Math.round( this.y );
  1264. this.z = Math.round( this.z );
  1265. return this;
  1266. },
  1267. roundToZero: function () {
  1268. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1269. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1270. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1271. return this;
  1272. },
  1273. negate: function () {
  1274. this.x = - this.x;
  1275. this.y = - this.y;
  1276. this.z = - this.z;
  1277. return this;
  1278. },
  1279. dot: function ( v ) {
  1280. return this.x * v.x + this.y * v.y + this.z * v.z;
  1281. },
  1282. lengthSq: function () {
  1283. return this.x * this.x + this.y * this.y + this.z * this.z;
  1284. },
  1285. length: function () {
  1286. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1287. },
  1288. lengthManhattan: function () {
  1289. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1290. },
  1291. normalize: function () {
  1292. return this.divideScalar( this.length() );
  1293. },
  1294. setLength: function ( l ) {
  1295. var oldLength = this.length();
  1296. if ( oldLength !== 0 && l !== oldLength ) {
  1297. this.multiplyScalar( l / oldLength );
  1298. }
  1299. return this;
  1300. },
  1301. lerp: function ( v, alpha ) {
  1302. this.x += ( v.x - this.x ) * alpha;
  1303. this.y += ( v.y - this.y ) * alpha;
  1304. this.z += ( v.z - this.z ) * alpha;
  1305. return this;
  1306. },
  1307. lerpVectors: function ( v1, v2, alpha ) {
  1308. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1309. return this;
  1310. },
  1311. cross: function ( v, w ) {
  1312. if ( w !== undefined ) {
  1313. THREE.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1314. return this.crossVectors( v, w );
  1315. }
  1316. var x = this.x, y = this.y, z = this.z;
  1317. this.x = y * v.z - z * v.y;
  1318. this.y = z * v.x - x * v.z;
  1319. this.z = x * v.y - y * v.x;
  1320. return this;
  1321. },
  1322. crossVectors: function ( a, b ) {
  1323. var ax = a.x, ay = a.y, az = a.z;
  1324. var bx = b.x, by = b.y, bz = b.z;
  1325. this.x = ay * bz - az * by;
  1326. this.y = az * bx - ax * bz;
  1327. this.z = ax * by - ay * bx;
  1328. return this;
  1329. },
  1330. projectOnVector: function () {
  1331. var v1, dot;
  1332. return function ( vector ) {
  1333. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1334. v1.copy( vector ).normalize();
  1335. dot = this.dot( v1 );
  1336. return this.copy( v1 ).multiplyScalar( dot );
  1337. };
  1338. }(),
  1339. projectOnPlane: function () {
  1340. var v1;
  1341. return function ( planeNormal ) {
  1342. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1343. v1.copy( this ).projectOnVector( planeNormal );
  1344. return this.sub( v1 );
  1345. }
  1346. }(),
  1347. reflect: function () {
  1348. // reflect incident vector off plane orthogonal to normal
  1349. // normal is assumed to have unit length
  1350. var v1;
  1351. return function ( normal ) {
  1352. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1353. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1354. }
  1355. }(),
  1356. angleTo: function ( v ) {
  1357. var theta = this.dot( v ) / ( this.length() * v.length() );
  1358. // clamp, to handle numerical problems
  1359. return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) );
  1360. },
  1361. distanceTo: function ( v ) {
  1362. return Math.sqrt( this.distanceToSquared( v ) );
  1363. },
  1364. distanceToSquared: function ( v ) {
  1365. var dx = this.x - v.x;
  1366. var dy = this.y - v.y;
  1367. var dz = this.z - v.z;
  1368. return dx * dx + dy * dy + dz * dz;
  1369. },
  1370. setEulerFromRotationMatrix: function ( m, order ) {
  1371. THREE.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  1372. },
  1373. setEulerFromQuaternion: function ( q, order ) {
  1374. THREE.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  1375. },
  1376. getPositionFromMatrix: function ( m ) {
  1377. THREE.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  1378. return this.setFromMatrixPosition( m );
  1379. },
  1380. getScaleFromMatrix: function ( m ) {
  1381. THREE.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  1382. return this.setFromMatrixScale( m );
  1383. },
  1384. getColumnFromMatrix: function ( index, matrix ) {
  1385. THREE.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  1386. return this.setFromMatrixColumn( index, matrix );
  1387. },
  1388. setFromMatrixPosition: function ( m ) {
  1389. this.x = m.elements[ 12 ];
  1390. this.y = m.elements[ 13 ];
  1391. this.z = m.elements[ 14 ];
  1392. return this;
  1393. },
  1394. setFromMatrixScale: function ( m ) {
  1395. var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
  1396. var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
  1397. var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
  1398. this.x = sx;
  1399. this.y = sy;
  1400. this.z = sz;
  1401. return this;
  1402. },
  1403. setFromMatrixColumn: function ( index, matrix ) {
  1404. var offset = index * 4;
  1405. var me = matrix.elements;
  1406. this.x = me[ offset ];
  1407. this.y = me[ offset + 1 ];
  1408. this.z = me[ offset + 2 ];
  1409. return this;
  1410. },
  1411. equals: function ( v ) {
  1412. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1413. },
  1414. fromArray: function ( array, offset ) {
  1415. if ( offset === undefined ) offset = 0;
  1416. this.x = array[ offset ];
  1417. this.y = array[ offset + 1 ];
  1418. this.z = array[ offset + 2 ];
  1419. return this;
  1420. },
  1421. toArray: function ( array, offset ) {
  1422. if ( array === undefined ) array = [];
  1423. if ( offset === undefined ) offset = 0;
  1424. array[ offset ] = this.x;
  1425. array[ offset + 1 ] = this.y;
  1426. array[ offset + 2 ] = this.z;
  1427. return array;
  1428. },
  1429. fromAttribute: function ( attribute, index, offset ) {
  1430. if ( offset === undefined ) offset = 0;
  1431. index = index * attribute.itemSize + offset;
  1432. this.x = attribute.array[ index ];
  1433. this.y = attribute.array[ index + 1 ];
  1434. this.z = attribute.array[ index + 2 ];
  1435. return this;
  1436. },
  1437. clone: function () {
  1438. return new THREE.Vector3( this.x, this.y, this.z );
  1439. }
  1440. };
  1441. // File:src/math/Vector4.js
  1442. /**
  1443. * @author supereggbert / http://www.paulbrunt.co.uk/
  1444. * @author philogb / http://blog.thejit.org/
  1445. * @author mikael emtinger / http://gomo.se/
  1446. * @author egraether / http://egraether.com/
  1447. * @author WestLangley / http://github.com/WestLangley
  1448. */
  1449. THREE.Vector4 = function ( x, y, z, w ) {
  1450. this.x = x || 0;
  1451. this.y = y || 0;
  1452. this.z = z || 0;
  1453. this.w = ( w !== undefined ) ? w : 1;
  1454. };
  1455. THREE.Vector4.prototype = {
  1456. constructor: THREE.Vector4,
  1457. set: function ( x, y, z, w ) {
  1458. this.x = x;
  1459. this.y = y;
  1460. this.z = z;
  1461. this.w = w;
  1462. return this;
  1463. },
  1464. setX: function ( x ) {
  1465. this.x = x;
  1466. return this;
  1467. },
  1468. setY: function ( y ) {
  1469. this.y = y;
  1470. return this;
  1471. },
  1472. setZ: function ( z ) {
  1473. this.z = z;
  1474. return this;
  1475. },
  1476. setW: function ( w ) {
  1477. this.w = w;
  1478. return this;
  1479. },
  1480. setComponent: function ( index, value ) {
  1481. switch ( index ) {
  1482. case 0: this.x = value; break;
  1483. case 1: this.y = value; break;
  1484. case 2: this.z = value; break;
  1485. case 3: this.w = value; break;
  1486. default: throw new Error( 'index is out of range: ' + index );
  1487. }
  1488. },
  1489. getComponent: function ( index ) {
  1490. switch ( index ) {
  1491. case 0: return this.x;
  1492. case 1: return this.y;
  1493. case 2: return this.z;
  1494. case 3: return this.w;
  1495. default: throw new Error( 'index is out of range: ' + index );
  1496. }
  1497. },
  1498. copy: function ( v ) {
  1499. this.x = v.x;
  1500. this.y = v.y;
  1501. this.z = v.z;
  1502. this.w = ( v.w !== undefined ) ? v.w : 1;
  1503. return this;
  1504. },
  1505. add: function ( v, w ) {
  1506. if ( w !== undefined ) {
  1507. THREE.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1508. return this.addVectors( v, w );
  1509. }
  1510. this.x += v.x;
  1511. this.y += v.y;
  1512. this.z += v.z;
  1513. this.w += v.w;
  1514. return this;
  1515. },
  1516. addScalar: function ( s ) {
  1517. this.x += s;
  1518. this.y += s;
  1519. this.z += s;
  1520. this.w += s;
  1521. return this;
  1522. },
  1523. addVectors: function ( a, b ) {
  1524. this.x = a.x + b.x;
  1525. this.y = a.y + b.y;
  1526. this.z = a.z + b.z;
  1527. this.w = a.w + b.w;
  1528. return this;
  1529. },
  1530. sub: function ( v, w ) {
  1531. if ( w !== undefined ) {
  1532. THREE.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1533. return this.subVectors( v, w );
  1534. }
  1535. this.x -= v.x;
  1536. this.y -= v.y;
  1537. this.z -= v.z;
  1538. this.w -= v.w;
  1539. return this;
  1540. },
  1541. subScalar: function ( s ) {
  1542. this.x -= s;
  1543. this.y -= s;
  1544. this.z -= s;
  1545. this.w -= s;
  1546. return this;
  1547. },
  1548. subVectors: function ( a, b ) {
  1549. this.x = a.x - b.x;
  1550. this.y = a.y - b.y;
  1551. this.z = a.z - b.z;
  1552. this.w = a.w - b.w;
  1553. return this;
  1554. },
  1555. multiplyScalar: function ( scalar ) {
  1556. this.x *= scalar;
  1557. this.y *= scalar;
  1558. this.z *= scalar;
  1559. this.w *= scalar;
  1560. return this;
  1561. },
  1562. applyMatrix4: function ( m ) {
  1563. var x = this.x;
  1564. var y = this.y;
  1565. var z = this.z;
  1566. var w = this.w;
  1567. var e = m.elements;
  1568. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1569. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1570. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1571. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1572. return this;
  1573. },
  1574. divideScalar: function ( scalar ) {
  1575. if ( scalar !== 0 ) {
  1576. var invScalar = 1 / scalar;
  1577. this.x *= invScalar;
  1578. this.y *= invScalar;
  1579. this.z *= invScalar;
  1580. this.w *= invScalar;
  1581. } else {
  1582. this.x = 0;
  1583. this.y = 0;
  1584. this.z = 0;
  1585. this.w = 1;
  1586. }
  1587. return this;
  1588. },
  1589. setAxisAngleFromQuaternion: function ( q ) {
  1590. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1591. // q is assumed to be normalized
  1592. this.w = 2 * Math.acos( q.w );
  1593. var s = Math.sqrt( 1 - q.w * q.w );
  1594. if ( s < 0.0001 ) {
  1595. this.x = 1;
  1596. this.y = 0;
  1597. this.z = 0;
  1598. } else {
  1599. this.x = q.x / s;
  1600. this.y = q.y / s;
  1601. this.z = q.z / s;
  1602. }
  1603. return this;
  1604. },
  1605. setAxisAngleFromRotationMatrix: function ( m ) {
  1606. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1607. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1608. var angle, x, y, z, // variables for result
  1609. epsilon = 0.01, // margin to allow for rounding errors
  1610. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1611. te = m.elements,
  1612. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1613. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1614. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1615. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1616. && ( Math.abs( m13 - m31 ) < epsilon )
  1617. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1618. // singularity found
  1619. // first check for identity matrix which must have +1 for all terms
  1620. // in leading diagonal and zero in other terms
  1621. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1622. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1623. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1624. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1625. // this singularity is identity matrix so angle = 0
  1626. this.set( 1, 0, 0, 0 );
  1627. return this; // zero angle, arbitrary axis
  1628. }
  1629. // otherwise this singularity is angle = 180
  1630. angle = Math.PI;
  1631. var xx = ( m11 + 1 ) / 2;
  1632. var yy = ( m22 + 1 ) / 2;
  1633. var zz = ( m33 + 1 ) / 2;
  1634. var xy = ( m12 + m21 ) / 4;
  1635. var xz = ( m13 + m31 ) / 4;
  1636. var yz = ( m23 + m32 ) / 4;
  1637. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1638. if ( xx < epsilon ) {
  1639. x = 0;
  1640. y = 0.707106781;
  1641. z = 0.707106781;
  1642. } else {
  1643. x = Math.sqrt( xx );
  1644. y = xy / x;
  1645. z = xz / x;
  1646. }
  1647. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1648. if ( yy < epsilon ) {
  1649. x = 0.707106781;
  1650. y = 0;
  1651. z = 0.707106781;
  1652. } else {
  1653. y = Math.sqrt( yy );
  1654. x = xy / y;
  1655. z = yz / y;
  1656. }
  1657. } else { // m33 is the largest diagonal term so base result on this
  1658. if ( zz < epsilon ) {
  1659. x = 0.707106781;
  1660. y = 0.707106781;
  1661. z = 0;
  1662. } else {
  1663. z = Math.sqrt( zz );
  1664. x = xz / z;
  1665. y = yz / z;
  1666. }
  1667. }
  1668. this.set( x, y, z, angle );
  1669. return this; // return 180 deg rotation
  1670. }
  1671. // as we have reached here there are no singularities so we can handle normally
  1672. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1673. + ( m13 - m31 ) * ( m13 - m31 )
  1674. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1675. if ( Math.abs( s ) < 0.001 ) s = 1;
  1676. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1677. // caught by singularity test above, but I've left it in just in case
  1678. this.x = ( m32 - m23 ) / s;
  1679. this.y = ( m13 - m31 ) / s;
  1680. this.z = ( m21 - m12 ) / s;
  1681. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1682. return this;
  1683. },
  1684. min: function ( v ) {
  1685. if ( this.x > v.x ) {
  1686. this.x = v.x;
  1687. }
  1688. if ( this.y > v.y ) {
  1689. this.y = v.y;
  1690. }
  1691. if ( this.z > v.z ) {
  1692. this.z = v.z;
  1693. }
  1694. if ( this.w > v.w ) {
  1695. this.w = v.w;
  1696. }
  1697. return this;
  1698. },
  1699. max: function ( v ) {
  1700. if ( this.x < v.x ) {
  1701. this.x = v.x;
  1702. }
  1703. if ( this.y < v.y ) {
  1704. this.y = v.y;
  1705. }
  1706. if ( this.z < v.z ) {
  1707. this.z = v.z;
  1708. }
  1709. if ( this.w < v.w ) {
  1710. this.w = v.w;
  1711. }
  1712. return this;
  1713. },
  1714. clamp: function ( min, max ) {
  1715. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1716. if ( this.x < min.x ) {
  1717. this.x = min.x;
  1718. } else if ( this.x > max.x ) {
  1719. this.x = max.x;
  1720. }
  1721. if ( this.y < min.y ) {
  1722. this.y = min.y;
  1723. } else if ( this.y > max.y ) {
  1724. this.y = max.y;
  1725. }
  1726. if ( this.z < min.z ) {
  1727. this.z = min.z;
  1728. } else if ( this.z > max.z ) {
  1729. this.z = max.z;
  1730. }
  1731. if ( this.w < min.w ) {
  1732. this.w = min.w;
  1733. } else if ( this.w > max.w ) {
  1734. this.w = max.w;
  1735. }
  1736. return this;
  1737. },
  1738. clampScalar: ( function () {
  1739. var min, max;
  1740. return function ( minVal, maxVal ) {
  1741. if ( min === undefined ) {
  1742. min = new THREE.Vector4();
  1743. max = new THREE.Vector4();
  1744. }
  1745. min.set( minVal, minVal, minVal, minVal );
  1746. max.set( maxVal, maxVal, maxVal, maxVal );
  1747. return this.clamp( min, max );
  1748. };
  1749. } )(),
  1750. floor: function () {
  1751. this.x = Math.floor( this.x );
  1752. this.y = Math.floor( this.y );
  1753. this.z = Math.floor( this.z );
  1754. this.w = Math.floor( this.w );
  1755. return this;
  1756. },
  1757. ceil: function () {
  1758. this.x = Math.ceil( this.x );
  1759. this.y = Math.ceil( this.y );
  1760. this.z = Math.ceil( this.z );
  1761. this.w = Math.ceil( this.w );
  1762. return this;
  1763. },
  1764. round: function () {
  1765. this.x = Math.round( this.x );
  1766. this.y = Math.round( this.y );
  1767. this.z = Math.round( this.z );
  1768. this.w = Math.round( this.w );
  1769. return this;
  1770. },
  1771. roundToZero: function () {
  1772. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1773. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1774. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1775. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1776. return this;
  1777. },
  1778. negate: function () {
  1779. this.x = - this.x;
  1780. this.y = - this.y;
  1781. this.z = - this.z;
  1782. this.w = - this.w;
  1783. return this;
  1784. },
  1785. dot: function ( v ) {
  1786. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1787. },
  1788. lengthSq: function () {
  1789. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1790. },
  1791. length: function () {
  1792. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1793. },
  1794. lengthManhattan: function () {
  1795. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1796. },
  1797. normalize: function () {
  1798. return this.divideScalar( this.length() );
  1799. },
  1800. setLength: function ( l ) {
  1801. var oldLength = this.length();
  1802. if ( oldLength !== 0 && l !== oldLength ) {
  1803. this.multiplyScalar( l / oldLength );
  1804. }
  1805. return this;
  1806. },
  1807. lerp: function ( v, alpha ) {
  1808. this.x += ( v.x - this.x ) * alpha;
  1809. this.y += ( v.y - this.y ) * alpha;
  1810. this.z += ( v.z - this.z ) * alpha;
  1811. this.w += ( v.w - this.w ) * alpha;
  1812. return this;
  1813. },
  1814. lerpVectors: function ( v1, v2, alpha ) {
  1815. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1816. return this;
  1817. },
  1818. equals: function ( v ) {
  1819. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1820. },
  1821. fromArray: function ( array, offset ) {
  1822. if ( offset === undefined ) offset = 0;
  1823. this.x = array[ offset ];
  1824. this.y = array[ offset + 1 ];
  1825. this.z = array[ offset + 2 ];
  1826. this.w = array[ offset + 3 ];
  1827. return this;
  1828. },
  1829. toArray: function ( array, offset ) {
  1830. if ( array === undefined ) array = [];
  1831. if ( offset === undefined ) offset = 0;
  1832. array[ offset ] = this.x;
  1833. array[ offset + 1 ] = this.y;
  1834. array[ offset + 2 ] = this.z;
  1835. array[ offset + 3 ] = this.w;
  1836. return array;
  1837. },
  1838. fromAttribute: function ( attribute, index, offset ) {
  1839. if ( offset === undefined ) offset = 0;
  1840. index = index * attribute.itemSize + offset;
  1841. this.x = attribute.array[ index ];
  1842. this.y = attribute.array[ index + 1 ];
  1843. this.z = attribute.array[ index + 2 ];
  1844. this.w = attribute.array[ index + 3 ];
  1845. return this;
  1846. },
  1847. clone: function () {
  1848. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1849. }
  1850. };
  1851. // File:src/math/Euler.js
  1852. /**
  1853. * @author mrdoob / http://mrdoob.com/
  1854. * @author WestLangley / http://github.com/WestLangley
  1855. * @author bhouston / http://exocortex.com
  1856. */
  1857. THREE.Euler = function ( x, y, z, order ) {
  1858. this._x = x || 0;
  1859. this._y = y || 0;
  1860. this._z = z || 0;
  1861. this._order = order || THREE.Euler.DefaultOrder;
  1862. };
  1863. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1864. THREE.Euler.DefaultOrder = 'XYZ';
  1865. THREE.Euler.prototype = {
  1866. constructor: THREE.Euler,
  1867. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1868. get x () {
  1869. return this._x;
  1870. },
  1871. set x ( value ) {
  1872. this._x = value;
  1873. this.onChangeCallback();
  1874. },
  1875. get y () {
  1876. return this._y;
  1877. },
  1878. set y ( value ) {
  1879. this._y = value;
  1880. this.onChangeCallback();
  1881. },
  1882. get z () {
  1883. return this._z;
  1884. },
  1885. set z ( value ) {
  1886. this._z = value;
  1887. this.onChangeCallback();
  1888. },
  1889. get order () {
  1890. return this._order;
  1891. },
  1892. set order ( value ) {
  1893. this._order = value;
  1894. this.onChangeCallback();
  1895. },
  1896. set: function ( x, y, z, order ) {
  1897. this._x = x;
  1898. this._y = y;
  1899. this._z = z;
  1900. this._order = order || this._order;
  1901. this.onChangeCallback();
  1902. return this;
  1903. },
  1904. copy: function ( euler ) {
  1905. this._x = euler._x;
  1906. this._y = euler._y;
  1907. this._z = euler._z;
  1908. this._order = euler._order;
  1909. this.onChangeCallback();
  1910. return this;
  1911. },
  1912. setFromRotationMatrix: function ( m, order, update ) {
  1913. var clamp = THREE.Math.clamp;
  1914. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1915. var te = m.elements;
  1916. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  1917. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  1918. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1919. order = order || this._order;
  1920. if ( order === 'XYZ' ) {
  1921. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  1922. if ( Math.abs( m13 ) < 0.99999 ) {
  1923. this._x = Math.atan2( - m23, m33 );
  1924. this._z = Math.atan2( - m12, m11 );
  1925. } else {
  1926. this._x = Math.atan2( m32, m22 );
  1927. this._z = 0;
  1928. }
  1929. } else if ( order === 'YXZ' ) {
  1930. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  1931. if ( Math.abs( m23 ) < 0.99999 ) {
  1932. this._y = Math.atan2( m13, m33 );
  1933. this._z = Math.atan2( m21, m22 );
  1934. } else {
  1935. this._y = Math.atan2( - m31, m11 );
  1936. this._z = 0;
  1937. }
  1938. } else if ( order === 'ZXY' ) {
  1939. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  1940. if ( Math.abs( m32 ) < 0.99999 ) {
  1941. this._y = Math.atan2( - m31, m33 );
  1942. this._z = Math.atan2( - m12, m22 );
  1943. } else {
  1944. this._y = 0;
  1945. this._z = Math.atan2( m21, m11 );
  1946. }
  1947. } else if ( order === 'ZYX' ) {
  1948. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  1949. if ( Math.abs( m31 ) < 0.99999 ) {
  1950. this._x = Math.atan2( m32, m33 );
  1951. this._z = Math.atan2( m21, m11 );
  1952. } else {
  1953. this._x = 0;
  1954. this._z = Math.atan2( - m12, m22 );
  1955. }
  1956. } else if ( order === 'YZX' ) {
  1957. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  1958. if ( Math.abs( m21 ) < 0.99999 ) {
  1959. this._x = Math.atan2( - m23, m22 );
  1960. this._y = Math.atan2( - m31, m11 );
  1961. } else {
  1962. this._x = 0;
  1963. this._y = Math.atan2( m13, m33 );
  1964. }
  1965. } else if ( order === 'XZY' ) {
  1966. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  1967. if ( Math.abs( m12 ) < 0.99999 ) {
  1968. this._x = Math.atan2( m32, m22 );
  1969. this._y = Math.atan2( m13, m11 );
  1970. } else {
  1971. this._x = Math.atan2( - m23, m33 );
  1972. this._y = 0;
  1973. }
  1974. } else {
  1975. THREE.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order )
  1976. }
  1977. this._order = order;
  1978. if ( update !== false ) this.onChangeCallback();
  1979. return this;
  1980. },
  1981. setFromQuaternion: function () {
  1982. var matrix;
  1983. return function ( q, order, update ) {
  1984. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1985. matrix.makeRotationFromQuaternion( q );
  1986. this.setFromRotationMatrix( matrix, order, update );
  1987. return this;
  1988. };
  1989. }(),
  1990. setFromVector3: function ( v, order ) {
  1991. return this.set( v.x, v.y, v.z, order || this._order );
  1992. },
  1993. reorder: function () {
  1994. // WARNING: this discards revolution information -bhouston
  1995. var q = new THREE.Quaternion();
  1996. return function ( newOrder ) {
  1997. q.setFromEuler( this );
  1998. this.setFromQuaternion( q, newOrder );
  1999. };
  2000. }(),
  2001. equals: function ( euler ) {
  2002. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  2003. },
  2004. fromArray: function ( array ) {
  2005. this._x = array[ 0 ];
  2006. this._y = array[ 1 ];
  2007. this._z = array[ 2 ];
  2008. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  2009. this.onChangeCallback();
  2010. return this;
  2011. },
  2012. toArray: function ( array, offset ) {
  2013. if ( array === undefined ) array = [];
  2014. if ( offset === undefined ) offset = 0;
  2015. array[ offset ] = this._x;
  2016. array[ offset + 1 ] = this._y;
  2017. array[ offset + 2 ] = this._z;
  2018. array[ offset + 3 ] = this._order;
  2019. return array;
  2020. },
  2021. toVector3: function ( optionalResult ) {
  2022. if ( optionalResult ) {
  2023. return optionalResult.set( this._x, this._y, this._z );
  2024. } else {
  2025. return new THREE.Vector3( this._x, this._y, this._z );
  2026. }
  2027. },
  2028. onChange: function ( callback ) {
  2029. this.onChangeCallback = callback;
  2030. return this;
  2031. },
  2032. onChangeCallback: function () {},
  2033. clone: function () {
  2034. return new THREE.Euler( this._x, this._y, this._z, this._order );
  2035. }
  2036. };
  2037. // File:src/math/Line3.js
  2038. /**
  2039. * @author bhouston / http://exocortex.com
  2040. */
  2041. THREE.Line3 = function ( start, end ) {
  2042. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  2043. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  2044. };
  2045. THREE.Line3.prototype = {
  2046. constructor: THREE.Line3,
  2047. set: function ( start, end ) {
  2048. this.start.copy( start );
  2049. this.end.copy( end );
  2050. return this;
  2051. },
  2052. copy: function ( line ) {
  2053. this.start.copy( line.start );
  2054. this.end.copy( line.end );
  2055. return this;
  2056. },
  2057. center: function ( optionalTarget ) {
  2058. var result = optionalTarget || new THREE.Vector3();
  2059. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  2060. },
  2061. delta: function ( optionalTarget ) {
  2062. var result = optionalTarget || new THREE.Vector3();
  2063. return result.subVectors( this.end, this.start );
  2064. },
  2065. distanceSq: function () {
  2066. return this.start.distanceToSquared( this.end );
  2067. },
  2068. distance: function () {
  2069. return this.start.distanceTo( this.end );
  2070. },
  2071. at: function ( t, optionalTarget ) {
  2072. var result = optionalTarget || new THREE.Vector3();
  2073. return this.delta( result ).multiplyScalar( t ).add( this.start );
  2074. },
  2075. closestPointToPointParameter: function () {
  2076. var startP = new THREE.Vector3();
  2077. var startEnd = new THREE.Vector3();
  2078. return function ( point, clampToLine ) {
  2079. startP.subVectors( point, this.start );
  2080. startEnd.subVectors( this.end, this.start );
  2081. var startEnd2 = startEnd.dot( startEnd );
  2082. var startEnd_startP = startEnd.dot( startP );
  2083. var t = startEnd_startP / startEnd2;
  2084. if ( clampToLine ) {
  2085. t = THREE.Math.clamp( t, 0, 1 );
  2086. }
  2087. return t;
  2088. };
  2089. }(),
  2090. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  2091. var t = this.closestPointToPointParameter( point, clampToLine );
  2092. var result = optionalTarget || new THREE.Vector3();
  2093. return this.delta( result ).multiplyScalar( t ).add( this.start );
  2094. },
  2095. applyMatrix4: function ( matrix ) {
  2096. this.start.applyMatrix4( matrix );
  2097. this.end.applyMatrix4( matrix );
  2098. return this;
  2099. },
  2100. equals: function ( line ) {
  2101. return line.start.equals( this.start ) && line.end.equals( this.end );
  2102. },
  2103. clone: function () {
  2104. return new THREE.Line3().copy( this );
  2105. }
  2106. };
  2107. // File:src/math/Box2.js
  2108. /**
  2109. * @author bhouston / http://exocortex.com
  2110. */
  2111. THREE.Box2 = function ( min, max ) {
  2112. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  2113. this.max = ( max !== undefined ) ? max : new THREE.Vector2( - Infinity, - Infinity );
  2114. };
  2115. THREE.Box2.prototype = {
  2116. constructor: THREE.Box2,
  2117. set: function ( min, max ) {
  2118. this.min.copy( min );
  2119. this.max.copy( max );
  2120. return this;
  2121. },
  2122. setFromPoints: function ( points ) {
  2123. this.makeEmpty();
  2124. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2125. this.expandByPoint( points[ i ] )
  2126. }
  2127. return this;
  2128. },
  2129. setFromCenterAndSize: function () {
  2130. var v1 = new THREE.Vector2();
  2131. return function ( center, size ) {
  2132. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2133. this.min.copy( center ).sub( halfSize );
  2134. this.max.copy( center ).add( halfSize );
  2135. return this;
  2136. };
  2137. }(),
  2138. copy: function ( box ) {
  2139. this.min.copy( box.min );
  2140. this.max.copy( box.max );
  2141. return this;
  2142. },
  2143. makeEmpty: function () {
  2144. this.min.x = this.min.y = Infinity;
  2145. this.max.x = this.max.y = - Infinity;
  2146. return this;
  2147. },
  2148. empty: function () {
  2149. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2150. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  2151. },
  2152. center: function ( optionalTarget ) {
  2153. var result = optionalTarget || new THREE.Vector2();
  2154. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2155. },
  2156. size: function ( optionalTarget ) {
  2157. var result = optionalTarget || new THREE.Vector2();
  2158. return result.subVectors( this.max, this.min );
  2159. },
  2160. expandByPoint: function ( point ) {
  2161. this.min.min( point );
  2162. this.max.max( point );
  2163. return this;
  2164. },
  2165. expandByVector: function ( vector ) {
  2166. this.min.sub( vector );
  2167. this.max.add( vector );
  2168. return this;
  2169. },
  2170. expandByScalar: function ( scalar ) {
  2171. this.min.addScalar( - scalar );
  2172. this.max.addScalar( scalar );
  2173. return this;
  2174. },
  2175. containsPoint: function ( point ) {
  2176. if ( point.x < this.min.x || point.x > this.max.x ||
  2177. point.y < this.min.y || point.y > this.max.y ) {
  2178. return false;
  2179. }
  2180. return true;
  2181. },
  2182. containsBox: function ( box ) {
  2183. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2184. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  2185. return true;
  2186. }
  2187. return false;
  2188. },
  2189. getParameter: function ( point, optionalTarget ) {
  2190. // This can potentially have a divide by zero if the box
  2191. // has a size dimension of 0.
  2192. var result = optionalTarget || new THREE.Vector2();
  2193. return result.set(
  2194. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2195. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  2196. );
  2197. },
  2198. isIntersectionBox: function ( box ) {
  2199. // using 6 splitting planes to rule out intersections.
  2200. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2201. box.max.y < this.min.y || box.min.y > this.max.y ) {
  2202. return false;
  2203. }
  2204. return true;
  2205. },
  2206. clampPoint: function ( point, optionalTarget ) {
  2207. var result = optionalTarget || new THREE.Vector2();
  2208. return result.copy( point ).clamp( this.min, this.max );
  2209. },
  2210. distanceToPoint: function () {
  2211. var v1 = new THREE.Vector2();
  2212. return function ( point ) {
  2213. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2214. return clampedPoint.sub( point ).length();
  2215. };
  2216. }(),
  2217. intersect: function ( box ) {
  2218. this.min.max( box.min );
  2219. this.max.min( box.max );
  2220. return this;
  2221. },
  2222. union: function ( box ) {
  2223. this.min.min( box.min );
  2224. this.max.max( box.max );
  2225. return this;
  2226. },
  2227. translate: function ( offset ) {
  2228. this.min.add( offset );
  2229. this.max.add( offset );
  2230. return this;
  2231. },
  2232. equals: function ( box ) {
  2233. return box.min.equals( this.min ) && box.max.equals( this.max );
  2234. },
  2235. clone: function () {
  2236. return new THREE.Box2().copy( this );
  2237. }
  2238. };
  2239. // File:src/math/Box3.js
  2240. /**
  2241. * @author bhouston / http://exocortex.com
  2242. * @author WestLangley / http://github.com/WestLangley
  2243. */
  2244. THREE.Box3 = function ( min, max ) {
  2245. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2246. this.max = ( max !== undefined ) ? max : new THREE.Vector3( - Infinity, - Infinity, - Infinity );
  2247. };
  2248. THREE.Box3.prototype = {
  2249. constructor: THREE.Box3,
  2250. set: function ( min, max ) {
  2251. this.min.copy( min );
  2252. this.max.copy( max );
  2253. return this;
  2254. },
  2255. setFromPoints: function ( points ) {
  2256. this.makeEmpty();
  2257. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2258. this.expandByPoint( points[ i ] )
  2259. }
  2260. return this;
  2261. },
  2262. setFromCenterAndSize: function () {
  2263. var v1 = new THREE.Vector3();
  2264. return function ( center, size ) {
  2265. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2266. this.min.copy( center ).sub( halfSize );
  2267. this.max.copy( center ).add( halfSize );
  2268. return this;
  2269. };
  2270. }(),
  2271. setFromObject: function () {
  2272. // Computes the world-axis-aligned bounding box of an object (including its children),
  2273. // accounting for both the object's, and childrens', world transforms
  2274. var v1 = new THREE.Vector3();
  2275. return function ( object ) {
  2276. var scope = this;
  2277. object.updateMatrixWorld( true );
  2278. this.makeEmpty();
  2279. object.traverse( function ( node ) {
  2280. var geometry = node.geometry;
  2281. if ( geometry !== undefined ) {
  2282. if ( geometry instanceof THREE.Geometry ) {
  2283. var vertices = geometry.vertices;
  2284. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  2285. v1.copy( vertices[ i ] );
  2286. v1.applyMatrix4( node.matrixWorld );
  2287. scope.expandByPoint( v1 );
  2288. }
  2289. } else if ( geometry instanceof THREE.BufferGeometry && geometry.attributes[ 'position' ] !== undefined ) {
  2290. var positions = geometry.attributes[ 'position' ].array;
  2291. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  2292. v1.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  2293. v1.applyMatrix4( node.matrixWorld );
  2294. scope.expandByPoint( v1 );
  2295. }
  2296. }
  2297. }
  2298. } );
  2299. return this;
  2300. };
  2301. }(),
  2302. copy: function ( box ) {
  2303. this.min.copy( box.min );
  2304. this.max.copy( box.max );
  2305. return this;
  2306. },
  2307. makeEmpty: function () {
  2308. this.min.x = this.min.y = this.min.z = Infinity;
  2309. this.max.x = this.max.y = this.max.z = - Infinity;
  2310. return this;
  2311. },
  2312. empty: function () {
  2313. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2314. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2315. },
  2316. center: function ( optionalTarget ) {
  2317. var result = optionalTarget || new THREE.Vector3();
  2318. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2319. },
  2320. size: function ( optionalTarget ) {
  2321. var result = optionalTarget || new THREE.Vector3();
  2322. return result.subVectors( this.max, this.min );
  2323. },
  2324. expandByPoint: function ( point ) {
  2325. this.min.min( point );
  2326. this.max.max( point );
  2327. return this;
  2328. },
  2329. expandByVector: function ( vector ) {
  2330. this.min.sub( vector );
  2331. this.max.add( vector );
  2332. return this;
  2333. },
  2334. expandByScalar: function ( scalar ) {
  2335. this.min.addScalar( - scalar );
  2336. this.max.addScalar( scalar );
  2337. return this;
  2338. },
  2339. containsPoint: function ( point ) {
  2340. if ( point.x < this.min.x || point.x > this.max.x ||
  2341. point.y < this.min.y || point.y > this.max.y ||
  2342. point.z < this.min.z || point.z > this.max.z ) {
  2343. return false;
  2344. }
  2345. return true;
  2346. },
  2347. containsBox: function ( box ) {
  2348. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2349. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2350. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2351. return true;
  2352. }
  2353. return false;
  2354. },
  2355. getParameter: function ( point, optionalTarget ) {
  2356. // This can potentially have a divide by zero if the box
  2357. // has a size dimension of 0.
  2358. var result = optionalTarget || new THREE.Vector3();
  2359. return result.set(
  2360. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2361. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2362. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2363. );
  2364. },
  2365. isIntersectionBox: function ( box ) {
  2366. // using 6 splitting planes to rule out intersections.
  2367. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2368. box.max.y < this.min.y || box.min.y > this.max.y ||
  2369. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2370. return false;
  2371. }
  2372. return true;
  2373. },
  2374. clampPoint: function ( point, optionalTarget ) {
  2375. var result = optionalTarget || new THREE.Vector3();
  2376. return result.copy( point ).clamp( this.min, this.max );
  2377. },
  2378. distanceToPoint: function () {
  2379. var v1 = new THREE.Vector3();
  2380. return function ( point ) {
  2381. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2382. return clampedPoint.sub( point ).length();
  2383. };
  2384. }(),
  2385. getBoundingSphere: function () {
  2386. var v1 = new THREE.Vector3();
  2387. return function ( optionalTarget ) {
  2388. var result = optionalTarget || new THREE.Sphere();
  2389. result.center = this.center();
  2390. result.radius = this.size( v1 ).length() * 0.5;
  2391. return result;
  2392. };
  2393. }(),
  2394. intersect: function ( box ) {
  2395. this.min.max( box.min );
  2396. this.max.min( box.max );
  2397. return this;
  2398. },
  2399. union: function ( box ) {
  2400. this.min.min( box.min );
  2401. this.max.max( box.max );
  2402. return this;
  2403. },
  2404. applyMatrix4: function () {
  2405. var points = [
  2406. new THREE.Vector3(),
  2407. new THREE.Vector3(),
  2408. new THREE.Vector3(),
  2409. new THREE.Vector3(),
  2410. new THREE.Vector3(),
  2411. new THREE.Vector3(),
  2412. new THREE.Vector3(),
  2413. new THREE.Vector3()
  2414. ];
  2415. return function ( matrix ) {
  2416. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2417. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2418. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2419. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2420. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2421. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2422. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2423. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2424. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2425. this.makeEmpty();
  2426. this.setFromPoints( points );
  2427. return this;
  2428. };
  2429. }(),
  2430. translate: function ( offset ) {
  2431. this.min.add( offset );
  2432. this.max.add( offset );
  2433. return this;
  2434. },
  2435. equals: function ( box ) {
  2436. return box.min.equals( this.min ) && box.max.equals( this.max );
  2437. },
  2438. clone: function () {
  2439. return new THREE.Box3().copy( this );
  2440. }
  2441. };
  2442. // File:src/math/Matrix3.js
  2443. /**
  2444. * @author alteredq / http://alteredqualia.com/
  2445. * @author WestLangley / http://github.com/WestLangley
  2446. * @author bhouston / http://exocortex.com
  2447. */
  2448. THREE.Matrix3 = function () {
  2449. this.elements = new Float32Array( [
  2450. 1, 0, 0,
  2451. 0, 1, 0,
  2452. 0, 0, 1
  2453. ] );
  2454. if ( arguments.length > 0 ) {
  2455. THREE.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  2456. }
  2457. };
  2458. THREE.Matrix3.prototype = {
  2459. constructor: THREE.Matrix3,
  2460. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2461. var te = this.elements;
  2462. te[ 0 ] = n11; te[ 3 ] = n12; te[ 6 ] = n13;
  2463. te[ 1 ] = n21; te[ 4 ] = n22; te[ 7 ] = n23;
  2464. te[ 2 ] = n31; te[ 5 ] = n32; te[ 8 ] = n33;
  2465. return this;
  2466. },
  2467. identity: function () {
  2468. this.set(
  2469. 1, 0, 0,
  2470. 0, 1, 0,
  2471. 0, 0, 1
  2472. );
  2473. return this;
  2474. },
  2475. copy: function ( m ) {
  2476. var me = m.elements;
  2477. this.set(
  2478. me[ 0 ], me[ 3 ], me[ 6 ],
  2479. me[ 1 ], me[ 4 ], me[ 7 ],
  2480. me[ 2 ], me[ 5 ], me[ 8 ]
  2481. );
  2482. return this;
  2483. },
  2484. multiplyVector3: function ( vector ) {
  2485. THREE.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2486. return vector.applyMatrix3( this );
  2487. },
  2488. multiplyVector3Array: function ( a ) {
  2489. THREE.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2490. return this.applyToVector3Array( a );
  2491. },
  2492. applyToVector3Array: function () {
  2493. var v1 = new THREE.Vector3();
  2494. return function ( array, offset, length ) {
  2495. if ( offset === undefined ) offset = 0;
  2496. if ( length === undefined ) length = array.length;
  2497. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  2498. v1.x = array[ j ];
  2499. v1.y = array[ j + 1 ];
  2500. v1.z = array[ j + 2 ];
  2501. v1.applyMatrix3( this );
  2502. array[ j ] = v1.x;
  2503. array[ j + 1 ] = v1.y;
  2504. array[ j + 2 ] = v1.z;
  2505. }
  2506. return array;
  2507. };
  2508. }(),
  2509. multiplyScalar: function ( s ) {
  2510. var te = this.elements;
  2511. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  2512. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  2513. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  2514. return this;
  2515. },
  2516. determinant: function () {
  2517. var te = this.elements;
  2518. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  2519. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  2520. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  2521. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  2522. },
  2523. getInverse: function ( matrix, throwOnInvertible ) {
  2524. // input: THREE.Matrix4
  2525. // ( based on http://code.google.com/p/webgl-mjs/ )
  2526. var me = matrix.elements;
  2527. var te = this.elements;
  2528. te[ 0 ] = me[ 10 ] * me[ 5 ] - me[ 6 ] * me[ 9 ];
  2529. te[ 1 ] = - me[ 10 ] * me[ 1 ] + me[ 2 ] * me[ 9 ];
  2530. te[ 2 ] = me[ 6 ] * me[ 1 ] - me[ 2 ] * me[ 5 ];
  2531. te[ 3 ] = - me[ 10 ] * me[ 4 ] + me[ 6 ] * me[ 8 ];
  2532. te[ 4 ] = me[ 10 ] * me[ 0 ] - me[ 2 ] * me[ 8 ];
  2533. te[ 5 ] = - me[ 6 ] * me[ 0 ] + me[ 2 ] * me[ 4 ];
  2534. te[ 6 ] = me[ 9 ] * me[ 4 ] - me[ 5 ] * me[ 8 ];
  2535. te[ 7 ] = - me[ 9 ] * me[ 0 ] + me[ 1 ] * me[ 8 ];
  2536. te[ 8 ] = me[ 5 ] * me[ 0 ] - me[ 1 ] * me[ 4 ];
  2537. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2538. // no inverse
  2539. if ( det === 0 ) {
  2540. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2541. if ( throwOnInvertible || false ) {
  2542. throw new Error( msg );
  2543. } else {
  2544. THREE.warn( msg );
  2545. }
  2546. this.identity();
  2547. return this;
  2548. }
  2549. this.multiplyScalar( 1.0 / det );
  2550. return this;
  2551. },
  2552. transpose: function () {
  2553. var tmp, m = this.elements;
  2554. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  2555. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  2556. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  2557. return this;
  2558. },
  2559. flattenToArrayOffset: function ( array, offset ) {
  2560. var te = this.elements;
  2561. array[ offset ] = te[ 0 ];
  2562. array[ offset + 1 ] = te[ 1 ];
  2563. array[ offset + 2 ] = te[ 2 ];
  2564. array[ offset + 3 ] = te[ 3 ];
  2565. array[ offset + 4 ] = te[ 4 ];
  2566. array[ offset + 5 ] = te[ 5 ];
  2567. array[ offset + 6 ] = te[ 6 ];
  2568. array[ offset + 7 ] = te[ 7 ];
  2569. array[ offset + 8 ] = te[ 8 ];
  2570. return array;
  2571. },
  2572. getNormalMatrix: function ( m ) {
  2573. // input: THREE.Matrix4
  2574. this.getInverse( m ).transpose();
  2575. return this;
  2576. },
  2577. transposeIntoArray: function ( r ) {
  2578. var m = this.elements;
  2579. r[ 0 ] = m[ 0 ];
  2580. r[ 1 ] = m[ 3 ];
  2581. r[ 2 ] = m[ 6 ];
  2582. r[ 3 ] = m[ 1 ];
  2583. r[ 4 ] = m[ 4 ];
  2584. r[ 5 ] = m[ 7 ];
  2585. r[ 6 ] = m[ 2 ];
  2586. r[ 7 ] = m[ 5 ];
  2587. r[ 8 ] = m[ 8 ];
  2588. return this;
  2589. },
  2590. fromArray: function ( array ) {
  2591. this.elements.set( array );
  2592. return this;
  2593. },
  2594. toArray: function () {
  2595. var te = this.elements;
  2596. return [
  2597. te[ 0 ], te[ 1 ], te[ 2 ],
  2598. te[ 3 ], te[ 4 ], te[ 5 ],
  2599. te[ 6 ], te[ 7 ], te[ 8 ]
  2600. ];
  2601. },
  2602. clone: function () {
  2603. return new THREE.Matrix3().fromArray( this.elements );
  2604. }
  2605. };
  2606. // File:src/math/Matrix4.js
  2607. /**
  2608. * @author mrdoob / http://mrdoob.com/
  2609. * @author supereggbert / http://www.paulbrunt.co.uk/
  2610. * @author philogb / http://blog.thejit.org/
  2611. * @author jordi_ros / http://plattsoft.com
  2612. * @author D1plo1d / http://github.com/D1plo1d
  2613. * @author alteredq / http://alteredqualia.com/
  2614. * @author mikael emtinger / http://gomo.se/
  2615. * @author timknip / http://www.floorplanner.com/
  2616. * @author bhouston / http://exocortex.com
  2617. * @author WestLangley / http://github.com/WestLangley
  2618. */
  2619. THREE.Matrix4 = function () {
  2620. this.elements = new Float32Array( [
  2621. 1, 0, 0, 0,
  2622. 0, 1, 0, 0,
  2623. 0, 0, 1, 0,
  2624. 0, 0, 0, 1
  2625. ] );
  2626. if ( arguments.length > 0 ) {
  2627. THREE.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  2628. }
  2629. };
  2630. THREE.Matrix4.prototype = {
  2631. constructor: THREE.Matrix4,
  2632. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2633. var te = this.elements;
  2634. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  2635. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  2636. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  2637. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  2638. return this;
  2639. },
  2640. identity: function () {
  2641. this.set(
  2642. 1, 0, 0, 0,
  2643. 0, 1, 0, 0,
  2644. 0, 0, 1, 0,
  2645. 0, 0, 0, 1
  2646. );
  2647. return this;
  2648. },
  2649. copy: function ( m ) {
  2650. this.elements.set( m.elements );
  2651. return this;
  2652. },
  2653. extractPosition: function ( m ) {
  2654. THREE.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  2655. return this.copyPosition( m );
  2656. },
  2657. copyPosition: function ( m ) {
  2658. var te = this.elements;
  2659. var me = m.elements;
  2660. te[ 12 ] = me[ 12 ];
  2661. te[ 13 ] = me[ 13 ];
  2662. te[ 14 ] = me[ 14 ];
  2663. return this;
  2664. },
  2665. extractBasis: function ( xAxis, yAxis, zAxis ) {
  2666. var te = this.elements;
  2667. xAxis.set( te[ 0 ], te[ 1 ], te[ 2 ] );
  2668. yAxis.set( te[ 4 ], te[ 5 ], te[ 6 ] );
  2669. zAxis.set( te[ 8 ], te[ 9 ], te[ 10 ] );
  2670. return this;
  2671. },
  2672. makeBasis: function ( xAxis, yAxis, zAxis ) {
  2673. this.set(
  2674. xAxis.x, yAxis.x, zAxis.x, 0,
  2675. xAxis.y, yAxis.y, zAxis.y, 0,
  2676. xAxis.z, yAxis.z, zAxis.z, 0,
  2677. 0, 0, 0, 1
  2678. );
  2679. return this;
  2680. },
  2681. extractRotation: function () {
  2682. var v1 = new THREE.Vector3();
  2683. return function ( m ) {
  2684. var te = this.elements;
  2685. var me = m.elements;
  2686. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  2687. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  2688. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  2689. te[ 0 ] = me[ 0 ] * scaleX;
  2690. te[ 1 ] = me[ 1 ] * scaleX;
  2691. te[ 2 ] = me[ 2 ] * scaleX;
  2692. te[ 4 ] = me[ 4 ] * scaleY;
  2693. te[ 5 ] = me[ 5 ] * scaleY;
  2694. te[ 6 ] = me[ 6 ] * scaleY;
  2695. te[ 8 ] = me[ 8 ] * scaleZ;
  2696. te[ 9 ] = me[ 9 ] * scaleZ;
  2697. te[ 10 ] = me[ 10 ] * scaleZ;
  2698. return this;
  2699. };
  2700. }(),
  2701. makeRotationFromEuler: function ( euler ) {
  2702. if ( euler instanceof THREE.Euler === false ) {
  2703. THREE.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  2704. }
  2705. var te = this.elements;
  2706. var x = euler.x, y = euler.y, z = euler.z;
  2707. var a = Math.cos( x ), b = Math.sin( x );
  2708. var c = Math.cos( y ), d = Math.sin( y );
  2709. var e = Math.cos( z ), f = Math.sin( z );
  2710. if ( euler.order === 'XYZ' ) {
  2711. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2712. te[ 0 ] = c * e;
  2713. te[ 4 ] = - c * f;
  2714. te[ 8 ] = d;
  2715. te[ 1 ] = af + be * d;
  2716. te[ 5 ] = ae - bf * d;
  2717. te[ 9 ] = - b * c;
  2718. te[ 2 ] = bf - ae * d;
  2719. te[ 6 ] = be + af * d;
  2720. te[ 10 ] = a * c;
  2721. } else if ( euler.order === 'YXZ' ) {
  2722. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2723. te[ 0 ] = ce + df * b;
  2724. te[ 4 ] = de * b - cf;
  2725. te[ 8 ] = a * d;
  2726. te[ 1 ] = a * f;
  2727. te[ 5 ] = a * e;
  2728. te[ 9 ] = - b;
  2729. te[ 2 ] = cf * b - de;
  2730. te[ 6 ] = df + ce * b;
  2731. te[ 10 ] = a * c;
  2732. } else if ( euler.order === 'ZXY' ) {
  2733. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2734. te[ 0 ] = ce - df * b;
  2735. te[ 4 ] = - a * f;
  2736. te[ 8 ] = de + cf * b;
  2737. te[ 1 ] = cf + de * b;
  2738. te[ 5 ] = a * e;
  2739. te[ 9 ] = df - ce * b;
  2740. te[ 2 ] = - a * d;
  2741. te[ 6 ] = b;
  2742. te[ 10 ] = a * c;
  2743. } else if ( euler.order === 'ZYX' ) {
  2744. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2745. te[ 0 ] = c * e;
  2746. te[ 4 ] = be * d - af;
  2747. te[ 8 ] = ae * d + bf;
  2748. te[ 1 ] = c * f;
  2749. te[ 5 ] = bf * d + ae;
  2750. te[ 9 ] = af * d - be;
  2751. te[ 2 ] = - d;
  2752. te[ 6 ] = b * c;
  2753. te[ 10 ] = a * c;
  2754. } else if ( euler.order === 'YZX' ) {
  2755. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2756. te[ 0 ] = c * e;
  2757. te[ 4 ] = bd - ac * f;
  2758. te[ 8 ] = bc * f + ad;
  2759. te[ 1 ] = f;
  2760. te[ 5 ] = a * e;
  2761. te[ 9 ] = - b * e;
  2762. te[ 2 ] = - d * e;
  2763. te[ 6 ] = ad * f + bc;
  2764. te[ 10 ] = ac - bd * f;
  2765. } else if ( euler.order === 'XZY' ) {
  2766. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2767. te[ 0 ] = c * e;
  2768. te[ 4 ] = - f;
  2769. te[ 8 ] = d * e;
  2770. te[ 1 ] = ac * f + bd;
  2771. te[ 5 ] = a * e;
  2772. te[ 9 ] = ad * f - bc;
  2773. te[ 2 ] = bc * f - ad;
  2774. te[ 6 ] = b * e;
  2775. te[ 10 ] = bd * f + ac;
  2776. }
  2777. // last column
  2778. te[ 3 ] = 0;
  2779. te[ 7 ] = 0;
  2780. te[ 11 ] = 0;
  2781. // bottom row
  2782. te[ 12 ] = 0;
  2783. te[ 13 ] = 0;
  2784. te[ 14 ] = 0;
  2785. te[ 15 ] = 1;
  2786. return this;
  2787. },
  2788. setRotationFromQuaternion: function ( q ) {
  2789. THREE.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  2790. return this.makeRotationFromQuaternion( q );
  2791. },
  2792. makeRotationFromQuaternion: function ( q ) {
  2793. var te = this.elements;
  2794. var x = q.x, y = q.y, z = q.z, w = q.w;
  2795. var x2 = x + x, y2 = y + y, z2 = z + z;
  2796. var xx = x * x2, xy = x * y2, xz = x * z2;
  2797. var yy = y * y2, yz = y * z2, zz = z * z2;
  2798. var wx = w * x2, wy = w * y2, wz = w * z2;
  2799. te[ 0 ] = 1 - ( yy + zz );
  2800. te[ 4 ] = xy - wz;
  2801. te[ 8 ] = xz + wy;
  2802. te[ 1 ] = xy + wz;
  2803. te[ 5 ] = 1 - ( xx + zz );
  2804. te[ 9 ] = yz - wx;
  2805. te[ 2 ] = xz - wy;
  2806. te[ 6 ] = yz + wx;
  2807. te[ 10 ] = 1 - ( xx + yy );
  2808. // last column
  2809. te[ 3 ] = 0;
  2810. te[ 7 ] = 0;
  2811. te[ 11 ] = 0;
  2812. // bottom row
  2813. te[ 12 ] = 0;
  2814. te[ 13 ] = 0;
  2815. te[ 14 ] = 0;
  2816. te[ 15 ] = 1;
  2817. return this;
  2818. },
  2819. lookAt: function () {
  2820. var x = new THREE.Vector3();
  2821. var y = new THREE.Vector3();
  2822. var z = new THREE.Vector3();
  2823. return function ( eye, target, up ) {
  2824. var te = this.elements;
  2825. z.subVectors( eye, target ).normalize();
  2826. if ( z.length() === 0 ) {
  2827. z.z = 1;
  2828. }
  2829. x.crossVectors( up, z ).normalize();
  2830. if ( x.length() === 0 ) {
  2831. z.x += 0.0001;
  2832. x.crossVectors( up, z ).normalize();
  2833. }
  2834. y.crossVectors( z, x );
  2835. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  2836. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  2837. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  2838. return this;
  2839. };
  2840. }(),
  2841. multiply: function ( m, n ) {
  2842. if ( n !== undefined ) {
  2843. THREE.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2844. return this.multiplyMatrices( m, n );
  2845. }
  2846. return this.multiplyMatrices( this, m );
  2847. },
  2848. multiplyMatrices: function ( a, b ) {
  2849. var ae = a.elements;
  2850. var be = b.elements;
  2851. var te = this.elements;
  2852. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  2853. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  2854. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  2855. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  2856. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  2857. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  2858. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  2859. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  2860. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2861. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2862. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2863. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2864. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2865. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2866. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2867. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2868. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2869. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2870. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2871. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2872. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2873. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2874. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2875. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2876. return this;
  2877. },
  2878. multiplyToArray: function ( a, b, r ) {
  2879. var te = this.elements;
  2880. this.multiplyMatrices( a, b );
  2881. r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ];
  2882. r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ];
  2883. r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ];
  2884. r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ];
  2885. return this;
  2886. },
  2887. multiplyScalar: function ( s ) {
  2888. var te = this.elements;
  2889. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  2890. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  2891. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  2892. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  2893. return this;
  2894. },
  2895. multiplyVector3: function ( vector ) {
  2896. THREE.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2897. return vector.applyProjection( this );
  2898. },
  2899. multiplyVector4: function ( vector ) {
  2900. THREE.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2901. return vector.applyMatrix4( this );
  2902. },
  2903. multiplyVector3Array: function ( a ) {
  2904. THREE.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2905. return this.applyToVector3Array( a );
  2906. },
  2907. applyToVector3Array: function () {
  2908. var v1 = new THREE.Vector3();
  2909. return function ( array, offset, length ) {
  2910. if ( offset === undefined ) offset = 0;
  2911. if ( length === undefined ) length = array.length;
  2912. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  2913. v1.x = array[ j ];
  2914. v1.y = array[ j + 1 ];
  2915. v1.z = array[ j + 2 ];
  2916. v1.applyMatrix4( this );
  2917. array[ j ] = v1.x;
  2918. array[ j + 1 ] = v1.y;
  2919. array[ j + 2 ] = v1.z;
  2920. }
  2921. return array;
  2922. };
  2923. }(),
  2924. rotateAxis: function ( v ) {
  2925. THREE.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2926. v.transformDirection( this );
  2927. },
  2928. crossVector: function ( vector ) {
  2929. THREE.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2930. return vector.applyMatrix4( this );
  2931. },
  2932. determinant: function () {
  2933. var te = this.elements;
  2934. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  2935. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  2936. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  2937. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  2938. //TODO: make this more efficient
  2939. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2940. return (
  2941. n41 * (
  2942. + n14 * n23 * n32
  2943. - n13 * n24 * n32
  2944. - n14 * n22 * n33
  2945. + n12 * n24 * n33
  2946. + n13 * n22 * n34
  2947. - n12 * n23 * n34
  2948. ) +
  2949. n42 * (
  2950. + n11 * n23 * n34
  2951. - n11 * n24 * n33
  2952. + n14 * n21 * n33
  2953. - n13 * n21 * n34
  2954. + n13 * n24 * n31
  2955. - n14 * n23 * n31
  2956. ) +
  2957. n43 * (
  2958. + n11 * n24 * n32
  2959. - n11 * n22 * n34
  2960. - n14 * n21 * n32
  2961. + n12 * n21 * n34
  2962. + n14 * n22 * n31
  2963. - n12 * n24 * n31
  2964. ) +
  2965. n44 * (
  2966. - n13 * n22 * n31
  2967. - n11 * n23 * n32
  2968. + n11 * n22 * n33
  2969. + n13 * n21 * n32
  2970. - n12 * n21 * n33
  2971. + n12 * n23 * n31
  2972. )
  2973. );
  2974. },
  2975. transpose: function () {
  2976. var te = this.elements;
  2977. var tmp;
  2978. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  2979. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  2980. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  2981. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  2982. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  2983. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  2984. return this;
  2985. },
  2986. flattenToArrayOffset: function ( array, offset ) {
  2987. var te = this.elements;
  2988. array[ offset ] = te[ 0 ];
  2989. array[ offset + 1 ] = te[ 1 ];
  2990. array[ offset + 2 ] = te[ 2 ];
  2991. array[ offset + 3 ] = te[ 3 ];
  2992. array[ offset + 4 ] = te[ 4 ];
  2993. array[ offset + 5 ] = te[ 5 ];
  2994. array[ offset + 6 ] = te[ 6 ];
  2995. array[ offset + 7 ] = te[ 7 ];
  2996. array[ offset + 8 ] = te[ 8 ];
  2997. array[ offset + 9 ] = te[ 9 ];
  2998. array[ offset + 10 ] = te[ 10 ];
  2999. array[ offset + 11 ] = te[ 11 ];
  3000. array[ offset + 12 ] = te[ 12 ];
  3001. array[ offset + 13 ] = te[ 13 ];
  3002. array[ offset + 14 ] = te[ 14 ];
  3003. array[ offset + 15 ] = te[ 15 ];
  3004. return array;
  3005. },
  3006. getPosition: function () {
  3007. var v1 = new THREE.Vector3();
  3008. return function () {
  3009. THREE.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  3010. var te = this.elements;
  3011. return v1.set( te[ 12 ], te[ 13 ], te[ 14 ] );
  3012. };
  3013. }(),
  3014. setPosition: function ( v ) {
  3015. var te = this.elements;
  3016. te[ 12 ] = v.x;
  3017. te[ 13 ] = v.y;
  3018. te[ 14 ] = v.z;
  3019. return this;
  3020. },
  3021. getInverse: function ( m, throwOnInvertible ) {
  3022. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3023. var te = this.elements;
  3024. var me = m.elements;
  3025. var n11 = me[ 0 ], n12 = me[ 4 ], n13 = me[ 8 ], n14 = me[ 12 ];
  3026. var n21 = me[ 1 ], n22 = me[ 5 ], n23 = me[ 9 ], n24 = me[ 13 ];
  3027. var n31 = me[ 2 ], n32 = me[ 6 ], n33 = me[ 10 ], n34 = me[ 14 ];
  3028. var n41 = me[ 3 ], n42 = me[ 7 ], n43 = me[ 11 ], n44 = me[ 15 ];
  3029. te[ 0 ] = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44;
  3030. te[ 4 ] = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44;
  3031. te[ 8 ] = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44;
  3032. te[ 12 ] = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3033. te[ 1 ] = n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44;
  3034. te[ 5 ] = n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44;
  3035. te[ 9 ] = n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44;
  3036. te[ 13 ] = n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34;
  3037. te[ 2 ] = n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44;
  3038. te[ 6 ] = n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44;
  3039. te[ 10 ] = n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44;
  3040. te[ 14 ] = n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34;
  3041. te[ 3 ] = n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43;
  3042. te[ 7 ] = n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43;
  3043. te[ 11 ] = n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43;
  3044. te[ 15 ] = n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33;
  3045. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  3046. if ( det == 0 ) {
  3047. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  3048. if ( throwOnInvertible || false ) {
  3049. throw new Error( msg );
  3050. } else {
  3051. THREE.warn( msg );
  3052. }
  3053. this.identity();
  3054. return this;
  3055. }
  3056. this.multiplyScalar( 1 / det );
  3057. return this;
  3058. },
  3059. translate: function ( v ) {
  3060. THREE.error( 'THREE.Matrix4: .translate() has been removed.' );
  3061. },
  3062. rotateX: function ( angle ) {
  3063. THREE.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  3064. },
  3065. rotateY: function ( angle ) {
  3066. THREE.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  3067. },
  3068. rotateZ: function ( angle ) {
  3069. THREE.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  3070. },
  3071. rotateByAxis: function ( axis, angle ) {
  3072. THREE.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  3073. },
  3074. scale: function ( v ) {
  3075. var te = this.elements;
  3076. var x = v.x, y = v.y, z = v.z;
  3077. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3078. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3079. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3080. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3081. return this;
  3082. },
  3083. getMaxScaleOnAxis: function () {
  3084. var te = this.elements;
  3085. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3086. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3087. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3088. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  3089. },
  3090. makeTranslation: function ( x, y, z ) {
  3091. this.set(
  3092. 1, 0, 0, x,
  3093. 0, 1, 0, y,
  3094. 0, 0, 1, z,
  3095. 0, 0, 0, 1
  3096. );
  3097. return this;
  3098. },
  3099. makeRotationX: function ( theta ) {
  3100. var c = Math.cos( theta ), s = Math.sin( theta );
  3101. this.set(
  3102. 1, 0, 0, 0,
  3103. 0, c, - s, 0,
  3104. 0, s, c, 0,
  3105. 0, 0, 0, 1
  3106. );
  3107. return this;
  3108. },
  3109. makeRotationY: function ( theta ) {
  3110. var c = Math.cos( theta ), s = Math.sin( theta );
  3111. this.set(
  3112. c, 0, s, 0,
  3113. 0, 1, 0, 0,
  3114. - s, 0, c, 0,
  3115. 0, 0, 0, 1
  3116. );
  3117. return this;
  3118. },
  3119. makeRotationZ: function ( theta ) {
  3120. var c = Math.cos( theta ), s = Math.sin( theta );
  3121. this.set(
  3122. c, - s, 0, 0,
  3123. s, c, 0, 0,
  3124. 0, 0, 1, 0,
  3125. 0, 0, 0, 1
  3126. );
  3127. return this;
  3128. },
  3129. makeRotationAxis: function ( axis, angle ) {
  3130. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3131. var c = Math.cos( angle );
  3132. var s = Math.sin( angle );
  3133. var t = 1 - c;
  3134. var x = axis.x, y = axis.y, z = axis.z;
  3135. var tx = t * x, ty = t * y;
  3136. this.set(
  3137. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3138. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3139. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3140. 0, 0, 0, 1
  3141. );
  3142. return this;
  3143. },
  3144. makeScale: function ( x, y, z ) {
  3145. this.set(
  3146. x, 0, 0, 0,
  3147. 0, y, 0, 0,
  3148. 0, 0, z, 0,
  3149. 0, 0, 0, 1
  3150. );
  3151. return this;
  3152. },
  3153. compose: function ( position, quaternion, scale ) {
  3154. this.makeRotationFromQuaternion( quaternion );
  3155. this.scale( scale );
  3156. this.setPosition( position );
  3157. return this;
  3158. },
  3159. decompose: function () {
  3160. var vector = new THREE.Vector3();
  3161. var matrix = new THREE.Matrix4();
  3162. return function ( position, quaternion, scale ) {
  3163. var te = this.elements;
  3164. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3165. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3166. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3167. // if determine is negative, we need to invert one scale
  3168. var det = this.determinant();
  3169. if ( det < 0 ) {
  3170. sx = - sx;
  3171. }
  3172. position.x = te[ 12 ];
  3173. position.y = te[ 13 ];
  3174. position.z = te[ 14 ];
  3175. // scale the rotation part
  3176. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  3177. var invSX = 1 / sx;
  3178. var invSY = 1 / sy;
  3179. var invSZ = 1 / sz;
  3180. matrix.elements[ 0 ] *= invSX;
  3181. matrix.elements[ 1 ] *= invSX;
  3182. matrix.elements[ 2 ] *= invSX;
  3183. matrix.elements[ 4 ] *= invSY;
  3184. matrix.elements[ 5 ] *= invSY;
  3185. matrix.elements[ 6 ] *= invSY;
  3186. matrix.elements[ 8 ] *= invSZ;
  3187. matrix.elements[ 9 ] *= invSZ;
  3188. matrix.elements[ 10 ] *= invSZ;
  3189. quaternion.setFromRotationMatrix( matrix );
  3190. scale.x = sx;
  3191. scale.y = sy;
  3192. scale.z = sz;
  3193. return this;
  3194. };
  3195. }(),
  3196. makeFrustum: function ( left, right, bottom, top, near, far ) {
  3197. var te = this.elements;
  3198. var x = 2 * near / ( right - left );
  3199. var y = 2 * near / ( top - bottom );
  3200. var a = ( right + left ) / ( right - left );
  3201. var b = ( top + bottom ) / ( top - bottom );
  3202. var c = - ( far + near ) / ( far - near );
  3203. var d = - 2 * far * near / ( far - near );
  3204. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3205. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3206. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3207. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3208. return this;
  3209. },
  3210. makePerspective: function ( fov, aspect, near, far ) {
  3211. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  3212. var ymin = - ymax;
  3213. var xmin = ymin * aspect;
  3214. var xmax = ymax * aspect;
  3215. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  3216. },
  3217. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  3218. var te = this.elements;
  3219. var w = right - left;
  3220. var h = top - bottom;
  3221. var p = far - near;
  3222. var x = ( right + left ) / w;
  3223. var y = ( top + bottom ) / h;
  3224. var z = ( far + near ) / p;
  3225. te[ 0 ] = 2 / w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3226. te[ 1 ] = 0; te[ 5 ] = 2 / h; te[ 9 ] = 0; te[ 13 ] = - y;
  3227. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 / p; te[ 14 ] = - z;
  3228. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3229. return this;
  3230. },
  3231. fromArray: function ( array ) {
  3232. this.elements.set( array );
  3233. return this;
  3234. },
  3235. toArray: function () {
  3236. var te = this.elements;
  3237. return [
  3238. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  3239. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  3240. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  3241. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  3242. ];
  3243. },
  3244. clone: function () {
  3245. return new THREE.Matrix4().fromArray( this.elements );
  3246. }
  3247. };
  3248. // File:src/math/Ray.js
  3249. /**
  3250. * @author bhouston / http://exocortex.com
  3251. */
  3252. THREE.Ray = function ( origin, direction ) {
  3253. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  3254. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  3255. };
  3256. THREE.Ray.prototype = {
  3257. constructor: THREE.Ray,
  3258. set: function ( origin, direction ) {
  3259. this.origin.copy( origin );
  3260. this.direction.copy( direction );
  3261. return this;
  3262. },
  3263. copy: function ( ray ) {
  3264. this.origin.copy( ray.origin );
  3265. this.direction.copy( ray.direction );
  3266. return this;
  3267. },
  3268. at: function ( t, optionalTarget ) {
  3269. var result = optionalTarget || new THREE.Vector3();
  3270. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3271. },
  3272. recast: function () {
  3273. var v1 = new THREE.Vector3();
  3274. return function ( t ) {
  3275. this.origin.copy( this.at( t, v1 ) );
  3276. return this;
  3277. };
  3278. }(),
  3279. closestPointToPoint: function ( point, optionalTarget ) {
  3280. var result = optionalTarget || new THREE.Vector3();
  3281. result.subVectors( point, this.origin );
  3282. var directionDistance = result.dot( this.direction );
  3283. if ( directionDistance < 0 ) {
  3284. return result.copy( this.origin );
  3285. }
  3286. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3287. },
  3288. distanceToPoint: function () {
  3289. var v1 = new THREE.Vector3();
  3290. return function ( point ) {
  3291. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3292. // point behind the ray
  3293. if ( directionDistance < 0 ) {
  3294. return this.origin.distanceTo( point );
  3295. }
  3296. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3297. return v1.distanceTo( point );
  3298. };
  3299. }(),
  3300. distanceSqToSegment: function () {
  3301. var segCenter = new THREE.Vector3();
  3302. var segDir = new THREE.Vector3();
  3303. var diff = new THREE.Vector3();
  3304. return function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3305. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3306. // It returns the min distance between the ray and the segment
  3307. // defined by v0 and v1
  3308. // It can also set two optional targets :
  3309. // - The closest point on the ray
  3310. // - The closest point on the segment
  3311. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3312. segDir.copy( v1 ).sub( v0 ).normalize();
  3313. diff.copy( this.origin ).sub( segCenter );
  3314. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3315. var a01 = - this.direction.dot( segDir );
  3316. var b0 = diff.dot( this.direction );
  3317. var b1 = - diff.dot( segDir );
  3318. var c = diff.lengthSq();
  3319. var det = Math.abs( 1 - a01 * a01 );
  3320. var s0, s1, sqrDist, extDet;
  3321. if ( det > 0 ) {
  3322. // The ray and segment are not parallel.
  3323. s0 = a01 * b1 - b0;
  3324. s1 = a01 * b0 - b1;
  3325. extDet = segExtent * det;
  3326. if ( s0 >= 0 ) {
  3327. if ( s1 >= - extDet ) {
  3328. if ( s1 <= extDet ) {
  3329. // region 0
  3330. // Minimum at interior points of ray and segment.
  3331. var invDet = 1 / det;
  3332. s0 *= invDet;
  3333. s1 *= invDet;
  3334. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3335. } else {
  3336. // region 1
  3337. s1 = segExtent;
  3338. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3339. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3340. }
  3341. } else {
  3342. // region 5
  3343. s1 = - segExtent;
  3344. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3345. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3346. }
  3347. } else {
  3348. if ( s1 <= - extDet ) {
  3349. // region 4
  3350. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3351. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3352. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3353. } else if ( s1 <= extDet ) {
  3354. // region 3
  3355. s0 = 0;
  3356. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3357. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3358. } else {
  3359. // region 2
  3360. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3361. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3362. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3363. }
  3364. }
  3365. } else {
  3366. // Ray and segment are parallel.
  3367. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3368. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3369. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3370. }
  3371. if ( optionalPointOnRay ) {
  3372. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  3373. }
  3374. if ( optionalPointOnSegment ) {
  3375. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  3376. }
  3377. return sqrDist;
  3378. };
  3379. }(),
  3380. isIntersectionSphere: function ( sphere ) {
  3381. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3382. },
  3383. intersectSphere: function () {
  3384. // from http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-sphere-intersection/
  3385. var v1 = new THREE.Vector3();
  3386. return function ( sphere, optionalTarget ) {
  3387. v1.subVectors( sphere.center, this.origin );
  3388. var tca = v1.dot( this.direction );
  3389. var d2 = v1.dot( v1 ) - tca * tca;
  3390. var radius2 = sphere.radius * sphere.radius;
  3391. if ( d2 > radius2 ) return null;
  3392. var thc = Math.sqrt( radius2 - d2 );
  3393. // t0 = first intersect point - entrance on front of sphere
  3394. var t0 = tca - thc;
  3395. // t1 = second intersect point - exit point on back of sphere
  3396. var t1 = tca + thc;
  3397. // test to see if both t0 and t1 are behind the ray - if so, return null
  3398. if ( t0 < 0 && t1 < 0 ) return null;
  3399. // test to see if t0 is behind the ray:
  3400. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3401. // in order to always return an intersect point that is in front of the ray.
  3402. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  3403. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3404. return this.at( t0, optionalTarget );
  3405. }
  3406. }(),
  3407. isIntersectionPlane: function ( plane ) {
  3408. // check if the ray lies on the plane first
  3409. var distToPoint = plane.distanceToPoint( this.origin );
  3410. if ( distToPoint === 0 ) {
  3411. return true;
  3412. }
  3413. var denominator = plane.normal.dot( this.direction );
  3414. if ( denominator * distToPoint < 0 ) {
  3415. return true;
  3416. }
  3417. // ray origin is behind the plane (and is pointing behind it)
  3418. return false;
  3419. },
  3420. distanceToPlane: function ( plane ) {
  3421. var denominator = plane.normal.dot( this.direction );
  3422. if ( denominator == 0 ) {
  3423. // line is coplanar, return origin
  3424. if ( plane.distanceToPoint( this.origin ) == 0 ) {
  3425. return 0;
  3426. }
  3427. // Null is preferable to undefined since undefined means.... it is undefined
  3428. return null;
  3429. }
  3430. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3431. // Return if the ray never intersects the plane
  3432. return t >= 0 ? t : null;
  3433. },
  3434. intersectPlane: function ( plane, optionalTarget ) {
  3435. var t = this.distanceToPlane( plane );
  3436. if ( t === null ) {
  3437. return null;
  3438. }
  3439. return this.at( t, optionalTarget );
  3440. },
  3441. isIntersectionBox: function () {
  3442. var v = new THREE.Vector3();
  3443. return function ( box ) {
  3444. return this.intersectBox( box, v ) !== null;
  3445. };
  3446. }(),
  3447. intersectBox: function ( box, optionalTarget ) {
  3448. // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
  3449. var tmin,tmax,tymin,tymax,tzmin,tzmax;
  3450. var invdirx = 1 / this.direction.x,
  3451. invdiry = 1 / this.direction.y,
  3452. invdirz = 1 / this.direction.z;
  3453. var origin = this.origin;
  3454. if ( invdirx >= 0 ) {
  3455. tmin = ( box.min.x - origin.x ) * invdirx;
  3456. tmax = ( box.max.x - origin.x ) * invdirx;
  3457. } else {
  3458. tmin = ( box.max.x - origin.x ) * invdirx;
  3459. tmax = ( box.min.x - origin.x ) * invdirx;
  3460. }
  3461. if ( invdiry >= 0 ) {
  3462. tymin = ( box.min.y - origin.y ) * invdiry;
  3463. tymax = ( box.max.y - origin.y ) * invdiry;
  3464. } else {
  3465. tymin = ( box.max.y - origin.y ) * invdiry;
  3466. tymax = ( box.min.y - origin.y ) * invdiry;
  3467. }
  3468. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3469. // These lines also handle the case where tmin or tmax is NaN
  3470. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3471. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3472. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3473. if ( invdirz >= 0 ) {
  3474. tzmin = ( box.min.z - origin.z ) * invdirz;
  3475. tzmax = ( box.max.z - origin.z ) * invdirz;
  3476. } else {
  3477. tzmin = ( box.max.z - origin.z ) * invdirz;
  3478. tzmax = ( box.min.z - origin.z ) * invdirz;
  3479. }
  3480. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3481. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3482. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3483. //return point closest to the ray (positive side)
  3484. if ( tmax < 0 ) return null;
  3485. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3486. },
  3487. intersectTriangle: function () {
  3488. // Compute the offset origin, edges, and normal.
  3489. var diff = new THREE.Vector3();
  3490. var edge1 = new THREE.Vector3();
  3491. var edge2 = new THREE.Vector3();
  3492. var normal = new THREE.Vector3();
  3493. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3494. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3495. edge1.subVectors( b, a );
  3496. edge2.subVectors( c, a );
  3497. normal.crossVectors( edge1, edge2 );
  3498. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3499. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3500. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3501. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3502. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3503. var DdN = this.direction.dot( normal );
  3504. var sign;
  3505. if ( DdN > 0 ) {
  3506. if ( backfaceCulling ) return null;
  3507. sign = 1;
  3508. } else if ( DdN < 0 ) {
  3509. sign = - 1;
  3510. DdN = - DdN;
  3511. } else {
  3512. return null;
  3513. }
  3514. diff.subVectors( this.origin, a );
  3515. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3516. // b1 < 0, no intersection
  3517. if ( DdQxE2 < 0 ) {
  3518. return null;
  3519. }
  3520. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3521. // b2 < 0, no intersection
  3522. if ( DdE1xQ < 0 ) {
  3523. return null;
  3524. }
  3525. // b1+b2 > 1, no intersection
  3526. if ( DdQxE2 + DdE1xQ > DdN ) {
  3527. return null;
  3528. }
  3529. // Line intersects triangle, check if ray does.
  3530. var QdN = - sign * diff.dot( normal );
  3531. // t < 0, no intersection
  3532. if ( QdN < 0 ) {
  3533. return null;
  3534. }
  3535. // Ray intersects triangle.
  3536. return this.at( QdN / DdN, optionalTarget );
  3537. };
  3538. }(),
  3539. applyMatrix4: function ( matrix4 ) {
  3540. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3541. this.origin.applyMatrix4( matrix4 );
  3542. this.direction.sub( this.origin );
  3543. this.direction.normalize();
  3544. return this;
  3545. },
  3546. equals: function ( ray ) {
  3547. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3548. },
  3549. clone: function () {
  3550. return new THREE.Ray().copy( this );
  3551. }
  3552. };
  3553. // File:src/math/Sphere.js
  3554. /**
  3555. * @author bhouston / http://exocortex.com
  3556. * @author mrdoob / http://mrdoob.com/
  3557. */
  3558. THREE.Sphere = function ( center, radius ) {
  3559. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3560. this.radius = ( radius !== undefined ) ? radius : 0;
  3561. };
  3562. THREE.Sphere.prototype = {
  3563. constructor: THREE.Sphere,
  3564. set: function ( center, radius ) {
  3565. this.center.copy( center );
  3566. this.radius = radius;
  3567. return this;
  3568. },
  3569. setFromPoints: function () {
  3570. var box = new THREE.Box3();
  3571. return function ( points, optionalCenter ) {
  3572. var center = this.center;
  3573. if ( optionalCenter !== undefined ) {
  3574. center.copy( optionalCenter );
  3575. } else {
  3576. box.setFromPoints( points ).center( center );
  3577. }
  3578. var maxRadiusSq = 0;
  3579. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3580. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3581. }
  3582. this.radius = Math.sqrt( maxRadiusSq );
  3583. return this;
  3584. };
  3585. }(),
  3586. copy: function ( sphere ) {
  3587. this.center.copy( sphere.center );
  3588. this.radius = sphere.radius;
  3589. return this;
  3590. },
  3591. empty: function () {
  3592. return ( this.radius <= 0 );
  3593. },
  3594. containsPoint: function ( point ) {
  3595. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3596. },
  3597. distanceToPoint: function ( point ) {
  3598. return ( point.distanceTo( this.center ) - this.radius );
  3599. },
  3600. intersectsSphere: function ( sphere ) {
  3601. var radiusSum = this.radius + sphere.radius;
  3602. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3603. },
  3604. clampPoint: function ( point, optionalTarget ) {
  3605. var deltaLengthSq = this.center.distanceToSquared( point );
  3606. var result = optionalTarget || new THREE.Vector3();
  3607. result.copy( point );
  3608. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3609. result.sub( this.center ).normalize();
  3610. result.multiplyScalar( this.radius ).add( this.center );
  3611. }
  3612. return result;
  3613. },
  3614. getBoundingBox: function ( optionalTarget ) {
  3615. var box = optionalTarget || new THREE.Box3();
  3616. box.set( this.center, this.center );
  3617. box.expandByScalar( this.radius );
  3618. return box;
  3619. },
  3620. applyMatrix4: function ( matrix ) {
  3621. this.center.applyMatrix4( matrix );
  3622. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3623. return this;
  3624. },
  3625. translate: function ( offset ) {
  3626. this.center.add( offset );
  3627. return this;
  3628. },
  3629. equals: function ( sphere ) {
  3630. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3631. },
  3632. clone: function () {
  3633. return new THREE.Sphere().copy( this );
  3634. }
  3635. };
  3636. // File:src/math/Frustum.js
  3637. /**
  3638. * @author mrdoob / http://mrdoob.com/
  3639. * @author alteredq / http://alteredqualia.com/
  3640. * @author bhouston / http://exocortex.com
  3641. */
  3642. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3643. this.planes = [
  3644. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3645. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3646. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3647. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3648. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3649. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3650. ];
  3651. };
  3652. THREE.Frustum.prototype = {
  3653. constructor: THREE.Frustum,
  3654. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3655. var planes = this.planes;
  3656. planes[ 0 ].copy( p0 );
  3657. planes[ 1 ].copy( p1 );
  3658. planes[ 2 ].copy( p2 );
  3659. planes[ 3 ].copy( p3 );
  3660. planes[ 4 ].copy( p4 );
  3661. planes[ 5 ].copy( p5 );
  3662. return this;
  3663. },
  3664. copy: function ( frustum ) {
  3665. var planes = this.planes;
  3666. for ( var i = 0; i < 6; i ++ ) {
  3667. planes[ i ].copy( frustum.planes[ i ] );
  3668. }
  3669. return this;
  3670. },
  3671. setFromMatrix: function ( m ) {
  3672. var planes = this.planes;
  3673. var me = m.elements;
  3674. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  3675. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  3676. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  3677. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  3678. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3679. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3680. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3681. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3682. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3683. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3684. return this;
  3685. },
  3686. intersectsObject: function () {
  3687. var sphere = new THREE.Sphere();
  3688. return function ( object ) {
  3689. var geometry = object.geometry;
  3690. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3691. sphere.copy( geometry.boundingSphere );
  3692. sphere.applyMatrix4( object.matrixWorld );
  3693. return this.intersectsSphere( sphere );
  3694. };
  3695. }(),
  3696. intersectsSphere: function ( sphere ) {
  3697. var planes = this.planes;
  3698. var center = sphere.center;
  3699. var negRadius = - sphere.radius;
  3700. for ( var i = 0; i < 6; i ++ ) {
  3701. var distance = planes[ i ].distanceToPoint( center );
  3702. if ( distance < negRadius ) {
  3703. return false;
  3704. }
  3705. }
  3706. return true;
  3707. },
  3708. intersectsBox: function () {
  3709. var p1 = new THREE.Vector3(),
  3710. p2 = new THREE.Vector3();
  3711. return function ( box ) {
  3712. var planes = this.planes;
  3713. for ( var i = 0; i < 6 ; i ++ ) {
  3714. var plane = planes[ i ];
  3715. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3716. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3717. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3718. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3719. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3720. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3721. var d1 = plane.distanceToPoint( p1 );
  3722. var d2 = plane.distanceToPoint( p2 );
  3723. // if both outside plane, no intersection
  3724. if ( d1 < 0 && d2 < 0 ) {
  3725. return false;
  3726. }
  3727. }
  3728. return true;
  3729. };
  3730. }(),
  3731. containsPoint: function ( point ) {
  3732. var planes = this.planes;
  3733. for ( var i = 0; i < 6; i ++ ) {
  3734. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3735. return false;
  3736. }
  3737. }
  3738. return true;
  3739. },
  3740. clone: function () {
  3741. return new THREE.Frustum().copy( this );
  3742. }
  3743. };
  3744. // File:src/math/Plane.js
  3745. /**
  3746. * @author bhouston / http://exocortex.com
  3747. */
  3748. THREE.Plane = function ( normal, constant ) {
  3749. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3750. this.constant = ( constant !== undefined ) ? constant : 0;
  3751. };
  3752. THREE.Plane.prototype = {
  3753. constructor: THREE.Plane,
  3754. set: function ( normal, constant ) {
  3755. this.normal.copy( normal );
  3756. this.constant = constant;
  3757. return this;
  3758. },
  3759. setComponents: function ( x, y, z, w ) {
  3760. this.normal.set( x, y, z );
  3761. this.constant = w;
  3762. return this;
  3763. },
  3764. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3765. this.normal.copy( normal );
  3766. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3767. return this;
  3768. },
  3769. setFromCoplanarPoints: function () {
  3770. var v1 = new THREE.Vector3();
  3771. var v2 = new THREE.Vector3();
  3772. return function ( a, b, c ) {
  3773. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3774. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3775. this.setFromNormalAndCoplanarPoint( normal, a );
  3776. return this;
  3777. };
  3778. }(),
  3779. copy: function ( plane ) {
  3780. this.normal.copy( plane.normal );
  3781. this.constant = plane.constant;
  3782. return this;
  3783. },
  3784. normalize: function () {
  3785. // Note: will lead to a divide by zero if the plane is invalid.
  3786. var inverseNormalLength = 1.0 / this.normal.length();
  3787. this.normal.multiplyScalar( inverseNormalLength );
  3788. this.constant *= inverseNormalLength;
  3789. return this;
  3790. },
  3791. negate: function () {
  3792. this.constant *= - 1;
  3793. this.normal.negate();
  3794. return this;
  3795. },
  3796. distanceToPoint: function ( point ) {
  3797. return this.normal.dot( point ) + this.constant;
  3798. },
  3799. distanceToSphere: function ( sphere ) {
  3800. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3801. },
  3802. projectPoint: function ( point, optionalTarget ) {
  3803. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3804. },
  3805. orthoPoint: function ( point, optionalTarget ) {
  3806. var perpendicularMagnitude = this.distanceToPoint( point );
  3807. var result = optionalTarget || new THREE.Vector3();
  3808. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3809. },
  3810. isIntersectionLine: function ( line ) {
  3811. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3812. var startSign = this.distanceToPoint( line.start );
  3813. var endSign = this.distanceToPoint( line.end );
  3814. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3815. },
  3816. intersectLine: function () {
  3817. var v1 = new THREE.Vector3();
  3818. return function ( line, optionalTarget ) {
  3819. var result = optionalTarget || new THREE.Vector3();
  3820. var direction = line.delta( v1 );
  3821. var denominator = this.normal.dot( direction );
  3822. if ( denominator == 0 ) {
  3823. // line is coplanar, return origin
  3824. if ( this.distanceToPoint( line.start ) == 0 ) {
  3825. return result.copy( line.start );
  3826. }
  3827. // Unsure if this is the correct method to handle this case.
  3828. return undefined;
  3829. }
  3830. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3831. if ( t < 0 || t > 1 ) {
  3832. return undefined;
  3833. }
  3834. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3835. };
  3836. }(),
  3837. coplanarPoint: function ( optionalTarget ) {
  3838. var result = optionalTarget || new THREE.Vector3();
  3839. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3840. },
  3841. applyMatrix4: function () {
  3842. var v1 = new THREE.Vector3();
  3843. var v2 = new THREE.Vector3();
  3844. var m1 = new THREE.Matrix3();
  3845. return function ( matrix, optionalNormalMatrix ) {
  3846. // compute new normal based on theory here:
  3847. // http://www.songho.ca/opengl/gl_normaltransform.html
  3848. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  3849. var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix );
  3850. var newCoplanarPoint = this.coplanarPoint( v2 );
  3851. newCoplanarPoint.applyMatrix4( matrix );
  3852. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3853. return this;
  3854. };
  3855. }(),
  3856. translate: function ( offset ) {
  3857. this.constant = this.constant - offset.dot( this.normal );
  3858. return this;
  3859. },
  3860. equals: function ( plane ) {
  3861. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3862. },
  3863. clone: function () {
  3864. return new THREE.Plane().copy( this );
  3865. }
  3866. };
  3867. // File:src/math/Math.js
  3868. /**
  3869. * @author alteredq / http://alteredqualia.com/
  3870. * @author mrdoob / http://mrdoob.com/
  3871. */
  3872. THREE.Math = {
  3873. generateUUID: function () {
  3874. // http://www.broofa.com/Tools/Math.uuid.htm
  3875. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  3876. var uuid = new Array( 36 );
  3877. var rnd = 0, r;
  3878. return function () {
  3879. for ( var i = 0; i < 36; i ++ ) {
  3880. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3881. uuid[ i ] = '-';
  3882. } else if ( i == 14 ) {
  3883. uuid[ i ] = '4';
  3884. } else {
  3885. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  3886. r = rnd & 0xf;
  3887. rnd = rnd >> 4;
  3888. uuid[ i ] = chars[ ( i == 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  3889. }
  3890. }
  3891. return uuid.join( '' );
  3892. };
  3893. }(),
  3894. // Clamp value to range <a, b>
  3895. clamp: function ( x, a, b ) {
  3896. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3897. },
  3898. // Clamp value to range <a, inf)
  3899. clampBottom: function ( x, a ) {
  3900. return x < a ? a : x;
  3901. },
  3902. // Linear mapping from range <a1, a2> to range <b1, b2>
  3903. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3904. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3905. },
  3906. // http://en.wikipedia.org/wiki/Smoothstep
  3907. smoothstep: function ( x, min, max ) {
  3908. if ( x <= min ) return 0;
  3909. if ( x >= max ) return 1;
  3910. x = ( x - min ) / ( max - min );
  3911. return x * x * ( 3 - 2 * x );
  3912. },
  3913. smootherstep: function ( x, min, max ) {
  3914. if ( x <= min ) return 0;
  3915. if ( x >= max ) return 1;
  3916. x = ( x - min ) / ( max - min );
  3917. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  3918. },
  3919. // Random float from <0, 1> with 16 bits of randomness
  3920. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3921. random16: function () {
  3922. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3923. },
  3924. // Random integer from <low, high> interval
  3925. randInt: function ( low, high ) {
  3926. return Math.floor( this.randFloat( low, high ) );
  3927. },
  3928. // Random float from <low, high> interval
  3929. randFloat: function ( low, high ) {
  3930. return low + Math.random() * ( high - low );
  3931. },
  3932. // Random float from <-range/2, range/2> interval
  3933. randFloatSpread: function ( range ) {
  3934. return range * ( 0.5 - Math.random() );
  3935. },
  3936. degToRad: function () {
  3937. var degreeToRadiansFactor = Math.PI / 180;
  3938. return function ( degrees ) {
  3939. return degrees * degreeToRadiansFactor;
  3940. };
  3941. }(),
  3942. radToDeg: function () {
  3943. var radianToDegreesFactor = 180 / Math.PI;
  3944. return function ( radians ) {
  3945. return radians * radianToDegreesFactor;
  3946. };
  3947. }(),
  3948. isPowerOfTwo: function ( value ) {
  3949. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  3950. },
  3951. nextPowerOfTwo: function ( value ) {
  3952. value --;
  3953. value |= value >> 1;
  3954. value |= value >> 2;
  3955. value |= value >> 4;
  3956. value |= value >> 8;
  3957. value |= value >> 16;
  3958. value ++;
  3959. return value;
  3960. }
  3961. };
  3962. // File:src/math/Spline.js
  3963. /**
  3964. * Spline from Tween.js, slightly optimized (and trashed)
  3965. * http://sole.github.com/tween.js/examples/05_spline.html
  3966. *
  3967. * @author mrdoob / http://mrdoob.com/
  3968. * @author alteredq / http://alteredqualia.com/
  3969. */
  3970. THREE.Spline = function ( points ) {
  3971. this.points = points;
  3972. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3973. point, intPoint, weight, w2, w3,
  3974. pa, pb, pc, pd;
  3975. this.initFromArray = function ( a ) {
  3976. this.points = [];
  3977. for ( var i = 0; i < a.length; i ++ ) {
  3978. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3979. }
  3980. };
  3981. this.getPoint = function ( k ) {
  3982. point = ( this.points.length - 1 ) * k;
  3983. intPoint = Math.floor( point );
  3984. weight = point - intPoint;
  3985. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3986. c[ 1 ] = intPoint;
  3987. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3988. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3989. pa = this.points[ c[ 0 ] ];
  3990. pb = this.points[ c[ 1 ] ];
  3991. pc = this.points[ c[ 2 ] ];
  3992. pd = this.points[ c[ 3 ] ];
  3993. w2 = weight * weight;
  3994. w3 = weight * w2;
  3995. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3996. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3997. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3998. return v3;
  3999. };
  4000. this.getControlPointsArray = function () {
  4001. var i, p, l = this.points.length,
  4002. coords = [];
  4003. for ( i = 0; i < l; i ++ ) {
  4004. p = this.points[ i ];
  4005. coords[ i ] = [ p.x, p.y, p.z ];
  4006. }
  4007. return coords;
  4008. };
  4009. // approximate length by summing linear segments
  4010. this.getLength = function ( nSubDivisions ) {
  4011. var i, index, nSamples, position,
  4012. point = 0, intPoint = 0, oldIntPoint = 0,
  4013. oldPosition = new THREE.Vector3(),
  4014. tmpVec = new THREE.Vector3(),
  4015. chunkLengths = [],
  4016. totalLength = 0;
  4017. // first point has 0 length
  4018. chunkLengths[ 0 ] = 0;
  4019. if ( ! nSubDivisions ) nSubDivisions = 100;
  4020. nSamples = this.points.length * nSubDivisions;
  4021. oldPosition.copy( this.points[ 0 ] );
  4022. for ( i = 1; i < nSamples; i ++ ) {
  4023. index = i / nSamples;
  4024. position = this.getPoint( index );
  4025. tmpVec.copy( position );
  4026. totalLength += tmpVec.distanceTo( oldPosition );
  4027. oldPosition.copy( position );
  4028. point = ( this.points.length - 1 ) * index;
  4029. intPoint = Math.floor( point );
  4030. if ( intPoint != oldIntPoint ) {
  4031. chunkLengths[ intPoint ] = totalLength;
  4032. oldIntPoint = intPoint;
  4033. }
  4034. }
  4035. // last point ends with total length
  4036. chunkLengths[ chunkLengths.length ] = totalLength;
  4037. return { chunks: chunkLengths, total: totalLength };
  4038. };
  4039. this.reparametrizeByArcLength = function ( samplingCoef ) {
  4040. var i, j,
  4041. index, indexCurrent, indexNext,
  4042. realDistance,
  4043. sampling, position,
  4044. newpoints = [],
  4045. tmpVec = new THREE.Vector3(),
  4046. sl = this.getLength();
  4047. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  4048. for ( i = 1; i < this.points.length; i ++ ) {
  4049. //tmpVec.copy( this.points[ i - 1 ] );
  4050. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  4051. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  4052. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  4053. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  4054. indexNext = i / ( this.points.length - 1 );
  4055. for ( j = 1; j < sampling - 1; j ++ ) {
  4056. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  4057. position = this.getPoint( index );
  4058. newpoints.push( tmpVec.copy( position ).clone() );
  4059. }
  4060. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  4061. }
  4062. this.points = newpoints;
  4063. };
  4064. // Catmull-Rom
  4065. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  4066. var v0 = ( p2 - p0 ) * 0.5,
  4067. v1 = ( p3 - p1 ) * 0.5;
  4068. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  4069. };
  4070. };
  4071. // File:src/math/Triangle.js
  4072. /**
  4073. * @author bhouston / http://exocortex.com
  4074. * @author mrdoob / http://mrdoob.com/
  4075. */
  4076. THREE.Triangle = function ( a, b, c ) {
  4077. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  4078. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  4079. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  4080. };
  4081. THREE.Triangle.normal = function () {
  4082. var v0 = new THREE.Vector3();
  4083. return function ( a, b, c, optionalTarget ) {
  4084. var result = optionalTarget || new THREE.Vector3();
  4085. result.subVectors( c, b );
  4086. v0.subVectors( a, b );
  4087. result.cross( v0 );
  4088. var resultLengthSq = result.lengthSq();
  4089. if ( resultLengthSq > 0 ) {
  4090. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  4091. }
  4092. return result.set( 0, 0, 0 );
  4093. };
  4094. }();
  4095. // static/instance method to calculate barycoordinates
  4096. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4097. THREE.Triangle.barycoordFromPoint = function () {
  4098. var v0 = new THREE.Vector3();
  4099. var v1 = new THREE.Vector3();
  4100. var v2 = new THREE.Vector3();
  4101. return function ( point, a, b, c, optionalTarget ) {
  4102. v0.subVectors( c, a );
  4103. v1.subVectors( b, a );
  4104. v2.subVectors( point, a );
  4105. var dot00 = v0.dot( v0 );
  4106. var dot01 = v0.dot( v1 );
  4107. var dot02 = v0.dot( v2 );
  4108. var dot11 = v1.dot( v1 );
  4109. var dot12 = v1.dot( v2 );
  4110. var denom = ( dot00 * dot11 - dot01 * dot01 );
  4111. var result = optionalTarget || new THREE.Vector3();
  4112. // colinear or singular triangle
  4113. if ( denom == 0 ) {
  4114. // arbitrary location outside of triangle?
  4115. // not sure if this is the best idea, maybe should be returning undefined
  4116. return result.set( - 2, - 1, - 1 );
  4117. }
  4118. var invDenom = 1 / denom;
  4119. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4120. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4121. // barycoordinates must always sum to 1
  4122. return result.set( 1 - u - v, v, u );
  4123. };
  4124. }();
  4125. THREE.Triangle.containsPoint = function () {
  4126. var v1 = new THREE.Vector3();
  4127. return function ( point, a, b, c ) {
  4128. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  4129. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  4130. };
  4131. }();
  4132. THREE.Triangle.prototype = {
  4133. constructor: THREE.Triangle,
  4134. set: function ( a, b, c ) {
  4135. this.a.copy( a );
  4136. this.b.copy( b );
  4137. this.c.copy( c );
  4138. return this;
  4139. },
  4140. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  4141. this.a.copy( points[ i0 ] );
  4142. this.b.copy( points[ i1 ] );
  4143. this.c.copy( points[ i2 ] );
  4144. return this;
  4145. },
  4146. copy: function ( triangle ) {
  4147. this.a.copy( triangle.a );
  4148. this.b.copy( triangle.b );
  4149. this.c.copy( triangle.c );
  4150. return this;
  4151. },
  4152. area: function () {
  4153. var v0 = new THREE.Vector3();
  4154. var v1 = new THREE.Vector3();
  4155. return function () {
  4156. v0.subVectors( this.c, this.b );
  4157. v1.subVectors( this.a, this.b );
  4158. return v0.cross( v1 ).length() * 0.5;
  4159. };
  4160. }(),
  4161. midpoint: function ( optionalTarget ) {
  4162. var result = optionalTarget || new THREE.Vector3();
  4163. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4164. },
  4165. normal: function ( optionalTarget ) {
  4166. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  4167. },
  4168. plane: function ( optionalTarget ) {
  4169. var result = optionalTarget || new THREE.Plane();
  4170. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  4171. },
  4172. barycoordFromPoint: function ( point, optionalTarget ) {
  4173. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  4174. },
  4175. containsPoint: function ( point ) {
  4176. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  4177. },
  4178. equals: function ( triangle ) {
  4179. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4180. },
  4181. clone: function () {
  4182. return new THREE.Triangle().copy( this );
  4183. }
  4184. };
  4185. // File:src/core/Clock.js
  4186. /**
  4187. * @author alteredq / http://alteredqualia.com/
  4188. */
  4189. THREE.Clock = function ( autoStart ) {
  4190. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  4191. this.startTime = 0;
  4192. this.oldTime = 0;
  4193. this.elapsedTime = 0;
  4194. this.running = false;
  4195. };
  4196. THREE.Clock.prototype = {
  4197. constructor: THREE.Clock,
  4198. start: function () {
  4199. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  4200. ? self.performance.now()
  4201. : Date.now();
  4202. this.oldTime = this.startTime;
  4203. this.running = true;
  4204. },
  4205. stop: function () {
  4206. this.getElapsedTime();
  4207. this.running = false;
  4208. },
  4209. getElapsedTime: function () {
  4210. this.getDelta();
  4211. return this.elapsedTime;
  4212. },
  4213. getDelta: function () {
  4214. var diff = 0;
  4215. if ( this.autoStart && ! this.running ) {
  4216. this.start();
  4217. }
  4218. if ( this.running ) {
  4219. var newTime = self.performance !== undefined && self.performance.now !== undefined
  4220. ? self.performance.now()
  4221. : Date.now();
  4222. diff = 0.001 * ( newTime - this.oldTime );
  4223. this.oldTime = newTime;
  4224. this.elapsedTime += diff;
  4225. }
  4226. return diff;
  4227. }
  4228. };
  4229. // File:src/core/EventDispatcher.js
  4230. /**
  4231. * https://github.com/mrdoob/eventdispatcher.js/
  4232. */
  4233. THREE.EventDispatcher = function () {}
  4234. THREE.EventDispatcher.prototype = {
  4235. constructor: THREE.EventDispatcher,
  4236. apply: function ( object ) {
  4237. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  4238. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  4239. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  4240. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  4241. },
  4242. addEventListener: function ( type, listener ) {
  4243. if ( this._listeners === undefined ) this._listeners = {};
  4244. var listeners = this._listeners;
  4245. if ( listeners[ type ] === undefined ) {
  4246. listeners[ type ] = [];
  4247. }
  4248. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4249. listeners[ type ].push( listener );
  4250. }
  4251. },
  4252. hasEventListener: function ( type, listener ) {
  4253. if ( this._listeners === undefined ) return false;
  4254. var listeners = this._listeners;
  4255. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  4256. return true;
  4257. }
  4258. return false;
  4259. },
  4260. removeEventListener: function ( type, listener ) {
  4261. if ( this._listeners === undefined ) return;
  4262. var listeners = this._listeners;
  4263. var listenerArray = listeners[ type ];
  4264. if ( listenerArray !== undefined ) {
  4265. var index = listenerArray.indexOf( listener );
  4266. if ( index !== - 1 ) {
  4267. listenerArray.splice( index, 1 );
  4268. }
  4269. }
  4270. },
  4271. dispatchEvent: function ( event ) {
  4272. if ( this._listeners === undefined ) return;
  4273. var listeners = this._listeners;
  4274. var listenerArray = listeners[ event.type ];
  4275. if ( listenerArray !== undefined ) {
  4276. event.target = this;
  4277. var array = [];
  4278. var length = listenerArray.length;
  4279. for ( var i = 0; i < length; i ++ ) {
  4280. array[ i ] = listenerArray[ i ];
  4281. }
  4282. for ( var i = 0; i < length; i ++ ) {
  4283. array[ i ].call( this, event );
  4284. }
  4285. }
  4286. }
  4287. };
  4288. // File:src/core/Raycaster.js
  4289. /**
  4290. * @author mrdoob / http://mrdoob.com/
  4291. * @author bhouston / http://exocortex.com/
  4292. * @author stephomi / http://stephaneginier.com/
  4293. */
  4294. ( function ( THREE ) {
  4295. THREE.Raycaster = function ( origin, direction, near, far ) {
  4296. this.ray = new THREE.Ray( origin, direction );
  4297. // direction is assumed to be normalized (for accurate distance calculations)
  4298. this.near = near || 0;
  4299. this.far = far || Infinity;
  4300. this.params = {
  4301. Sprite: {},
  4302. Mesh: {},
  4303. PointCloud: { threshold: 1 },
  4304. LOD: {},
  4305. Line: {}
  4306. };
  4307. };
  4308. var descSort = function ( a, b ) {
  4309. return a.distance - b.distance;
  4310. };
  4311. var intersectObject = function ( object, raycaster, intersects, recursive ) {
  4312. object.raycast( raycaster, intersects );
  4313. if ( recursive === true ) {
  4314. var children = object.children;
  4315. for ( var i = 0, l = children.length; i < l; i ++ ) {
  4316. intersectObject( children[ i ], raycaster, intersects, true );
  4317. }
  4318. }
  4319. };
  4320. //
  4321. THREE.Raycaster.prototype = {
  4322. constructor: THREE.Raycaster,
  4323. precision: 0.0001,
  4324. linePrecision: 1,
  4325. set: function ( origin, direction ) {
  4326. // direction is assumed to be normalized (for accurate distance calculations)
  4327. this.ray.set( origin, direction );
  4328. },
  4329. setFromCamera: function ( coords, camera ) {
  4330. if ( camera instanceof THREE.PerspectiveCamera ) {
  4331. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  4332. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  4333. } else if ( camera instanceof THREE.OrthographicCamera ) {
  4334. this.ray.origin.set( coords.x, coords.y, - 1 ).unproject( camera );
  4335. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  4336. } else {
  4337. THREE.error( 'THREE.Raycaster: Unsupported camera type.' );
  4338. }
  4339. },
  4340. intersectObject: function ( object, recursive ) {
  4341. var intersects = [];
  4342. intersectObject( object, this, intersects, recursive );
  4343. intersects.sort( descSort );
  4344. return intersects;
  4345. },
  4346. intersectObjects: function ( objects, recursive ) {
  4347. var intersects = [];
  4348. if ( objects instanceof Array === false ) {
  4349. THREE.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  4350. return intersects;
  4351. }
  4352. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4353. intersectObject( objects[ i ], this, intersects, recursive );
  4354. }
  4355. intersects.sort( descSort );
  4356. return intersects;
  4357. }
  4358. };
  4359. }( THREE ) );
  4360. // File:src/core/Object3D.js
  4361. /**
  4362. * @author mrdoob / http://mrdoob.com/
  4363. * @author mikael emtinger / http://gomo.se/
  4364. * @author alteredq / http://alteredqualia.com/
  4365. * @author WestLangley / http://github.com/WestLangley
  4366. */
  4367. THREE.Object3D = function () {
  4368. Object.defineProperty( this, 'id', { value: THREE.Object3DIdCount ++ } );
  4369. this.uuid = THREE.Math.generateUUID();
  4370. this.name = '';
  4371. this.type = 'Object3D';
  4372. this.parent = undefined;
  4373. this.children = [];
  4374. this.up = THREE.Object3D.DefaultUp.clone();
  4375. var position = new THREE.Vector3();
  4376. var rotation = new THREE.Euler();
  4377. var quaternion = new THREE.Quaternion();
  4378. var scale = new THREE.Vector3( 1, 1, 1 );
  4379. var onRotationChange = function () {
  4380. quaternion.setFromEuler( rotation, false );
  4381. };
  4382. var onQuaternionChange = function () {
  4383. rotation.setFromQuaternion( quaternion, undefined, false );
  4384. };
  4385. rotation.onChange( onRotationChange );
  4386. quaternion.onChange( onQuaternionChange );
  4387. Object.defineProperties( this, {
  4388. position: {
  4389. enumerable: true,
  4390. value: position
  4391. },
  4392. rotation: {
  4393. enumerable: true,
  4394. value: rotation
  4395. },
  4396. quaternion: {
  4397. enumerable: true,
  4398. value: quaternion
  4399. },
  4400. scale: {
  4401. enumerable: true,
  4402. value: scale
  4403. }
  4404. } );
  4405. this.rotationAutoUpdate = true;
  4406. this.matrix = new THREE.Matrix4();
  4407. this.matrixWorld = new THREE.Matrix4();
  4408. this.matrixAutoUpdate = true;
  4409. this.matrixWorldNeedsUpdate = false;
  4410. this.visible = true;
  4411. this.castShadow = false;
  4412. this.receiveShadow = false;
  4413. this.frustumCulled = true;
  4414. this.renderOrder = 0;
  4415. this.userData = {};
  4416. };
  4417. THREE.Object3D.DefaultUp = new THREE.Vector3( 0, 1, 0 );
  4418. THREE.Object3D.prototype = {
  4419. constructor: THREE.Object3D,
  4420. get eulerOrder () {
  4421. THREE.warn( 'THREE.Object3D: .eulerOrder has been moved to .rotation.order.' );
  4422. return this.rotation.order;
  4423. },
  4424. set eulerOrder ( value ) {
  4425. THREE.warn( 'THREE.Object3D: .eulerOrder has been moved to .rotation.order.' );
  4426. this.rotation.order = value;
  4427. },
  4428. get useQuaternion () {
  4429. THREE.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  4430. },
  4431. set useQuaternion ( value ) {
  4432. THREE.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  4433. },
  4434. applyMatrix: function ( matrix ) {
  4435. this.matrix.multiplyMatrices( matrix, this.matrix );
  4436. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4437. },
  4438. setRotationFromAxisAngle: function ( axis, angle ) {
  4439. // assumes axis is normalized
  4440. this.quaternion.setFromAxisAngle( axis, angle );
  4441. },
  4442. setRotationFromEuler: function ( euler ) {
  4443. this.quaternion.setFromEuler( euler, true );
  4444. },
  4445. setRotationFromMatrix: function ( m ) {
  4446. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4447. this.quaternion.setFromRotationMatrix( m );
  4448. },
  4449. setRotationFromQuaternion: function ( q ) {
  4450. // assumes q is normalized
  4451. this.quaternion.copy( q );
  4452. },
  4453. rotateOnAxis: function () {
  4454. // rotate object on axis in object space
  4455. // axis is assumed to be normalized
  4456. var q1 = new THREE.Quaternion();
  4457. return function ( axis, angle ) {
  4458. q1.setFromAxisAngle( axis, angle );
  4459. this.quaternion.multiply( q1 );
  4460. return this;
  4461. }
  4462. }(),
  4463. rotateX: function () {
  4464. var v1 = new THREE.Vector3( 1, 0, 0 );
  4465. return function ( angle ) {
  4466. return this.rotateOnAxis( v1, angle );
  4467. };
  4468. }(),
  4469. rotateY: function () {
  4470. var v1 = new THREE.Vector3( 0, 1, 0 );
  4471. return function ( angle ) {
  4472. return this.rotateOnAxis( v1, angle );
  4473. };
  4474. }(),
  4475. rotateZ: function () {
  4476. var v1 = new THREE.Vector3( 0, 0, 1 );
  4477. return function ( angle ) {
  4478. return this.rotateOnAxis( v1, angle );
  4479. };
  4480. }(),
  4481. translateOnAxis: function () {
  4482. // translate object by distance along axis in object space
  4483. // axis is assumed to be normalized
  4484. var v1 = new THREE.Vector3();
  4485. return function ( axis, distance ) {
  4486. v1.copy( axis ).applyQuaternion( this.quaternion );
  4487. this.position.add( v1.multiplyScalar( distance ) );
  4488. return this;
  4489. }
  4490. }(),
  4491. translate: function ( distance, axis ) {
  4492. THREE.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  4493. return this.translateOnAxis( axis, distance );
  4494. },
  4495. translateX: function () {
  4496. var v1 = new THREE.Vector3( 1, 0, 0 );
  4497. return function ( distance ) {
  4498. return this.translateOnAxis( v1, distance );
  4499. };
  4500. }(),
  4501. translateY: function () {
  4502. var v1 = new THREE.Vector3( 0, 1, 0 );
  4503. return function ( distance ) {
  4504. return this.translateOnAxis( v1, distance );
  4505. };
  4506. }(),
  4507. translateZ: function () {
  4508. var v1 = new THREE.Vector3( 0, 0, 1 );
  4509. return function ( distance ) {
  4510. return this.translateOnAxis( v1, distance );
  4511. };
  4512. }(),
  4513. localToWorld: function ( vector ) {
  4514. return vector.applyMatrix4( this.matrixWorld );
  4515. },
  4516. worldToLocal: function () {
  4517. var m1 = new THREE.Matrix4();
  4518. return function ( vector ) {
  4519. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4520. };
  4521. }(),
  4522. lookAt: function () {
  4523. // This routine does not support objects with rotated and/or translated parent(s)
  4524. var m1 = new THREE.Matrix4();
  4525. return function ( vector ) {
  4526. m1.lookAt( vector, this.position, this.up );
  4527. this.quaternion.setFromRotationMatrix( m1 );
  4528. };
  4529. }(),
  4530. add: function ( object ) {
  4531. if ( arguments.length > 1 ) {
  4532. for ( var i = 0; i < arguments.length; i ++ ) {
  4533. this.add( arguments[ i ] );
  4534. }
  4535. return this;
  4536. };
  4537. if ( object === this ) {
  4538. THREE.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  4539. return this;
  4540. }
  4541. if ( object instanceof THREE.Object3D ) {
  4542. if ( object.parent !== undefined ) {
  4543. object.parent.remove( object );
  4544. }
  4545. object.parent = this;
  4546. object.dispatchEvent( { type: 'added' } );
  4547. this.children.push( object );
  4548. } else {
  4549. THREE.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  4550. }
  4551. return this;
  4552. },
  4553. remove: function ( object ) {
  4554. if ( arguments.length > 1 ) {
  4555. for ( var i = 0; i < arguments.length; i ++ ) {
  4556. this.remove( arguments[ i ] );
  4557. }
  4558. };
  4559. var index = this.children.indexOf( object );
  4560. if ( index !== - 1 ) {
  4561. object.parent = undefined;
  4562. object.dispatchEvent( { type: 'removed' } );
  4563. this.children.splice( index, 1 );
  4564. }
  4565. },
  4566. getChildByName: function ( name ) {
  4567. THREE.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  4568. return this.getObjectByName( name );
  4569. },
  4570. getObjectById: function ( id ) {
  4571. return this.getObjectByProperty( 'id', id );
  4572. },
  4573. getObjectByName: function ( name ) {
  4574. return this.getObjectByProperty( 'name', name );
  4575. },
  4576. getObjectByProperty: function ( name, value ) {
  4577. if ( this[ name ] === value ) return this;
  4578. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4579. var child = this.children[ i ];
  4580. var object = child.getObjectByProperty( name, value );
  4581. if ( object !== undefined ) {
  4582. return object;
  4583. }
  4584. }
  4585. return undefined;
  4586. },
  4587. getWorldPosition: function ( optionalTarget ) {
  4588. var result = optionalTarget || new THREE.Vector3();
  4589. this.updateMatrixWorld( true );
  4590. return result.setFromMatrixPosition( this.matrixWorld );
  4591. },
  4592. getWorldQuaternion: function () {
  4593. var position = new THREE.Vector3();
  4594. var scale = new THREE.Vector3();
  4595. return function ( optionalTarget ) {
  4596. var result = optionalTarget || new THREE.Quaternion();
  4597. this.updateMatrixWorld( true );
  4598. this.matrixWorld.decompose( position, result, scale );
  4599. return result;
  4600. }
  4601. }(),
  4602. getWorldRotation: function () {
  4603. var quaternion = new THREE.Quaternion();
  4604. return function ( optionalTarget ) {
  4605. var result = optionalTarget || new THREE.Euler();
  4606. this.getWorldQuaternion( quaternion );
  4607. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  4608. }
  4609. }(),
  4610. getWorldScale: function () {
  4611. var position = new THREE.Vector3();
  4612. var quaternion = new THREE.Quaternion();
  4613. return function ( optionalTarget ) {
  4614. var result = optionalTarget || new THREE.Vector3();
  4615. this.updateMatrixWorld( true );
  4616. this.matrixWorld.decompose( position, quaternion, result );
  4617. return result;
  4618. }
  4619. }(),
  4620. getWorldDirection: function () {
  4621. var quaternion = new THREE.Quaternion();
  4622. return function ( optionalTarget ) {
  4623. var result = optionalTarget || new THREE.Vector3();
  4624. this.getWorldQuaternion( quaternion );
  4625. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  4626. }
  4627. }(),
  4628. raycast: function () {},
  4629. traverse: function ( callback ) {
  4630. callback( this );
  4631. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4632. this.children[ i ].traverse( callback );
  4633. }
  4634. },
  4635. traverseVisible: function ( callback ) {
  4636. if ( this.visible === false ) return;
  4637. callback( this );
  4638. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4639. this.children[ i ].traverseVisible( callback );
  4640. }
  4641. },
  4642. traverseAncestors: function ( callback ) {
  4643. if ( this.parent ) {
  4644. callback( this.parent );
  4645. this.parent.traverseAncestors( callback );
  4646. }
  4647. },
  4648. updateMatrix: function () {
  4649. this.matrix.compose( this.position, this.quaternion, this.scale );
  4650. this.matrixWorldNeedsUpdate = true;
  4651. },
  4652. updateMatrixWorld: function ( force ) {
  4653. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4654. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4655. if ( this.parent === undefined ) {
  4656. this.matrixWorld.copy( this.matrix );
  4657. } else {
  4658. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4659. }
  4660. this.matrixWorldNeedsUpdate = false;
  4661. force = true;
  4662. }
  4663. // update children
  4664. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4665. this.children[ i ].updateMatrixWorld( force );
  4666. }
  4667. },
  4668. toJSON: function( meta ) {
  4669. var isRootObject = ( meta === undefined );
  4670. // we will store all serialization data on 'data'
  4671. var data = {};
  4672. var metadata;
  4673. // meta is a hash used to collect geometries, materials.
  4674. // not providing it implies that this is the root object
  4675. // being serialized.
  4676. if ( isRootObject ) {
  4677. // initialize meta obj
  4678. meta = {
  4679. geometries: {},
  4680. materials: {}
  4681. }
  4682. // add metadata
  4683. metadata = {
  4684. version: 4.4,
  4685. type: 'Object',
  4686. generator: 'Object3D.toJSON'
  4687. }
  4688. }
  4689. // standard Object3D serialization
  4690. data.type = this.type;
  4691. data.uuid = this.uuid;
  4692. if ( this.name !== '' ) data.name = this.name;
  4693. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  4694. if ( this.visible !== true ) data.visible = this.visible;
  4695. data.matrix = this.matrix.toArray();
  4696. if ( this.children.length > 0 ) {
  4697. data.children = [];
  4698. for ( var i = 0; i < this.children.length; i ++ ) {
  4699. data.children.push( this.children[ i ].toJSON( meta ).object );
  4700. }
  4701. }
  4702. // wrap serialized object with additional data
  4703. var output;
  4704. if ( isRootObject ) {
  4705. output = {
  4706. metadata: metadata,
  4707. geometries: extractFromCache(meta.geometries),
  4708. materials: extractFromCache(meta.materials),
  4709. object: data
  4710. };
  4711. } else {
  4712. output = { object: data };
  4713. }
  4714. return output;
  4715. // extract data from the cache hash
  4716. // remove metadata on each item
  4717. // and return as array
  4718. function extractFromCache ( cache ) {
  4719. var values = [];
  4720. for ( var key in cache ) {
  4721. var data = cache[ key ];
  4722. delete data.metadata;
  4723. values.push( data );
  4724. }
  4725. return values;
  4726. }
  4727. },
  4728. clone: function ( object, recursive ) {
  4729. if ( object === undefined ) object = new THREE.Object3D();
  4730. if ( recursive === undefined ) recursive = true;
  4731. object.name = this.name;
  4732. object.up.copy( this.up );
  4733. object.position.copy( this.position );
  4734. object.quaternion.copy( this.quaternion );
  4735. object.scale.copy( this.scale );
  4736. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4737. object.matrix.copy( this.matrix );
  4738. object.matrixWorld.copy( this.matrixWorld );
  4739. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4740. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4741. object.visible = this.visible;
  4742. object.castShadow = this.castShadow;
  4743. object.receiveShadow = this.receiveShadow;
  4744. object.frustumCulled = this.frustumCulled;
  4745. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4746. if ( recursive === true ) {
  4747. for ( var i = 0; i < this.children.length; i ++ ) {
  4748. var child = this.children[ i ];
  4749. object.add( child.clone() );
  4750. }
  4751. }
  4752. return object;
  4753. }
  4754. };
  4755. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  4756. THREE.Object3DIdCount = 0;
  4757. // File:src/core/Face3.js
  4758. /**
  4759. * @author mrdoob / http://mrdoob.com/
  4760. * @author alteredq / http://alteredqualia.com/
  4761. */
  4762. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4763. this.a = a;
  4764. this.b = b;
  4765. this.c = c;
  4766. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4767. this.vertexNormals = normal instanceof Array ? normal : [];
  4768. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4769. this.vertexColors = color instanceof Array ? color : [];
  4770. this.vertexTangents = [];
  4771. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4772. };
  4773. THREE.Face3.prototype = {
  4774. constructor: THREE.Face3,
  4775. clone: function () {
  4776. var face = new THREE.Face3( this.a, this.b, this.c );
  4777. face.normal.copy( this.normal );
  4778. face.color.copy( this.color );
  4779. face.materialIndex = this.materialIndex;
  4780. for ( var i = 0, il = this.vertexNormals.length; i < il; i ++ ) {
  4781. face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4782. }
  4783. for ( var i = 0, il = this.vertexColors.length; i < il; i ++ ) {
  4784. face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4785. }
  4786. for ( var i = 0, il = this.vertexTangents.length; i < il; i ++ ) {
  4787. face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4788. }
  4789. return face;
  4790. }
  4791. };
  4792. // File:src/core/Face4.js
  4793. /**
  4794. * @author mrdoob / http://mrdoob.com/
  4795. */
  4796. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4797. THREE.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' )
  4798. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  4799. };
  4800. // File:src/core/BufferAttribute.js
  4801. /**
  4802. * @author mrdoob / http://mrdoob.com/
  4803. */
  4804. THREE.BufferAttribute = function ( array, itemSize ) {
  4805. this.array = array;
  4806. this.itemSize = itemSize;
  4807. this.needsUpdate = false;
  4808. };
  4809. THREE.BufferAttribute.prototype = {
  4810. constructor: THREE.BufferAttribute,
  4811. get length () {
  4812. return this.array.length;
  4813. },
  4814. copyAt: function ( index1, attribute, index2 ) {
  4815. index1 *= this.itemSize;
  4816. index2 *= attribute.itemSize;
  4817. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  4818. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  4819. }
  4820. return this;
  4821. },
  4822. set: function ( value, offset ) {
  4823. if ( offset === undefined ) offset = 0;
  4824. this.array.set( value, offset );
  4825. return this;
  4826. },
  4827. setX: function ( index, x ) {
  4828. this.array[ index * this.itemSize ] = x;
  4829. return this;
  4830. },
  4831. setY: function ( index, y ) {
  4832. this.array[ index * this.itemSize + 1 ] = y;
  4833. return this;
  4834. },
  4835. setZ: function ( index, z ) {
  4836. this.array[ index * this.itemSize + 2 ] = z;
  4837. return this;
  4838. },
  4839. setXY: function ( index, x, y ) {
  4840. index *= this.itemSize;
  4841. this.array[ index ] = x;
  4842. this.array[ index + 1 ] = y;
  4843. return this;
  4844. },
  4845. setXYZ: function ( index, x, y, z ) {
  4846. index *= this.itemSize;
  4847. this.array[ index ] = x;
  4848. this.array[ index + 1 ] = y;
  4849. this.array[ index + 2 ] = z;
  4850. return this;
  4851. },
  4852. setXYZW: function ( index, x, y, z, w ) {
  4853. index *= this.itemSize;
  4854. this.array[ index ] = x;
  4855. this.array[ index + 1 ] = y;
  4856. this.array[ index + 2 ] = z;
  4857. this.array[ index + 3 ] = w;
  4858. return this;
  4859. },
  4860. clone: function () {
  4861. return new THREE.BufferAttribute( new this.array.constructor( this.array ), this.itemSize );
  4862. }
  4863. };
  4864. //
  4865. THREE.Int8Attribute = function ( data, itemSize ) {
  4866. THREE.warn( 'THREE.Int8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  4867. return new THREE.BufferAttribute( data, itemSize );
  4868. };
  4869. THREE.Uint8Attribute = function ( data, itemSize ) {
  4870. THREE.warn( 'THREE.Uint8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  4871. return new THREE.BufferAttribute( data, itemSize );
  4872. };
  4873. THREE.Uint8ClampedAttribute = function ( data, itemSize ) {
  4874. THREE.warn( 'THREE.Uint8ClampedAttribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  4875. return new THREE.BufferAttribute( data, itemSize );
  4876. };
  4877. THREE.Int16Attribute = function ( data, itemSize ) {
  4878. THREE.warn( 'THREE.Int16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  4879. return new THREE.BufferAttribute( data, itemSize );
  4880. };
  4881. THREE.Uint16Attribute = function ( data, itemSize ) {
  4882. THREE.warn( 'THREE.Uint16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  4883. return new THREE.BufferAttribute( data, itemSize );
  4884. };
  4885. THREE.Int32Attribute = function ( data, itemSize ) {
  4886. THREE.warn( 'THREE.Int32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  4887. return new THREE.BufferAttribute( data, itemSize );
  4888. };
  4889. THREE.Uint32Attribute = function ( data, itemSize ) {
  4890. THREE.warn( 'THREE.Uint32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  4891. return new THREE.BufferAttribute( data, itemSize );
  4892. };
  4893. THREE.Float32Attribute = function ( data, itemSize ) {
  4894. THREE.warn( 'THREE.Float32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  4895. return new THREE.BufferAttribute( data, itemSize );
  4896. };
  4897. THREE.Float64Attribute = function ( data, itemSize ) {
  4898. THREE.warn( 'THREE.Float64Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  4899. return new THREE.BufferAttribute( data, itemSize );
  4900. };
  4901. // File:src/core/DynamicBufferAttribute.js
  4902. /**
  4903. * @author benaadams / https://twitter.com/ben_a_adams
  4904. * @author mrdoob / http://mrdoob.com/
  4905. */
  4906. THREE.DynamicBufferAttribute = function ( array, itemSize ) {
  4907. THREE.BufferAttribute.call( this, array, itemSize );
  4908. this.updateRange = { offset: 0, count: -1 };
  4909. };
  4910. THREE.DynamicBufferAttribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  4911. THREE.DynamicBufferAttribute.prototype.constructor = THREE.DynamicBufferAttribute;
  4912. THREE.DynamicBufferAttribute.prototype.clone = function () {
  4913. return new THREE.DynamicBufferAttribute( new this.array.constructor( this.array ), this.itemSize );
  4914. };
  4915. // File:src/core/BufferGeometry.js
  4916. /**
  4917. * @author alteredq / http://alteredqualia.com/
  4918. * @author mrdoob / http://mrdoob.com/
  4919. */
  4920. THREE.BufferGeometry = function () {
  4921. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  4922. this.uuid = THREE.Math.generateUUID();
  4923. this.name = '';
  4924. this.type = 'BufferGeometry';
  4925. this.attributes = {};
  4926. this.attributesKeys = [];
  4927. this.drawcalls = [];
  4928. this.offsets = this.drawcalls; // backwards compatibility
  4929. this.boundingBox = null;
  4930. this.boundingSphere = null;
  4931. };
  4932. THREE.BufferGeometry.prototype = {
  4933. constructor: THREE.BufferGeometry,
  4934. addAttribute: function ( name, attribute ) {
  4935. if ( attribute instanceof THREE.BufferAttribute === false ) {
  4936. THREE.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  4937. this.attributes[ name ] = { array: arguments[ 1 ], itemSize: arguments[ 2 ] };
  4938. return;
  4939. }
  4940. this.attributes[ name ] = attribute;
  4941. this.attributesKeys = Object.keys( this.attributes );
  4942. },
  4943. getAttribute: function ( name ) {
  4944. return this.attributes[ name ];
  4945. },
  4946. addDrawCall: function ( start, count, indexOffset ) {
  4947. this.drawcalls.push( {
  4948. start: start,
  4949. count: count,
  4950. index: indexOffset !== undefined ? indexOffset : 0
  4951. } );
  4952. },
  4953. applyMatrix: function ( matrix ) {
  4954. var position = this.attributes.position;
  4955. if ( position !== undefined ) {
  4956. matrix.applyToVector3Array( position.array );
  4957. position.needsUpdate = true;
  4958. }
  4959. var normal = this.attributes.normal;
  4960. if ( normal !== undefined ) {
  4961. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  4962. normalMatrix.applyToVector3Array( normal.array );
  4963. normal.needsUpdate = true;
  4964. }
  4965. if ( this.boundingBox !== null ) {
  4966. this.computeBoundingBox();
  4967. }
  4968. if ( this.boundingSphere !== null ) {
  4969. this.computeBoundingSphere();
  4970. }
  4971. },
  4972. center: function () {
  4973. this.computeBoundingBox();
  4974. var offset = this.boundingBox.center().negate();
  4975. this.applyMatrix( new THREE.Matrix4().setPosition( offset ) );
  4976. return offset;
  4977. },
  4978. fromGeometry: function ( geometry, settings ) {
  4979. settings = settings || { 'vertexColors': THREE.NoColors };
  4980. var vertices = geometry.vertices;
  4981. var faces = geometry.faces;
  4982. var faceVertexUvs = geometry.faceVertexUvs;
  4983. var vertexColors = settings.vertexColors;
  4984. var hasFaceVertexUv = faceVertexUvs[ 0 ].length > 0;
  4985. var hasFaceVertexNormals = faces[ 0 ].vertexNormals.length == 3;
  4986. var positions = new Float32Array( faces.length * 3 * 3 );
  4987. this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  4988. var normals = new Float32Array( faces.length * 3 * 3 );
  4989. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  4990. if ( vertexColors !== THREE.NoColors ) {
  4991. var colors = new Float32Array( faces.length * 3 * 3 );
  4992. this.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
  4993. }
  4994. if ( hasFaceVertexUv === true ) {
  4995. var uvs = new Float32Array( faces.length * 3 * 2 );
  4996. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  4997. }
  4998. for ( var i = 0, i2 = 0, i3 = 0; i < faces.length; i ++, i2 += 6, i3 += 9 ) {
  4999. var face = faces[ i ];
  5000. var a = vertices[ face.a ];
  5001. var b = vertices[ face.b ];
  5002. var c = vertices[ face.c ];
  5003. positions[ i3 ] = a.x;
  5004. positions[ i3 + 1 ] = a.y;
  5005. positions[ i3 + 2 ] = a.z;
  5006. positions[ i3 + 3 ] = b.x;
  5007. positions[ i3 + 4 ] = b.y;
  5008. positions[ i3 + 5 ] = b.z;
  5009. positions[ i3 + 6 ] = c.x;
  5010. positions[ i3 + 7 ] = c.y;
  5011. positions[ i3 + 8 ] = c.z;
  5012. if ( hasFaceVertexNormals === true ) {
  5013. var na = face.vertexNormals[ 0 ];
  5014. var nb = face.vertexNormals[ 1 ];
  5015. var nc = face.vertexNormals[ 2 ];
  5016. normals[ i3 ] = na.x;
  5017. normals[ i3 + 1 ] = na.y;
  5018. normals[ i3 + 2 ] = na.z;
  5019. normals[ i3 + 3 ] = nb.x;
  5020. normals[ i3 + 4 ] = nb.y;
  5021. normals[ i3 + 5 ] = nb.z;
  5022. normals[ i3 + 6 ] = nc.x;
  5023. normals[ i3 + 7 ] = nc.y;
  5024. normals[ i3 + 8 ] = nc.z;
  5025. } else {
  5026. var n = face.normal;
  5027. normals[ i3 ] = n.x;
  5028. normals[ i3 + 1 ] = n.y;
  5029. normals[ i3 + 2 ] = n.z;
  5030. normals[ i3 + 3 ] = n.x;
  5031. normals[ i3 + 4 ] = n.y;
  5032. normals[ i3 + 5 ] = n.z;
  5033. normals[ i3 + 6 ] = n.x;
  5034. normals[ i3 + 7 ] = n.y;
  5035. normals[ i3 + 8 ] = n.z;
  5036. }
  5037. if ( vertexColors === THREE.FaceColors ) {
  5038. var fc = face.color;
  5039. colors[ i3 ] = fc.r;
  5040. colors[ i3 + 1 ] = fc.g;
  5041. colors[ i3 + 2 ] = fc.b;
  5042. colors[ i3 + 3 ] = fc.r;
  5043. colors[ i3 + 4 ] = fc.g;
  5044. colors[ i3 + 5 ] = fc.b;
  5045. colors[ i3 + 6 ] = fc.r;
  5046. colors[ i3 + 7 ] = fc.g;
  5047. colors[ i3 + 8 ] = fc.b;
  5048. } else if ( vertexColors === THREE.VertexColors ) {
  5049. var vca = face.vertexColors[ 0 ];
  5050. var vcb = face.vertexColors[ 1 ];
  5051. var vcc = face.vertexColors[ 2 ];
  5052. colors[ i3 ] = vca.r;
  5053. colors[ i3 + 1 ] = vca.g;
  5054. colors[ i3 + 2 ] = vca.b;
  5055. colors[ i3 + 3 ] = vcb.r;
  5056. colors[ i3 + 4 ] = vcb.g;
  5057. colors[ i3 + 5 ] = vcb.b;
  5058. colors[ i3 + 6 ] = vcc.r;
  5059. colors[ i3 + 7 ] = vcc.g;
  5060. colors[ i3 + 8 ] = vcc.b;
  5061. }
  5062. if ( hasFaceVertexUv === true ) {
  5063. var uva = faceVertexUvs[ 0 ][ i ][ 0 ];
  5064. var uvb = faceVertexUvs[ 0 ][ i ][ 1 ];
  5065. var uvc = faceVertexUvs[ 0 ][ i ][ 2 ];
  5066. uvs[ i2 ] = uva.x;
  5067. uvs[ i2 + 1 ] = uva.y;
  5068. uvs[ i2 + 2 ] = uvb.x;
  5069. uvs[ i2 + 3 ] = uvb.y;
  5070. uvs[ i2 + 4 ] = uvc.x;
  5071. uvs[ i2 + 5 ] = uvc.y;
  5072. }
  5073. }
  5074. this.computeBoundingSphere()
  5075. return this;
  5076. },
  5077. computeBoundingBox: function () {
  5078. var vector = new THREE.Vector3();
  5079. return function () {
  5080. if ( this.boundingBox === null ) {
  5081. this.boundingBox = new THREE.Box3();
  5082. }
  5083. var positions = this.attributes.position.array;
  5084. if ( positions ) {
  5085. var bb = this.boundingBox;
  5086. bb.makeEmpty();
  5087. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5088. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5089. bb.expandByPoint( vector );
  5090. }
  5091. }
  5092. if ( positions === undefined || positions.length === 0 ) {
  5093. this.boundingBox.min.set( 0, 0, 0 );
  5094. this.boundingBox.max.set( 0, 0, 0 );
  5095. }
  5096. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  5097. THREE.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.' );
  5098. }
  5099. }
  5100. }(),
  5101. computeBoundingSphere: function () {
  5102. var box = new THREE.Box3();
  5103. var vector = new THREE.Vector3();
  5104. return function () {
  5105. if ( this.boundingSphere === null ) {
  5106. this.boundingSphere = new THREE.Sphere();
  5107. }
  5108. var positions = this.attributes.position.array;
  5109. if ( positions ) {
  5110. box.makeEmpty();
  5111. var center = this.boundingSphere.center;
  5112. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5113. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5114. box.expandByPoint( vector );
  5115. }
  5116. box.center( center );
  5117. // hoping to find a boundingSphere with a radius smaller than the
  5118. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  5119. var maxRadiusSq = 0;
  5120. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5121. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5122. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  5123. }
  5124. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5125. if ( isNaN( this.boundingSphere.radius ) ) {
  5126. THREE.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.' );
  5127. }
  5128. }
  5129. }
  5130. }(),
  5131. computeFaceNormals: function () {
  5132. // backwards compatibility
  5133. },
  5134. computeVertexNormals: function () {
  5135. var attributes = this.attributes;
  5136. if ( attributes.position ) {
  5137. var positions = attributes.position.array;
  5138. if ( attributes.normal === undefined ) {
  5139. this.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( positions.length ), 3 ) );
  5140. } else {
  5141. // reset existing normals to zero
  5142. var normals = attributes.normal.array;
  5143. for ( var i = 0, il = normals.length; i < il; i ++ ) {
  5144. normals[ i ] = 0;
  5145. }
  5146. }
  5147. var normals = attributes.normal.array;
  5148. var vA, vB, vC,
  5149. pA = new THREE.Vector3(),
  5150. pB = new THREE.Vector3(),
  5151. pC = new THREE.Vector3(),
  5152. cb = new THREE.Vector3(),
  5153. ab = new THREE.Vector3();
  5154. // indexed elements
  5155. if ( attributes.index ) {
  5156. var indices = attributes.index.array;
  5157. var offsets = ( this.offsets.length > 0 ? this.offsets : [ { start: 0, count: indices.length, index: 0 } ] );
  5158. for ( var j = 0, jl = offsets.length; j < jl; ++ j ) {
  5159. var start = offsets[ j ].start;
  5160. var count = offsets[ j ].count;
  5161. var index = offsets[ j ].index;
  5162. for ( var i = start, il = start + count; i < il; i += 3 ) {
  5163. vA = ( index + indices[ i ] ) * 3;
  5164. vB = ( index + indices[ i + 1 ] ) * 3;
  5165. vC = ( index + indices[ i + 2 ] ) * 3;
  5166. pA.fromArray( positions, vA );
  5167. pB.fromArray( positions, vB );
  5168. pC.fromArray( positions, vC );
  5169. cb.subVectors( pC, pB );
  5170. ab.subVectors( pA, pB );
  5171. cb.cross( ab );
  5172. normals[ vA ] += cb.x;
  5173. normals[ vA + 1 ] += cb.y;
  5174. normals[ vA + 2 ] += cb.z;
  5175. normals[ vB ] += cb.x;
  5176. normals[ vB + 1 ] += cb.y;
  5177. normals[ vB + 2 ] += cb.z;
  5178. normals[ vC ] += cb.x;
  5179. normals[ vC + 1 ] += cb.y;
  5180. normals[ vC + 2 ] += cb.z;
  5181. }
  5182. }
  5183. } else {
  5184. // non-indexed elements (unconnected triangle soup)
  5185. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  5186. pA.fromArray( positions, i );
  5187. pB.fromArray( positions, i + 3 );
  5188. pC.fromArray( positions, i + 6 );
  5189. cb.subVectors( pC, pB );
  5190. ab.subVectors( pA, pB );
  5191. cb.cross( ab );
  5192. normals[ i ] = cb.x;
  5193. normals[ i + 1 ] = cb.y;
  5194. normals[ i + 2 ] = cb.z;
  5195. normals[ i + 3 ] = cb.x;
  5196. normals[ i + 4 ] = cb.y;
  5197. normals[ i + 5 ] = cb.z;
  5198. normals[ i + 6 ] = cb.x;
  5199. normals[ i + 7 ] = cb.y;
  5200. normals[ i + 8 ] = cb.z;
  5201. }
  5202. }
  5203. this.normalizeNormals();
  5204. attributes.normal.needsUpdate = true;
  5205. }
  5206. },
  5207. computeTangents: function () {
  5208. // based on http://www.terathon.com/code/tangent.html
  5209. // (per vertex tangents)
  5210. if ( this.attributes.index === undefined ||
  5211. this.attributes.position === undefined ||
  5212. this.attributes.normal === undefined ||
  5213. this.attributes.uv === undefined ) {
  5214. THREE.warn( 'THREE.BufferGeometry: Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()' );
  5215. return;
  5216. }
  5217. var indices = this.attributes.index.array;
  5218. var positions = this.attributes.position.array;
  5219. var normals = this.attributes.normal.array;
  5220. var uvs = this.attributes.uv.array;
  5221. var nVertices = positions.length / 3;
  5222. if ( this.attributes.tangent === undefined ) {
  5223. this.addAttribute( 'tangent', new THREE.BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  5224. }
  5225. var tangents = this.attributes.tangent.array;
  5226. var tan1 = [], tan2 = [];
  5227. for ( var k = 0; k < nVertices; k ++ ) {
  5228. tan1[ k ] = new THREE.Vector3();
  5229. tan2[ k ] = new THREE.Vector3();
  5230. }
  5231. var vA = new THREE.Vector3(),
  5232. vB = new THREE.Vector3(),
  5233. vC = new THREE.Vector3(),
  5234. uvA = new THREE.Vector2(),
  5235. uvB = new THREE.Vector2(),
  5236. uvC = new THREE.Vector2(),
  5237. x1, x2, y1, y2, z1, z2,
  5238. s1, s2, t1, t2, r;
  5239. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5240. function handleTriangle( a, b, c ) {
  5241. vA.fromArray( positions, a * 3 );
  5242. vB.fromArray( positions, b * 3 );
  5243. vC.fromArray( positions, c * 3 );
  5244. uvA.fromArray( uvs, a * 2 );
  5245. uvB.fromArray( uvs, b * 2 );
  5246. uvC.fromArray( uvs, c * 2 );
  5247. x1 = vB.x - vA.x;
  5248. x2 = vC.x - vA.x;
  5249. y1 = vB.y - vA.y;
  5250. y2 = vC.y - vA.y;
  5251. z1 = vB.z - vA.z;
  5252. z2 = vC.z - vA.z;
  5253. s1 = uvB.x - uvA.x;
  5254. s2 = uvC.x - uvA.x;
  5255. t1 = uvB.y - uvA.y;
  5256. t2 = uvC.y - uvA.y;
  5257. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5258. sdir.set(
  5259. ( t2 * x1 - t1 * x2 ) * r,
  5260. ( t2 * y1 - t1 * y2 ) * r,
  5261. ( t2 * z1 - t1 * z2 ) * r
  5262. );
  5263. tdir.set(
  5264. ( s1 * x2 - s2 * x1 ) * r,
  5265. ( s1 * y2 - s2 * y1 ) * r,
  5266. ( s1 * z2 - s2 * z1 ) * r
  5267. );
  5268. tan1[ a ].add( sdir );
  5269. tan1[ b ].add( sdir );
  5270. tan1[ c ].add( sdir );
  5271. tan2[ a ].add( tdir );
  5272. tan2[ b ].add( tdir );
  5273. tan2[ c ].add( tdir );
  5274. }
  5275. var i, il;
  5276. var j, jl;
  5277. var iA, iB, iC;
  5278. if ( this.drawcalls.length === 0 ) {
  5279. this.addDrawCall( 0, indices.length, 0 );
  5280. }
  5281. var drawcalls = this.drawcalls;
  5282. for ( j = 0, jl = drawcalls.length; j < jl; ++ j ) {
  5283. var start = drawcalls[ j ].start;
  5284. var count = drawcalls[ j ].count;
  5285. var index = drawcalls[ j ].index;
  5286. for ( i = start, il = start + count; i < il; i += 3 ) {
  5287. iA = index + indices[ i ];
  5288. iB = index + indices[ i + 1 ];
  5289. iC = index + indices[ i + 2 ];
  5290. handleTriangle( iA, iB, iC );
  5291. }
  5292. }
  5293. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5294. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5295. var w, t, test;
  5296. function handleVertex( v ) {
  5297. n.fromArray( normals, v * 3 );
  5298. n2.copy( n );
  5299. t = tan1[ v ];
  5300. // Gram-Schmidt orthogonalize
  5301. tmp.copy( t );
  5302. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5303. // Calculate handedness
  5304. tmp2.crossVectors( n2, t );
  5305. test = tmp2.dot( tan2[ v ] );
  5306. w = ( test < 0.0 ) ? - 1.0 : 1.0;
  5307. tangents[ v * 4 ] = tmp.x;
  5308. tangents[ v * 4 + 1 ] = tmp.y;
  5309. tangents[ v * 4 + 2 ] = tmp.z;
  5310. tangents[ v * 4 + 3 ] = w;
  5311. }
  5312. for ( j = 0, jl = drawcalls.length; j < jl; ++ j ) {
  5313. var start = drawcalls[ j ].start;
  5314. var count = drawcalls[ j ].count;
  5315. var index = drawcalls[ j ].index;
  5316. for ( i = start, il = start + count; i < il; i += 3 ) {
  5317. iA = index + indices[ i ];
  5318. iB = index + indices[ i + 1 ];
  5319. iC = index + indices[ i + 2 ];
  5320. handleVertex( iA );
  5321. handleVertex( iB );
  5322. handleVertex( iC );
  5323. }
  5324. }
  5325. },
  5326. /*
  5327. Compute the draw offset for large models by chunking the index buffer into chunks of 65k addressable vertices.
  5328. This method will effectively rewrite the index buffer and remap all attributes to match the new indices.
  5329. WARNING: This method will also expand the vertex count to prevent sprawled triangles across draw offsets.
  5330. size - Defaults to 65535, but allows for larger or smaller chunks.
  5331. */
  5332. computeOffsets: function ( size ) {
  5333. if ( size === undefined ) size = 65535; // WebGL limits type of index buffer values to 16-bit.
  5334. var indices = this.attributes.index.array;
  5335. var vertices = this.attributes.position.array;
  5336. var facesCount = ( indices.length / 3 );
  5337. /*
  5338. THREE.log("Computing buffers in offsets of "+size+" -> indices:"+indices.length+" vertices:"+vertices.length);
  5339. THREE.log("Faces to process: "+(indices.length/3));
  5340. THREE.log("Reordering "+verticesCount+" vertices.");
  5341. */
  5342. var sortedIndices = new Uint16Array( indices.length ); //16-bit buffers
  5343. var indexPtr = 0;
  5344. var vertexPtr = 0;
  5345. var offsets = [ { start:0, count:0, index:0 } ];
  5346. var offset = offsets[ 0 ];
  5347. var duplicatedVertices = 0;
  5348. var newVerticeMaps = 0;
  5349. var faceVertices = new Int32Array( 6 );
  5350. var vertexMap = new Int32Array( vertices.length );
  5351. var revVertexMap = new Int32Array( vertices.length );
  5352. for ( var j = 0; j < vertices.length; j ++ ) { vertexMap[ j ] = - 1; revVertexMap[ j ] = - 1; }
  5353. /*
  5354. Traverse every face and reorder vertices in the proper offsets of 65k.
  5355. We can have more than 65k entries in the index buffer per offset, but only reference 65k values.
  5356. */
  5357. for ( var findex = 0; findex < facesCount; findex ++ ) {
  5358. newVerticeMaps = 0;
  5359. for ( var vo = 0; vo < 3; vo ++ ) {
  5360. var vid = indices[ findex * 3 + vo ];
  5361. if ( vertexMap[ vid ] == - 1 ) {
  5362. //Unmapped vertice
  5363. faceVertices[ vo * 2 ] = vid;
  5364. faceVertices[ vo * 2 + 1 ] = - 1;
  5365. newVerticeMaps ++;
  5366. } else if ( vertexMap[ vid ] < offset.index ) {
  5367. //Reused vertices from previous block (duplicate)
  5368. faceVertices[ vo * 2 ] = vid;
  5369. faceVertices[ vo * 2 + 1 ] = - 1;
  5370. duplicatedVertices ++;
  5371. } else {
  5372. //Reused vertice in the current block
  5373. faceVertices[ vo * 2 ] = vid;
  5374. faceVertices[ vo * 2 + 1 ] = vertexMap[ vid ];
  5375. }
  5376. }
  5377. var faceMax = vertexPtr + newVerticeMaps;
  5378. if ( faceMax > ( offset.index + size ) ) {
  5379. var new_offset = { start:indexPtr, count:0, index:vertexPtr };
  5380. offsets.push( new_offset );
  5381. offset = new_offset;
  5382. //Re-evaluate reused vertices in light of new offset.
  5383. for ( var v = 0; v < 6; v += 2 ) {
  5384. var new_vid = faceVertices[ v + 1 ];
  5385. if ( new_vid > - 1 && new_vid < offset.index )
  5386. faceVertices[ v + 1 ] = - 1;
  5387. }
  5388. }
  5389. //Reindex the face.
  5390. for ( var v = 0; v < 6; v += 2 ) {
  5391. var vid = faceVertices[ v ];
  5392. var new_vid = faceVertices[ v + 1 ];
  5393. if ( new_vid === - 1 )
  5394. new_vid = vertexPtr ++;
  5395. vertexMap[ vid ] = new_vid;
  5396. revVertexMap[ new_vid ] = vid;
  5397. sortedIndices[ indexPtr ++ ] = new_vid - offset.index; //XXX overflows at 16bit
  5398. offset.count ++;
  5399. }
  5400. }
  5401. /* Move all attribute values to map to the new computed indices , also expand the vertice stack to match our new vertexPtr. */
  5402. this.reorderBuffers( sortedIndices, revVertexMap, vertexPtr );
  5403. this.offsets = offsets; // TODO: Deprecate
  5404. this.drawcalls = offsets;
  5405. /*
  5406. var orderTime = Date.now();
  5407. THREE.log("Reorder time: "+(orderTime-s)+"ms");
  5408. THREE.log("Duplicated "+duplicatedVertices+" vertices.");
  5409. THREE.log("Compute Buffers time: "+(Date.now()-s)+"ms");
  5410. THREE.log("Draw offsets: "+offsets.length);
  5411. */
  5412. return offsets;
  5413. },
  5414. merge: function ( geometry, offset ) {
  5415. if ( geometry instanceof THREE.BufferGeometry === false ) {
  5416. THREE.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  5417. return;
  5418. }
  5419. if ( offset === undefined ) offset = 0;
  5420. var attributes = this.attributes;
  5421. for ( var key in attributes ) {
  5422. if ( geometry.attributes[ key ] === undefined ) continue;
  5423. var attribute1 = attributes[ key ];
  5424. var attributeArray1 = attribute1.array;
  5425. var attribute2 = geometry.attributes[ key ];
  5426. var attributeArray2 = attribute2.array;
  5427. var attributeSize = attribute2.itemSize;
  5428. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  5429. attributeArray1[ j ] = attributeArray2[ i ];
  5430. }
  5431. }
  5432. return this;
  5433. },
  5434. normalizeNormals: function () {
  5435. var normals = this.attributes.normal.array;
  5436. var x, y, z, n;
  5437. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5438. x = normals[ i ];
  5439. y = normals[ i + 1 ];
  5440. z = normals[ i + 2 ];
  5441. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5442. normals[ i ] *= n;
  5443. normals[ i + 1 ] *= n;
  5444. normals[ i + 2 ] *= n;
  5445. }
  5446. },
  5447. /*
  5448. reoderBuffers:
  5449. Reorder attributes based on a new indexBuffer and indexMap.
  5450. indexBuffer - Uint16Array of the new ordered indices.
  5451. indexMap - Int32Array where the position is the new vertex ID and the value the old vertex ID for each vertex.
  5452. vertexCount - Amount of total vertices considered in this reordering (in case you want to grow the vertice stack).
  5453. */
  5454. reorderBuffers: function ( indexBuffer, indexMap, vertexCount ) {
  5455. /* Create a copy of all attributes for reordering. */
  5456. var sortedAttributes = {};
  5457. for ( var attr in this.attributes ) {
  5458. if ( attr == 'index' )
  5459. continue;
  5460. var sourceArray = this.attributes[ attr ].array;
  5461. sortedAttributes[ attr ] = new sourceArray.constructor( this.attributes[ attr ].itemSize * vertexCount );
  5462. }
  5463. /* Move attribute positions based on the new index map */
  5464. for ( var new_vid = 0; new_vid < vertexCount; new_vid ++ ) {
  5465. var vid = indexMap[ new_vid ];
  5466. for ( var attr in this.attributes ) {
  5467. if ( attr == 'index' )
  5468. continue;
  5469. var attrArray = this.attributes[ attr ].array;
  5470. var attrSize = this.attributes[ attr ].itemSize;
  5471. var sortedAttr = sortedAttributes[ attr ];
  5472. for ( var k = 0; k < attrSize; k ++ )
  5473. sortedAttr[ new_vid * attrSize + k ] = attrArray[ vid * attrSize + k ];
  5474. }
  5475. }
  5476. /* Carry the new sorted buffers locally */
  5477. this.attributes[ 'index' ].array = indexBuffer;
  5478. for ( var attr in this.attributes ) {
  5479. if ( attr == 'index' )
  5480. continue;
  5481. this.attributes[ attr ].array = sortedAttributes[ attr ];
  5482. this.attributes[ attr ].numItems = this.attributes[ attr ].itemSize * vertexCount;
  5483. }
  5484. },
  5485. toJSON: function() {
  5486. // we will store all serialization data on 'data'
  5487. var data = {};
  5488. // add metadata
  5489. data.metadata = {
  5490. version: 4.4,
  5491. type: 'BufferGeometry',
  5492. generator: 'BufferGeometry.toJSON'
  5493. }
  5494. // standard BufferGeometry serialization
  5495. data.type = this.type;
  5496. data.uuid = this.uuid;
  5497. if ( this.name !== '' ) data.name = this.name;
  5498. data.data = {};
  5499. data.data.attributes = {};
  5500. var attributes = this.attributes;
  5501. var offsets = this.offsets;
  5502. var boundingSphere = this.boundingSphere;
  5503. for ( var key in attributes ) {
  5504. var attribute = attributes[ key ];
  5505. var array = Array.prototype.slice.call( attribute.array );
  5506. data.data.attributes[ key ] = {
  5507. itemSize: attribute.itemSize,
  5508. type: attribute.array.constructor.name,
  5509. array: array
  5510. }
  5511. }
  5512. if ( offsets.length > 0 ) {
  5513. data.data.offsets = JSON.parse( JSON.stringify( offsets ) );
  5514. }
  5515. if ( boundingSphere !== null ) {
  5516. data.data.boundingSphere = {
  5517. center: boundingSphere.center.toArray(),
  5518. radius: boundingSphere.radius
  5519. }
  5520. }
  5521. return data;
  5522. },
  5523. clone: function () {
  5524. var geometry = new THREE.BufferGeometry();
  5525. for ( var attr in this.attributes ) {
  5526. var sourceAttr = this.attributes[ attr ];
  5527. geometry.addAttribute( attr, sourceAttr.clone() );
  5528. }
  5529. for ( var i = 0, il = this.offsets.length; i < il; i ++ ) {
  5530. var offset = this.offsets[ i ];
  5531. geometry.offsets.push( {
  5532. start: offset.start,
  5533. index: offset.index,
  5534. count: offset.count
  5535. } );
  5536. }
  5537. return geometry;
  5538. },
  5539. dispose: function () {
  5540. this.dispatchEvent( { type: 'dispose' } );
  5541. }
  5542. };
  5543. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  5544. // File:src/core/Geometry.js
  5545. /**
  5546. * @author mrdoob / http://mrdoob.com/
  5547. * @author kile / http://kile.stravaganza.org/
  5548. * @author alteredq / http://alteredqualia.com/
  5549. * @author mikael emtinger / http://gomo.se/
  5550. * @author zz85 / http://www.lab4games.net/zz85/blog
  5551. * @author bhouston / http://exocortex.com
  5552. */
  5553. THREE.Geometry = function () {
  5554. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  5555. this.uuid = THREE.Math.generateUUID();
  5556. this.name = '';
  5557. this.type = 'Geometry';
  5558. this.vertices = [];
  5559. this.colors = []; // one-to-one vertex colors, used in Points and Line
  5560. this.faces = [];
  5561. this.faceVertexUvs = [ [] ];
  5562. this.morphTargets = [];
  5563. this.morphColors = [];
  5564. this.morphNormals = [];
  5565. this.skinWeights = [];
  5566. this.skinIndices = [];
  5567. this.lineDistances = [];
  5568. this.boundingBox = null;
  5569. this.boundingSphere = null;
  5570. this.hasTangents = false;
  5571. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  5572. // update flags
  5573. this.verticesNeedUpdate = false;
  5574. this.elementsNeedUpdate = false;
  5575. this.uvsNeedUpdate = false;
  5576. this.normalsNeedUpdate = false;
  5577. this.tangentsNeedUpdate = false;
  5578. this.colorsNeedUpdate = false;
  5579. this.lineDistancesNeedUpdate = false;
  5580. this.groupsNeedUpdate = false;
  5581. };
  5582. THREE.Geometry.prototype = {
  5583. constructor: THREE.Geometry,
  5584. applyMatrix: function ( matrix ) {
  5585. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5586. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  5587. var vertex = this.vertices[ i ];
  5588. vertex.applyMatrix4( matrix );
  5589. }
  5590. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  5591. var face = this.faces[ i ];
  5592. face.normal.applyMatrix3( normalMatrix ).normalize();
  5593. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  5594. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  5595. }
  5596. }
  5597. if ( this.boundingBox !== null ) {
  5598. this.computeBoundingBox();
  5599. }
  5600. if ( this.boundingSphere !== null ) {
  5601. this.computeBoundingSphere();
  5602. }
  5603. this.verticesNeedUpdate = true;
  5604. this.normalsNeedUpdate = true;
  5605. },
  5606. fromBufferGeometry: function ( geometry ) {
  5607. var scope = this;
  5608. var attributes = geometry.attributes;
  5609. var vertices = attributes.position.array;
  5610. var indices = attributes.index !== undefined ? attributes.index.array : undefined;
  5611. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  5612. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  5613. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  5614. var tempNormals = [];
  5615. var tempUVs = [];
  5616. for ( var i = 0, j = 0; i < vertices.length; i += 3, j += 2 ) {
  5617. scope.vertices.push( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  5618. if ( normals !== undefined ) {
  5619. tempNormals.push( new THREE.Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  5620. }
  5621. if ( colors !== undefined ) {
  5622. scope.colors.push( new THREE.Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  5623. }
  5624. if ( uvs !== undefined ) {
  5625. tempUVs.push( new THREE.Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  5626. }
  5627. }
  5628. var addFace = function ( a, b, c ) {
  5629. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  5630. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  5631. scope.faces.push( new THREE.Face3( a, b, c, vertexNormals, vertexColors ) );
  5632. if ( uvs !== undefined ) {
  5633. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  5634. }
  5635. };
  5636. if ( indices !== undefined ) {
  5637. var drawcalls = geometry.drawcalls;
  5638. if ( drawcalls.length > 0 ) {
  5639. for ( var i = 0; i < drawcalls.length; i ++ ) {
  5640. var drawcall = drawcalls[ i ];
  5641. var start = drawcall.start;
  5642. var count = drawcall.count;
  5643. var index = drawcall.index;
  5644. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  5645. addFace( index + indices[ j ], index + indices[ j + 1 ], index + indices[ j + 2 ] );
  5646. }
  5647. }
  5648. } else {
  5649. for ( var i = 0; i < indices.length; i += 3 ) {
  5650. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  5651. }
  5652. }
  5653. } else {
  5654. for ( var i = 0; i < vertices.length / 3; i += 3 ) {
  5655. addFace( i, i + 1, i + 2 );
  5656. }
  5657. }
  5658. this.computeFaceNormals();
  5659. if ( geometry.boundingBox !== null ) {
  5660. this.boundingBox = geometry.boundingBox.clone();
  5661. }
  5662. if ( geometry.boundingSphere !== null ) {
  5663. this.boundingSphere = geometry.boundingSphere.clone();
  5664. }
  5665. return this;
  5666. },
  5667. center: function () {
  5668. this.computeBoundingBox();
  5669. var offset = this.boundingBox.center().negate();
  5670. this.applyMatrix( new THREE.Matrix4().setPosition( offset ) );
  5671. return offset;
  5672. },
  5673. computeFaceNormals: function () {
  5674. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5675. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5676. var face = this.faces[ f ];
  5677. var vA = this.vertices[ face.a ];
  5678. var vB = this.vertices[ face.b ];
  5679. var vC = this.vertices[ face.c ];
  5680. cb.subVectors( vC, vB );
  5681. ab.subVectors( vA, vB );
  5682. cb.cross( ab );
  5683. cb.normalize();
  5684. face.normal.copy( cb );
  5685. }
  5686. },
  5687. computeVertexNormals: function ( areaWeighted ) {
  5688. var v, vl, f, fl, face, vertices;
  5689. vertices = new Array( this.vertices.length );
  5690. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5691. vertices[ v ] = new THREE.Vector3();
  5692. }
  5693. if ( areaWeighted ) {
  5694. // vertex normals weighted by triangle areas
  5695. // http://www.iquilezles.org/www/articles/normals/normals.htm
  5696. var vA, vB, vC;
  5697. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5698. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5699. face = this.faces[ f ];
  5700. vA = this.vertices[ face.a ];
  5701. vB = this.vertices[ face.b ];
  5702. vC = this.vertices[ face.c ];
  5703. cb.subVectors( vC, vB );
  5704. ab.subVectors( vA, vB );
  5705. cb.cross( ab );
  5706. vertices[ face.a ].add( cb );
  5707. vertices[ face.b ].add( cb );
  5708. vertices[ face.c ].add( cb );
  5709. }
  5710. } else {
  5711. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5712. face = this.faces[ f ];
  5713. vertices[ face.a ].add( face.normal );
  5714. vertices[ face.b ].add( face.normal );
  5715. vertices[ face.c ].add( face.normal );
  5716. }
  5717. }
  5718. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5719. vertices[ v ].normalize();
  5720. }
  5721. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5722. face = this.faces[ f ];
  5723. face.vertexNormals[ 0 ] = vertices[ face.a ].clone();
  5724. face.vertexNormals[ 1 ] = vertices[ face.b ].clone();
  5725. face.vertexNormals[ 2 ] = vertices[ face.c ].clone();
  5726. }
  5727. },
  5728. computeMorphNormals: function () {
  5729. var i, il, f, fl, face;
  5730. // save original normals
  5731. // - create temp variables on first access
  5732. // otherwise just copy (for faster repeated calls)
  5733. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5734. face = this.faces[ f ];
  5735. if ( ! face.__originalFaceNormal ) {
  5736. face.__originalFaceNormal = face.normal.clone();
  5737. } else {
  5738. face.__originalFaceNormal.copy( face.normal );
  5739. }
  5740. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  5741. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  5742. if ( ! face.__originalVertexNormals[ i ] ) {
  5743. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  5744. } else {
  5745. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  5746. }
  5747. }
  5748. }
  5749. // use temp geometry to compute face and vertex normals for each morph
  5750. var tmpGeo = new THREE.Geometry();
  5751. tmpGeo.faces = this.faces;
  5752. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  5753. // create on first access
  5754. if ( ! this.morphNormals[ i ] ) {
  5755. this.morphNormals[ i ] = {};
  5756. this.morphNormals[ i ].faceNormals = [];
  5757. this.morphNormals[ i ].vertexNormals = [];
  5758. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  5759. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  5760. var faceNormal, vertexNormals;
  5761. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5762. faceNormal = new THREE.Vector3();
  5763. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  5764. dstNormalsFace.push( faceNormal );
  5765. dstNormalsVertex.push( vertexNormals );
  5766. }
  5767. }
  5768. var morphNormals = this.morphNormals[ i ];
  5769. // set vertices to morph target
  5770. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  5771. // compute morph normals
  5772. tmpGeo.computeFaceNormals();
  5773. tmpGeo.computeVertexNormals();
  5774. // store morph normals
  5775. var faceNormal, vertexNormals;
  5776. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5777. face = this.faces[ f ];
  5778. faceNormal = morphNormals.faceNormals[ f ];
  5779. vertexNormals = morphNormals.vertexNormals[ f ];
  5780. faceNormal.copy( face.normal );
  5781. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  5782. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  5783. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  5784. }
  5785. }
  5786. // restore original normals
  5787. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5788. face = this.faces[ f ];
  5789. face.normal = face.__originalFaceNormal;
  5790. face.vertexNormals = face.__originalVertexNormals;
  5791. }
  5792. },
  5793. computeTangents: function () {
  5794. // based on http://www.terathon.com/code/tangent.html
  5795. // tangents go to vertices
  5796. var f, fl, v, vl, i, vertexIndex,
  5797. face, uv, vA, vB, vC, uvA, uvB, uvC,
  5798. x1, x2, y1, y2, z1, z2,
  5799. s1, s2, t1, t2, r, t, test,
  5800. tan1 = [], tan2 = [],
  5801. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  5802. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  5803. n = new THREE.Vector3(), w;
  5804. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5805. tan1[ v ] = new THREE.Vector3();
  5806. tan2[ v ] = new THREE.Vector3();
  5807. }
  5808. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  5809. vA = context.vertices[ a ];
  5810. vB = context.vertices[ b ];
  5811. vC = context.vertices[ c ];
  5812. uvA = uv[ ua ];
  5813. uvB = uv[ ub ];
  5814. uvC = uv[ uc ];
  5815. x1 = vB.x - vA.x;
  5816. x2 = vC.x - vA.x;
  5817. y1 = vB.y - vA.y;
  5818. y2 = vC.y - vA.y;
  5819. z1 = vB.z - vA.z;
  5820. z2 = vC.z - vA.z;
  5821. s1 = uvB.x - uvA.x;
  5822. s2 = uvC.x - uvA.x;
  5823. t1 = uvB.y - uvA.y;
  5824. t2 = uvC.y - uvA.y;
  5825. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5826. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  5827. ( t2 * y1 - t1 * y2 ) * r,
  5828. ( t2 * z1 - t1 * z2 ) * r );
  5829. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  5830. ( s1 * y2 - s2 * y1 ) * r,
  5831. ( s1 * z2 - s2 * z1 ) * r );
  5832. tan1[ a ].add( sdir );
  5833. tan1[ b ].add( sdir );
  5834. tan1[ c ].add( sdir );
  5835. tan2[ a ].add( tdir );
  5836. tan2[ b ].add( tdir );
  5837. tan2[ c ].add( tdir );
  5838. }
  5839. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5840. face = this.faces[ f ];
  5841. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  5842. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  5843. }
  5844. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  5845. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5846. face = this.faces[ f ];
  5847. for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i ++ ) {
  5848. n.copy( face.vertexNormals[ i ] );
  5849. vertexIndex = face[ faceIndex[ i ] ];
  5850. t = tan1[ vertexIndex ];
  5851. // Gram-Schmidt orthogonalize
  5852. tmp.copy( t );
  5853. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5854. // Calculate handedness
  5855. tmp2.crossVectors( face.vertexNormals[ i ], t );
  5856. test = tmp2.dot( tan2[ vertexIndex ] );
  5857. w = ( test < 0.0 ) ? - 1.0 : 1.0;
  5858. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  5859. }
  5860. }
  5861. this.hasTangents = true;
  5862. },
  5863. computeLineDistances: function () {
  5864. var d = 0;
  5865. var vertices = this.vertices;
  5866. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5867. if ( i > 0 ) {
  5868. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  5869. }
  5870. this.lineDistances[ i ] = d;
  5871. }
  5872. },
  5873. computeBoundingBox: function () {
  5874. if ( this.boundingBox === null ) {
  5875. this.boundingBox = new THREE.Box3();
  5876. }
  5877. this.boundingBox.setFromPoints( this.vertices );
  5878. },
  5879. computeBoundingSphere: function () {
  5880. if ( this.boundingSphere === null ) {
  5881. this.boundingSphere = new THREE.Sphere();
  5882. }
  5883. this.boundingSphere.setFromPoints( this.vertices );
  5884. },
  5885. merge: function ( geometry, matrix, materialIndexOffset ) {
  5886. if ( geometry instanceof THREE.Geometry === false ) {
  5887. THREE.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  5888. return;
  5889. }
  5890. var normalMatrix,
  5891. vertexOffset = this.vertices.length,
  5892. vertices1 = this.vertices,
  5893. vertices2 = geometry.vertices,
  5894. faces1 = this.faces,
  5895. faces2 = geometry.faces,
  5896. uvs1 = this.faceVertexUvs[ 0 ],
  5897. uvs2 = geometry.faceVertexUvs[ 0 ];
  5898. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  5899. if ( matrix !== undefined ) {
  5900. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5901. }
  5902. // vertices
  5903. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  5904. var vertex = vertices2[ i ];
  5905. var vertexCopy = vertex.clone();
  5906. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  5907. vertices1.push( vertexCopy );
  5908. }
  5909. // faces
  5910. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  5911. var face = faces2[ i ], faceCopy, normal, color,
  5912. faceVertexNormals = face.vertexNormals,
  5913. faceVertexColors = face.vertexColors;
  5914. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  5915. faceCopy.normal.copy( face.normal );
  5916. if ( normalMatrix !== undefined ) {
  5917. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  5918. }
  5919. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  5920. normal = faceVertexNormals[ j ].clone();
  5921. if ( normalMatrix !== undefined ) {
  5922. normal.applyMatrix3( normalMatrix ).normalize();
  5923. }
  5924. faceCopy.vertexNormals.push( normal );
  5925. }
  5926. faceCopy.color.copy( face.color );
  5927. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  5928. color = faceVertexColors[ j ];
  5929. faceCopy.vertexColors.push( color.clone() );
  5930. }
  5931. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  5932. faces1.push( faceCopy );
  5933. }
  5934. // uvs
  5935. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  5936. var uv = uvs2[ i ], uvCopy = [];
  5937. if ( uv === undefined ) {
  5938. continue;
  5939. }
  5940. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  5941. uvCopy.push( uv[ j ].clone() );
  5942. }
  5943. uvs1.push( uvCopy );
  5944. }
  5945. },
  5946. mergeMesh: function ( mesh ) {
  5947. if ( mesh instanceof THREE.Mesh === false ) {
  5948. THREE.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  5949. return;
  5950. }
  5951. mesh.matrixAutoUpdate && mesh.updateMatrix();
  5952. this.merge( mesh.geometry, mesh.matrix );
  5953. },
  5954. /*
  5955. * Checks for duplicate vertices with hashmap.
  5956. * Duplicated vertices are removed
  5957. * and faces' vertices are updated.
  5958. */
  5959. mergeVertices: function () {
  5960. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  5961. var unique = [], changes = [];
  5962. var v, key;
  5963. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  5964. var precision = Math.pow( 10, precisionPoints );
  5965. var i, il, face;
  5966. var indices, j, jl;
  5967. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  5968. v = this.vertices[ i ];
  5969. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  5970. if ( verticesMap[ key ] === undefined ) {
  5971. verticesMap[ key ] = i;
  5972. unique.push( this.vertices[ i ] );
  5973. changes[ i ] = unique.length - 1;
  5974. } else {
  5975. //THREE.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  5976. changes[ i ] = changes[ verticesMap[ key ] ];
  5977. }
  5978. };
  5979. // if faces are completely degenerate after merging vertices, we
  5980. // have to remove them from the geometry.
  5981. var faceIndicesToRemove = [];
  5982. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  5983. face = this.faces[ i ];
  5984. face.a = changes[ face.a ];
  5985. face.b = changes[ face.b ];
  5986. face.c = changes[ face.c ];
  5987. indices = [ face.a, face.b, face.c ];
  5988. var dupIndex = - 1;
  5989. // if any duplicate vertices are found in a Face3
  5990. // we have to remove the face as nothing can be saved
  5991. for ( var n = 0; n < 3; n ++ ) {
  5992. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  5993. dupIndex = n;
  5994. faceIndicesToRemove.push( i );
  5995. break;
  5996. }
  5997. }
  5998. }
  5999. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  6000. var idx = faceIndicesToRemove[ i ];
  6001. this.faces.splice( idx, 1 );
  6002. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  6003. this.faceVertexUvs[ j ].splice( idx, 1 );
  6004. }
  6005. }
  6006. // Use unique set of vertices
  6007. var diff = this.vertices.length - unique.length;
  6008. this.vertices = unique;
  6009. return diff;
  6010. },
  6011. toJSON: function() {
  6012. // we will store all serialization data on 'data'
  6013. var data = {};
  6014. // add metadata
  6015. data.metadata = {
  6016. version: 4.4,
  6017. type: 'Geometry',
  6018. generator: 'Geometry.toJSON'
  6019. };
  6020. // standard Geometry serialization
  6021. data.type = this.type;
  6022. data.uuid = this.uuid;
  6023. if ( this.name !== '' ) data.name = this.name;
  6024. if ( this.parameters !== undefined ) {
  6025. var parameters = this.parameters;
  6026. for ( var key in parameters ) {
  6027. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6028. }
  6029. return data;
  6030. }
  6031. var vertices = [];
  6032. for ( var i = 0; i < this.vertices.length; i ++ ) {
  6033. var vertex = this.vertices[ i ];
  6034. vertices.push( vertex.x, vertex.y, vertex.z );
  6035. }
  6036. var faces = [];
  6037. var normals = [];
  6038. var normalsHash = {};
  6039. var colors = [];
  6040. var colorsHash = {};
  6041. var uvs = [];
  6042. var uvsHash = {};
  6043. for ( var i = 0; i < this.faces.length; i ++ ) {
  6044. var face = this.faces[ i ];
  6045. var hasMaterial = false; // face.materialIndex !== undefined;
  6046. var hasFaceUv = false; // deprecated
  6047. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  6048. var hasFaceNormal = face.normal.length() > 0;
  6049. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  6050. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  6051. var hasFaceVertexColor = face.vertexColors.length > 0;
  6052. var faceType = 0;
  6053. faceType = setBit( faceType, 0, 0 );
  6054. faceType = setBit( faceType, 1, hasMaterial );
  6055. faceType = setBit( faceType, 2, hasFaceUv );
  6056. faceType = setBit( faceType, 3, hasFaceVertexUv );
  6057. faceType = setBit( faceType, 4, hasFaceNormal );
  6058. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  6059. faceType = setBit( faceType, 6, hasFaceColor );
  6060. faceType = setBit( faceType, 7, hasFaceVertexColor );
  6061. faces.push( faceType );
  6062. faces.push( face.a, face.b, face.c );
  6063. /*
  6064. if ( hasMaterial ) {
  6065. faces.push( face.materialIndex );
  6066. }
  6067. */
  6068. if ( hasFaceVertexUv ) {
  6069. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  6070. faces.push(
  6071. getUvIndex( faceVertexUvs[ 0 ] ),
  6072. getUvIndex( faceVertexUvs[ 1 ] ),
  6073. getUvIndex( faceVertexUvs[ 2 ] )
  6074. );
  6075. }
  6076. if ( hasFaceNormal ) {
  6077. faces.push( getNormalIndex( face.normal ) );
  6078. }
  6079. if ( hasFaceVertexNormal ) {
  6080. var vertexNormals = face.vertexNormals;
  6081. faces.push(
  6082. getNormalIndex( vertexNormals[ 0 ] ),
  6083. getNormalIndex( vertexNormals[ 1 ] ),
  6084. getNormalIndex( vertexNormals[ 2 ] )
  6085. );
  6086. }
  6087. if ( hasFaceColor ) {
  6088. faces.push( getColorIndex( face.color ) );
  6089. }
  6090. if ( hasFaceVertexColor ) {
  6091. var vertexColors = face.vertexColors;
  6092. faces.push(
  6093. getColorIndex( vertexColors[ 0 ] ),
  6094. getColorIndex( vertexColors[ 1 ] ),
  6095. getColorIndex( vertexColors[ 2 ] )
  6096. );
  6097. }
  6098. }
  6099. function setBit( value, position, enabled ) {
  6100. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position) );
  6101. }
  6102. function getNormalIndex( normal ) {
  6103. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  6104. if ( normalsHash[ hash ] !== undefined ) {
  6105. return normalsHash[ hash ];
  6106. }
  6107. normalsHash[ hash ] = normals.length / 3;
  6108. normals.push( normal.x, normal.y, normal.z );
  6109. return normalsHash[ hash ];
  6110. }
  6111. function getColorIndex( color ) {
  6112. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  6113. if ( colorsHash[ hash ] !== undefined ) {
  6114. return colorsHash[ hash ];
  6115. }
  6116. colorsHash[ hash ] = colors.length;
  6117. colors.push( color.getHex() );
  6118. return colorsHash[ hash ];
  6119. }
  6120. function getUvIndex( uv ) {
  6121. var hash = uv.x.toString() + uv.y.toString();
  6122. if ( uvsHash[ hash ] !== undefined ) {
  6123. return uvsHash[ hash ];
  6124. }
  6125. uvsHash[ hash ] = uvs.length / 2;
  6126. uvs.push( uv.x, uv.y );
  6127. return uvsHash[ hash ];
  6128. }
  6129. data.data = {};
  6130. data.data.vertices = vertices;
  6131. data.data.normals = normals;
  6132. if ( colors.length > 0 ) data.data.colors = colors;
  6133. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  6134. data.data.faces = faces;
  6135. return data;
  6136. },
  6137. clone: function () {
  6138. var geometry = new THREE.Geometry();
  6139. var vertices = this.vertices;
  6140. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6141. geometry.vertices.push( vertices[ i ].clone() );
  6142. }
  6143. var faces = this.faces;
  6144. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  6145. geometry.faces.push( faces[ i ].clone() );
  6146. }
  6147. for ( var i = 0, il = this.faceVertexUvs.length; i < il; i ++ ) {
  6148. var faceVertexUvs = this.faceVertexUvs[ i ];
  6149. if ( geometry.faceVertexUvs[ i ] === undefined ) {
  6150. geometry.faceVertexUvs[ i ] = [];
  6151. }
  6152. for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  6153. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  6154. for ( var k = 0, kl = uvs.length; k < kl; k ++ ) {
  6155. var uv = uvs[ k ];
  6156. uvsCopy.push( uv.clone() );
  6157. }
  6158. geometry.faceVertexUvs[ i ].push( uvsCopy );
  6159. }
  6160. }
  6161. return geometry;
  6162. },
  6163. dispose: function () {
  6164. this.dispatchEvent( { type: 'dispose' } );
  6165. }
  6166. };
  6167. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  6168. THREE.GeometryIdCount = 0;
  6169. // File:src/cameras/Camera.js
  6170. /**
  6171. * @author mrdoob / http://mrdoob.com/
  6172. * @author mikael emtinger / http://gomo.se/
  6173. * @author WestLangley / http://github.com/WestLangley
  6174. */
  6175. THREE.Camera = function () {
  6176. THREE.Object3D.call( this );
  6177. this.type = 'Camera';
  6178. this.matrixWorldInverse = new THREE.Matrix4();
  6179. this.projectionMatrix = new THREE.Matrix4();
  6180. };
  6181. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  6182. THREE.Camera.prototype.constructor = THREE.Camera;
  6183. THREE.Camera.prototype.getWorldDirection = function () {
  6184. var quaternion = new THREE.Quaternion();
  6185. return function ( optionalTarget ) {
  6186. var result = optionalTarget || new THREE.Vector3();
  6187. this.getWorldQuaternion( quaternion );
  6188. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  6189. }
  6190. }();
  6191. THREE.Camera.prototype.lookAt = function () {
  6192. // This routine does not support cameras with rotated and/or translated parent(s)
  6193. var m1 = new THREE.Matrix4();
  6194. return function ( vector ) {
  6195. m1.lookAt( this.position, vector, this.up );
  6196. this.quaternion.setFromRotationMatrix( m1 );
  6197. };
  6198. }();
  6199. THREE.Camera.prototype.clone = function ( camera ) {
  6200. if ( camera === undefined ) camera = new THREE.Camera();
  6201. THREE.Object3D.prototype.clone.call( this, camera );
  6202. camera.matrixWorldInverse.copy( this.matrixWorldInverse );
  6203. camera.projectionMatrix.copy( this.projectionMatrix );
  6204. return camera;
  6205. };
  6206. // File:src/cameras/CubeCamera.js
  6207. /**
  6208. * Camera for rendering cube maps
  6209. * - renders scene into axis-aligned cube
  6210. *
  6211. * @author alteredq / http://alteredqualia.com/
  6212. */
  6213. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  6214. THREE.Object3D.call( this );
  6215. this.type = 'CubeCamera';
  6216. var fov = 90, aspect = 1;
  6217. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6218. cameraPX.up.set( 0, - 1, 0 );
  6219. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  6220. this.add( cameraPX );
  6221. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6222. cameraNX.up.set( 0, - 1, 0 );
  6223. cameraNX.lookAt( new THREE.Vector3( - 1, 0, 0 ) );
  6224. this.add( cameraNX );
  6225. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6226. cameraPY.up.set( 0, 0, 1 );
  6227. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  6228. this.add( cameraPY );
  6229. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6230. cameraNY.up.set( 0, 0, - 1 );
  6231. cameraNY.lookAt( new THREE.Vector3( 0, - 1, 0 ) );
  6232. this.add( cameraNY );
  6233. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6234. cameraPZ.up.set( 0, - 1, 0 );
  6235. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  6236. this.add( cameraPZ );
  6237. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6238. cameraNZ.up.set( 0, - 1, 0 );
  6239. cameraNZ.lookAt( new THREE.Vector3( 0, 0, - 1 ) );
  6240. this.add( cameraNZ );
  6241. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  6242. this.updateCubeMap = function ( renderer, scene ) {
  6243. var renderTarget = this.renderTarget;
  6244. var generateMipmaps = renderTarget.generateMipmaps;
  6245. renderTarget.generateMipmaps = false;
  6246. renderTarget.activeCubeFace = 0;
  6247. renderer.render( scene, cameraPX, renderTarget );
  6248. renderTarget.activeCubeFace = 1;
  6249. renderer.render( scene, cameraNX, renderTarget );
  6250. renderTarget.activeCubeFace = 2;
  6251. renderer.render( scene, cameraPY, renderTarget );
  6252. renderTarget.activeCubeFace = 3;
  6253. renderer.render( scene, cameraNY, renderTarget );
  6254. renderTarget.activeCubeFace = 4;
  6255. renderer.render( scene, cameraPZ, renderTarget );
  6256. renderTarget.generateMipmaps = generateMipmaps;
  6257. renderTarget.activeCubeFace = 5;
  6258. renderer.render( scene, cameraNZ, renderTarget );
  6259. };
  6260. };
  6261. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  6262. THREE.CubeCamera.prototype.constructor = THREE.CubeCamera;
  6263. // File:src/cameras/OrthographicCamera.js
  6264. /**
  6265. * @author alteredq / http://alteredqualia.com/
  6266. */
  6267. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  6268. THREE.Camera.call( this );
  6269. this.type = 'OrthographicCamera';
  6270. this.zoom = 1;
  6271. this.left = left;
  6272. this.right = right;
  6273. this.top = top;
  6274. this.bottom = bottom;
  6275. this.near = ( near !== undefined ) ? near : 0.1;
  6276. this.far = ( far !== undefined ) ? far : 2000;
  6277. this.updateProjectionMatrix();
  6278. };
  6279. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  6280. THREE.OrthographicCamera.prototype.constructor = THREE.OrthographicCamera;
  6281. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  6282. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  6283. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  6284. var cx = ( this.right + this.left ) / 2;
  6285. var cy = ( this.top + this.bottom ) / 2;
  6286. this.projectionMatrix.makeOrthographic( cx - dx, cx + dx, cy + dy, cy - dy, this.near, this.far );
  6287. };
  6288. THREE.OrthographicCamera.prototype.clone = function () {
  6289. var camera = new THREE.OrthographicCamera();
  6290. THREE.Camera.prototype.clone.call( this, camera );
  6291. camera.zoom = this.zoom;
  6292. camera.left = this.left;
  6293. camera.right = this.right;
  6294. camera.top = this.top;
  6295. camera.bottom = this.bottom;
  6296. camera.near = this.near;
  6297. camera.far = this.far;
  6298. camera.projectionMatrix.copy( this.projectionMatrix );
  6299. return camera;
  6300. };
  6301. THREE.OrthographicCamera.prototype.toJSON = function ( meta ) {
  6302. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  6303. data.object.left = this.left;
  6304. data.object.right = this.right;
  6305. data.object.top = this.top;
  6306. data.object.bottom = this.bottom;
  6307. data.object.near = this.near;
  6308. data.object.far = this.far;
  6309. return data;
  6310. };
  6311. // File:src/cameras/PerspectiveCamera.js
  6312. /**
  6313. * @author mrdoob / http://mrdoob.com/
  6314. * @author greggman / http://games.greggman.com/
  6315. * @author zz85 / http://www.lab4games.net/zz85/blog
  6316. */
  6317. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  6318. THREE.Camera.call( this );
  6319. this.type = 'PerspectiveCamera';
  6320. this.zoom = 1;
  6321. this.fov = fov !== undefined ? fov : 50;
  6322. this.aspect = aspect !== undefined ? aspect : 1;
  6323. this.near = near !== undefined ? near : 0.1;
  6324. this.far = far !== undefined ? far : 2000;
  6325. this.updateProjectionMatrix();
  6326. };
  6327. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  6328. THREE.PerspectiveCamera.prototype.constructor = THREE.PerspectiveCamera;
  6329. /**
  6330. * Uses Focal Length (in mm) to estimate and set FOV
  6331. * 35mm (fullframe) camera is used if frame size is not specified;
  6332. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  6333. */
  6334. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  6335. if ( frameHeight === undefined ) frameHeight = 24;
  6336. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  6337. this.updateProjectionMatrix();
  6338. }
  6339. /**
  6340. * Sets an offset in a larger frustum. This is useful for multi-window or
  6341. * multi-monitor/multi-machine setups.
  6342. *
  6343. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6344. * the monitors are in grid like this
  6345. *
  6346. * +---+---+---+
  6347. * | A | B | C |
  6348. * +---+---+---+
  6349. * | D | E | F |
  6350. * +---+---+---+
  6351. *
  6352. * then for each monitor you would call it like this
  6353. *
  6354. * var w = 1920;
  6355. * var h = 1080;
  6356. * var fullWidth = w * 3;
  6357. * var fullHeight = h * 2;
  6358. *
  6359. * --A--
  6360. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6361. * --B--
  6362. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6363. * --C--
  6364. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6365. * --D--
  6366. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6367. * --E--
  6368. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  6369. * --F--
  6370. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  6371. *
  6372. * Note there is no reason monitors have to be the same size or in a grid.
  6373. */
  6374. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  6375. this.fullWidth = fullWidth;
  6376. this.fullHeight = fullHeight;
  6377. this.x = x;
  6378. this.y = y;
  6379. this.width = width;
  6380. this.height = height;
  6381. this.updateProjectionMatrix();
  6382. };
  6383. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  6384. var fov = THREE.Math.radToDeg( 2 * Math.atan( Math.tan( THREE.Math.degToRad( this.fov ) * 0.5 ) / this.zoom ) );
  6385. if ( this.fullWidth ) {
  6386. var aspect = this.fullWidth / this.fullHeight;
  6387. var top = Math.tan( THREE.Math.degToRad( fov * 0.5 ) ) * this.near;
  6388. var bottom = - top;
  6389. var left = aspect * bottom;
  6390. var right = aspect * top;
  6391. var width = Math.abs( right - left );
  6392. var height = Math.abs( top - bottom );
  6393. this.projectionMatrix.makeFrustum(
  6394. left + this.x * width / this.fullWidth,
  6395. left + ( this.x + this.width ) * width / this.fullWidth,
  6396. top - ( this.y + this.height ) * height / this.fullHeight,
  6397. top - this.y * height / this.fullHeight,
  6398. this.near,
  6399. this.far
  6400. );
  6401. } else {
  6402. this.projectionMatrix.makePerspective( fov, this.aspect, this.near, this.far );
  6403. }
  6404. };
  6405. THREE.PerspectiveCamera.prototype.clone = function () {
  6406. var camera = new THREE.PerspectiveCamera();
  6407. THREE.Camera.prototype.clone.call( this, camera );
  6408. camera.zoom = this.zoom;
  6409. camera.fov = this.fov;
  6410. camera.aspect = this.aspect;
  6411. camera.near = this.near;
  6412. camera.far = this.far;
  6413. camera.projectionMatrix.copy( this.projectionMatrix );
  6414. return camera;
  6415. };
  6416. THREE.PerspectiveCamera.prototype.toJSON = function ( meta ) {
  6417. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  6418. data.object.fov = this.fov;
  6419. data.object.aspect = this.aspect;
  6420. data.object.near = this.near;
  6421. data.object.far = this.far;
  6422. return data;
  6423. };
  6424. // File:src/lights/Light.js
  6425. /**
  6426. * @author mrdoob / http://mrdoob.com/
  6427. * @author alteredq / http://alteredqualia.com/
  6428. */
  6429. THREE.Light = function ( color ) {
  6430. THREE.Object3D.call( this );
  6431. this.type = 'Light';
  6432. this.color = new THREE.Color( color );
  6433. };
  6434. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  6435. THREE.Light.prototype.constructor = THREE.Light;
  6436. THREE.Light.prototype.clone = function ( light ) {
  6437. if ( light === undefined ) light = new THREE.Light();
  6438. THREE.Object3D.prototype.clone.call( this, light );
  6439. light.color.copy( this.color );
  6440. return light;
  6441. };
  6442. // File:src/lights/AmbientLight.js
  6443. /**
  6444. * @author mrdoob / http://mrdoob.com/
  6445. */
  6446. THREE.AmbientLight = function ( color ) {
  6447. THREE.Light.call( this, color );
  6448. this.type = 'AmbientLight';
  6449. };
  6450. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  6451. THREE.AmbientLight.prototype.constructor = THREE.AmbientLight;
  6452. THREE.AmbientLight.prototype.clone = function () {
  6453. var light = new THREE.AmbientLight();
  6454. THREE.Light.prototype.clone.call( this, light );
  6455. return light;
  6456. };
  6457. THREE.AmbientLight.prototype.toJSON = function ( meta ) {
  6458. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  6459. data.object.color = this.color.getHex();
  6460. return data;
  6461. };
  6462. // File:src/lights/AreaLight.js
  6463. /**
  6464. * @author MPanknin / http://www.redplant.de/
  6465. * @author alteredq / http://alteredqualia.com/
  6466. */
  6467. THREE.AreaLight = function ( color, intensity ) {
  6468. THREE.Light.call( this, color );
  6469. this.type = 'AreaLight';
  6470. this.normal = new THREE.Vector3( 0, - 1, 0 );
  6471. this.right = new THREE.Vector3( 1, 0, 0 );
  6472. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6473. this.width = 1.0;
  6474. this.height = 1.0;
  6475. this.constantAttenuation = 1.5;
  6476. this.linearAttenuation = 0.5;
  6477. this.quadraticAttenuation = 0.1;
  6478. };
  6479. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  6480. THREE.AreaLight.prototype.constructor = THREE.AreaLight;
  6481. // File:src/lights/DirectionalLight.js
  6482. /**
  6483. * @author mrdoob / http://mrdoob.com/
  6484. * @author alteredq / http://alteredqualia.com/
  6485. */
  6486. THREE.DirectionalLight = function ( color, intensity ) {
  6487. THREE.Light.call( this, color );
  6488. this.type = 'DirectionalLight';
  6489. this.position.set( 0, 1, 0 );
  6490. this.target = new THREE.Object3D();
  6491. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6492. this.castShadow = false;
  6493. this.onlyShadow = false;
  6494. //
  6495. this.shadowCameraNear = 50;
  6496. this.shadowCameraFar = 5000;
  6497. this.shadowCameraLeft = - 500;
  6498. this.shadowCameraRight = 500;
  6499. this.shadowCameraTop = 500;
  6500. this.shadowCameraBottom = - 500;
  6501. this.shadowCameraVisible = false;
  6502. this.shadowBias = 0;
  6503. this.shadowDarkness = 0.5;
  6504. this.shadowMapWidth = 512;
  6505. this.shadowMapHeight = 512;
  6506. //
  6507. this.shadowCascade = false;
  6508. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, - 1000 );
  6509. this.shadowCascadeCount = 2;
  6510. this.shadowCascadeBias = [ 0, 0, 0 ];
  6511. this.shadowCascadeWidth = [ 512, 512, 512 ];
  6512. this.shadowCascadeHeight = [ 512, 512, 512 ];
  6513. this.shadowCascadeNearZ = [ - 1.000, 0.990, 0.998 ];
  6514. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  6515. this.shadowCascadeArray = [];
  6516. //
  6517. this.shadowMap = null;
  6518. this.shadowMapSize = null;
  6519. this.shadowCamera = null;
  6520. this.shadowMatrix = null;
  6521. };
  6522. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  6523. THREE.DirectionalLight.prototype.constructor = THREE.DirectionalLight;
  6524. THREE.DirectionalLight.prototype.clone = function () {
  6525. var light = new THREE.DirectionalLight();
  6526. THREE.Light.prototype.clone.call( this, light );
  6527. light.target = this.target.clone();
  6528. light.intensity = this.intensity;
  6529. light.castShadow = this.castShadow;
  6530. light.onlyShadow = this.onlyShadow;
  6531. //
  6532. light.shadowCameraNear = this.shadowCameraNear;
  6533. light.shadowCameraFar = this.shadowCameraFar;
  6534. light.shadowCameraLeft = this.shadowCameraLeft;
  6535. light.shadowCameraRight = this.shadowCameraRight;
  6536. light.shadowCameraTop = this.shadowCameraTop;
  6537. light.shadowCameraBottom = this.shadowCameraBottom;
  6538. light.shadowCameraVisible = this.shadowCameraVisible;
  6539. light.shadowBias = this.shadowBias;
  6540. light.shadowDarkness = this.shadowDarkness;
  6541. light.shadowMapWidth = this.shadowMapWidth;
  6542. light.shadowMapHeight = this.shadowMapHeight;
  6543. //
  6544. light.shadowCascade = this.shadowCascade;
  6545. light.shadowCascadeOffset.copy( this.shadowCascadeOffset );
  6546. light.shadowCascadeCount = this.shadowCascadeCount;
  6547. light.shadowCascadeBias = this.shadowCascadeBias.slice( 0 );
  6548. light.shadowCascadeWidth = this.shadowCascadeWidth.slice( 0 );
  6549. light.shadowCascadeHeight = this.shadowCascadeHeight.slice( 0 );
  6550. light.shadowCascadeNearZ = this.shadowCascadeNearZ.slice( 0 );
  6551. light.shadowCascadeFarZ = this.shadowCascadeFarZ.slice( 0 );
  6552. return light;
  6553. };
  6554. THREE.DirectionalLight.prototype.toJSON = function ( meta ) {
  6555. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  6556. data.object.color = this.color.getHex();
  6557. data.object.intensity = this.intensity;
  6558. return data;
  6559. };
  6560. // File:src/lights/HemisphereLight.js
  6561. /**
  6562. * @author alteredq / http://alteredqualia.com/
  6563. */
  6564. THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
  6565. THREE.Light.call( this, skyColor );
  6566. this.type = 'HemisphereLight';
  6567. this.position.set( 0, 100, 0 );
  6568. this.groundColor = new THREE.Color( groundColor );
  6569. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6570. };
  6571. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  6572. THREE.HemisphereLight.prototype.constructor = THREE.HemisphereLight;
  6573. THREE.HemisphereLight.prototype.clone = function () {
  6574. var light = new THREE.HemisphereLight();
  6575. THREE.Light.prototype.clone.call( this, light );
  6576. light.groundColor.copy( this.groundColor );
  6577. light.intensity = this.intensity;
  6578. return light;
  6579. };
  6580. THREE.HemisphereLight.prototype.toJSON = function ( meta ) {
  6581. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  6582. data.object.color = this.color.getHex();
  6583. data.object.groundColor = this.groundColor.getHex();
  6584. return data;
  6585. };
  6586. // File:src/lights/PointLight.js
  6587. /**
  6588. * @author mrdoob / http://mrdoob.com/
  6589. */
  6590. THREE.PointLight = function ( color, intensity, distance, decay ) {
  6591. THREE.Light.call( this, color );
  6592. this.type = 'PointLight';
  6593. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6594. this.distance = ( distance !== undefined ) ? distance : 0;
  6595. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  6596. };
  6597. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  6598. THREE.PointLight.prototype.constructor = THREE.PointLight;
  6599. THREE.PointLight.prototype.clone = function () {
  6600. var light = new THREE.PointLight();
  6601. THREE.Light.prototype.clone.call( this, light );
  6602. light.intensity = this.intensity;
  6603. light.distance = this.distance;
  6604. light.decay = this.decay;
  6605. return light;
  6606. };
  6607. THREE.PointLight.prototype.toJSON = function ( meta ) {
  6608. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  6609. data.object.color = this.color.getHex();
  6610. data.object.intensity = this.intensity;
  6611. data.object.distance = this.distance;
  6612. data.object.decay = this.decay;
  6613. return data;
  6614. };
  6615. // File:src/lights/SpotLight.js
  6616. /**
  6617. * @author alteredq / http://alteredqualia.com/
  6618. */
  6619. THREE.SpotLight = function ( color, intensity, distance, angle, exponent, decay ) {
  6620. THREE.Light.call( this, color );
  6621. this.type = 'SpotLight';
  6622. this.position.set( 0, 1, 0 );
  6623. this.target = new THREE.Object3D();
  6624. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6625. this.distance = ( distance !== undefined ) ? distance : 0;
  6626. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  6627. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  6628. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  6629. this.castShadow = false;
  6630. this.onlyShadow = false;
  6631. //
  6632. this.shadowCameraNear = 50;
  6633. this.shadowCameraFar = 5000;
  6634. this.shadowCameraFov = 50;
  6635. this.shadowCameraVisible = false;
  6636. this.shadowBias = 0;
  6637. this.shadowDarkness = 0.5;
  6638. this.shadowMapWidth = 512;
  6639. this.shadowMapHeight = 512;
  6640. //
  6641. this.shadowMap = null;
  6642. this.shadowMapSize = null;
  6643. this.shadowCamera = null;
  6644. this.shadowMatrix = null;
  6645. };
  6646. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  6647. THREE.SpotLight.prototype.constructor = THREE.SpotLight;
  6648. THREE.SpotLight.prototype.clone = function () {
  6649. var light = new THREE.SpotLight();
  6650. THREE.Light.prototype.clone.call( this, light );
  6651. light.target = this.target.clone();
  6652. light.intensity = this.intensity;
  6653. light.distance = this.distance;
  6654. light.angle = this.angle;
  6655. light.exponent = this.exponent;
  6656. light.decay = this.decay;
  6657. light.castShadow = this.castShadow;
  6658. light.onlyShadow = this.onlyShadow;
  6659. //
  6660. light.shadowCameraNear = this.shadowCameraNear;
  6661. light.shadowCameraFar = this.shadowCameraFar;
  6662. light.shadowCameraFov = this.shadowCameraFov;
  6663. light.shadowCameraVisible = this.shadowCameraVisible;
  6664. light.shadowBias = this.shadowBias;
  6665. light.shadowDarkness = this.shadowDarkness;
  6666. light.shadowMapWidth = this.shadowMapWidth;
  6667. light.shadowMapHeight = this.shadowMapHeight;
  6668. return light;
  6669. };
  6670. THREE.SpotLight.prototype.toJSON = function ( meta ) {
  6671. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  6672. data.object.color = this.color.getHex();
  6673. data.object.intensity = this.intensity;
  6674. data.object.distance = this.distance;
  6675. data.object.angle = this.angle;
  6676. data.object.exponent = this.exponent;
  6677. data.object.decay = this.decay;
  6678. return data;
  6679. };
  6680. // File:src/loaders/Cache.js
  6681. /**
  6682. * @author mrdoob / http://mrdoob.com/
  6683. */
  6684. THREE.Cache = {
  6685. files: {},
  6686. add: function ( key, file ) {
  6687. // THREE.log( 'THREE.Cache', 'Adding key:', key );
  6688. this.files[ key ] = file;
  6689. },
  6690. get: function ( key ) {
  6691. // THREE.log( 'THREE.Cache', 'Checking key:', key );
  6692. return this.files[ key ];
  6693. },
  6694. remove: function ( key ) {
  6695. delete this.files[ key ];
  6696. },
  6697. clear: function () {
  6698. this.files = {}
  6699. }
  6700. };
  6701. // File:src/loaders/Loader.js
  6702. /**
  6703. * @author alteredq / http://alteredqualia.com/
  6704. */
  6705. THREE.Loader = function ( showStatus ) {
  6706. this.showStatus = showStatus;
  6707. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  6708. this.imageLoader = new THREE.ImageLoader();
  6709. this.onLoadStart = function () {};
  6710. this.onLoadProgress = function () {};
  6711. this.onLoadComplete = function () {};
  6712. };
  6713. THREE.Loader.prototype = {
  6714. constructor: THREE.Loader,
  6715. crossOrigin: undefined,
  6716. addStatusElement: function () {
  6717. var e = document.createElement( 'div' );
  6718. e.style.position = 'absolute';
  6719. e.style.right = '0px';
  6720. e.style.top = '0px';
  6721. e.style.fontSize = '0.8em';
  6722. e.style.textAlign = 'left';
  6723. e.style.background = 'rgba(0,0,0,0.25)';
  6724. e.style.color = '#fff';
  6725. e.style.width = '120px';
  6726. e.style.padding = '0.5em 0.5em 0.5em 0.5em';
  6727. e.style.zIndex = 1000;
  6728. e.innerHTML = 'Loading ...';
  6729. return e;
  6730. },
  6731. updateProgress: function ( progress ) {
  6732. var message = 'Loaded ';
  6733. if ( progress.total ) {
  6734. message += ( 100 * progress.loaded / progress.total ).toFixed( 0 ) + '%';
  6735. } else {
  6736. message += ( progress.loaded / 1024 ).toFixed( 2 ) + ' KB';
  6737. }
  6738. this.statusDomElement.innerHTML = message;
  6739. },
  6740. extractUrlBase: function ( url ) {
  6741. var parts = url.split( '/' );
  6742. if ( parts.length === 1 ) return './';
  6743. parts.pop();
  6744. return parts.join( '/' ) + '/';
  6745. },
  6746. initMaterials: function ( materials, texturePath ) {
  6747. var array = [];
  6748. for ( var i = 0; i < materials.length; ++ i ) {
  6749. array[ i ] = this.createMaterial( materials[ i ], texturePath );
  6750. }
  6751. return array;
  6752. },
  6753. needsTangents: function ( materials ) {
  6754. for ( var i = 0, il = materials.length; i < il; i ++ ) {
  6755. var m = materials[ i ];
  6756. if ( m instanceof THREE.ShaderMaterial ) return true;
  6757. }
  6758. return false;
  6759. },
  6760. createMaterial: function ( m, texturePath ) {
  6761. var scope = this;
  6762. function nearest_pow2( n ) {
  6763. var l = Math.log( n ) / Math.LN2;
  6764. return Math.pow( 2, Math.round( l ) );
  6765. }
  6766. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  6767. var fullPath = texturePath + sourceFile;
  6768. var texture;
  6769. var loader = THREE.Loader.Handlers.get( fullPath );
  6770. if ( loader !== null ) {
  6771. texture = loader.load( fullPath );
  6772. } else {
  6773. texture = new THREE.Texture();
  6774. loader = scope.imageLoader;
  6775. loader.crossOrigin = scope.crossOrigin;
  6776. loader.load( fullPath, function ( image ) {
  6777. if ( THREE.Math.isPowerOfTwo( image.width ) === false ||
  6778. THREE.Math.isPowerOfTwo( image.height ) === false ) {
  6779. var width = nearest_pow2( image.width );
  6780. var height = nearest_pow2( image.height );
  6781. var canvas = document.createElement( 'canvas' );
  6782. canvas.width = width;
  6783. canvas.height = height;
  6784. var context = canvas.getContext( '2d' );
  6785. context.drawImage( image, 0, 0, width, height );
  6786. texture.image = canvas;
  6787. } else {
  6788. texture.image = image;
  6789. }
  6790. texture.needsUpdate = true;
  6791. } );
  6792. }
  6793. texture.sourceFile = sourceFile;
  6794. if ( repeat ) {
  6795. texture.repeat.set( repeat[ 0 ], repeat[ 1 ] );
  6796. if ( repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  6797. if ( repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  6798. }
  6799. if ( offset ) {
  6800. texture.offset.set( offset[ 0 ], offset[ 1 ] );
  6801. }
  6802. if ( wrap ) {
  6803. var wrapMap = {
  6804. 'repeat': THREE.RepeatWrapping,
  6805. 'mirror': THREE.MirroredRepeatWrapping
  6806. }
  6807. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ wrap[ 0 ] ];
  6808. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ wrap[ 1 ] ];
  6809. }
  6810. if ( anisotropy ) {
  6811. texture.anisotropy = anisotropy;
  6812. }
  6813. where[ name ] = texture;
  6814. }
  6815. function rgb2hex( rgb ) {
  6816. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  6817. }
  6818. // defaults
  6819. var mtype = 'MeshLambertMaterial';
  6820. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  6821. // parameters from model file
  6822. if ( m.shading ) {
  6823. var shading = m.shading.toLowerCase();
  6824. if ( shading === 'phong' ) mtype = 'MeshPhongMaterial';
  6825. else if ( shading === 'basic' ) mtype = 'MeshBasicMaterial';
  6826. }
  6827. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  6828. mpars.blending = THREE[ m.blending ];
  6829. }
  6830. if ( m.transparent !== undefined ) {
  6831. mpars.transparent = m.transparent;
  6832. }
  6833. if ( m.opacity !== undefined && m.opacity < 1.0 ) {
  6834. mpars.transparent = true;
  6835. }
  6836. if ( m.depthTest !== undefined ) {
  6837. mpars.depthTest = m.depthTest;
  6838. }
  6839. if ( m.depthWrite !== undefined ) {
  6840. mpars.depthWrite = m.depthWrite;
  6841. }
  6842. if ( m.visible !== undefined ) {
  6843. mpars.visible = m.visible;
  6844. }
  6845. if ( m.flipSided !== undefined ) {
  6846. mpars.side = THREE.BackSide;
  6847. }
  6848. if ( m.doubleSided !== undefined ) {
  6849. mpars.side = THREE.DoubleSide;
  6850. }
  6851. if ( m.wireframe !== undefined ) {
  6852. mpars.wireframe = m.wireframe;
  6853. }
  6854. if ( m.vertexColors !== undefined ) {
  6855. if ( m.vertexColors === 'face' ) {
  6856. mpars.vertexColors = THREE.FaceColors;
  6857. } else if ( m.vertexColors ) {
  6858. mpars.vertexColors = THREE.VertexColors;
  6859. }
  6860. }
  6861. // colors
  6862. if ( m.colorDiffuse ) {
  6863. mpars.color = rgb2hex( m.colorDiffuse );
  6864. } else if ( m.DbgColor ) {
  6865. mpars.color = m.DbgColor;
  6866. }
  6867. if ( m.colorSpecular ) {
  6868. mpars.specular = rgb2hex( m.colorSpecular );
  6869. }
  6870. if ( m.colorEmissive ) {
  6871. mpars.emissive = rgb2hex( m.colorEmissive );
  6872. }
  6873. // modifiers
  6874. if ( m.transparency !== undefined ) {
  6875. THREE.warn( 'THREE.Loader: transparency has been renamed to opacity' );
  6876. m.opacity = m.transparency;
  6877. }
  6878. if ( m.opacity !== undefined ) {
  6879. mpars.opacity = m.opacity;
  6880. }
  6881. if ( m.specularCoef ) {
  6882. mpars.shininess = m.specularCoef;
  6883. }
  6884. // textures
  6885. if ( m.mapDiffuse && texturePath ) {
  6886. create_texture( mpars, 'map', m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  6887. }
  6888. if ( m.mapLight && texturePath ) {
  6889. create_texture( mpars, 'lightMap', m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  6890. }
  6891. if ( m.mapAO && texturePath ) {
  6892. create_texture( mpars, 'aoMap', m.mapAO, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  6893. }
  6894. if ( m.mapBump && texturePath ) {
  6895. create_texture( mpars, 'bumpMap', m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  6896. }
  6897. if ( m.mapNormal && texturePath ) {
  6898. create_texture( mpars, 'normalMap', m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  6899. }
  6900. if ( m.mapSpecular && texturePath ) {
  6901. create_texture( mpars, 'specularMap', m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  6902. }
  6903. if ( m.mapAlpha && texturePath ) {
  6904. create_texture( mpars, 'alphaMap', m.mapAlpha, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  6905. }
  6906. //
  6907. if ( m.mapBumpScale ) {
  6908. mpars.bumpScale = m.mapBumpScale;
  6909. }
  6910. if ( m.mapNormalFactor ) {
  6911. mpars.normalScale = new THREE.Vector2( m.mapNormalFactor, m.mapNormalFactor );
  6912. }
  6913. var material = new THREE[ mtype ]( mpars );
  6914. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6915. return material;
  6916. }
  6917. };
  6918. THREE.Loader.Handlers = {
  6919. handlers: [],
  6920. add: function ( regex, loader ) {
  6921. this.handlers.push( regex, loader );
  6922. },
  6923. get: function ( file ) {
  6924. for ( var i = 0, l = this.handlers.length; i < l; i += 2 ) {
  6925. var regex = this.handlers[ i ];
  6926. var loader = this.handlers[ i + 1 ];
  6927. if ( regex.test( file ) ) {
  6928. return loader;
  6929. }
  6930. }
  6931. return null;
  6932. }
  6933. };
  6934. // File:src/loaders/XHRLoader.js
  6935. /**
  6936. * @author mrdoob / http://mrdoob.com/
  6937. */
  6938. THREE.XHRLoader = function ( manager ) {
  6939. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6940. };
  6941. THREE.XHRLoader.prototype = {
  6942. constructor: THREE.XHRLoader,
  6943. load: function ( url, onLoad, onProgress, onError ) {
  6944. var scope = this;
  6945. var cached = THREE.Cache.get( url );
  6946. if ( cached !== undefined ) {
  6947. if ( onLoad ) onLoad( cached );
  6948. return;
  6949. }
  6950. var request = new XMLHttpRequest();
  6951. request.open( 'GET', url, true );
  6952. request.addEventListener( 'load', function ( event ) {
  6953. THREE.Cache.add( url, this.response );
  6954. if ( onLoad ) onLoad( this.response );
  6955. scope.manager.itemEnd( url );
  6956. }, false );
  6957. if ( onProgress !== undefined ) {
  6958. request.addEventListener( 'progress', function ( event ) {
  6959. onProgress( event );
  6960. }, false );
  6961. }
  6962. if ( onError !== undefined ) {
  6963. request.addEventListener( 'error', function ( event ) {
  6964. onError( event );
  6965. }, false );
  6966. }
  6967. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  6968. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  6969. request.send( null );
  6970. scope.manager.itemStart( url );
  6971. },
  6972. setResponseType: function ( value ) {
  6973. this.responseType = value;
  6974. },
  6975. setCrossOrigin: function ( value ) {
  6976. this.crossOrigin = value;
  6977. }
  6978. };
  6979. // File:src/loaders/ImageLoader.js
  6980. /**
  6981. * @author mrdoob / http://mrdoob.com/
  6982. */
  6983. THREE.ImageLoader = function ( manager ) {
  6984. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6985. };
  6986. THREE.ImageLoader.prototype = {
  6987. constructor: THREE.ImageLoader,
  6988. load: function ( url, onLoad, onProgress, onError ) {
  6989. var scope = this;
  6990. var cached = THREE.Cache.get( url );
  6991. if ( cached !== undefined ) {
  6992. onLoad( cached );
  6993. return;
  6994. }
  6995. var image = document.createElement( 'img' );
  6996. image.addEventListener( 'load', function ( event ) {
  6997. THREE.Cache.add( url, this );
  6998. if ( onLoad ) onLoad( this );
  6999. scope.manager.itemEnd( url );
  7000. }, false );
  7001. if ( onProgress !== undefined ) {
  7002. image.addEventListener( 'progress', function ( event ) {
  7003. onProgress( event );
  7004. }, false );
  7005. }
  7006. if ( onError !== undefined ) {
  7007. image.addEventListener( 'error', function ( event ) {
  7008. onError( event );
  7009. }, false );
  7010. }
  7011. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  7012. image.src = url;
  7013. scope.manager.itemStart( url );
  7014. return image;
  7015. },
  7016. setCrossOrigin: function ( value ) {
  7017. this.crossOrigin = value;
  7018. }
  7019. }
  7020. // File:src/loaders/JSONLoader.js
  7021. /**
  7022. * @author mrdoob / http://mrdoob.com/
  7023. * @author alteredq / http://alteredqualia.com/
  7024. */
  7025. THREE.JSONLoader = function ( showStatus ) {
  7026. THREE.Loader.call( this, showStatus );
  7027. this.withCredentials = false;
  7028. };
  7029. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  7030. THREE.JSONLoader.prototype.constructor = THREE.JSONLoader;
  7031. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  7032. // todo: unify load API to for easier SceneLoader use
  7033. texturePath = texturePath && ( typeof texturePath === 'string' ) ? texturePath : this.extractUrlBase( url );
  7034. this.onLoadStart();
  7035. this.loadAjaxJSON( this, url, callback, texturePath );
  7036. };
  7037. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  7038. var xhr = new XMLHttpRequest();
  7039. var length = 0;
  7040. xhr.onreadystatechange = function () {
  7041. if ( xhr.readyState === xhr.DONE ) {
  7042. if ( xhr.status === 200 || xhr.status === 0 ) {
  7043. if ( xhr.responseText ) {
  7044. var json = JSON.parse( xhr.responseText );
  7045. var metadata = json.metadata;
  7046. if ( metadata !== undefined ) {
  7047. if ( metadata.type === 'object' ) {
  7048. THREE.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  7049. return;
  7050. }
  7051. if ( metadata.type === 'scene' ) {
  7052. THREE.error( 'THREE.JSONLoader: ' + url + ' seems to be a Scene. Use THREE.SceneLoader instead.' );
  7053. return;
  7054. }
  7055. }
  7056. var result = context.parse( json, texturePath );
  7057. callback( result.geometry, result.materials );
  7058. } else {
  7059. THREE.error( 'THREE.JSONLoader: ' + url + ' seems to be unreachable or the file is empty.' );
  7060. }
  7061. // in context of more complex asset initialization
  7062. // do not block on single failed file
  7063. // maybe should go even one more level up
  7064. context.onLoadComplete();
  7065. } else {
  7066. THREE.error( 'THREE.JSONLoader: Couldn\'t load ' + url + ' (' + xhr.status + ')' );
  7067. }
  7068. } else if ( xhr.readyState === xhr.LOADING ) {
  7069. if ( callbackProgress ) {
  7070. if ( length === 0 ) {
  7071. length = xhr.getResponseHeader( 'Content-Length' );
  7072. }
  7073. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  7074. }
  7075. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  7076. if ( callbackProgress !== undefined ) {
  7077. length = xhr.getResponseHeader( 'Content-Length' );
  7078. }
  7079. }
  7080. };
  7081. xhr.open( 'GET', url, true );
  7082. xhr.withCredentials = this.withCredentials;
  7083. xhr.send( null );
  7084. };
  7085. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  7086. var geometry = new THREE.Geometry(),
  7087. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  7088. parseModel( scale );
  7089. parseSkin();
  7090. parseMorphing( scale );
  7091. geometry.computeFaceNormals();
  7092. geometry.computeBoundingSphere();
  7093. function parseModel( scale ) {
  7094. function isBitSet( value, position ) {
  7095. return value & ( 1 << position );
  7096. }
  7097. var i, j, fi,
  7098. offset, zLength,
  7099. colorIndex, normalIndex, uvIndex, materialIndex,
  7100. type,
  7101. isQuad,
  7102. hasMaterial,
  7103. hasFaceVertexUv,
  7104. hasFaceNormal, hasFaceVertexNormal,
  7105. hasFaceColor, hasFaceVertexColor,
  7106. vertex, face, faceA, faceB, hex, normal,
  7107. uvLayer, uv, u, v,
  7108. faces = json.faces,
  7109. vertices = json.vertices,
  7110. normals = json.normals,
  7111. colors = json.colors,
  7112. nUvLayers = 0;
  7113. if ( json.uvs !== undefined ) {
  7114. // disregard empty arrays
  7115. for ( i = 0; i < json.uvs.length; i ++ ) {
  7116. if ( json.uvs[ i ].length ) nUvLayers ++;
  7117. }
  7118. for ( i = 0; i < nUvLayers; i ++ ) {
  7119. geometry.faceVertexUvs[ i ] = [];
  7120. }
  7121. }
  7122. offset = 0;
  7123. zLength = vertices.length;
  7124. while ( offset < zLength ) {
  7125. vertex = new THREE.Vector3();
  7126. vertex.x = vertices[ offset ++ ] * scale;
  7127. vertex.y = vertices[ offset ++ ] * scale;
  7128. vertex.z = vertices[ offset ++ ] * scale;
  7129. geometry.vertices.push( vertex );
  7130. }
  7131. offset = 0;
  7132. zLength = faces.length;
  7133. while ( offset < zLength ) {
  7134. type = faces[ offset ++ ];
  7135. isQuad = isBitSet( type, 0 );
  7136. hasMaterial = isBitSet( type, 1 );
  7137. hasFaceVertexUv = isBitSet( type, 3 );
  7138. hasFaceNormal = isBitSet( type, 4 );
  7139. hasFaceVertexNormal = isBitSet( type, 5 );
  7140. hasFaceColor = isBitSet( type, 6 );
  7141. hasFaceVertexColor = isBitSet( type, 7 );
  7142. // THREE.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  7143. if ( isQuad ) {
  7144. faceA = new THREE.Face3();
  7145. faceA.a = faces[ offset ];
  7146. faceA.b = faces[ offset + 1 ];
  7147. faceA.c = faces[ offset + 3 ];
  7148. faceB = new THREE.Face3();
  7149. faceB.a = faces[ offset + 1 ];
  7150. faceB.b = faces[ offset + 2 ];
  7151. faceB.c = faces[ offset + 3 ];
  7152. offset += 4;
  7153. if ( hasMaterial ) {
  7154. materialIndex = faces[ offset ++ ];
  7155. faceA.materialIndex = materialIndex;
  7156. faceB.materialIndex = materialIndex;
  7157. }
  7158. // to get face <=> uv index correspondence
  7159. fi = geometry.faces.length;
  7160. if ( hasFaceVertexUv ) {
  7161. for ( i = 0; i < nUvLayers; i ++ ) {
  7162. uvLayer = json.uvs[ i ];
  7163. geometry.faceVertexUvs[ i ][ fi ] = [];
  7164. geometry.faceVertexUvs[ i ][ fi + 1 ] = []
  7165. for ( j = 0; j < 4; j ++ ) {
  7166. uvIndex = faces[ offset ++ ];
  7167. u = uvLayer[ uvIndex * 2 ];
  7168. v = uvLayer[ uvIndex * 2 + 1 ];
  7169. uv = new THREE.Vector2( u, v );
  7170. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7171. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  7172. }
  7173. }
  7174. }
  7175. if ( hasFaceNormal ) {
  7176. normalIndex = faces[ offset ++ ] * 3;
  7177. faceA.normal.set(
  7178. normals[ normalIndex ++ ],
  7179. normals[ normalIndex ++ ],
  7180. normals[ normalIndex ]
  7181. );
  7182. faceB.normal.copy( faceA.normal );
  7183. }
  7184. if ( hasFaceVertexNormal ) {
  7185. for ( i = 0; i < 4; i ++ ) {
  7186. normalIndex = faces[ offset ++ ] * 3;
  7187. normal = new THREE.Vector3(
  7188. normals[ normalIndex ++ ],
  7189. normals[ normalIndex ++ ],
  7190. normals[ normalIndex ]
  7191. );
  7192. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  7193. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  7194. }
  7195. }
  7196. if ( hasFaceColor ) {
  7197. colorIndex = faces[ offset ++ ];
  7198. hex = colors[ colorIndex ];
  7199. faceA.color.setHex( hex );
  7200. faceB.color.setHex( hex );
  7201. }
  7202. if ( hasFaceVertexColor ) {
  7203. for ( i = 0; i < 4; i ++ ) {
  7204. colorIndex = faces[ offset ++ ];
  7205. hex = colors[ colorIndex ];
  7206. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  7207. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  7208. }
  7209. }
  7210. geometry.faces.push( faceA );
  7211. geometry.faces.push( faceB );
  7212. } else {
  7213. face = new THREE.Face3();
  7214. face.a = faces[ offset ++ ];
  7215. face.b = faces[ offset ++ ];
  7216. face.c = faces[ offset ++ ];
  7217. if ( hasMaterial ) {
  7218. materialIndex = faces[ offset ++ ];
  7219. face.materialIndex = materialIndex;
  7220. }
  7221. // to get face <=> uv index correspondence
  7222. fi = geometry.faces.length;
  7223. if ( hasFaceVertexUv ) {
  7224. for ( i = 0; i < nUvLayers; i ++ ) {
  7225. uvLayer = json.uvs[ i ];
  7226. geometry.faceVertexUvs[ i ][ fi ] = [];
  7227. for ( j = 0; j < 3; j ++ ) {
  7228. uvIndex = faces[ offset ++ ];
  7229. u = uvLayer[ uvIndex * 2 ];
  7230. v = uvLayer[ uvIndex * 2 + 1 ];
  7231. uv = new THREE.Vector2( u, v );
  7232. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7233. }
  7234. }
  7235. }
  7236. if ( hasFaceNormal ) {
  7237. normalIndex = faces[ offset ++ ] * 3;
  7238. face.normal.set(
  7239. normals[ normalIndex ++ ],
  7240. normals[ normalIndex ++ ],
  7241. normals[ normalIndex ]
  7242. );
  7243. }
  7244. if ( hasFaceVertexNormal ) {
  7245. for ( i = 0; i < 3; i ++ ) {
  7246. normalIndex = faces[ offset ++ ] * 3;
  7247. normal = new THREE.Vector3(
  7248. normals[ normalIndex ++ ],
  7249. normals[ normalIndex ++ ],
  7250. normals[ normalIndex ]
  7251. );
  7252. face.vertexNormals.push( normal );
  7253. }
  7254. }
  7255. if ( hasFaceColor ) {
  7256. colorIndex = faces[ offset ++ ];
  7257. face.color.setHex( colors[ colorIndex ] );
  7258. }
  7259. if ( hasFaceVertexColor ) {
  7260. for ( i = 0; i < 3; i ++ ) {
  7261. colorIndex = faces[ offset ++ ];
  7262. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  7263. }
  7264. }
  7265. geometry.faces.push( face );
  7266. }
  7267. }
  7268. };
  7269. function parseSkin() {
  7270. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  7271. if ( json.skinWeights ) {
  7272. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  7273. var x = json.skinWeights[ i ];
  7274. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  7275. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  7276. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  7277. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  7278. }
  7279. }
  7280. if ( json.skinIndices ) {
  7281. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  7282. var a = json.skinIndices[ i ];
  7283. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  7284. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  7285. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  7286. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  7287. }
  7288. }
  7289. geometry.bones = json.bones;
  7290. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  7291. THREE.warn( 'THREE.JSONLoader: When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  7292. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  7293. }
  7294. // could change this to json.animations[0] or remove completely
  7295. geometry.animation = json.animation;
  7296. geometry.animations = json.animations;
  7297. };
  7298. function parseMorphing( scale ) {
  7299. if ( json.morphTargets !== undefined ) {
  7300. var i, l, v, vl, dstVertices, srcVertices;
  7301. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  7302. geometry.morphTargets[ i ] = {};
  7303. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  7304. geometry.morphTargets[ i ].vertices = [];
  7305. dstVertices = geometry.morphTargets[ i ].vertices;
  7306. srcVertices = json.morphTargets [ i ].vertices;
  7307. for ( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  7308. var vertex = new THREE.Vector3();
  7309. vertex.x = srcVertices[ v ] * scale;
  7310. vertex.y = srcVertices[ v + 1 ] * scale;
  7311. vertex.z = srcVertices[ v + 2 ] * scale;
  7312. dstVertices.push( vertex );
  7313. }
  7314. }
  7315. }
  7316. if ( json.morphColors !== undefined ) {
  7317. var i, l, c, cl, dstColors, srcColors, color;
  7318. for ( i = 0, l = json.morphColors.length; i < l; i ++ ) {
  7319. geometry.morphColors[ i ] = {};
  7320. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  7321. geometry.morphColors[ i ].colors = [];
  7322. dstColors = geometry.morphColors[ i ].colors;
  7323. srcColors = json.morphColors [ i ].colors;
  7324. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  7325. color = new THREE.Color( 0xffaa00 );
  7326. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  7327. dstColors.push( color );
  7328. }
  7329. }
  7330. }
  7331. };
  7332. if ( json.materials === undefined || json.materials.length === 0 ) {
  7333. return { geometry: geometry };
  7334. } else {
  7335. var materials = this.initMaterials( json.materials, texturePath );
  7336. if ( this.needsTangents( materials ) ) {
  7337. geometry.computeTangents();
  7338. }
  7339. return { geometry: geometry, materials: materials };
  7340. }
  7341. };
  7342. // File:src/loaders/LoadingManager.js
  7343. /**
  7344. * @author mrdoob / http://mrdoob.com/
  7345. */
  7346. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  7347. var scope = this;
  7348. var loaded = 0, total = 0;
  7349. this.onLoad = onLoad;
  7350. this.onProgress = onProgress;
  7351. this.onError = onError;
  7352. this.itemStart = function ( url ) {
  7353. total ++;
  7354. };
  7355. this.itemEnd = function ( url ) {
  7356. loaded ++;
  7357. if ( scope.onProgress !== undefined ) {
  7358. scope.onProgress( url, loaded, total );
  7359. }
  7360. if ( loaded === total && scope.onLoad !== undefined ) {
  7361. scope.onLoad();
  7362. }
  7363. };
  7364. };
  7365. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  7366. // File:src/loaders/BufferGeometryLoader.js
  7367. /**
  7368. * @author mrdoob / http://mrdoob.com/
  7369. */
  7370. THREE.BufferGeometryLoader = function ( manager ) {
  7371. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7372. };
  7373. THREE.BufferGeometryLoader.prototype = {
  7374. constructor: THREE.BufferGeometryLoader,
  7375. load: function ( url, onLoad, onProgress, onError ) {
  7376. var scope = this;
  7377. var loader = new THREE.XHRLoader( scope.manager );
  7378. loader.setCrossOrigin( this.crossOrigin );
  7379. loader.load( url, function ( text ) {
  7380. onLoad( scope.parse( JSON.parse( text ) ) );
  7381. }, onProgress, onError );
  7382. },
  7383. setCrossOrigin: function ( value ) {
  7384. this.crossOrigin = value;
  7385. },
  7386. parse: function ( json ) {
  7387. var geometry = new THREE.BufferGeometry();
  7388. var attributes = json.data.attributes;
  7389. for ( var key in attributes ) {
  7390. var attribute = attributes[ key ];
  7391. var typedArray = new self[ attribute.type ]( attribute.array );
  7392. geometry.addAttribute( key, new THREE.BufferAttribute( typedArray, attribute.itemSize ) );
  7393. }
  7394. var offsets = json.data.offsets;
  7395. if ( offsets !== undefined ) {
  7396. geometry.offsets = JSON.parse( JSON.stringify( offsets ) );
  7397. }
  7398. var boundingSphere = json.data.boundingSphere;
  7399. if ( boundingSphere !== undefined ) {
  7400. var center = new THREE.Vector3();
  7401. if ( boundingSphere.center !== undefined ) {
  7402. center.fromArray( boundingSphere.center );
  7403. }
  7404. geometry.boundingSphere = new THREE.Sphere( center, boundingSphere.radius );
  7405. }
  7406. return geometry;
  7407. }
  7408. };
  7409. // File:src/loaders/MaterialLoader.js
  7410. /**
  7411. * @author mrdoob / http://mrdoob.com/
  7412. */
  7413. THREE.MaterialLoader = function ( manager ) {
  7414. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7415. };
  7416. THREE.MaterialLoader.prototype = {
  7417. constructor: THREE.MaterialLoader,
  7418. load: function ( url, onLoad, onProgress, onError ) {
  7419. var scope = this;
  7420. var loader = new THREE.XHRLoader( scope.manager );
  7421. loader.setCrossOrigin( this.crossOrigin );
  7422. loader.load( url, function ( text ) {
  7423. onLoad( scope.parse( JSON.parse( text ) ) );
  7424. }, onProgress, onError );
  7425. },
  7426. setCrossOrigin: function ( value ) {
  7427. this.crossOrigin = value;
  7428. },
  7429. parse: function ( json ) {
  7430. var material = new THREE[ json.type ];
  7431. if ( json.color !== undefined ) material.color.setHex( json.color );
  7432. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  7433. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  7434. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  7435. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  7436. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  7437. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  7438. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  7439. if ( json.shading !== undefined ) material.shading = json.shading;
  7440. if ( json.blending !== undefined ) material.blending = json.blending;
  7441. if ( json.side !== undefined ) material.side = json.side;
  7442. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  7443. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  7444. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  7445. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  7446. // for PointCloudMaterial
  7447. if ( json.size !== undefined ) material.size = json.size;
  7448. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  7449. if ( json.materials !== undefined ) {
  7450. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  7451. material.materials.push( this.parse( json.materials[ i ] ) );
  7452. }
  7453. }
  7454. return material;
  7455. }
  7456. };
  7457. // File:src/loaders/ObjectLoader.js
  7458. /**
  7459. * @author mrdoob / http://mrdoob.com/
  7460. */
  7461. THREE.ObjectLoader = function ( manager ) {
  7462. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7463. this.texturePath = '';
  7464. };
  7465. THREE.ObjectLoader.prototype = {
  7466. constructor: THREE.ObjectLoader,
  7467. load: function ( url, onLoad, onProgress, onError ) {
  7468. if ( this.texturePath === '' ) {
  7469. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  7470. }
  7471. var scope = this;
  7472. var loader = new THREE.XHRLoader( scope.manager );
  7473. loader.setCrossOrigin( this.crossOrigin );
  7474. loader.load( url, function ( text ) {
  7475. scope.parse( JSON.parse( text ), onLoad );
  7476. }, onProgress, onError );
  7477. },
  7478. setTexturePath: function ( value ) {
  7479. this.texturePath = value;
  7480. },
  7481. setCrossOrigin: function ( value ) {
  7482. this.crossOrigin = value;
  7483. },
  7484. parse: function ( json, onLoad ) {
  7485. var geometries = this.parseGeometries( json.geometries );
  7486. var images = this.parseImages( json.images, function () {
  7487. if ( onLoad !== undefined ) onLoad( object );
  7488. } );
  7489. var textures = this.parseTextures( json.textures, images );
  7490. var materials = this.parseMaterials( json.materials, textures );
  7491. var object = this.parseObject( json.object, geometries, materials );
  7492. if ( json.images === undefined || json.images.length === 0 ) {
  7493. if ( onLoad !== undefined ) onLoad( object );
  7494. }
  7495. return object;
  7496. },
  7497. parseGeometries: function ( json ) {
  7498. var geometries = {};
  7499. if ( json !== undefined ) {
  7500. var geometryLoader = new THREE.JSONLoader();
  7501. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  7502. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7503. var geometry;
  7504. var data = json[ i ];
  7505. switch ( data.type ) {
  7506. case 'PlaneGeometry':
  7507. case 'PlaneBufferGeometry':
  7508. geometry = new THREE[ data.type ](
  7509. data.width,
  7510. data.height,
  7511. data.widthSegments,
  7512. data.heightSegments
  7513. );
  7514. break;
  7515. case 'BoxGeometry':
  7516. case 'CubeGeometry': // backwards compatible
  7517. geometry = new THREE.BoxGeometry(
  7518. data.width,
  7519. data.height,
  7520. data.depth,
  7521. data.widthSegments,
  7522. data.heightSegments,
  7523. data.depthSegments
  7524. );
  7525. break;
  7526. case 'CircleGeometry':
  7527. geometry = new THREE.CircleGeometry(
  7528. data.radius,
  7529. data.segments
  7530. );
  7531. break;
  7532. case 'CylinderGeometry':
  7533. geometry = new THREE.CylinderGeometry(
  7534. data.radiusTop,
  7535. data.radiusBottom,
  7536. data.height,
  7537. data.radialSegments,
  7538. data.heightSegments,
  7539. data.openEnded
  7540. );
  7541. break;
  7542. case 'SphereGeometry':
  7543. geometry = new THREE.SphereGeometry(
  7544. data.radius,
  7545. data.widthSegments,
  7546. data.heightSegments,
  7547. data.phiStart,
  7548. data.phiLength,
  7549. data.thetaStart,
  7550. data.thetaLength
  7551. );
  7552. break;
  7553. case 'IcosahedronGeometry':
  7554. geometry = new THREE.IcosahedronGeometry(
  7555. data.radius,
  7556. data.detail
  7557. );
  7558. break;
  7559. case 'TorusGeometry':
  7560. geometry = new THREE.TorusGeometry(
  7561. data.radius,
  7562. data.tube,
  7563. data.radialSegments,
  7564. data.tubularSegments,
  7565. data.arc
  7566. );
  7567. break;
  7568. case 'TorusKnotGeometry':
  7569. geometry = new THREE.TorusKnotGeometry(
  7570. data.radius,
  7571. data.tube,
  7572. data.radialSegments,
  7573. data.tubularSegments,
  7574. data.p,
  7575. data.q,
  7576. data.heightScale
  7577. );
  7578. break;
  7579. case 'BufferGeometry':
  7580. geometry = bufferGeometryLoader.parse( data );
  7581. break;
  7582. case 'Geometry':
  7583. geometry = geometryLoader.parse( data.data ).geometry;
  7584. break;
  7585. }
  7586. geometry.uuid = data.uuid;
  7587. if ( data.name !== undefined ) geometry.name = data.name;
  7588. geometries[ data.uuid ] = geometry;
  7589. }
  7590. }
  7591. return geometries;
  7592. },
  7593. parseMaterials: function ( json, textures ) {
  7594. var materials = {};
  7595. if ( json !== undefined ) {
  7596. var getTexture = function ( name ) {
  7597. if ( textures[ name ] === undefined ) {
  7598. THREE.warn( 'THREE.ObjectLoader: Undefined texture', name );
  7599. }
  7600. return textures[ name ];
  7601. };
  7602. var loader = new THREE.MaterialLoader();
  7603. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7604. var data = json[ i ];
  7605. var material = loader.parse( data );
  7606. material.uuid = data.uuid;
  7607. if ( data.name !== undefined ) material.name = data.name;
  7608. if ( data.map !== undefined ) {
  7609. material.map = getTexture( data.map );
  7610. }
  7611. if ( data.bumpMap !== undefined ) {
  7612. material.bumpMap = getTexture( data.bumpMap );
  7613. if ( data.bumpScale !== undefined ) {
  7614. material.bumpScale = data.bumpScale;
  7615. }
  7616. }
  7617. if ( data.alphaMap !== undefined ) {
  7618. material.alphaMap = getTexture( data.alphaMap );
  7619. }
  7620. if ( data.envMap !== undefined ) {
  7621. material.envMap = getTexture( data.envMap );
  7622. }
  7623. if ( data.normalMap !== undefined ) {
  7624. material.normalMap = getTexture( data.normalMap );
  7625. if ( data.normalScale !== undefined ) {
  7626. material.normalScale = new THREE.Vector2( data.normalScale, data.normalScale );
  7627. }
  7628. }
  7629. if ( data.lightMap !== undefined ) {
  7630. material.lightMap = getTexture( data.lightMap );
  7631. if ( data.lightMapIntensity !== undefined ) {
  7632. material.lightMapIntensity = data.lightMapIntensity;
  7633. }
  7634. }
  7635. if ( data.aoMap !== undefined ) {
  7636. material.aoMap = getTexture( data.aoMap );
  7637. if ( data.aoMapIntensity !== undefined ) {
  7638. material.aoMapIntensity = data.aoMapIntensity;
  7639. }
  7640. }
  7641. if ( data.specularMap !== undefined ) {
  7642. material.specularMap = getTexture( data.specularMap );
  7643. }
  7644. materials[ data.uuid ] = material;
  7645. }
  7646. }
  7647. return materials;
  7648. },
  7649. parseImages: function ( json, onLoad ) {
  7650. var scope = this;
  7651. var images = {};
  7652. if ( json !== undefined && json.length > 0 ) {
  7653. var manager = new THREE.LoadingManager( onLoad );
  7654. var loader = new THREE.ImageLoader( manager );
  7655. loader.setCrossOrigin( this.crossOrigin );
  7656. var loadImage = function ( url ) {
  7657. scope.manager.itemStart( url );
  7658. return loader.load( url, function () {
  7659. scope.manager.itemEnd( url );
  7660. } );
  7661. };
  7662. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7663. var image = json[ i ];
  7664. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  7665. images[ image.uuid ] = loadImage( path );
  7666. }
  7667. }
  7668. return images;
  7669. },
  7670. parseTextures: function ( json, images ) {
  7671. var textures = {};
  7672. if ( json !== undefined ) {
  7673. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7674. var data = json[ i ];
  7675. if ( data.image === undefined ) {
  7676. THREE.warn( 'THREE.ObjectLoader: No "image" speficied for', data.uuid );
  7677. }
  7678. if ( images[ data.image ] === undefined ) {
  7679. THREE.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  7680. }
  7681. var texture = new THREE.Texture( images[ data.image ] );
  7682. texture.needsUpdate = true;
  7683. texture.uuid = data.uuid;
  7684. if ( data.name !== undefined ) texture.name = data.name;
  7685. if ( data.repeat !== undefined ) texture.repeat = new THREE.Vector2( data.repeat[ 0 ], data.repeat[ 1 ] );
  7686. if ( data.minFilter !== undefined ) texture.minFilter = THREE[ data.minFilter ];
  7687. if ( data.magFilter !== undefined ) texture.magFilter = THREE[ data.magFilter ];
  7688. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  7689. if ( data.wrap instanceof Array ) {
  7690. texture.wrapS = THREE[ data.wrap[ 0 ] ];
  7691. texture.wrapT = THREE[ data.wrap[ 1 ] ];
  7692. }
  7693. textures[ data.uuid ] = texture;
  7694. }
  7695. }
  7696. return textures;
  7697. },
  7698. parseObject: function () {
  7699. var matrix = new THREE.Matrix4();
  7700. return function ( data, geometries, materials ) {
  7701. var object;
  7702. var getGeometry = function ( name ) {
  7703. if ( geometries[ name ] === undefined ) {
  7704. THREE.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  7705. }
  7706. return geometries[ name ];
  7707. };
  7708. var getMaterial = function ( name ) {
  7709. if ( materials[ name ] === undefined ) {
  7710. THREE.warn( 'THREE.ObjectLoader: Undefined material', name );
  7711. }
  7712. return materials[ name ];
  7713. };
  7714. switch ( data.type ) {
  7715. case 'Scene':
  7716. object = new THREE.Scene();
  7717. break;
  7718. case 'PerspectiveCamera':
  7719. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  7720. break;
  7721. case 'OrthographicCamera':
  7722. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  7723. break;
  7724. case 'AmbientLight':
  7725. object = new THREE.AmbientLight( data.color );
  7726. break;
  7727. case 'DirectionalLight':
  7728. object = new THREE.DirectionalLight( data.color, data.intensity );
  7729. break;
  7730. case 'PointLight':
  7731. object = new THREE.PointLight( data.color, data.intensity, data.distance, data.decay );
  7732. break;
  7733. case 'SpotLight':
  7734. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent, data.decay );
  7735. break;
  7736. case 'HemisphereLight':
  7737. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  7738. break;
  7739. case 'Mesh':
  7740. object = new THREE.Mesh( getGeometry( data.geometry ), getMaterial( data.material ) );
  7741. break;
  7742. case 'Line':
  7743. object = new THREE.Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  7744. break;
  7745. case 'PointCloud':
  7746. object = new THREE.PointCloud( getGeometry( data.geometry ), getMaterial( data.material ) );
  7747. break;
  7748. case 'Sprite':
  7749. object = new THREE.Sprite( getMaterial( data.material ) );
  7750. break;
  7751. case 'Group':
  7752. object = new THREE.Group();
  7753. break;
  7754. default:
  7755. object = new THREE.Object3D();
  7756. }
  7757. object.uuid = data.uuid;
  7758. if ( data.name !== undefined ) object.name = data.name;
  7759. if ( data.matrix !== undefined ) {
  7760. matrix.fromArray( data.matrix );
  7761. matrix.decompose( object.position, object.quaternion, object.scale );
  7762. } else {
  7763. if ( data.position !== undefined ) object.position.fromArray( data.position );
  7764. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  7765. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  7766. }
  7767. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  7768. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  7769. if ( data.visible !== undefined ) object.visible = data.visible;
  7770. if ( data.userData !== undefined ) object.userData = data.userData;
  7771. if ( data.children !== undefined ) {
  7772. for ( var child in data.children ) {
  7773. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  7774. }
  7775. }
  7776. return object;
  7777. }
  7778. }()
  7779. };
  7780. // File:src/loaders/TextureLoader.js
  7781. /**
  7782. * @author mrdoob / http://mrdoob.com/
  7783. */
  7784. THREE.TextureLoader = function ( manager ) {
  7785. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7786. };
  7787. THREE.TextureLoader.prototype = {
  7788. constructor: THREE.TextureLoader,
  7789. load: function ( url, onLoad, onProgress, onError ) {
  7790. var scope = this;
  7791. var loader = new THREE.ImageLoader( scope.manager );
  7792. loader.setCrossOrigin( this.crossOrigin );
  7793. loader.load( url, function ( image ) {
  7794. var texture = new THREE.Texture( image );
  7795. texture.needsUpdate = true;
  7796. if ( onLoad !== undefined ) {
  7797. onLoad( texture );
  7798. }
  7799. }, onProgress, onError );
  7800. },
  7801. setCrossOrigin: function ( value ) {
  7802. this.crossOrigin = value;
  7803. }
  7804. };
  7805. // File:src/loaders/BinaryTextureLoader.js
  7806. /**
  7807. * @author Nikos M. / https://github.com/foo123/
  7808. *
  7809. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  7810. */
  7811. THREE.DataTextureLoader = THREE.BinaryTextureLoader = function () {
  7812. // override in sub classes
  7813. this._parser = null;
  7814. };
  7815. THREE.BinaryTextureLoader.prototype = {
  7816. constructor: THREE.BinaryTextureLoader,
  7817. load: function ( url, onLoad, onProgress, onError ) {
  7818. var scope = this;
  7819. var texture = new THREE.DataTexture( );
  7820. var loader = new THREE.XHRLoader();
  7821. loader.setResponseType( 'arraybuffer' );
  7822. loader.load( url, function ( buffer ) {
  7823. var texData = scope._parser( buffer );
  7824. if ( !texData ) return;
  7825. if ( undefined !== texData.image ) {
  7826. texture.image = texData.image;
  7827. } else if ( undefined !== texData.data ) {
  7828. texture.image.width = texData.width;
  7829. texture.image.height = texData.height;
  7830. texture.image.data = texData.data;
  7831. }
  7832. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : THREE.ClampToEdgeWrapping;
  7833. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : THREE.ClampToEdgeWrapping;
  7834. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : THREE.LinearFilter;
  7835. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : THREE.LinearMipMapLinearFilter;
  7836. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  7837. if ( undefined !== texData.format ) {
  7838. texture.format = texData.format;
  7839. }
  7840. if ( undefined !== texData.type ) {
  7841. texture.type = texData.type;
  7842. }
  7843. if ( undefined !== texData.mipmaps ) {
  7844. texture.mipmaps = texData.mipmaps;
  7845. }
  7846. if ( 1 === texData.mipmapCount ) {
  7847. texture.minFilter = THREE.LinearFilter;
  7848. }
  7849. texture.needsUpdate = true;
  7850. if ( onLoad ) onLoad( texture, texData );
  7851. }, onProgress, onError );
  7852. return texture;
  7853. }
  7854. };
  7855. // File:src/loaders/CompressedTextureLoader.js
  7856. /**
  7857. * @author mrdoob / http://mrdoob.com/
  7858. *
  7859. * Abstract Base class to block based textures loader (dds, pvr, ...)
  7860. */
  7861. THREE.CompressedTextureLoader = function () {
  7862. // override in sub classes
  7863. this._parser = null;
  7864. };
  7865. THREE.CompressedTextureLoader.prototype = {
  7866. constructor: THREE.CompressedTextureLoader,
  7867. load: function ( url, onLoad, onError ) {
  7868. var scope = this;
  7869. var images = [];
  7870. var texture = new THREE.CompressedTexture();
  7871. texture.image = images;
  7872. var loader = new THREE.XHRLoader();
  7873. loader.setResponseType( 'arraybuffer' );
  7874. if ( url instanceof Array ) {
  7875. var loaded = 0;
  7876. var loadTexture = function ( i ) {
  7877. loader.load( url[ i ], function ( buffer ) {
  7878. var texDatas = scope._parser( buffer, true );
  7879. images[ i ] = {
  7880. width: texDatas.width,
  7881. height: texDatas.height,
  7882. format: texDatas.format,
  7883. mipmaps: texDatas.mipmaps
  7884. };
  7885. loaded += 1;
  7886. if ( loaded === 6 ) {
  7887. if (texDatas.mipmapCount == 1)
  7888. texture.minFilter = THREE.LinearFilter;
  7889. texture.format = texDatas.format;
  7890. texture.needsUpdate = true;
  7891. if ( onLoad ) onLoad( texture );
  7892. }
  7893. } );
  7894. };
  7895. for ( var i = 0, il = url.length; i < il; ++ i ) {
  7896. loadTexture( i );
  7897. }
  7898. } else {
  7899. // compressed cubemap texture stored in a single DDS file
  7900. loader.load( url, function ( buffer ) {
  7901. var texDatas = scope._parser( buffer, true );
  7902. if ( texDatas.isCubemap ) {
  7903. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  7904. for ( var f = 0; f < faces; f ++ ) {
  7905. images[ f ] = { mipmaps : [] };
  7906. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  7907. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  7908. images[ f ].format = texDatas.format;
  7909. images[ f ].width = texDatas.width;
  7910. images[ f ].height = texDatas.height;
  7911. }
  7912. }
  7913. } else {
  7914. texture.image.width = texDatas.width;
  7915. texture.image.height = texDatas.height;
  7916. texture.mipmaps = texDatas.mipmaps;
  7917. }
  7918. if ( texDatas.mipmapCount === 1 ) {
  7919. texture.minFilter = THREE.LinearFilter;
  7920. }
  7921. texture.format = texDatas.format;
  7922. texture.needsUpdate = true;
  7923. if ( onLoad ) onLoad( texture );
  7924. } );
  7925. }
  7926. return texture;
  7927. }
  7928. };
  7929. // File:src/materials/Material.js
  7930. /**
  7931. * @author mrdoob / http://mrdoob.com/
  7932. * @author alteredq / http://alteredqualia.com/
  7933. */
  7934. THREE.Material = function () {
  7935. Object.defineProperty( this, 'id', { value: THREE.MaterialIdCount ++ } );
  7936. this.uuid = THREE.Math.generateUUID();
  7937. this.name = '';
  7938. this.type = 'Material';
  7939. this.side = THREE.FrontSide;
  7940. this.opacity = 1;
  7941. this.transparent = false;
  7942. this.blending = THREE.NormalBlending;
  7943. this.blendSrc = THREE.SrcAlphaFactor;
  7944. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  7945. this.blendEquation = THREE.AddEquation;
  7946. this.blendSrcAlpha = null;
  7947. this.blendDstAlpha = null;
  7948. this.blendEquationAlpha = null;
  7949. this.depthTest = true;
  7950. this.depthWrite = true;
  7951. this.colorWrite = true;
  7952. this.polygonOffset = false;
  7953. this.polygonOffsetFactor = 0;
  7954. this.polygonOffsetUnits = 0;
  7955. this.alphaTest = 0;
  7956. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  7957. this.visible = true;
  7958. this._needsUpdate = true;
  7959. };
  7960. THREE.Material.prototype = {
  7961. constructor: THREE.Material,
  7962. get needsUpdate () {
  7963. return this._needsUpdate;
  7964. },
  7965. set needsUpdate ( value ) {
  7966. if ( value === true ) this.update();
  7967. this._needsUpdate = value;
  7968. },
  7969. setValues: function ( values ) {
  7970. if ( values === undefined ) return;
  7971. for ( var key in values ) {
  7972. var newValue = values[ key ];
  7973. if ( newValue === undefined ) {
  7974. THREE.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  7975. continue;
  7976. }
  7977. if ( key in this ) {
  7978. var currentValue = this[ key ];
  7979. if ( currentValue instanceof THREE.Color ) {
  7980. currentValue.set( newValue );
  7981. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  7982. currentValue.copy( newValue );
  7983. } else if ( key == 'overdraw' ) {
  7984. // ensure overdraw is backwards-compatable with legacy boolean type
  7985. this[ key ] = Number( newValue );
  7986. } else {
  7987. this[ key ] = newValue;
  7988. }
  7989. }
  7990. }
  7991. },
  7992. toJSON: function() {
  7993. // we will store all serialization data on 'data'
  7994. var data = {};
  7995. // add metadata
  7996. data.metadata = {
  7997. version: 4.4,
  7998. type: 'Material',
  7999. generator: 'Material.toJSON'
  8000. }
  8001. // standard Material serialization
  8002. data.type = this.type;
  8003. data.uuid = this.uuid;
  8004. if ( this.name !== '' ) data.name = this.name;
  8005. if ( this.opacity < 1 ) data.opacity = this.opacity;
  8006. if ( this.transparent !== false ) data.transparent = this.transparent;
  8007. if ( this.wireframe !== false ) data.wireframe = this.wireframe;
  8008. return data;
  8009. },
  8010. clone: function ( material ) {
  8011. if ( material === undefined ) material = new THREE.Material();
  8012. material.name = this.name;
  8013. material.side = this.side;
  8014. material.opacity = this.opacity;
  8015. material.transparent = this.transparent;
  8016. material.blending = this.blending;
  8017. material.blendSrc = this.blendSrc;
  8018. material.blendDst = this.blendDst;
  8019. material.blendEquation = this.blendEquation;
  8020. material.blendSrcAlpha = this.blendSrcAlpha;
  8021. material.blendDstAlpha = this.blendDstAlpha;
  8022. material.blendEquationAlpha = this.blendEquationAlpha;
  8023. material.depthTest = this.depthTest;
  8024. material.depthWrite = this.depthWrite;
  8025. material.polygonOffset = this.polygonOffset;
  8026. material.polygonOffsetFactor = this.polygonOffsetFactor;
  8027. material.polygonOffsetUnits = this.polygonOffsetUnits;
  8028. material.alphaTest = this.alphaTest;
  8029. material.overdraw = this.overdraw;
  8030. material.visible = this.visible;
  8031. return material;
  8032. },
  8033. update: function () {
  8034. this.dispatchEvent( { type: 'update' } );
  8035. },
  8036. dispose: function () {
  8037. this.dispatchEvent( { type: 'dispose' } );
  8038. }
  8039. };
  8040. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  8041. THREE.MaterialIdCount = 0;
  8042. // File:src/materials/LineBasicMaterial.js
  8043. /**
  8044. * @author mrdoob / http://mrdoob.com/
  8045. * @author alteredq / http://alteredqualia.com/
  8046. *
  8047. * parameters = {
  8048. * color: <hex>,
  8049. * opacity: <float>,
  8050. *
  8051. * blending: THREE.NormalBlending,
  8052. * depthTest: <bool>,
  8053. * depthWrite: <bool>,
  8054. *
  8055. * linewidth: <float>,
  8056. * linecap: "round",
  8057. * linejoin: "round",
  8058. *
  8059. * vertexColors: <bool>
  8060. *
  8061. * fog: <bool>
  8062. * }
  8063. */
  8064. THREE.LineBasicMaterial = function ( parameters ) {
  8065. THREE.Material.call( this );
  8066. this.type = 'LineBasicMaterial';
  8067. this.color = new THREE.Color( 0xffffff );
  8068. this.linewidth = 1;
  8069. this.linecap = 'round';
  8070. this.linejoin = 'round';
  8071. this.vertexColors = THREE.NoColors;
  8072. this.fog = true;
  8073. this.setValues( parameters );
  8074. };
  8075. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8076. THREE.LineBasicMaterial.prototype.constructor = THREE.LineBasicMaterial;
  8077. THREE.LineBasicMaterial.prototype.clone = function () {
  8078. var material = new THREE.LineBasicMaterial();
  8079. THREE.Material.prototype.clone.call( this, material );
  8080. material.color.copy( this.color );
  8081. material.linewidth = this.linewidth;
  8082. material.linecap = this.linecap;
  8083. material.linejoin = this.linejoin;
  8084. material.vertexColors = this.vertexColors;
  8085. material.fog = this.fog;
  8086. return material;
  8087. };
  8088. // File:src/materials/LineDashedMaterial.js
  8089. /**
  8090. * @author alteredq / http://alteredqualia.com/
  8091. *
  8092. * parameters = {
  8093. * color: <hex>,
  8094. * opacity: <float>,
  8095. *
  8096. * blending: THREE.NormalBlending,
  8097. * depthTest: <bool>,
  8098. * depthWrite: <bool>,
  8099. *
  8100. * linewidth: <float>,
  8101. *
  8102. * scale: <float>,
  8103. * dashSize: <float>,
  8104. * gapSize: <float>,
  8105. *
  8106. * vertexColors: <bool>
  8107. *
  8108. * fog: <bool>
  8109. * }
  8110. */
  8111. THREE.LineDashedMaterial = function ( parameters ) {
  8112. THREE.Material.call( this );
  8113. this.type = 'LineDashedMaterial';
  8114. this.color = new THREE.Color( 0xffffff );
  8115. this.linewidth = 1;
  8116. this.scale = 1;
  8117. this.dashSize = 3;
  8118. this.gapSize = 1;
  8119. this.vertexColors = false;
  8120. this.fog = true;
  8121. this.setValues( parameters );
  8122. };
  8123. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  8124. THREE.LineDashedMaterial.prototype.constructor = THREE.LineDashedMaterial;
  8125. THREE.LineDashedMaterial.prototype.clone = function () {
  8126. var material = new THREE.LineDashedMaterial();
  8127. THREE.Material.prototype.clone.call( this, material );
  8128. material.color.copy( this.color );
  8129. material.linewidth = this.linewidth;
  8130. material.scale = this.scale;
  8131. material.dashSize = this.dashSize;
  8132. material.gapSize = this.gapSize;
  8133. material.vertexColors = this.vertexColors;
  8134. material.fog = this.fog;
  8135. return material;
  8136. };
  8137. // File:src/materials/MeshBasicMaterial.js
  8138. /**
  8139. * @author mrdoob / http://mrdoob.com/
  8140. * @author alteredq / http://alteredqualia.com/
  8141. *
  8142. * parameters = {
  8143. * color: <hex>,
  8144. * opacity: <float>,
  8145. * map: new THREE.Texture( <Image> ),
  8146. *
  8147. * lightMap: new THREE.Texture( <Image> ),
  8148. *
  8149. * specularMap: new THREE.Texture( <Image> ),
  8150. *
  8151. * alphaMap: new THREE.Texture( <Image> ),
  8152. *
  8153. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8154. * combine: THREE.Multiply,
  8155. * reflectivity: <float>,
  8156. * refractionRatio: <float>,
  8157. *
  8158. * shading: THREE.SmoothShading,
  8159. * blending: THREE.NormalBlending,
  8160. * depthTest: <bool>,
  8161. * depthWrite: <bool>,
  8162. *
  8163. * wireframe: <boolean>,
  8164. * wireframeLinewidth: <float>,
  8165. *
  8166. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8167. *
  8168. * skinning: <bool>,
  8169. * morphTargets: <bool>,
  8170. *
  8171. * fog: <bool>
  8172. * }
  8173. */
  8174. THREE.MeshBasicMaterial = function ( parameters ) {
  8175. THREE.Material.call( this );
  8176. this.type = 'MeshBasicMaterial';
  8177. this.color = new THREE.Color( 0xffffff ); // emissive
  8178. this.map = null;
  8179. this.lightMap = null;
  8180. this.specularMap = null;
  8181. this.alphaMap = null;
  8182. this.envMap = null;
  8183. this.combine = THREE.MultiplyOperation;
  8184. this.reflectivity = 1;
  8185. this.refractionRatio = 0.98;
  8186. this.fog = true;
  8187. this.shading = THREE.SmoothShading;
  8188. this.wireframe = false;
  8189. this.wireframeLinewidth = 1;
  8190. this.wireframeLinecap = 'round';
  8191. this.wireframeLinejoin = 'round';
  8192. this.vertexColors = THREE.NoColors;
  8193. this.skinning = false;
  8194. this.morphTargets = false;
  8195. this.setValues( parameters );
  8196. };
  8197. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8198. THREE.MeshBasicMaterial.prototype.constructor = THREE.MeshBasicMaterial;
  8199. THREE.MeshBasicMaterial.prototype.clone = function () {
  8200. var material = new THREE.MeshBasicMaterial();
  8201. THREE.Material.prototype.clone.call( this, material );
  8202. material.color.copy( this.color );
  8203. material.map = this.map;
  8204. material.lightMap = this.lightMap;
  8205. material.specularMap = this.specularMap;
  8206. material.alphaMap = this.alphaMap;
  8207. material.envMap = this.envMap;
  8208. material.combine = this.combine;
  8209. material.reflectivity = this.reflectivity;
  8210. material.refractionRatio = this.refractionRatio;
  8211. material.fog = this.fog;
  8212. material.shading = this.shading;
  8213. material.wireframe = this.wireframe;
  8214. material.wireframeLinewidth = this.wireframeLinewidth;
  8215. material.wireframeLinecap = this.wireframeLinecap;
  8216. material.wireframeLinejoin = this.wireframeLinejoin;
  8217. material.vertexColors = this.vertexColors;
  8218. material.skinning = this.skinning;
  8219. material.morphTargets = this.morphTargets;
  8220. return material;
  8221. };
  8222. THREE.MeshBasicMaterial.prototype.toJSON = function () {
  8223. var data = THREE.Material.prototype.toJSON.call( this );
  8224. data.color = this.color.getHex();
  8225. if ( this.vertexColors !== THREE.NoColors ) data.vertexColors = this.vertexColors;
  8226. if ( this.blending !== THREE.NormalBlending ) data.blending = this.blending;
  8227. if ( this.side !== THREE.FrontSide ) data.side = this.side;
  8228. return data;
  8229. };
  8230. // File:src/materials/MeshLambertMaterial.js
  8231. /**
  8232. * @author mrdoob / http://mrdoob.com/
  8233. * @author alteredq / http://alteredqualia.com/
  8234. *
  8235. * parameters = {
  8236. * color: <hex>,
  8237. * emissive: <hex>,
  8238. * opacity: <float>,
  8239. *
  8240. * map: new THREE.Texture( <Image> ),
  8241. *
  8242. * lightMap: new THREE.Texture( <Image> ),
  8243. *
  8244. * specularMap: new THREE.Texture( <Image> ),
  8245. *
  8246. * alphaMap: new THREE.Texture( <Image> ),
  8247. *
  8248. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8249. * combine: THREE.Multiply,
  8250. * reflectivity: <float>,
  8251. * refractionRatio: <float>,
  8252. *
  8253. * shading: THREE.SmoothShading,
  8254. * blending: THREE.NormalBlending,
  8255. * depthTest: <bool>,
  8256. * depthWrite: <bool>,
  8257. *
  8258. * wireframe: <boolean>,
  8259. * wireframeLinewidth: <float>,
  8260. *
  8261. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8262. *
  8263. * skinning: <bool>,
  8264. * morphTargets: <bool>,
  8265. * morphNormals: <bool>,
  8266. *
  8267. * fog: <bool>
  8268. * }
  8269. */
  8270. THREE.MeshLambertMaterial = function ( parameters ) {
  8271. THREE.Material.call( this );
  8272. this.type = 'MeshLambertMaterial';
  8273. this.color = new THREE.Color( 0xffffff ); // diffuse
  8274. this.emissive = new THREE.Color( 0x000000 );
  8275. this.wrapAround = false;
  8276. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8277. this.map = null;
  8278. this.lightMap = null;
  8279. this.specularMap = null;
  8280. this.alphaMap = null;
  8281. this.envMap = null;
  8282. this.combine = THREE.MultiplyOperation;
  8283. this.reflectivity = 1;
  8284. this.refractionRatio = 0.98;
  8285. this.fog = true;
  8286. this.shading = THREE.SmoothShading;
  8287. this.wireframe = false;
  8288. this.wireframeLinewidth = 1;
  8289. this.wireframeLinecap = 'round';
  8290. this.wireframeLinejoin = 'round';
  8291. this.vertexColors = THREE.NoColors;
  8292. this.skinning = false;
  8293. this.morphTargets = false;
  8294. this.morphNormals = false;
  8295. this.setValues( parameters );
  8296. };
  8297. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  8298. THREE.MeshLambertMaterial.prototype.constructor = THREE.MeshLambertMaterial;
  8299. THREE.MeshLambertMaterial.prototype.clone = function () {
  8300. var material = new THREE.MeshLambertMaterial();
  8301. THREE.Material.prototype.clone.call( this, material );
  8302. material.color.copy( this.color );
  8303. material.emissive.copy( this.emissive );
  8304. material.wrapAround = this.wrapAround;
  8305. material.wrapRGB.copy( this.wrapRGB );
  8306. material.map = this.map;
  8307. material.lightMap = this.lightMap;
  8308. material.specularMap = this.specularMap;
  8309. material.alphaMap = this.alphaMap;
  8310. material.envMap = this.envMap;
  8311. material.combine = this.combine;
  8312. material.reflectivity = this.reflectivity;
  8313. material.refractionRatio = this.refractionRatio;
  8314. material.fog = this.fog;
  8315. material.shading = this.shading;
  8316. material.wireframe = this.wireframe;
  8317. material.wireframeLinewidth = this.wireframeLinewidth;
  8318. material.wireframeLinecap = this.wireframeLinecap;
  8319. material.wireframeLinejoin = this.wireframeLinejoin;
  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. THREE.MeshLambertMaterial.prototype.toJSON = function () {
  8327. var data = THREE.Material.prototype.toJSON.call( this );
  8328. data.color = this.color.getHex();
  8329. data.emissive = this.emissive.getHex();
  8330. if ( this.vertexColors !== THREE.NoColors ) data.vertexColors = this.vertexColors;
  8331. if ( this.shading !== THREE.SmoothShading ) data.shading = this.shading;
  8332. if ( this.blending !== THREE.NormalBlending ) data.blending = this.blending;
  8333. if ( this.side !== THREE.FrontSide ) data.side = this.side;
  8334. return data;
  8335. };
  8336. // File:src/materials/MeshPhongMaterial.js
  8337. /**
  8338. * @author mrdoob / http://mrdoob.com/
  8339. * @author alteredq / http://alteredqualia.com/
  8340. *
  8341. * parameters = {
  8342. * color: <hex>,
  8343. * emissive: <hex>,
  8344. * specular: <hex>,
  8345. * shininess: <float>,
  8346. * opacity: <float>,
  8347. *
  8348. * map: new THREE.Texture( <Image> ),
  8349. *
  8350. * lightMap: new THREE.Texture( <Image> ),
  8351. * lightMapIntensity: <float>
  8352. *
  8353. * aoMap: new THREE.Texture( <Image> ),
  8354. * aoMapIntensity: <float>
  8355. *
  8356. * bumpMap: new THREE.Texture( <Image> ),
  8357. * bumpScale: <float>,
  8358. *
  8359. * normalMap: new THREE.Texture( <Image> ),
  8360. * normalScale: <Vector2>,
  8361. *
  8362. * specularMap: new THREE.Texture( <Image> ),
  8363. *
  8364. * alphaMap: new THREE.Texture( <Image> ),
  8365. *
  8366. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8367. * combine: THREE.Multiply,
  8368. * reflectivity: <float>,
  8369. * refractionRatio: <float>,
  8370. *
  8371. * shading: THREE.SmoothShading,
  8372. * blending: THREE.NormalBlending,
  8373. * depthTest: <bool>,
  8374. * depthWrite: <bool>,
  8375. *
  8376. * wireframe: <boolean>,
  8377. * wireframeLinewidth: <float>,
  8378. *
  8379. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8380. *
  8381. * skinning: <bool>,
  8382. * morphTargets: <bool>,
  8383. * morphNormals: <bool>,
  8384. *
  8385. * fog: <bool>
  8386. * }
  8387. */
  8388. THREE.MeshPhongMaterial = function ( parameters ) {
  8389. THREE.Material.call( this );
  8390. this.type = 'MeshPhongMaterial';
  8391. this.color = new THREE.Color( 0xffffff ); // diffuse
  8392. this.emissive = new THREE.Color( 0x000000 );
  8393. this.specular = new THREE.Color( 0x111111 );
  8394. this.shininess = 30;
  8395. this.metal = false;
  8396. this.wrapAround = false;
  8397. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8398. this.map = null;
  8399. this.lightMap = null;
  8400. this.lightMapIntensity = 1.0;
  8401. this.aoMap = null;
  8402. this.aoMapIntensity = 1.0;
  8403. this.bumpMap = null;
  8404. this.bumpScale = 1;
  8405. this.normalMap = null;
  8406. this.normalScale = new THREE.Vector2( 1, 1 );
  8407. this.specularMap = null;
  8408. this.alphaMap = null;
  8409. this.envMap = null;
  8410. this.combine = THREE.MultiplyOperation;
  8411. this.reflectivity = 1;
  8412. this.refractionRatio = 0.98;
  8413. this.fog = true;
  8414. this.shading = THREE.SmoothShading;
  8415. this.wireframe = false;
  8416. this.wireframeLinewidth = 1;
  8417. this.wireframeLinecap = 'round';
  8418. this.wireframeLinejoin = 'round';
  8419. this.vertexColors = THREE.NoColors;
  8420. this.skinning = false;
  8421. this.morphTargets = false;
  8422. this.morphNormals = false;
  8423. this.setValues( parameters );
  8424. };
  8425. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  8426. THREE.MeshPhongMaterial.prototype.constructor = THREE.MeshPhongMaterial;
  8427. THREE.MeshPhongMaterial.prototype.clone = function () {
  8428. var material = new THREE.MeshPhongMaterial();
  8429. THREE.Material.prototype.clone.call( this, material );
  8430. material.color.copy( this.color );
  8431. material.emissive.copy( this.emissive );
  8432. material.specular.copy( this.specular );
  8433. material.shininess = this.shininess;
  8434. material.metal = this.metal;
  8435. material.wrapAround = this.wrapAround;
  8436. material.wrapRGB.copy( this.wrapRGB );
  8437. material.map = this.map;
  8438. material.lightMap = this.lightMap;
  8439. material.lightMapIntensity = this.lightMapIntensity;
  8440. material.aoMap = this.aoMap;
  8441. material.aoMapIntensity = this.aoMapIntensity;
  8442. material.bumpMap = this.bumpMap;
  8443. material.bumpScale = this.bumpScale;
  8444. material.normalMap = this.normalMap;
  8445. material.normalScale.copy( this.normalScale );
  8446. material.specularMap = this.specularMap;
  8447. material.alphaMap = this.alphaMap;
  8448. material.envMap = this.envMap;
  8449. material.combine = this.combine;
  8450. material.reflectivity = this.reflectivity;
  8451. material.refractionRatio = this.refractionRatio;
  8452. material.fog = this.fog;
  8453. material.shading = this.shading;
  8454. material.wireframe = this.wireframe;
  8455. material.wireframeLinewidth = this.wireframeLinewidth;
  8456. material.wireframeLinecap = this.wireframeLinecap;
  8457. material.wireframeLinejoin = this.wireframeLinejoin;
  8458. material.vertexColors = this.vertexColors;
  8459. material.skinning = this.skinning;
  8460. material.morphTargets = this.morphTargets;
  8461. material.morphNormals = this.morphNormals;
  8462. return material;
  8463. };
  8464. THREE.MeshPhongMaterial.prototype.toJSON = function () {
  8465. var data = THREE.Material.prototype.toJSON.call( this );
  8466. data.color = this.color.getHex();
  8467. data.emissive = this.emissive.getHex();
  8468. data.specular = this.specular.getHex();
  8469. data.shininess = this.shininess;
  8470. if ( this.vertexColors !== THREE.NoColors ) data.vertexColors = this.vertexColors;
  8471. if ( this.shading !== THREE.SmoothShading ) data.shading = this.shading;
  8472. if ( this.blending !== THREE.NormalBlending ) data.blending = this.blending;
  8473. if ( this.side !== THREE.FrontSide ) data.side = this.side;
  8474. return data;
  8475. };
  8476. // File:src/materials/MeshDepthMaterial.js
  8477. /**
  8478. * @author mrdoob / http://mrdoob.com/
  8479. * @author alteredq / http://alteredqualia.com/
  8480. *
  8481. * parameters = {
  8482. * opacity: <float>,
  8483. *
  8484. * blending: THREE.NormalBlending,
  8485. * depthTest: <bool>,
  8486. * depthWrite: <bool>,
  8487. *
  8488. * wireframe: <boolean>,
  8489. * wireframeLinewidth: <float>
  8490. * }
  8491. */
  8492. THREE.MeshDepthMaterial = function ( parameters ) {
  8493. THREE.Material.call( this );
  8494. this.type = 'MeshDepthMaterial';
  8495. this.morphTargets = false;
  8496. this.wireframe = false;
  8497. this.wireframeLinewidth = 1;
  8498. this.setValues( parameters );
  8499. };
  8500. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  8501. THREE.MeshDepthMaterial.prototype.constructor = THREE.MeshDepthMaterial;
  8502. THREE.MeshDepthMaterial.prototype.clone = function () {
  8503. var material = new THREE.MeshDepthMaterial();
  8504. THREE.Material.prototype.clone.call( this, material );
  8505. material.wireframe = this.wireframe;
  8506. material.wireframeLinewidth = this.wireframeLinewidth;
  8507. return material;
  8508. };
  8509. THREE.MeshDepthMaterial.prototype.toJSON = function () {
  8510. var data = THREE.Material.prototype.toJSON.call( this );
  8511. if ( this.blending !== THREE.NormalBlending ) data.blending = this.blending;
  8512. if ( this.side !== THREE.FrontSide ) data.side = this.side;
  8513. return data;
  8514. };
  8515. // File:src/materials/MeshNormalMaterial.js
  8516. /**
  8517. * @author mrdoob / http://mrdoob.com/
  8518. *
  8519. * parameters = {
  8520. * opacity: <float>,
  8521. *
  8522. * shading: THREE.FlatShading,
  8523. * blending: THREE.NormalBlending,
  8524. * depthTest: <bool>,
  8525. * depthWrite: <bool>,
  8526. *
  8527. * wireframe: <boolean>,
  8528. * wireframeLinewidth: <float>
  8529. * }
  8530. */
  8531. THREE.MeshNormalMaterial = function ( parameters ) {
  8532. THREE.Material.call( this, parameters );
  8533. this.type = 'MeshNormalMaterial';
  8534. this.wireframe = false;
  8535. this.wireframeLinewidth = 1;
  8536. this.morphTargets = false;
  8537. this.setValues( parameters );
  8538. };
  8539. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  8540. THREE.MeshNormalMaterial.prototype.constructor = THREE.MeshNormalMaterial;
  8541. THREE.MeshNormalMaterial.prototype.clone = function () {
  8542. var material = new THREE.MeshNormalMaterial();
  8543. THREE.Material.prototype.clone.call( this, material );
  8544. material.wireframe = this.wireframe;
  8545. material.wireframeLinewidth = this.wireframeLinewidth;
  8546. return material;
  8547. };
  8548. THREE.MeshPhongMaterial.prototype.toJSON = function () {
  8549. var data = THREE.Material.prototype.toJSON.call( this );
  8550. if ( this.blending !== THREE.NormalBlending ) data.blending = this.blending;
  8551. if ( this.side !== THREE.FrontSide ) data.side = this.side;
  8552. return data;
  8553. };
  8554. // File:src/materials/MeshFaceMaterial.js
  8555. /**
  8556. * @author mrdoob / http://mrdoob.com/
  8557. */
  8558. THREE.MeshFaceMaterial = function ( materials ) {
  8559. this.uuid = THREE.Math.generateUUID();
  8560. this.type = 'MeshFaceMaterial';
  8561. this.materials = materials instanceof Array ? materials : [];
  8562. };
  8563. THREE.MeshFaceMaterial.prototype = {
  8564. constructor: THREE.MeshFaceMaterial,
  8565. toJSON: function () {
  8566. var data = THREE.Material.prototype.toJSON.call( this );
  8567. data.materials = [];
  8568. for ( var i = 0, l = this.materials.length; i < l; i ++ ) {
  8569. data.materials.push( this.materials[ i ].toJSON() );
  8570. }
  8571. return data;
  8572. },
  8573. clone: function () {
  8574. var material = new THREE.MeshFaceMaterial();
  8575. for ( var i = 0; i < this.materials.length; i ++ ) {
  8576. material.materials.push( this.materials[ i ].clone() );
  8577. }
  8578. return material;
  8579. }
  8580. };
  8581. // File:src/materials/PointCloudMaterial.js
  8582. /**
  8583. * @author mrdoob / http://mrdoob.com/
  8584. * @author alteredq / http://alteredqualia.com/
  8585. *
  8586. * parameters = {
  8587. * color: <hex>,
  8588. * opacity: <float>,
  8589. * map: new THREE.Texture( <Image> ),
  8590. *
  8591. * size: <float>,
  8592. * sizeAttenuation: <bool>,
  8593. *
  8594. * blending: THREE.NormalBlending,
  8595. * depthTest: <bool>,
  8596. * depthWrite: <bool>,
  8597. *
  8598. * vertexColors: <bool>,
  8599. *
  8600. * fog: <bool>
  8601. * }
  8602. */
  8603. THREE.PointCloudMaterial = function ( parameters ) {
  8604. THREE.Material.call( this );
  8605. this.type = 'PointCloudMaterial';
  8606. this.color = new THREE.Color( 0xffffff );
  8607. this.map = null;
  8608. this.size = 1;
  8609. this.sizeAttenuation = true;
  8610. this.vertexColors = THREE.NoColors;
  8611. this.fog = true;
  8612. this.setValues( parameters );
  8613. };
  8614. THREE.PointCloudMaterial.prototype = Object.create( THREE.Material.prototype );
  8615. THREE.PointCloudMaterial.prototype.constructor = THREE.PointCloudMaterial;
  8616. THREE.PointCloudMaterial.prototype.clone = function () {
  8617. var material = new THREE.PointCloudMaterial();
  8618. THREE.Material.prototype.clone.call( this, material );
  8619. material.color.copy( this.color );
  8620. material.map = this.map;
  8621. material.size = this.size;
  8622. material.sizeAttenuation = this.sizeAttenuation;
  8623. material.vertexColors = this.vertexColors;
  8624. material.fog = this.fog;
  8625. return material;
  8626. };
  8627. THREE.MeshDepthMaterial.prototype.toJSON = function () {
  8628. var data = THREE.Material.prototype.toJSON.call( this );
  8629. data.size = this.size;
  8630. data.sizeAttenuation = this.sizeAttenuation;
  8631. data.color = this.color.getHex();
  8632. if ( this.vertexColors !== THREE.NoColors ) data.vertexColors = this.vertexColors;
  8633. if ( this.blending !== THREE.NormalBlending ) data.blending = this.blending;
  8634. return data;
  8635. };
  8636. // backwards compatibility
  8637. THREE.ParticleBasicMaterial = function ( parameters ) {
  8638. THREE.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointCloudMaterial.' );
  8639. return new THREE.PointCloudMaterial( parameters );
  8640. };
  8641. THREE.ParticleSystemMaterial = function ( parameters ) {
  8642. THREE.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointCloudMaterial.' );
  8643. return new THREE.PointCloudMaterial( parameters );
  8644. };
  8645. // File:src/materials/ShaderMaterial.js
  8646. /**
  8647. * @author alteredq / http://alteredqualia.com/
  8648. *
  8649. * parameters = {
  8650. * defines: { "label" : "value" },
  8651. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  8652. *
  8653. * fragmentShader: <string>,
  8654. * vertexShader: <string>,
  8655. *
  8656. * shading: THREE.SmoothShading,
  8657. * blending: THREE.NormalBlending,
  8658. * depthTest: <bool>,
  8659. * depthWrite: <bool>,
  8660. *
  8661. * wireframe: <boolean>,
  8662. * wireframeLinewidth: <float>,
  8663. *
  8664. * lights: <bool>,
  8665. *
  8666. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8667. *
  8668. * skinning: <bool>,
  8669. * morphTargets: <bool>,
  8670. * morphNormals: <bool>,
  8671. *
  8672. * fog: <bool>
  8673. * }
  8674. */
  8675. THREE.ShaderMaterial = function ( parameters ) {
  8676. THREE.Material.call( this );
  8677. this.type = 'ShaderMaterial';
  8678. this.defines = {};
  8679. this.uniforms = {};
  8680. this.attributes = null;
  8681. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  8682. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  8683. this.shading = THREE.SmoothShading;
  8684. this.linewidth = 1;
  8685. this.wireframe = false;
  8686. this.wireframeLinewidth = 1;
  8687. this.fog = false; // set to use scene fog
  8688. this.lights = false; // set to use scene lights
  8689. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  8690. this.skinning = false; // set to use skinning attribute streams
  8691. this.morphTargets = false; // set to use morph targets
  8692. this.morphNormals = false; // set to use morph normals
  8693. // When rendered geometry doesn't include these attributes but the material does,
  8694. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8695. this.defaultAttributeValues = {
  8696. 'color': [ 1, 1, 1 ],
  8697. 'uv': [ 0, 0 ],
  8698. 'uv2': [ 0, 0 ]
  8699. };
  8700. this.index0AttributeName = undefined;
  8701. this.setValues( parameters );
  8702. };
  8703. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  8704. THREE.ShaderMaterial.prototype.constructor = THREE.ShaderMaterial;
  8705. THREE.ShaderMaterial.prototype.clone = function () {
  8706. var material = new THREE.ShaderMaterial();
  8707. THREE.Material.prototype.clone.call( this, material );
  8708. material.fragmentShader = this.fragmentShader;
  8709. material.vertexShader = this.vertexShader;
  8710. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  8711. material.attributes = this.attributes;
  8712. material.defines = this.defines;
  8713. material.shading = this.shading;
  8714. material.wireframe = this.wireframe;
  8715. material.wireframeLinewidth = this.wireframeLinewidth;
  8716. material.fog = this.fog;
  8717. material.lights = this.lights;
  8718. material.vertexColors = this.vertexColors;
  8719. material.skinning = this.skinning;
  8720. material.morphTargets = this.morphTargets;
  8721. material.morphNormals = this.morphNormals;
  8722. return material;
  8723. };
  8724. THREE.ShaderMaterial.prototype.toJSON = function () {
  8725. var data = THREE.Material.prototype.toJSON.call( this );
  8726. data.uniforms = this.uniforms;
  8727. data.vertexShader = this.vertexShader;
  8728. data.fragmentShader = this.fragmentShader;
  8729. return data;
  8730. };
  8731. // File:src/materials/RawShaderMaterial.js
  8732. /**
  8733. * @author mrdoob / http://mrdoob.com/
  8734. */
  8735. THREE.RawShaderMaterial = function ( parameters ) {
  8736. THREE.ShaderMaterial.call( this, parameters );
  8737. this.type = 'RawShaderMaterial';
  8738. };
  8739. THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype );
  8740. THREE.RawShaderMaterial.prototype.constructor = THREE.RawShaderMaterial;
  8741. THREE.RawShaderMaterial.prototype.clone = function () {
  8742. var material = new THREE.RawShaderMaterial();
  8743. THREE.ShaderMaterial.prototype.clone.call( this, material );
  8744. return material;
  8745. };
  8746. // File:src/materials/SpriteMaterial.js
  8747. /**
  8748. * @author alteredq / http://alteredqualia.com/
  8749. *
  8750. * parameters = {
  8751. * color: <hex>,
  8752. * opacity: <float>,
  8753. * map: new THREE.Texture( <Image> ),
  8754. *
  8755. * blending: THREE.NormalBlending,
  8756. * depthTest: <bool>,
  8757. * depthWrite: <bool>,
  8758. *
  8759. * uvOffset: new THREE.Vector2(),
  8760. * uvScale: new THREE.Vector2(),
  8761. *
  8762. * fog: <bool>
  8763. * }
  8764. */
  8765. THREE.SpriteMaterial = function ( parameters ) {
  8766. THREE.Material.call( this );
  8767. this.type = 'SpriteMaterial';
  8768. this.color = new THREE.Color( 0xffffff );
  8769. this.map = null;
  8770. this.rotation = 0;
  8771. this.fog = false;
  8772. // set parameters
  8773. this.setValues( parameters );
  8774. };
  8775. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  8776. THREE.SpriteMaterial.prototype.constructor = THREE.SpriteMaterial;
  8777. THREE.SpriteMaterial.prototype.clone = function () {
  8778. var material = new THREE.SpriteMaterial();
  8779. THREE.Material.prototype.clone.call( this, material );
  8780. material.color.copy( this.color );
  8781. material.map = this.map;
  8782. material.rotation = this.rotation;
  8783. material.fog = this.fog;
  8784. return material;
  8785. };
  8786. THREE.SpriteMaterial.prototype.toJSON = function () {
  8787. var data = THREE.Material.prototype.toJSON.call( this );
  8788. data.color = this.color.getHex();
  8789. return data;
  8790. };
  8791. // File:src/textures/Texture.js
  8792. /**
  8793. * @author mrdoob / http://mrdoob.com/
  8794. * @author alteredq / http://alteredqualia.com/
  8795. * @author szimek / https://github.com/szimek/
  8796. */
  8797. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8798. Object.defineProperty( this, 'id', { value: THREE.TextureIdCount ++ } );
  8799. this.uuid = THREE.Math.generateUUID();
  8800. this.name = '';
  8801. this.sourceFile = '';
  8802. this.image = image !== undefined ? image : THREE.Texture.DEFAULT_IMAGE;
  8803. this.mipmaps = [];
  8804. this.mapping = mapping !== undefined ? mapping : THREE.Texture.DEFAULT_MAPPING;
  8805. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  8806. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  8807. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  8808. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  8809. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  8810. this.format = format !== undefined ? format : THREE.RGBAFormat;
  8811. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  8812. this.offset = new THREE.Vector2( 0, 0 );
  8813. this.repeat = new THREE.Vector2( 1, 1 );
  8814. this.generateMipmaps = true;
  8815. this.premultiplyAlpha = false;
  8816. this.flipY = true;
  8817. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  8818. this._needsUpdate = false;
  8819. this.onUpdate = null;
  8820. };
  8821. THREE.Texture.DEFAULT_IMAGE = undefined;
  8822. THREE.Texture.DEFAULT_MAPPING = THREE.UVMapping;
  8823. THREE.Texture.prototype = {
  8824. constructor: THREE.Texture,
  8825. get needsUpdate () {
  8826. return this._needsUpdate;
  8827. },
  8828. set needsUpdate ( value ) {
  8829. if ( value === true ) this.update();
  8830. this._needsUpdate = value;
  8831. },
  8832. clone: function ( texture ) {
  8833. if ( texture === undefined ) texture = new THREE.Texture();
  8834. texture.image = this.image;
  8835. texture.mipmaps = this.mipmaps.slice( 0 );
  8836. texture.mapping = this.mapping;
  8837. texture.wrapS = this.wrapS;
  8838. texture.wrapT = this.wrapT;
  8839. texture.magFilter = this.magFilter;
  8840. texture.minFilter = this.minFilter;
  8841. texture.anisotropy = this.anisotropy;
  8842. texture.format = this.format;
  8843. texture.type = this.type;
  8844. texture.offset.copy( this.offset );
  8845. texture.repeat.copy( this.repeat );
  8846. texture.generateMipmaps = this.generateMipmaps;
  8847. texture.premultiplyAlpha = this.premultiplyAlpha;
  8848. texture.flipY = this.flipY;
  8849. texture.unpackAlignment = this.unpackAlignment;
  8850. return texture;
  8851. },
  8852. update: function () {
  8853. this.dispatchEvent( { type: 'update' } );
  8854. },
  8855. dispose: function () {
  8856. this.dispatchEvent( { type: 'dispose' } );
  8857. }
  8858. };
  8859. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  8860. THREE.TextureIdCount = 0;
  8861. // File:src/textures/CubeTexture.js
  8862. /**
  8863. * @author mrdoob / http://mrdoob.com/
  8864. */
  8865. THREE.CubeTexture = function ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8866. mapping = mapping !== undefined ? mapping : THREE.CubeReflectionMapping;
  8867. THREE.Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8868. this.images = images;
  8869. };
  8870. THREE.CubeTexture.prototype = Object.create( THREE.Texture.prototype );
  8871. THREE.CubeTexture.prototype.constructor = THREE.CubeTexture;
  8872. THREE.CubeTexture.clone = function ( texture ) {
  8873. if ( texture === undefined ) texture = new THREE.CubeTexture();
  8874. THREE.Texture.prototype.clone.call( this, texture );
  8875. texture.images = this.images;
  8876. return texture;
  8877. };
  8878. // File:src/textures/CompressedTexture.js
  8879. /**
  8880. * @author alteredq / http://alteredqualia.com/
  8881. */
  8882. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8883. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8884. this.image = { width: width, height: height };
  8885. this.mipmaps = mipmaps;
  8886. // no flipping for cube textures
  8887. // (also flipping doesn't work for compressed textures )
  8888. this.flipY = false;
  8889. // can't generate mipmaps for compressed textures
  8890. // mips must be embedded in DDS files
  8891. this.generateMipmaps = false;
  8892. };
  8893. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  8894. THREE.CompressedTexture.prototype.constructor = THREE.CompressedTexture;
  8895. THREE.CompressedTexture.prototype.clone = function () {
  8896. var texture = new THREE.CompressedTexture();
  8897. THREE.Texture.prototype.clone.call( this, texture );
  8898. return texture;
  8899. };
  8900. // File:src/textures/DataTexture.js
  8901. /**
  8902. * @author alteredq / http://alteredqualia.com/
  8903. */
  8904. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8905. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8906. this.image = { data: data, width: width, height: height };
  8907. };
  8908. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  8909. THREE.DataTexture.prototype.constructor = THREE.DataTexture;
  8910. THREE.DataTexture.prototype.clone = function () {
  8911. var texture = new THREE.DataTexture();
  8912. THREE.Texture.prototype.clone.call( this, texture );
  8913. return texture;
  8914. };
  8915. // File:src/textures/VideoTexture.js
  8916. /**
  8917. * @author mrdoob / http://mrdoob.com/
  8918. */
  8919. THREE.VideoTexture = function ( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8920. THREE.Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8921. this.generateMipmaps = false;
  8922. var scope = this;
  8923. var update = function () {
  8924. requestAnimationFrame( update );
  8925. if ( video.readyState === video.HAVE_ENOUGH_DATA ) {
  8926. scope.needsUpdate = true;
  8927. }
  8928. };
  8929. update();
  8930. };
  8931. THREE.VideoTexture.prototype = Object.create( THREE.Texture.prototype );
  8932. THREE.VideoTexture.prototype.constructor = THREE.VideoTexture;
  8933. // File:src/objects/Group.js
  8934. /**
  8935. * @author mrdoob / http://mrdoob.com/
  8936. */
  8937. THREE.Group = function () {
  8938. THREE.Object3D.call( this );
  8939. this.type = 'Group';
  8940. };
  8941. THREE.Group.prototype = Object.create( THREE.Object3D.prototype );
  8942. THREE.Group.prototype.constructor = THREE.Group;
  8943. // File:src/objects/PointCloud.js
  8944. /**
  8945. * @author alteredq / http://alteredqualia.com/
  8946. */
  8947. THREE.PointCloud = function ( geometry, material ) {
  8948. THREE.Object3D.call( this );
  8949. this.type = 'PointCloud';
  8950. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8951. this.material = material !== undefined ? material : new THREE.PointCloudMaterial( { color: Math.random() * 0xffffff } );
  8952. };
  8953. THREE.PointCloud.prototype = Object.create( THREE.Object3D.prototype );
  8954. THREE.PointCloud.prototype.constructor = THREE.PointCloud;
  8955. THREE.PointCloud.prototype.raycast = ( function () {
  8956. var inverseMatrix = new THREE.Matrix4();
  8957. var ray = new THREE.Ray();
  8958. return function ( raycaster, intersects ) {
  8959. var object = this;
  8960. var geometry = object.geometry;
  8961. var threshold = raycaster.params.PointCloud.threshold;
  8962. inverseMatrix.getInverse( this.matrixWorld );
  8963. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  8964. if ( geometry.boundingBox !== null ) {
  8965. if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) {
  8966. return;
  8967. }
  8968. }
  8969. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  8970. var position = new THREE.Vector3();
  8971. var testPoint = function ( point, index ) {
  8972. var rayPointDistance = ray.distanceToPoint( point );
  8973. if ( rayPointDistance < localThreshold ) {
  8974. var intersectPoint = ray.closestPointToPoint( point );
  8975. intersectPoint.applyMatrix4( object.matrixWorld );
  8976. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  8977. intersects.push( {
  8978. distance: distance,
  8979. distanceToRay: rayPointDistance,
  8980. point: intersectPoint.clone(),
  8981. index: index,
  8982. face: null,
  8983. object: object
  8984. } );
  8985. }
  8986. };
  8987. if ( geometry instanceof THREE.BufferGeometry ) {
  8988. var attributes = geometry.attributes;
  8989. var positions = attributes.position.array;
  8990. if ( attributes.index !== undefined ) {
  8991. var indices = attributes.index.array;
  8992. var offsets = geometry.offsets;
  8993. if ( offsets.length === 0 ) {
  8994. var offset = {
  8995. start: 0,
  8996. count: indices.length,
  8997. index: 0
  8998. };
  8999. offsets = [ offset ];
  9000. }
  9001. for ( var oi = 0, ol = offsets.length; oi < ol; ++ oi ) {
  9002. var start = offsets[ oi ].start;
  9003. var count = offsets[ oi ].count;
  9004. var index = offsets[ oi ].index;
  9005. for ( var i = start, il = start + count; i < il; i ++ ) {
  9006. var a = index + indices[ i ];
  9007. position.fromArray( positions, a * 3 );
  9008. testPoint( position, a );
  9009. }
  9010. }
  9011. } else {
  9012. var pointCount = positions.length / 3;
  9013. for ( var i = 0; i < pointCount; i ++ ) {
  9014. position.set(
  9015. positions[ 3 * i ],
  9016. positions[ 3 * i + 1 ],
  9017. positions[ 3 * i + 2 ]
  9018. );
  9019. testPoint( position, i );
  9020. }
  9021. }
  9022. } else {
  9023. var vertices = this.geometry.vertices;
  9024. for ( var i = 0; i < vertices.length; i ++ ) {
  9025. testPoint( vertices[ i ], i );
  9026. }
  9027. }
  9028. };
  9029. }() );
  9030. THREE.PointCloud.prototype.clone = function ( object ) {
  9031. if ( object === undefined ) object = new THREE.PointCloud( this.geometry, this.material );
  9032. THREE.Object3D.prototype.clone.call( this, object );
  9033. return object;
  9034. };
  9035. THREE.PointCloud.prototype.toJSON = function ( meta ) {
  9036. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  9037. // only serialize if not in meta geometries cache
  9038. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  9039. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON();
  9040. }
  9041. // only serialize if not in meta materials cache
  9042. if ( meta.materials[ this.material.uuid ] === undefined ) {
  9043. meta.materials[ this.material.uuid ] = this.material.toJSON();
  9044. }
  9045. data.object.geometry = this.geometry.uuid;
  9046. data.object.material = this.material.uuid;
  9047. return data;
  9048. };
  9049. // Backwards compatibility
  9050. THREE.ParticleSystem = function ( geometry, material ) {
  9051. THREE.warn( 'THREE.ParticleSystem has been renamed to THREE.PointCloud.' );
  9052. return new THREE.PointCloud( geometry, material );
  9053. };
  9054. // File:src/objects/Line.js
  9055. /**
  9056. * @author mrdoob / http://mrdoob.com/
  9057. */
  9058. THREE.Line = function ( geometry, material, mode ) {
  9059. THREE.Object3D.call( this );
  9060. this.type = 'Line';
  9061. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9062. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  9063. this.mode = mode !== undefined ? mode : THREE.LineStrip;
  9064. };
  9065. THREE.LineStrip = 0;
  9066. THREE.LinePieces = 1;
  9067. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  9068. THREE.Line.prototype.constructor = THREE.Line;
  9069. THREE.Line.prototype.raycast = ( function () {
  9070. var inverseMatrix = new THREE.Matrix4();
  9071. var ray = new THREE.Ray();
  9072. var sphere = new THREE.Sphere();
  9073. return function ( raycaster, intersects ) {
  9074. var precision = raycaster.linePrecision;
  9075. var precisionSq = precision * precision;
  9076. var geometry = this.geometry;
  9077. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9078. // Checking boundingSphere distance to ray
  9079. sphere.copy( geometry.boundingSphere );
  9080. sphere.applyMatrix4( this.matrixWorld );
  9081. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  9082. return;
  9083. }
  9084. inverseMatrix.getInverse( this.matrixWorld );
  9085. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  9086. var vStart = new THREE.Vector3();
  9087. var vEnd = new THREE.Vector3();
  9088. var interSegment = new THREE.Vector3();
  9089. var interRay = new THREE.Vector3();
  9090. var step = this.mode === THREE.LineStrip ? 1 : 2;
  9091. if ( geometry instanceof THREE.BufferGeometry ) {
  9092. var attributes = geometry.attributes;
  9093. if ( attributes.index !== undefined ) {
  9094. var indices = attributes.index.array;
  9095. var positions = attributes.position.array;
  9096. var offsets = geometry.offsets;
  9097. if ( offsets.length === 0 ) {
  9098. offsets = [ { start: 0, count: indices.length, index: 0 } ];
  9099. }
  9100. for ( var oi = 0; oi < offsets.length; oi ++) {
  9101. var start = offsets[ oi ].start;
  9102. var count = offsets[ oi ].count;
  9103. var index = offsets[ oi ].index;
  9104. for ( var i = start; i < start + count - 1; i += step ) {
  9105. var a = index + indices[ i ];
  9106. var b = index + indices[ i + 1 ];
  9107. vStart.fromArray( positions, a * 3 );
  9108. vEnd.fromArray( positions, b * 3 );
  9109. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  9110. if ( distSq > precisionSq ) continue;
  9111. var distance = ray.origin.distanceTo( interRay );
  9112. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  9113. intersects.push( {
  9114. distance: distance,
  9115. // What do we want? intersection point on the ray or on the segment??
  9116. // point: raycaster.ray.at( distance ),
  9117. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  9118. index: i,
  9119. offsetIndex: oi,
  9120. face: null,
  9121. faceIndex: null,
  9122. object: this
  9123. } );
  9124. }
  9125. }
  9126. } else {
  9127. var positions = attributes.position.array;
  9128. for ( var i = 0; i < positions.length / 3 - 1; i += step ) {
  9129. vStart.fromArray( positions, 3 * i );
  9130. vEnd.fromArray( positions, 3 * i + 3 );
  9131. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  9132. if ( distSq > precisionSq ) continue;
  9133. var distance = ray.origin.distanceTo( interRay );
  9134. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  9135. intersects.push( {
  9136. distance: distance,
  9137. // What do we want? intersection point on the ray or on the segment??
  9138. // point: raycaster.ray.at( distance ),
  9139. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  9140. index: i,
  9141. face: null,
  9142. faceIndex: null,
  9143. object: this
  9144. } );
  9145. }
  9146. }
  9147. } else if ( geometry instanceof THREE.Geometry ) {
  9148. var vertices = geometry.vertices;
  9149. var nbVertices = vertices.length;
  9150. for ( var i = 0; i < nbVertices - 1; i += step ) {
  9151. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  9152. if ( distSq > precisionSq ) continue;
  9153. var distance = ray.origin.distanceTo( interRay );
  9154. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  9155. intersects.push( {
  9156. distance: distance,
  9157. // What do we want? intersection point on the ray or on the segment??
  9158. // point: raycaster.ray.at( distance ),
  9159. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  9160. index: i,
  9161. face: null,
  9162. faceIndex: null,
  9163. object: this
  9164. } );
  9165. }
  9166. }
  9167. };
  9168. }() );
  9169. THREE.Line.prototype.clone = function ( object ) {
  9170. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.mode );
  9171. THREE.Object3D.prototype.clone.call( this, object );
  9172. return object;
  9173. };
  9174. THREE.Line.prototype.toJSON = function ( meta ) {
  9175. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  9176. data.object.mode = this.mode;
  9177. // only serialize if not in meta geometries cache
  9178. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  9179. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON();
  9180. }
  9181. // only serialize if not in meta materials cache
  9182. if ( meta.materials[ this.material.uuid ] === undefined ) {
  9183. meta.materials[ this.material.uuid ] = this.material.toJSON();
  9184. }
  9185. data.object.geometry = this.geometry.uuid;
  9186. data.object.material = this.material.uuid;
  9187. return data;
  9188. };
  9189. // File:src/objects/Mesh.js
  9190. /**
  9191. * @author mrdoob / http://mrdoob.com/
  9192. * @author alteredq / http://alteredqualia.com/
  9193. * @author mikael emtinger / http://gomo.se/
  9194. * @author jonobr1 / http://jonobr1.com/
  9195. */
  9196. THREE.Mesh = function ( geometry, material ) {
  9197. THREE.Object3D.call( this );
  9198. this.type = 'Mesh';
  9199. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9200. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  9201. this.updateMorphTargets();
  9202. };
  9203. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  9204. THREE.Mesh.prototype.constructor = THREE.Mesh;
  9205. THREE.Mesh.prototype.updateMorphTargets = function () {
  9206. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  9207. this.morphTargetBase = - 1;
  9208. this.morphTargetForcedOrder = [];
  9209. this.morphTargetInfluences = [];
  9210. this.morphTargetDictionary = {};
  9211. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  9212. this.morphTargetInfluences.push( 0 );
  9213. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  9214. }
  9215. }
  9216. };
  9217. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  9218. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  9219. return this.morphTargetDictionary[ name ];
  9220. }
  9221. THREE.warn( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' );
  9222. return 0;
  9223. };
  9224. THREE.Mesh.prototype.raycast = ( function () {
  9225. var inverseMatrix = new THREE.Matrix4();
  9226. var ray = new THREE.Ray();
  9227. var sphere = new THREE.Sphere();
  9228. var vA = new THREE.Vector3();
  9229. var vB = new THREE.Vector3();
  9230. var vC = new THREE.Vector3();
  9231. return function ( raycaster, intersects ) {
  9232. var geometry = this.geometry;
  9233. // Checking boundingSphere distance to ray
  9234. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9235. sphere.copy( geometry.boundingSphere );
  9236. sphere.applyMatrix4( this.matrixWorld );
  9237. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  9238. return;
  9239. }
  9240. // Check boundingBox before continuing
  9241. inverseMatrix.getInverse( this.matrixWorld );
  9242. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  9243. if ( geometry.boundingBox !== null ) {
  9244. if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) {
  9245. return;
  9246. }
  9247. }
  9248. if ( geometry instanceof THREE.BufferGeometry ) {
  9249. var material = this.material;
  9250. if ( material === undefined ) return;
  9251. var attributes = geometry.attributes;
  9252. var a, b, c;
  9253. var precision = raycaster.precision;
  9254. if ( attributes.index !== undefined ) {
  9255. var indices = attributes.index.array;
  9256. var positions = attributes.position.array;
  9257. var offsets = geometry.offsets;
  9258. if ( offsets.length === 0 ) {
  9259. offsets = [ { start: 0, count: indices.length, index: 0 } ];
  9260. }
  9261. for ( var oi = 0, ol = offsets.length; oi < ol; ++ oi ) {
  9262. var start = offsets[ oi ].start;
  9263. var count = offsets[ oi ].count;
  9264. var index = offsets[ oi ].index;
  9265. for ( var i = start, il = start + count; i < il; i += 3 ) {
  9266. a = index + indices[ i ];
  9267. b = index + indices[ i + 1 ];
  9268. c = index + indices[ i + 2 ];
  9269. vA.fromArray( positions, a * 3 );
  9270. vB.fromArray( positions, b * 3 );
  9271. vC.fromArray( positions, c * 3 );
  9272. if ( material.side === THREE.BackSide ) {
  9273. var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true );
  9274. } else {
  9275. var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  9276. }
  9277. if ( intersectionPoint === null ) continue;
  9278. intersectionPoint.applyMatrix4( this.matrixWorld );
  9279. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  9280. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  9281. intersects.push( {
  9282. distance: distance,
  9283. point: intersectionPoint,
  9284. face: new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) ),
  9285. faceIndex: null,
  9286. object: this
  9287. } );
  9288. }
  9289. }
  9290. } else {
  9291. var positions = attributes.position.array;
  9292. for ( var i = 0, j = 0, il = positions.length; i < il; i += 3, j += 9 ) {
  9293. a = i;
  9294. b = i + 1;
  9295. c = i + 2;
  9296. vA.fromArray( positions, j );
  9297. vB.fromArray( positions, j + 3 );
  9298. vC.fromArray( positions, j + 6 );
  9299. if ( material.side === THREE.BackSide ) {
  9300. var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true );
  9301. } else {
  9302. var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  9303. }
  9304. if ( intersectionPoint === null ) continue;
  9305. intersectionPoint.applyMatrix4( this.matrixWorld );
  9306. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  9307. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  9308. intersects.push( {
  9309. distance: distance,
  9310. point: intersectionPoint,
  9311. face: new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) ),
  9312. faceIndex: null,
  9313. object: this
  9314. } );
  9315. }
  9316. }
  9317. } else if ( geometry instanceof THREE.Geometry ) {
  9318. var isFaceMaterial = this.material instanceof THREE.MeshFaceMaterial;
  9319. var objectMaterials = isFaceMaterial === true ? this.material.materials : null;
  9320. var a, b, c;
  9321. var precision = raycaster.precision;
  9322. var vertices = geometry.vertices;
  9323. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  9324. var face = geometry.faces[ f ];
  9325. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : this.material;
  9326. if ( material === undefined ) continue;
  9327. a = vertices[ face.a ];
  9328. b = vertices[ face.b ];
  9329. c = vertices[ face.c ];
  9330. if ( material.morphTargets === true ) {
  9331. var morphTargets = geometry.morphTargets;
  9332. var morphInfluences = this.morphTargetInfluences;
  9333. vA.set( 0, 0, 0 );
  9334. vB.set( 0, 0, 0 );
  9335. vC.set( 0, 0, 0 );
  9336. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  9337. var influence = morphInfluences[ t ];
  9338. if ( influence === 0 ) continue;
  9339. var targets = morphTargets[ t ].vertices;
  9340. vA.x += ( targets[ face.a ].x - a.x ) * influence;
  9341. vA.y += ( targets[ face.a ].y - a.y ) * influence;
  9342. vA.z += ( targets[ face.a ].z - a.z ) * influence;
  9343. vB.x += ( targets[ face.b ].x - b.x ) * influence;
  9344. vB.y += ( targets[ face.b ].y - b.y ) * influence;
  9345. vB.z += ( targets[ face.b ].z - b.z ) * influence;
  9346. vC.x += ( targets[ face.c ].x - c.x ) * influence;
  9347. vC.y += ( targets[ face.c ].y - c.y ) * influence;
  9348. vC.z += ( targets[ face.c ].z - c.z ) * influence;
  9349. }
  9350. vA.add( a );
  9351. vB.add( b );
  9352. vC.add( c );
  9353. a = vA;
  9354. b = vB;
  9355. c = vC;
  9356. }
  9357. if ( material.side === THREE.BackSide ) {
  9358. var intersectionPoint = ray.intersectTriangle( c, b, a, true );
  9359. } else {
  9360. var intersectionPoint = ray.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide );
  9361. }
  9362. if ( intersectionPoint === null ) continue;
  9363. intersectionPoint.applyMatrix4( this.matrixWorld );
  9364. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  9365. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  9366. intersects.push( {
  9367. distance: distance,
  9368. point: intersectionPoint,
  9369. face: face,
  9370. faceIndex: f,
  9371. object: this
  9372. } );
  9373. }
  9374. }
  9375. };
  9376. }() );
  9377. THREE.Mesh.prototype.clone = function ( object, recursive ) {
  9378. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  9379. THREE.Object3D.prototype.clone.call( this, object, recursive );
  9380. return object;
  9381. };
  9382. THREE.Mesh.prototype.toJSON = function ( meta ) {
  9383. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  9384. // only serialize if not in meta geometries cache
  9385. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  9386. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON();
  9387. }
  9388. // only serialize if not in meta materials cache
  9389. if ( meta.materials[ this.material.uuid ] === undefined ) {
  9390. meta.materials[ this.material.uuid ] = this.material.toJSON();
  9391. }
  9392. data.object.geometry = this.geometry.uuid;
  9393. data.object.material = this.material.uuid;
  9394. return data;
  9395. };
  9396. // File:src/objects/Bone.js
  9397. /**
  9398. * @author mikael emtinger / http://gomo.se/
  9399. * @author alteredq / http://alteredqualia.com/
  9400. * @author ikerr / http://verold.com
  9401. */
  9402. THREE.Bone = function ( skin ) {
  9403. THREE.Object3D.call( this );
  9404. this.type = 'Bone';
  9405. this.skin = skin;
  9406. };
  9407. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  9408. THREE.Bone.prototype.constructor = THREE.Bone;
  9409. // File:src/objects/Skeleton.js
  9410. /**
  9411. * @author mikael emtinger / http://gomo.se/
  9412. * @author alteredq / http://alteredqualia.com/
  9413. * @author michael guerrero / http://realitymeltdown.com
  9414. * @author ikerr / http://verold.com
  9415. */
  9416. THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) {
  9417. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  9418. this.identityMatrix = new THREE.Matrix4();
  9419. // copy the bone array
  9420. bones = bones || [];
  9421. this.bones = bones.slice( 0 );
  9422. // create a bone texture or an array of floats
  9423. if ( this.useVertexTexture ) {
  9424. // layout (1 matrix = 4 pixels)
  9425. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  9426. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  9427. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  9428. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  9429. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  9430. var size;
  9431. if ( this.bones.length > 256 )
  9432. size = 64;
  9433. else if ( this.bones.length > 64 )
  9434. size = 32;
  9435. else if ( this.bones.length > 16 )
  9436. size = 16;
  9437. else
  9438. size = 8;
  9439. this.boneTextureWidth = size;
  9440. this.boneTextureHeight = size;
  9441. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  9442. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  9443. this.boneTexture.minFilter = THREE.NearestFilter;
  9444. this.boneTexture.magFilter = THREE.NearestFilter;
  9445. this.boneTexture.generateMipmaps = false;
  9446. this.boneTexture.flipY = false;
  9447. } else {
  9448. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  9449. }
  9450. // use the supplied bone inverses or calculate the inverses
  9451. if ( boneInverses === undefined ) {
  9452. this.calculateInverses();
  9453. } else {
  9454. if ( this.bones.length === boneInverses.length ) {
  9455. this.boneInverses = boneInverses.slice( 0 );
  9456. } else {
  9457. THREE.warn( 'THREE.Skeleton bonInverses is the wrong length.' );
  9458. this.boneInverses = [];
  9459. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9460. this.boneInverses.push( new THREE.Matrix4() );
  9461. }
  9462. }
  9463. }
  9464. };
  9465. THREE.Skeleton.prototype.calculateInverses = function () {
  9466. this.boneInverses = [];
  9467. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9468. var inverse = new THREE.Matrix4();
  9469. if ( this.bones[ b ] ) {
  9470. inverse.getInverse( this.bones[ b ].matrixWorld );
  9471. }
  9472. this.boneInverses.push( inverse );
  9473. }
  9474. };
  9475. THREE.Skeleton.prototype.pose = function () {
  9476. var bone;
  9477. // recover the bind-time world matrices
  9478. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9479. bone = this.bones[ b ];
  9480. if ( bone ) {
  9481. bone.matrixWorld.getInverse( this.boneInverses[ b ] );
  9482. }
  9483. }
  9484. // compute the local matrices, positions, rotations and scales
  9485. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9486. bone = this.bones[ b ];
  9487. if ( bone ) {
  9488. if ( bone.parent ) {
  9489. bone.matrix.getInverse( bone.parent.matrixWorld );
  9490. bone.matrix.multiply( bone.matrixWorld );
  9491. } else {
  9492. bone.matrix.copy( bone.matrixWorld );
  9493. }
  9494. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  9495. }
  9496. }
  9497. };
  9498. THREE.Skeleton.prototype.update = ( function () {
  9499. var offsetMatrix = new THREE.Matrix4();
  9500. return function () {
  9501. // flatten bone matrices to array
  9502. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9503. // compute the offset between the current and the original transform
  9504. var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix;
  9505. offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] );
  9506. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  9507. }
  9508. if ( this.useVertexTexture ) {
  9509. this.boneTexture.needsUpdate = true;
  9510. }
  9511. };
  9512. } )();
  9513. // File:src/objects/SkinnedMesh.js
  9514. /**
  9515. * @author mikael emtinger / http://gomo.se/
  9516. * @author alteredq / http://alteredqualia.com/
  9517. * @author ikerr / http://verold.com
  9518. */
  9519. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  9520. THREE.Mesh.call( this, geometry, material );
  9521. this.type = 'SkinnedMesh';
  9522. this.bindMode = "attached";
  9523. this.bindMatrix = new THREE.Matrix4();
  9524. this.bindMatrixInverse = new THREE.Matrix4();
  9525. // init bones
  9526. // TODO: remove bone creation as there is no reason (other than
  9527. // convenience) for THREE.SkinnedMesh to do this.
  9528. var bones = [];
  9529. if ( this.geometry && this.geometry.bones !== undefined ) {
  9530. var bone, gbone, p, q, s;
  9531. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  9532. gbone = this.geometry.bones[ b ];
  9533. p = gbone.pos;
  9534. q = gbone.rotq;
  9535. s = gbone.scl;
  9536. bone = new THREE.Bone( this );
  9537. bones.push( bone );
  9538. bone.name = gbone.name;
  9539. bone.position.set( p[ 0 ], p[ 1 ], p[ 2 ] );
  9540. bone.quaternion.set( q[ 0 ], q[ 1 ], q[ 2 ], q[ 3 ] );
  9541. if ( s !== undefined ) {
  9542. bone.scale.set( s[ 0 ], s[ 1 ], s[ 2 ] );
  9543. } else {
  9544. bone.scale.set( 1, 1, 1 );
  9545. }
  9546. }
  9547. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  9548. gbone = this.geometry.bones[ b ];
  9549. if ( gbone.parent !== - 1 ) {
  9550. bones[ gbone.parent ].add( bones[ b ] );
  9551. } else {
  9552. this.add( bones[ b ] );
  9553. }
  9554. }
  9555. }
  9556. this.normalizeSkinWeights();
  9557. this.updateMatrixWorld( true );
  9558. this.bind( new THREE.Skeleton( bones, undefined, useVertexTexture ) );
  9559. };
  9560. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  9561. THREE.SkinnedMesh.prototype.constructor = THREE.SkinnedMesh;
  9562. THREE.SkinnedMesh.prototype.bind = function( skeleton, bindMatrix ) {
  9563. this.skeleton = skeleton;
  9564. if ( bindMatrix === undefined ) {
  9565. this.updateMatrixWorld( true );
  9566. bindMatrix = this.matrixWorld;
  9567. }
  9568. this.bindMatrix.copy( bindMatrix );
  9569. this.bindMatrixInverse.getInverse( bindMatrix );
  9570. };
  9571. THREE.SkinnedMesh.prototype.pose = function () {
  9572. this.skeleton.pose();
  9573. };
  9574. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  9575. if ( this.geometry instanceof THREE.Geometry ) {
  9576. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  9577. var sw = this.geometry.skinWeights[ i ];
  9578. var scale = 1.0 / sw.lengthManhattan();
  9579. if ( scale !== Infinity ) {
  9580. sw.multiplyScalar( scale );
  9581. } else {
  9582. sw.set( 1 ); // this will be normalized by the shader anyway
  9583. }
  9584. }
  9585. } else {
  9586. // skinning weights assumed to be normalized for THREE.BufferGeometry
  9587. }
  9588. };
  9589. THREE.SkinnedMesh.prototype.updateMatrixWorld = function( force ) {
  9590. THREE.Mesh.prototype.updateMatrixWorld.call( this, true );
  9591. if ( this.bindMode === "attached" ) {
  9592. this.bindMatrixInverse.getInverse( this.matrixWorld );
  9593. } else if ( this.bindMode === "detached" ) {
  9594. this.bindMatrixInverse.getInverse( this.bindMatrix );
  9595. } else {
  9596. THREE.warn( 'THREE.SkinnedMesh unreckognized bindMode: ' + this.bindMode );
  9597. }
  9598. };
  9599. THREE.SkinnedMesh.prototype.clone = function( object ) {
  9600. if ( object === undefined ) {
  9601. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  9602. }
  9603. THREE.Mesh.prototype.clone.call( this, object );
  9604. return object;
  9605. };
  9606. // File:src/objects/MorphAnimMesh.js
  9607. /**
  9608. * @author alteredq / http://alteredqualia.com/
  9609. */
  9610. THREE.MorphAnimMesh = function ( geometry, material ) {
  9611. THREE.Mesh.call( this, geometry, material );
  9612. this.type = 'MorphAnimMesh';
  9613. // API
  9614. this.duration = 1000; // milliseconds
  9615. this.mirroredLoop = false;
  9616. this.time = 0;
  9617. // internals
  9618. this.lastKeyframe = 0;
  9619. this.currentKeyframe = 0;
  9620. this.direction = 1;
  9621. this.directionBackwards = false;
  9622. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  9623. };
  9624. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  9625. THREE.MorphAnimMesh.prototype.constructor = THREE.MorphAnimMesh;
  9626. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  9627. this.startKeyframe = start;
  9628. this.endKeyframe = end;
  9629. this.length = this.endKeyframe - this.startKeyframe + 1;
  9630. };
  9631. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  9632. this.direction = 1;
  9633. this.directionBackwards = false;
  9634. };
  9635. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  9636. this.direction = - 1;
  9637. this.directionBackwards = true;
  9638. };
  9639. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  9640. var geometry = this.geometry;
  9641. if ( ! geometry.animations ) geometry.animations = {};
  9642. var firstAnimation, animations = geometry.animations;
  9643. var pattern = /([a-z]+)_?(\d+)/;
  9644. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  9645. var morph = geometry.morphTargets[ i ];
  9646. var parts = morph.name.match( pattern );
  9647. if ( parts && parts.length > 1 ) {
  9648. var label = parts[ 1 ];
  9649. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: - Infinity };
  9650. var animation = animations[ label ];
  9651. if ( i < animation.start ) animation.start = i;
  9652. if ( i > animation.end ) animation.end = i;
  9653. if ( ! firstAnimation ) firstAnimation = label;
  9654. }
  9655. }
  9656. geometry.firstAnimation = firstAnimation;
  9657. };
  9658. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  9659. if ( ! this.geometry.animations ) this.geometry.animations = {};
  9660. this.geometry.animations[ label ] = { start: start, end: end };
  9661. };
  9662. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  9663. var animation = this.geometry.animations[ label ];
  9664. if ( animation ) {
  9665. this.setFrameRange( animation.start, animation.end );
  9666. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  9667. this.time = 0;
  9668. } else {
  9669. THREE.warn( 'THREE.MorphAnimMesh: animation[' + label + '] undefined in .playAnimation()' );
  9670. }
  9671. };
  9672. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  9673. var frameTime = this.duration / this.length;
  9674. this.time += this.direction * delta;
  9675. if ( this.mirroredLoop ) {
  9676. if ( this.time > this.duration || this.time < 0 ) {
  9677. this.direction *= - 1;
  9678. if ( this.time > this.duration ) {
  9679. this.time = this.duration;
  9680. this.directionBackwards = true;
  9681. }
  9682. if ( this.time < 0 ) {
  9683. this.time = 0;
  9684. this.directionBackwards = false;
  9685. }
  9686. }
  9687. } else {
  9688. this.time = this.time % this.duration;
  9689. if ( this.time < 0 ) this.time += this.duration;
  9690. }
  9691. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  9692. if ( keyframe !== this.currentKeyframe ) {
  9693. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  9694. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  9695. this.morphTargetInfluences[ keyframe ] = 0;
  9696. this.lastKeyframe = this.currentKeyframe;
  9697. this.currentKeyframe = keyframe;
  9698. }
  9699. var mix = ( this.time % frameTime ) / frameTime;
  9700. if ( this.directionBackwards ) {
  9701. mix = 1 - mix;
  9702. }
  9703. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  9704. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  9705. };
  9706. THREE.MorphAnimMesh.prototype.interpolateTargets = function ( a, b, t ) {
  9707. var influences = this.morphTargetInfluences;
  9708. for ( var i = 0, l = influences.length; i < l; i ++ ) {
  9709. influences[ i ] = 0;
  9710. }
  9711. if ( a > -1 ) influences[ a ] = 1 - t;
  9712. if ( b > -1 ) influences[ b ] = t;
  9713. };
  9714. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  9715. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  9716. object.duration = this.duration;
  9717. object.mirroredLoop = this.mirroredLoop;
  9718. object.time = this.time;
  9719. object.lastKeyframe = this.lastKeyframe;
  9720. object.currentKeyframe = this.currentKeyframe;
  9721. object.direction = this.direction;
  9722. object.directionBackwards = this.directionBackwards;
  9723. THREE.Mesh.prototype.clone.call( this, object );
  9724. return object;
  9725. };
  9726. // File:src/objects/LOD.js
  9727. /**
  9728. * @author mikael emtinger / http://gomo.se/
  9729. * @author alteredq / http://alteredqualia.com/
  9730. * @author mrdoob / http://mrdoob.com/
  9731. */
  9732. THREE.LOD = function () {
  9733. THREE.Object3D.call( this );
  9734. this.objects = [];
  9735. };
  9736. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  9737. THREE.LOD.prototype.constructor = THREE.LOD;
  9738. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  9739. if ( distance === undefined ) distance = 0;
  9740. distance = Math.abs( distance );
  9741. for ( var l = 0; l < this.objects.length; l ++ ) {
  9742. if ( distance < this.objects[ l ].distance ) {
  9743. break;
  9744. }
  9745. }
  9746. this.objects.splice( l, 0, { distance: distance, object: object } );
  9747. this.add( object );
  9748. };
  9749. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  9750. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9751. if ( distance < this.objects[ i ].distance ) {
  9752. break;
  9753. }
  9754. }
  9755. return this.objects[ i - 1 ].object;
  9756. };
  9757. THREE.LOD.prototype.raycast = ( function () {
  9758. var matrixPosition = new THREE.Vector3();
  9759. return function ( raycaster, intersects ) {
  9760. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  9761. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  9762. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  9763. };
  9764. }() );
  9765. THREE.LOD.prototype.update = function () {
  9766. var v1 = new THREE.Vector3();
  9767. var v2 = new THREE.Vector3();
  9768. return function ( camera ) {
  9769. if ( this.objects.length > 1 ) {
  9770. v1.setFromMatrixPosition( camera.matrixWorld );
  9771. v2.setFromMatrixPosition( this.matrixWorld );
  9772. var distance = v1.distanceTo( v2 );
  9773. this.objects[ 0 ].object.visible = true;
  9774. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9775. if ( distance >= this.objects[ i ].distance ) {
  9776. this.objects[ i - 1 ].object.visible = false;
  9777. this.objects[ i ].object.visible = true;
  9778. } else {
  9779. break;
  9780. }
  9781. }
  9782. for ( ; i < l; i ++ ) {
  9783. this.objects[ i ].object.visible = false;
  9784. }
  9785. }
  9786. };
  9787. }();
  9788. THREE.LOD.prototype.clone = function ( object ) {
  9789. if ( object === undefined ) object = new THREE.LOD();
  9790. THREE.Object3D.prototype.clone.call( this, object );
  9791. for ( var i = 0, l = this.objects.length; i < l; i ++ ) {
  9792. var x = this.objects[ i ].object.clone();
  9793. x.visible = i === 0;
  9794. object.addLevel( x, this.objects[ i ].distance );
  9795. }
  9796. return object;
  9797. };
  9798. // File:src/objects/Sprite.js
  9799. /**
  9800. * @author mikael emtinger / http://gomo.se/
  9801. * @author alteredq / http://alteredqualia.com/
  9802. */
  9803. THREE.Sprite = ( function () {
  9804. var indices = new Uint16Array( [ 0, 1, 2, 0, 2, 3 ] );
  9805. var vertices = new Float32Array( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0, - 0.5, 0.5, 0 ] );
  9806. var uvs = new Float32Array( [ 0, 0, 1, 0, 1, 1, 0, 1 ] );
  9807. var geometry = new THREE.BufferGeometry();
  9808. geometry.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) );
  9809. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  9810. geometry.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  9811. return function ( material ) {
  9812. THREE.Object3D.call( this );
  9813. this.type = 'Sprite';
  9814. this.geometry = geometry;
  9815. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  9816. };
  9817. } )();
  9818. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  9819. THREE.Sprite.prototype.constructor = THREE.Sprite;
  9820. THREE.Sprite.prototype.raycast = ( function () {
  9821. var matrixPosition = new THREE.Vector3();
  9822. return function ( raycaster, intersects ) {
  9823. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  9824. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  9825. if ( distance > this.scale.x ) {
  9826. return;
  9827. }
  9828. intersects.push( {
  9829. distance: distance,
  9830. point: this.position,
  9831. face: null,
  9832. object: this
  9833. } );
  9834. };
  9835. }() );
  9836. THREE.Sprite.prototype.clone = function ( object ) {
  9837. if ( object === undefined ) object = new THREE.Sprite( this.material );
  9838. THREE.Object3D.prototype.clone.call( this, object );
  9839. return object;
  9840. };
  9841. THREE.Sprite.prototype.toJSON = function ( meta ) {
  9842. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  9843. // only serialize if not in meta materials cache
  9844. if ( meta.materials[ this.material.uuid ] === undefined ) {
  9845. meta.materials[ this.material.uuid ] = this.material.toJSON();
  9846. }
  9847. data.object.material = this.material.uuid;
  9848. return data;
  9849. };
  9850. // Backwards compatibility
  9851. THREE.Particle = THREE.Sprite;
  9852. // File:src/objects/LensFlare.js
  9853. /**
  9854. * @author mikael emtinger / http://gomo.se/
  9855. * @author alteredq / http://alteredqualia.com/
  9856. */
  9857. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  9858. THREE.Object3D.call( this );
  9859. this.lensFlares = [];
  9860. this.positionScreen = new THREE.Vector3();
  9861. this.customUpdateCallback = undefined;
  9862. if ( texture !== undefined ) {
  9863. this.add( texture, size, distance, blending, color );
  9864. }
  9865. };
  9866. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  9867. THREE.LensFlare.prototype.constructor = THREE.LensFlare;
  9868. /*
  9869. * Add: adds another flare
  9870. */
  9871. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  9872. if ( size === undefined ) size = - 1;
  9873. if ( distance === undefined ) distance = 0;
  9874. if ( opacity === undefined ) opacity = 1;
  9875. if ( color === undefined ) color = new THREE.Color( 0xffffff );
  9876. if ( blending === undefined ) blending = THREE.NormalBlending;
  9877. distance = Math.min( distance, Math.max( 0, distance ) );
  9878. this.lensFlares.push( {
  9879. texture: texture, // THREE.Texture
  9880. size: size, // size in pixels (-1 = use texture.width)
  9881. distance: distance, // distance (0-1) from light source (0=at light source)
  9882. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  9883. scale: 1, // scale
  9884. rotation: 1, // rotation
  9885. opacity: opacity, // opacity
  9886. color: color, // color
  9887. blending: blending // blending
  9888. } );
  9889. };
  9890. /*
  9891. * Update lens flares update positions on all flares based on the screen position
  9892. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  9893. */
  9894. THREE.LensFlare.prototype.updateLensFlares = function () {
  9895. var f, fl = this.lensFlares.length;
  9896. var flare;
  9897. var vecX = - this.positionScreen.x * 2;
  9898. var vecY = - this.positionScreen.y * 2;
  9899. for ( f = 0; f < fl; f ++ ) {
  9900. flare = this.lensFlares[ f ];
  9901. flare.x = this.positionScreen.x + vecX * flare.distance;
  9902. flare.y = this.positionScreen.y + vecY * flare.distance;
  9903. flare.wantedRotation = flare.x * Math.PI * 0.25;
  9904. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  9905. }
  9906. };
  9907. // File:src/scenes/Scene.js
  9908. /**
  9909. * @author mrdoob / http://mrdoob.com/
  9910. */
  9911. THREE.Scene = function () {
  9912. THREE.Object3D.call( this );
  9913. this.type = 'Scene';
  9914. this.fog = null;
  9915. this.overrideMaterial = null;
  9916. this.autoUpdate = true; // checked by the renderer
  9917. };
  9918. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  9919. THREE.Scene.prototype.constructor = THREE.Scene;
  9920. THREE.Scene.prototype.clone = function ( object ) {
  9921. if ( object === undefined ) object = new THREE.Scene();
  9922. THREE.Object3D.prototype.clone.call( this, object );
  9923. if ( this.fog !== null ) object.fog = this.fog.clone();
  9924. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  9925. object.autoUpdate = this.autoUpdate;
  9926. object.matrixAutoUpdate = this.matrixAutoUpdate;
  9927. return object;
  9928. };
  9929. // File:src/scenes/Fog.js
  9930. /**
  9931. * @author mrdoob / http://mrdoob.com/
  9932. * @author alteredq / http://alteredqualia.com/
  9933. */
  9934. THREE.Fog = function ( color, near, far ) {
  9935. this.name = '';
  9936. this.color = new THREE.Color( color );
  9937. this.near = ( near !== undefined ) ? near : 1;
  9938. this.far = ( far !== undefined ) ? far : 1000;
  9939. };
  9940. THREE.Fog.prototype.clone = function () {
  9941. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  9942. };
  9943. // File:src/scenes/FogExp2.js
  9944. /**
  9945. * @author mrdoob / http://mrdoob.com/
  9946. * @author alteredq / http://alteredqualia.com/
  9947. */
  9948. THREE.FogExp2 = function ( color, density ) {
  9949. this.name = '';
  9950. this.color = new THREE.Color( color );
  9951. this.density = ( density !== undefined ) ? density : 0.00025;
  9952. };
  9953. THREE.FogExp2.prototype.clone = function () {
  9954. return new THREE.FogExp2( this.color.getHex(), this.density );
  9955. };
  9956. // File:src/renderers/shaders/ShaderChunk.js
  9957. THREE.ShaderChunk = {};
  9958. // File:src/renderers/shaders/ShaderChunk/alphamap_fragment.glsl
  9959. THREE.ShaderChunk[ 'alphamap_fragment'] = "#ifdef USE_ALPHAMAP\n\n diffuseColor.a *= texture2D( alphaMap, vUv ).g;\n\n#endif\n";
  9960. // File:src/renderers/shaders/ShaderChunk/alphamap_pars_fragment.glsl
  9961. THREE.ShaderChunk[ 'alphamap_pars_fragment'] = "#ifdef USE_ALPHAMAP\n\n uniform sampler2D alphaMap;\n\n#endif\n";
  9962. // File:src/renderers/shaders/ShaderChunk/alphatest_fragment.glsl
  9963. THREE.ShaderChunk[ 'alphatest_fragment'] = "#ifdef ALPHATEST\n\n if ( diffuseColor.a < ALPHATEST ) discard;\n\n#endif\n";
  9964. // File:src/renderers/shaders/ShaderChunk/aomap_fragment.glsl
  9965. THREE.ShaderChunk[ 'aomap_fragment'] = "#ifdef USE_AOMAP\n\n outgoingLight *= ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\n#endif";
  9966. // File:src/renderers/shaders/ShaderChunk/aomap_pars_fragment.glsl
  9967. THREE.ShaderChunk[ 'aomap_pars_fragment'] = "#ifdef USE_AOMAP\n\n uniform sampler2D aoMap;\n uniform float aoMapIntensity;\n\n#endif";
  9968. // File:src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl
  9969. THREE.ShaderChunk[ 'bumpmap_pars_fragment'] = "#ifdef USE_BUMPMAP\n\n uniform sampler2D bumpMap;\n uniform float bumpScale;\n\n // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen\n // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html\n\n // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)\n\n vec2 dHdxy_fwd() {\n\n vec2 dSTdx = dFdx( vUv );\n vec2 dSTdy = dFdy( vUv );\n\n float Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\n return vec2( dBx, dBy );\n\n }\n\n vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\n vec3 vSigmaX = dFdx( surf_pos );\n vec3 vSigmaY = dFdy( surf_pos );\n vec3 vN = surf_norm; // normalized\n\n vec3 R1 = cross( vSigmaY, vN );\n vec3 R2 = cross( vN, vSigmaX );\n\n float fDet = dot( vSigmaX, R1 );\n\n vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n return normalize( abs( fDet ) * surf_norm - vGrad );\n\n }\n\n#endif\n";
  9970. // File:src/renderers/shaders/ShaderChunk/color_fragment.glsl
  9971. THREE.ShaderChunk[ 'color_fragment'] = "#ifdef USE_COLOR\n\n diffuseColor.rgb *= vColor;\n\n#endif";
  9972. // File:src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl
  9973. THREE.ShaderChunk[ 'color_pars_fragment'] = "#ifdef USE_COLOR\n\n varying vec3 vColor;\n\n#endif\n";
  9974. // File:src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl
  9975. THREE.ShaderChunk[ 'color_pars_vertex'] = "#ifdef USE_COLOR\n\n varying vec3 vColor;\n\n#endif";
  9976. // File:src/renderers/shaders/ShaderChunk/color_vertex.glsl
  9977. THREE.ShaderChunk[ 'color_vertex'] = "#ifdef USE_COLOR\n\n vColor.xyz = inputToLinear( color.xyz );\n\n#endif";
  9978. // File:src/renderers/shaders/ShaderChunk/common.glsl
  9979. THREE.ShaderChunk[ 'common'] = "#define PI 3.14159\n#define PI2 6.28318\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n\nfloat square( in float a ) { return a*a; }\nvec2 square( in vec2 a ) { return vec2( a.x*a.x, a.y*a.y ); }\nvec3 square( in vec3 a ) { return vec3( a.x*a.x, a.y*a.y, a.z*a.z ); }\nvec4 square( in vec4 a ) { return vec4( a.x*a.x, a.y*a.y, a.z*a.z, a.w*a.w ); }\nfloat saturate( in float a ) { return clamp( a, 0.0, 1.0 ); }\nvec2 saturate( in vec2 a ) { return clamp( a, 0.0, 1.0 ); }\nvec3 saturate( in vec3 a ) { return clamp( a, 0.0, 1.0 ); }\nvec4 saturate( in vec4 a ) { return clamp( a, 0.0, 1.0 ); }\nfloat average( in float a ) { return a; }\nfloat average( in vec2 a ) { return ( a.x + a.y) * 0.5; }\nfloat average( in vec3 a ) { return ( a.x + a.y + a.z) / 3.0; }\nfloat average( in vec4 a ) { return ( a.x + a.y + a.z + a.w) * 0.25; }\nfloat whiteCompliment( in float a ) { return saturate( 1.0 - a ); }\nvec2 whiteCompliment( in vec2 a ) { return saturate( vec2(1.0) - a ); }\nvec3 whiteCompliment( in vec3 a ) { return saturate( vec3(1.0) - a ); }\nvec4 whiteCompliment( in vec4 a ) { return saturate( vec4(1.0) - a ); }\nvec3 transformDirection( in vec3 normal, in mat4 matrix ) {\n return normalize( ( matrix * vec4( normal, 0.0 ) ).xyz );\n}\n// http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations\nvec3 inverseTransformDirection( in vec3 normal, in mat4 matrix ) {\n return normalize( ( vec4( normal, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal) {\n float distance = dot( planeNormal, point-pointOnPlane );\n return point - distance * planeNormal;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n return sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n return pointOnLine + lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) );\n}\nfloat calcLightAttenuation( float lightDistance, float cutoffDistance, float decayExponent ) {\n if ( decayExponent > 0.0 ) {\n return pow( saturate( 1.0 - lightDistance / cutoffDistance ), decayExponent );\n }\n return 1.0;\n}\n\nvec3 inputToLinear( in vec3 a ) {\n#ifdef GAMMA_INPUT\n return pow( a, vec3( float( GAMMA_FACTOR ) ) );\n#else\n return a;\n#endif\n}\nvec3 linearToOutput( in vec3 a ) {\n#ifdef GAMMA_OUTPUT\n return pow( a, vec3( 1.0 / float( GAMMA_FACTOR ) ) );\n#else\n return a;\n#endif\n}\n";
  9980. // File:src/renderers/shaders/ShaderChunk/default_vertex.glsl
  9981. THREE.ShaderChunk[ 'default_vertex'] = "#ifdef USE_SKINNING\n\n vec4 mvPosition = modelViewMatrix * skinned;\n\n#elif defined( USE_MORPHTARGETS )\n\n vec4 mvPosition = modelViewMatrix * vec4( morphed, 1.0 );\n\n#else\n\n vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\n#endif\n\ngl_Position = projectionMatrix * mvPosition;\n";
  9982. // File:src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl
  9983. THREE.ShaderChunk[ 'defaultnormal_vertex'] = "#ifdef USE_SKINNING\n\n vec3 objectNormal = skinnedNormal.xyz;\n\n#elif defined( USE_MORPHNORMALS )\n\n vec3 objectNormal = morphedNormal;\n\n#else\n\n vec3 objectNormal = normal;\n\n#endif\n\n#ifdef FLIP_SIDED\n\n objectNormal = -objectNormal;\n\n#endif\n\nvec3 transformedNormal = normalMatrix * objectNormal;\n";
  9984. // File:src/renderers/shaders/ShaderChunk/envmap_fragment.glsl
  9985. THREE.ShaderChunk[ 'envmap_fragment'] = "#ifdef USE_ENVMAP\n\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\n vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\n // Transforming Normal Vectors with the Inverse Transformation\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\n #ifdef ENVMAP_MODE_REFLECTION\n\n vec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\n #else\n\n vec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\n #endif\n\n #else\n\n vec3 reflectVec = vReflect;\n\n #endif\n\n #ifdef DOUBLE_SIDED\n float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );\n #else\n float flipNormal = 1.0;\n #endif\n\n #ifdef ENVMAP_TYPE_CUBE\n vec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\n #elif defined( ENVMAP_TYPE_EQUIREC )\n vec2 sampleUV;\n sampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n sampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n vec4 envColor = texture2D( envMap, sampleUV );\n\n #elif defined( ENVMAP_TYPE_SPHERE )\n vec3 reflectView = flipNormal * normalize((viewMatrix * vec4( reflectVec, 0.0 )).xyz + vec3(0.0,0.0,1.0));\n vec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n #endif\n\n envColor.xyz = inputToLinear( envColor.xyz );\n\n #ifdef ENVMAP_BLENDING_MULTIPLY\n\n outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\n #elif defined( ENVMAP_BLENDING_MIX )\n\n outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\n #elif defined( ENVMAP_BLENDING_ADD )\n\n outgoingLight += envColor.xyz * specularStrength * reflectivity;\n\n #endif\n\n#endif\n";
  9986. // File:src/renderers/shaders/ShaderChunk/envmap_pars_fragment.glsl
  9987. THREE.ShaderChunk[ 'envmap_pars_fragment'] = "#ifdef USE_ENVMAP\n\n uniform float reflectivity;\n #ifdef ENVMAP_TYPE_CUBE\n uniform samplerCube envMap;\n #else\n uniform sampler2D envMap;\n #endif\n uniform float flipEnvMap;\n\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\n uniform float refractionRatio;\n\n #else\n\n varying vec3 vReflect;\n\n #endif\n\n#endif\n";
  9988. // File:src/renderers/shaders/ShaderChunk/envmap_pars_vertex.glsl
  9989. THREE.ShaderChunk[ 'envmap_pars_vertex'] = "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP ) && ! defined( PHONG )\n\n varying vec3 vReflect;\n\n uniform float refractionRatio;\n\n#endif\n";
  9990. // File:src/renderers/shaders/ShaderChunk/envmap_vertex.glsl
  9991. THREE.ShaderChunk[ 'envmap_vertex'] = "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP ) && ! defined( PHONG )\n\n vec3 worldNormal = transformDirection( objectNormal, modelMatrix );\n\n vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\n #ifdef ENVMAP_MODE_REFLECTION\n\n vReflect = reflect( cameraToVertex, worldNormal );\n\n #else\n\n vReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\n #endif\n\n#endif\n";
  9992. // File:src/renderers/shaders/ShaderChunk/fog_fragment.glsl
  9993. THREE.ShaderChunk[ 'fog_fragment'] = "#ifdef USE_FOG\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n float depth = gl_FragDepthEXT / gl_FragCoord.w;\n\n #else\n\n float depth = gl_FragCoord.z / gl_FragCoord.w;\n\n #endif\n\n #ifdef FOG_EXP2\n\n float fogFactor = exp2( - square( fogDensity ) * square( depth ) * LOG2 );\n fogFactor = whiteCompliment( fogFactor );\n\n #else\n\n float fogFactor = smoothstep( fogNear, fogFar, depth );\n\n #endif\n \n outgoingLight = mix( outgoingLight, fogColor, fogFactor );\n\n#endif";
  9994. // File:src/renderers/shaders/ShaderChunk/fog_pars_fragment.glsl
  9995. THREE.ShaderChunk[ 'fog_pars_fragment'] = "#ifdef USE_FOG\n\n uniform vec3 fogColor;\n\n #ifdef FOG_EXP2\n\n uniform float fogDensity;\n\n #else\n\n uniform float fogNear;\n uniform float fogFar;\n #endif\n\n#endif";
  9996. // File:src/renderers/shaders/ShaderChunk/lightmap_fragment.glsl
  9997. THREE.ShaderChunk[ 'lightmap_fragment'] = "#ifdef USE_LIGHTMAP\n\n outgoingLight += diffuseColor.xyz * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\n#endif";
  9998. // File:src/renderers/shaders/ShaderChunk/lightmap_pars_fragment.glsl
  9999. THREE.ShaderChunk[ 'lightmap_pars_fragment'] = "#ifdef USE_LIGHTMAP\n\n uniform sampler2D lightMap;\n uniform float lightMapIntensity;\n\n#endif";
  10000. // File:src/renderers/shaders/ShaderChunk/lights_lambert_pars_vertex.glsl
  10001. THREE.ShaderChunk[ 'lights_lambert_pars_vertex'] = "uniform vec3 ambientLightColor;\n\n#if MAX_DIR_LIGHTS > 0\n\n uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];\n uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];\n\n#endif\n\n#if MAX_POINT_LIGHTS > 0\n\n uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];\n uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];\n uniform float pointLightDistance[ MAX_POINT_LIGHTS ];\n uniform float pointLightDecay[ MAX_POINT_LIGHTS ];\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];\n uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];\n uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDecay[ MAX_SPOT_LIGHTS ];\n\n#endif\n\n#ifdef WRAP_AROUND\n\n uniform vec3 wrapRGB;\n\n#endif\n";
  10002. // File:src/renderers/shaders/ShaderChunk/lights_lambert_vertex.glsl
  10003. THREE.ShaderChunk[ 'lights_lambert_vertex'] = "vLightFront = vec3( 0.0 );\n\n#ifdef DOUBLE_SIDED\n\n vLightBack = vec3( 0.0 );\n\n#endif\n\ntransformedNormal = normalize( transformedNormal );\n\n#if MAX_DIR_LIGHTS > 0\n\nfor( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {\n\n vec3 dirVector = transformDirection( directionalLightDirection[ i ], viewMatrix );\n\n float dotProduct = dot( transformedNormal, dirVector );\n vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );\n\n #ifdef DOUBLE_SIDED\n\n vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );\n\n #ifdef WRAP_AROUND\n\n vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );\n\n #endif\n\n #endif\n\n #ifdef WRAP_AROUND\n\n vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );\n directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );\n\n #ifdef DOUBLE_SIDED\n\n directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );\n\n #endif\n\n #endif\n\n vLightFront += directionalLightColor[ i ] * directionalLightWeighting;\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;\n\n #endif\n\n}\n\n#endif\n\n#if MAX_POINT_LIGHTS > 0\n\n for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {\n\n vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );\n vec3 lVector = lPosition.xyz - mvPosition.xyz;\n\n float attenuation = calcLightAttenuation( length( lVector ), pointLightDistance[ i ], pointLightDecay[ i ] );\n\n lVector = normalize( lVector );\n float dotProduct = dot( transformedNormal, lVector );\n\n vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );\n\n #ifdef DOUBLE_SIDED\n\n vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );\n\n #ifdef WRAP_AROUND\n\n vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );\n\n #endif\n\n #endif\n\n #ifdef WRAP_AROUND\n\n vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );\n pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );\n\n #ifdef DOUBLE_SIDED\n\n pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );\n\n #endif\n\n #endif\n\n vLightFront += pointLightColor[ i ] * pointLightWeighting * attenuation;\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += pointLightColor[ i ] * pointLightWeightingBack * attenuation;\n\n #endif\n\n }\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {\n\n vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );\n vec3 lVector = lPosition.xyz - mvPosition.xyz;\n\n float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );\n\n if ( spotEffect > spotLightAngleCos[ i ] ) {\n\n spotEffect = max( pow( max( spotEffect, 0.0 ), spotLightExponent[ i ] ), 0.0 );\n\n float attenuation = calcLightAttenuation( length( lVector ), spotLightDistance[ i ], spotLightDecay[ i ] );\n\n lVector = normalize( lVector );\n\n float dotProduct = dot( transformedNormal, lVector );\n vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );\n\n #ifdef DOUBLE_SIDED\n\n vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );\n\n #ifdef WRAP_AROUND\n\n vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );\n\n #endif\n\n #endif\n\n #ifdef WRAP_AROUND\n\n vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );\n spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );\n\n #ifdef DOUBLE_SIDED\n\n spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );\n\n #endif\n\n #endif\n\n vLightFront += spotLightColor[ i ] * spotLightWeighting * attenuation * spotEffect;\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += spotLightColor[ i ] * spotLightWeightingBack * attenuation * spotEffect;\n\n #endif\n\n }\n\n }\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {\n\n vec3 lVector = transformDirection( hemisphereLightDirection[ i ], viewMatrix );\n\n float dotProduct = dot( transformedNormal, lVector );\n\n float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;\n float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;\n\n vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );\n\n #endif\n\n }\n\n#endif\n\nvLightFront += ambientLightColor;\n\n#ifdef DOUBLE_SIDED\n\n vLightBack += ambientLightColor;\n\n#endif\n";
  10004. // File:src/renderers/shaders/ShaderChunk/lights_phong_fragment.glsl
  10005. THREE.ShaderChunk[ 'lights_phong_fragment'] = "#ifndef FLAT_SHADED\n\n vec3 normal = normalize( vNormal );\n\n #ifdef DOUBLE_SIDED\n\n normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );\n\n #endif\n\n#else\n\n vec3 fdx = dFdx( vViewPosition );\n vec3 fdy = dFdy( vViewPosition );\n vec3 normal = normalize( cross( fdx, fdy ) );\n\n#endif\n\nvec3 viewPosition = normalize( vViewPosition );\n\n#ifdef USE_NORMALMAP\n\n normal = perturbNormal2Arb( -vViewPosition, normal );\n\n#elif defined( USE_BUMPMAP )\n\n normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n\n#endif\n\nvec3 totalDiffuseLight = vec3( 0.0 );\nvec3 totalSpecularLight = vec3( 0.0 );\n\n#if MAX_POINT_LIGHTS > 0\n\n for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {\n\n vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );\n vec3 lVector = lPosition.xyz + vViewPosition.xyz;\n\n float attenuation = calcLightAttenuation( length( lVector ), pointLightDistance[ i ], pointLightDecay[ i ] );\n\n lVector = normalize( lVector );\n\n // diffuse\n\n float dotProduct = dot( normal, lVector );\n\n #ifdef WRAP_AROUND\n\n float pointDiffuseWeightFull = max( dotProduct, 0.0 );\n float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );\n\n vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );\n\n #else\n\n float pointDiffuseWeight = max( dotProduct, 0.0 );\n\n #endif\n\n totalDiffuseLight += pointLightColor[ i ] * pointDiffuseWeight * attenuation;\n\n // specular\n\n vec3 pointHalfVector = normalize( lVector + viewPosition );\n float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );\n float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );\n\n float specularNormalization = ( shininess + 2.0 ) / 8.0;\n\n vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, pointHalfVector ), 0.0 ), 5.0 );\n totalSpecularLight += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * attenuation * specularNormalization;\n\n }\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {\n\n vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );\n vec3 lVector = lPosition.xyz + vViewPosition.xyz;\n\n float attenuation = calcLightAttenuation( length( lVector ), spotLightDistance[ i ], spotLightDecay[ i ] );\n\n lVector = normalize( lVector );\n\n float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );\n\n if ( spotEffect > spotLightAngleCos[ i ] ) {\n\n spotEffect = max( pow( max( spotEffect, 0.0 ), spotLightExponent[ i ] ), 0.0 );\n\n // diffuse\n\n float dotProduct = dot( normal, lVector );\n\n #ifdef WRAP_AROUND\n\n float spotDiffuseWeightFull = max( dotProduct, 0.0 );\n float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );\n\n vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );\n\n #else\n\n float spotDiffuseWeight = max( dotProduct, 0.0 );\n\n #endif\n\n totalDiffuseLight += spotLightColor[ i ] * spotDiffuseWeight * attenuation * spotEffect;\n\n // specular\n\n vec3 spotHalfVector = normalize( lVector + viewPosition );\n float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );\n float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );\n\n float specularNormalization = ( shininess + 2.0 ) / 8.0;\n\n vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, spotHalfVector ), 0.0 ), 5.0 );\n totalSpecularLight += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * attenuation * specularNormalization * spotEffect;\n\n }\n\n }\n\n#endif\n\n#if MAX_DIR_LIGHTS > 0\n\n for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {\n\n vec3 dirVector = transformDirection( directionalLightDirection[ i ], viewMatrix );\n\n // diffuse\n\n float dotProduct = dot( normal, dirVector );\n\n #ifdef WRAP_AROUND\n\n float dirDiffuseWeightFull = max( dotProduct, 0.0 );\n float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );\n\n vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );\n\n #else\n\n float dirDiffuseWeight = max( dotProduct, 0.0 );\n\n #endif\n\n totalDiffuseLight += directionalLightColor[ i ] * dirDiffuseWeight;\n\n // specular\n\n vec3 dirHalfVector = normalize( dirVector + viewPosition );\n float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );\n float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );\n\n /*\n // fresnel term from skin shader\n const float F0 = 0.128;\n\n float base = 1.0 - dot( viewPosition, dirHalfVector );\n float exponential = pow( base, 5.0 );\n\n float fresnel = exponential + F0 * ( 1.0 - exponential );\n */\n\n /*\n // fresnel term from fresnel shader\n const float mFresnelBias = 0.08;\n const float mFresnelScale = 0.3;\n const float mFresnelPower = 5.0;\n\n float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );\n */\n\n float specularNormalization = ( shininess + 2.0 ) / 8.0;\n\n // dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;\n\n vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( dirVector, dirHalfVector ), 0.0 ), 5.0 );\n totalSpecularLight += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;\n\n\n }\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {\n\n vec3 lVector = transformDirection( hemisphereLightDirection[ i ], viewMatrix );\n\n // diffuse\n\n float dotProduct = dot( normal, lVector );\n float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;\n\n vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );\n\n totalDiffuseLight += hemiColor;\n\n // specular (sky light)\n\n vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );\n float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;\n float hemiSpecularWeightSky = specularStrength * max( pow( max( hemiDotNormalHalfSky, 0.0 ), shininess ), 0.0 );\n\n // specular (ground light)\n\n vec3 lVectorGround = -lVector;\n\n vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );\n float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;\n float hemiSpecularWeightGround = specularStrength * max( pow( max( hemiDotNormalHalfGround, 0.0 ), shininess ), 0.0 );\n\n float dotProductGround = dot( normal, lVectorGround );\n\n float specularNormalization = ( shininess + 2.0 ) / 8.0;\n\n vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, hemiHalfVectorSky ), 0.0 ), 5.0 );\n vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 0.0 ), 5.0 );\n totalSpecularLight += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );\n\n }\n\n#endif\n\n#ifdef METAL\n\n outgoingLight += diffuseColor.rgb * ( totalDiffuseLight + ambientLightColor ) * specular + totalSpecularLight + emissive;\n\n#else\n\n outgoingLight += diffuseColor.rgb * ( totalDiffuseLight + ambientLightColor ) + totalSpecularLight + emissive;\n\n#endif\n";
  10006. // File:src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl
  10007. THREE.ShaderChunk[ 'lights_phong_pars_fragment'] = "uniform vec3 ambientLightColor;\n\n#if MAX_DIR_LIGHTS > 0\n\n uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];\n uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];\n\n#endif\n\n#if MAX_POINT_LIGHTS > 0\n\n uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];\n\n uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];\n uniform float pointLightDistance[ MAX_POINT_LIGHTS ];\n uniform float pointLightDecay[ MAX_POINT_LIGHTS ];\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];\n uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];\n uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDecay[ MAX_SPOT_LIGHTS ];\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )\n\n varying vec3 vWorldPosition;\n\n#endif\n\n#ifdef WRAP_AROUND\n\n uniform vec3 wrapRGB;\n\n#endif\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n varying vec3 vNormal;\n\n#endif\n";
  10008. // File:src/renderers/shaders/ShaderChunk/lights_phong_pars_vertex.glsl
  10009. THREE.ShaderChunk[ 'lights_phong_pars_vertex'] = "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )\n\n varying vec3 vWorldPosition;\n\n#endif\n";
  10010. // File:src/renderers/shaders/ShaderChunk/lights_phong_vertex.glsl
  10011. THREE.ShaderChunk[ 'lights_phong_vertex'] = "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )\n\n vWorldPosition = worldPosition.xyz;\n\n#endif";
  10012. // File:src/renderers/shaders/ShaderChunk/linear_to_gamma_fragment.glsl
  10013. THREE.ShaderChunk[ 'linear_to_gamma_fragment'] = "\n outgoingLight = linearToOutput( outgoingLight );\n";
  10014. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl
  10015. THREE.ShaderChunk[ 'logdepthbuf_fragment'] = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\n gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n\n#endif";
  10016. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl
  10017. THREE.ShaderChunk[ 'logdepthbuf_pars_fragment'] = "#ifdef USE_LOGDEPTHBUF\n\n uniform float logDepthBufFC;\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n #extension GL_EXT_frag_depth : enable\n varying float vFragDepth;\n\n #endif\n\n#endif";
  10018. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl
  10019. THREE.ShaderChunk[ 'logdepthbuf_pars_vertex'] = "#ifdef USE_LOGDEPTHBUF\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n varying float vFragDepth;\n\n #endif\n\n uniform float logDepthBufFC;\n\n#endif";
  10020. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl
  10021. THREE.ShaderChunk[ 'logdepthbuf_vertex'] = "#ifdef USE_LOGDEPTHBUF\n\n gl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n vFragDepth = 1.0 + gl_Position.w;\n\n#else\n\n gl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\n #endif\n\n#endif";
  10022. // File:src/renderers/shaders/ShaderChunk/map_fragment.glsl
  10023. THREE.ShaderChunk[ 'map_fragment'] = "#ifdef USE_MAP\n\n vec4 texelColor = texture2D( map, vUv );\n\n texelColor.xyz = inputToLinear( texelColor.xyz );\n\n diffuseColor *= texelColor;\n\n#endif";
  10024. // File:src/renderers/shaders/ShaderChunk/map_pars_fragment.glsl
  10025. THREE.ShaderChunk[ 'map_pars_fragment'] = "#ifdef USE_MAP\n\n uniform sampler2D map;\n\n#endif";
  10026. // File:src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl
  10027. THREE.ShaderChunk[ 'map_particle_fragment'] = "#ifdef USE_MAP\n\n diffuseColor *= texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\n#endif\n";
  10028. // File:src/renderers/shaders/ShaderChunk/map_particle_pars_fragment.glsl
  10029. THREE.ShaderChunk[ 'map_particle_pars_fragment'] = "#ifdef USE_MAP\n\n uniform vec4 offsetRepeat;\n uniform sampler2D map;\n\n#endif\n";
  10030. // File:src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl
  10031. THREE.ShaderChunk[ 'morphnormal_vertex'] = "#ifdef USE_MORPHNORMALS\n\n vec3 morphedNormal = vec3( 0.0 );\n\n morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n\n morphedNormal += normal;\n\n#endif";
  10032. // File:src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl
  10033. THREE.ShaderChunk[ 'morphtarget_pars_vertex'] = "#ifdef USE_MORPHTARGETS\n\n #ifndef USE_MORPHNORMALS\n\n uniform float morphTargetInfluences[ 8 ];\n\n #else\n\n uniform float morphTargetInfluences[ 4 ];\n\n #endif\n\n#endif";
  10034. // File:src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl
  10035. THREE.ShaderChunk[ 'morphtarget_vertex'] = "#ifdef USE_MORPHTARGETS\n\n vec3 morphed = vec3( 0.0 );\n morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\n #ifndef USE_MORPHNORMALS\n\n morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\n #endif\n\n morphed += position;\n\n#endif";
  10036. // File:src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl
  10037. THREE.ShaderChunk[ 'normalmap_pars_fragment'] = "#ifdef USE_NORMALMAP\n\n uniform sampler2D normalMap;\n uniform vec2 normalScale;\n\n // Per-Pixel Tangent Space Normal Mapping\n // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html\n\n vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\n vec3 q0 = dFdx( eye_pos.xyz );\n vec3 q1 = dFdy( eye_pos.xyz );\n vec2 st0 = dFdx( vUv.st );\n vec2 st1 = dFdy( vUv.st );\n\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normalize( surf_norm );\n\n vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n mapN.xy = normalScale * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n\n }\n\n#endif\n";
  10038. // File:src/renderers/shaders/ShaderChunk/shadowmap_fragment.glsl
  10039. THREE.ShaderChunk[ 'shadowmap_fragment'] = "#ifdef USE_SHADOWMAP\n\n #ifdef SHADOWMAP_DEBUG\n\n vec3 frustumColors[3];\n frustumColors[0] = vec3( 1.0, 0.5, 0.0 );\n frustumColors[1] = vec3( 0.0, 1.0, 0.8 );\n frustumColors[2] = vec3( 0.0, 0.5, 1.0 );\n\n #endif\n\n #ifdef SHADOWMAP_CASCADE\n\n int inFrustumCount = 0;\n\n #endif\n\n float fDepth;\n vec3 shadowColor = vec3( 1.0 );\n\n for( int i = 0; i < MAX_SHADOWS; i ++ ) {\n\n vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;\n\n // if ( something && something ) breaks ATI OpenGL shader compiler\n // if ( all( something, something ) ) using this instead\n\n bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n bool inFrustum = all( inFrustumVec );\n\n // don't shadow pixels outside of light frustum\n // use just first frustum (for cascades)\n // don't shadow pixels behind far plane of light frustum\n\n #ifdef SHADOWMAP_CASCADE\n\n inFrustumCount += int( inFrustum );\n bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );\n\n #else\n\n bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\n #endif\n\n bool frustumTest = all( frustumTestVec );\n\n if ( frustumTest ) {\n\n shadowCoord.z += shadowBias[ i ];\n\n #if defined( SHADOWMAP_TYPE_PCF )\n\n // Percentage-close filtering\n // (9 pixel kernel)\n // http://fabiensanglard.net/shadowmappingPCF/\n\n float shadow = 0.0;\n\n /*\n // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL\n // must enroll loop manually\n\n for ( float y = -1.25; y <= 1.25; y += 1.25 )\n for ( float x = -1.25; x <= 1.25; x += 1.25 ) {\n\n vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );\n\n // doesn't seem to produce any noticeable visual difference compared to simple texture2D lookup\n //vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );\n\n float fDepth = unpackDepth( rgbaDepth );\n\n if ( fDepth < shadowCoord.z )\n shadow += 1.0;\n\n }\n\n shadow /= 9.0;\n\n */\n\n const float shadowDelta = 1.0 / 9.0;\n\n float xPixelOffset = 1.0 / shadowMapSize[ i ].x;\n float yPixelOffset = 1.0 / shadowMapSize[ i ].y;\n\n float dx0 = -1.25 * xPixelOffset;\n float dy0 = -1.25 * yPixelOffset;\n float dx1 = 1.25 * xPixelOffset;\n float dy1 = 1.25 * yPixelOffset;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );\n\n #elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\n // Percentage-close filtering\n // (9 pixel kernel)\n // http://fabiensanglard.net/shadowmappingPCF/\n\n float shadow = 0.0;\n\n float xPixelOffset = 1.0 / shadowMapSize[ i ].x;\n float yPixelOffset = 1.0 / shadowMapSize[ i ].y;\n\n float dx0 = -1.0 * xPixelOffset;\n float dy0 = -1.0 * yPixelOffset;\n float dx1 = 1.0 * xPixelOffset;\n float dy1 = 1.0 * yPixelOffset;\n\n mat3 shadowKernel;\n mat3 depthKernel;\n\n depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );\n depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );\n depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );\n depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );\n depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );\n depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );\n depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );\n depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );\n depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );\n\n vec3 shadowZ = vec3( shadowCoord.z );\n shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));\n shadowKernel[0] *= vec3(0.25);\n\n shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));\n shadowKernel[1] *= vec3(0.25);\n\n shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));\n shadowKernel[2] *= vec3(0.25);\n\n vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );\n\n shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );\n shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );\n\n vec4 shadowValues;\n shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );\n shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );\n shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );\n shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );\n\n shadow = dot( shadowValues, vec4( 1.0 ) );\n\n shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );\n\n #else\n\n vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );\n float fDepth = unpackDepth( rgbaDepth );\n\n if ( fDepth < shadowCoord.z )\n\n // spot with multiple shadows is darker\n\n shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );\n\n // spot with multiple shadows has the same color as single shadow spot\n\n // shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );\n\n #endif\n\n }\n\n\n #ifdef SHADOWMAP_DEBUG\n\n #ifdef SHADOWMAP_CASCADE\n\n if ( inFrustum && inFrustumCount == 1 ) outgoingLight *= frustumColors[ i ];\n\n #else\n\n if ( inFrustum ) outgoingLight *= frustumColors[ i ];\n\n #endif\n\n #endif\n\n }\n\n // NOTE: I am unsure if this is correct in linear space. -bhouston, Dec 29, 2014\n shadowColor = inputToLinear( shadowColor );\n\n outgoingLight = outgoingLight * shadowColor;\n\n#endif\n";
  10040. // File:src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl
  10041. THREE.ShaderChunk[ 'shadowmap_pars_fragment'] = "#ifdef USE_SHADOWMAP\n\n uniform sampler2D shadowMap[ MAX_SHADOWS ];\n uniform vec2 shadowMapSize[ MAX_SHADOWS ];\n\n uniform float shadowDarkness[ MAX_SHADOWS ];\n uniform float shadowBias[ MAX_SHADOWS ];\n\n varying vec4 vShadowCoord[ MAX_SHADOWS ];\n\n float unpackDepth( const in vec4 rgba_depth ) {\n\n 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 );\n float depth = dot( rgba_depth, bit_shift );\n return depth;\n\n }\n\n#endif";
  10042. // File:src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl
  10043. THREE.ShaderChunk[ 'shadowmap_pars_vertex'] = "#ifdef USE_SHADOWMAP\n\n varying vec4 vShadowCoord[ MAX_SHADOWS ];\n uniform mat4 shadowMatrix[ MAX_SHADOWS ];\n\n#endif";
  10044. // File:src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl
  10045. THREE.ShaderChunk[ 'shadowmap_vertex'] = "#ifdef USE_SHADOWMAP\n\n for( int i = 0; i < MAX_SHADOWS; i ++ ) {\n\n vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;\n\n }\n\n#endif";
  10046. // File:src/renderers/shaders/ShaderChunk/skinbase_vertex.glsl
  10047. THREE.ShaderChunk[ 'skinbase_vertex'] = "#ifdef USE_SKINNING\n\n mat4 boneMatX = getBoneMatrix( skinIndex.x );\n mat4 boneMatY = getBoneMatrix( skinIndex.y );\n mat4 boneMatZ = getBoneMatrix( skinIndex.z );\n mat4 boneMatW = getBoneMatrix( skinIndex.w );\n\n#endif";
  10048. // File:src/renderers/shaders/ShaderChunk/skinning_pars_vertex.glsl
  10049. THREE.ShaderChunk[ 'skinning_pars_vertex'] = "#ifdef USE_SKINNING\n\n uniform mat4 bindMatrix;\n uniform mat4 bindMatrixInverse;\n\n #ifdef BONE_TEXTURE\n\n uniform sampler2D boneTexture;\n uniform int boneTextureWidth;\n uniform int boneTextureHeight;\n\n mat4 getBoneMatrix( const in float i ) {\n\n float j = i * 4.0;\n float x = mod( j, float( boneTextureWidth ) );\n float y = floor( j / float( boneTextureWidth ) );\n\n float dx = 1.0 / float( boneTextureWidth );\n float dy = 1.0 / float( boneTextureHeight );\n\n y = dy * ( y + 0.5 );\n\n vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\n mat4 bone = mat4( v1, v2, v3, v4 );\n\n return bone;\n\n }\n\n #else\n\n uniform mat4 boneGlobalMatrices[ MAX_BONES ];\n\n mat4 getBoneMatrix( const in float i ) {\n\n mat4 bone = boneGlobalMatrices[ int(i) ];\n return bone;\n\n }\n\n #endif\n\n#endif\n";
  10050. // File:src/renderers/shaders/ShaderChunk/skinning_vertex.glsl
  10051. THREE.ShaderChunk[ 'skinning_vertex'] = "#ifdef USE_SKINNING\n\n #ifdef USE_MORPHTARGETS\n\n vec4 skinVertex = bindMatrix * vec4( morphed, 1.0 );\n\n #else\n\n vec4 skinVertex = bindMatrix * vec4( position, 1.0 );\n\n #endif\n\n vec4 skinned = vec4( 0.0 );\n skinned += boneMatX * skinVertex * skinWeight.x;\n skinned += boneMatY * skinVertex * skinWeight.y;\n skinned += boneMatZ * skinVertex * skinWeight.z;\n skinned += boneMatW * skinVertex * skinWeight.w;\n skinned = bindMatrixInverse * skinned;\n\n#endif\n";
  10052. // File:src/renderers/shaders/ShaderChunk/skinnormal_vertex.glsl
  10053. THREE.ShaderChunk[ 'skinnormal_vertex'] = "#ifdef USE_SKINNING\n\n mat4 skinMatrix = mat4( 0.0 );\n skinMatrix += skinWeight.x * boneMatX;\n skinMatrix += skinWeight.y * boneMatY;\n skinMatrix += skinWeight.z * boneMatZ;\n skinMatrix += skinWeight.w * boneMatW;\n skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\n #ifdef USE_MORPHNORMALS\n\n vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );\n\n #else\n\n vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );\n\n #endif\n\n#endif\n";
  10054. // File:src/renderers/shaders/ShaderChunk/specularmap_fragment.glsl
  10055. THREE.ShaderChunk[ 'specularmap_fragment'] = "float specularStrength;\n\n#ifdef USE_SPECULARMAP\n\n vec4 texelSpecular = texture2D( specularMap, vUv );\n specularStrength = texelSpecular.r;\n\n#else\n\n specularStrength = 1.0;\n\n#endif";
  10056. // File:src/renderers/shaders/ShaderChunk/specularmap_pars_fragment.glsl
  10057. THREE.ShaderChunk[ 'specularmap_pars_fragment'] = "#ifdef USE_SPECULARMAP\n\n uniform sampler2D specularMap;\n\n#endif";
  10058. // File:src/renderers/shaders/ShaderChunk/uv2_pars_fragment.glsl
  10059. THREE.ShaderChunk[ 'uv2_pars_fragment'] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n varying vec2 vUv2;\n\n#endif";
  10060. // File:src/renderers/shaders/ShaderChunk/uv2_pars_vertex.glsl
  10061. THREE.ShaderChunk[ 'uv2_pars_vertex'] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n attribute vec2 uv2;\n varying vec2 vUv2;\n\n#endif";
  10062. // File:src/renderers/shaders/ShaderChunk/uv2_vertex.glsl
  10063. THREE.ShaderChunk[ 'uv2_vertex'] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n vUv2 = uv2;\n\n#endif";
  10064. // File:src/renderers/shaders/ShaderChunk/uv_pars_fragment.glsl
  10065. THREE.ShaderChunk[ 'uv_pars_fragment'] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP )\n\n varying vec2 vUv;\n\n#endif";
  10066. // File:src/renderers/shaders/ShaderChunk/uv_pars_vertex.glsl
  10067. THREE.ShaderChunk[ 'uv_pars_vertex'] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP )\n\n varying vec2 vUv;\n uniform vec4 offsetRepeat;\n\n#endif\n";
  10068. // File:src/renderers/shaders/ShaderChunk/uv_vertex.glsl
  10069. THREE.ShaderChunk[ 'uv_vertex'] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP )\n\n vUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n\n#endif";
  10070. // File:src/renderers/shaders/ShaderChunk/worldpos_vertex.glsl
  10071. THREE.ShaderChunk[ 'worldpos_vertex'] = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\n #ifdef USE_SKINNING\n\n vec4 worldPosition = modelMatrix * skinned;\n\n #elif defined( USE_MORPHTARGETS )\n\n vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );\n\n #else\n\n vec4 worldPosition = modelMatrix * vec4( position, 1.0 );\n\n #endif\n\n#endif\n";
  10072. // File:src/renderers/shaders/UniformsUtils.js
  10073. /**
  10074. * Uniform Utilities
  10075. */
  10076. THREE.UniformsUtils = {
  10077. merge: function ( uniforms ) {
  10078. var merged = {};
  10079. for ( var u = 0; u < uniforms.length; u ++ ) {
  10080. var tmp = this.clone( uniforms[ u ] );
  10081. for ( var p in tmp ) {
  10082. merged[ p ] = tmp[ p ];
  10083. }
  10084. }
  10085. return merged;
  10086. },
  10087. clone: function ( uniforms_src ) {
  10088. var uniforms_dst = {};
  10089. for ( var u in uniforms_src ) {
  10090. uniforms_dst[ u ] = {};
  10091. for ( var p in uniforms_src[ u ] ) {
  10092. var parameter_src = uniforms_src[ u ][ p ];
  10093. if ( parameter_src instanceof THREE.Color ||
  10094. parameter_src instanceof THREE.Vector2 ||
  10095. parameter_src instanceof THREE.Vector3 ||
  10096. parameter_src instanceof THREE.Vector4 ||
  10097. parameter_src instanceof THREE.Matrix4 ||
  10098. parameter_src instanceof THREE.Texture ) {
  10099. uniforms_dst[ u ][ p ] = parameter_src.clone();
  10100. } else if ( parameter_src instanceof Array ) {
  10101. uniforms_dst[ u ][ p ] = parameter_src.slice();
  10102. } else {
  10103. uniforms_dst[ u ][ p ] = parameter_src;
  10104. }
  10105. }
  10106. }
  10107. return uniforms_dst;
  10108. }
  10109. };
  10110. // File:src/renderers/shaders/UniformsLib.js
  10111. /**
  10112. * Uniforms library for shared webgl shaders
  10113. */
  10114. THREE.UniformsLib = {
  10115. common: {
  10116. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10117. "opacity" : { type: "f", value: 1.0 },
  10118. "map" : { type: "t", value: null },
  10119. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10120. "lightMap" : { type: "t", value: null },
  10121. "lightMapIntensity" : { type: "f", value: 1 },
  10122. "aoMap" : { type: "t", value: null },
  10123. "aoMapIntensity" : { type: "f", value: 1 },
  10124. "specularMap" : { type: "t", value: null },
  10125. "alphaMap" : { type: "t", value: null },
  10126. "envMap" : { type: "t", value: null },
  10127. "flipEnvMap" : { type: "f", value: - 1 },
  10128. "reflectivity" : { type: "f", value: 1.0 },
  10129. "refractionRatio" : { type: "f", value: 0.98 },
  10130. "morphTargetInfluences" : { type: "f", value: 0 }
  10131. },
  10132. bump: {
  10133. "bumpMap" : { type: "t", value: null },
  10134. "bumpScale" : { type: "f", value: 1 }
  10135. },
  10136. normalmap: {
  10137. "normalMap" : { type: "t", value: null },
  10138. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  10139. },
  10140. fog : {
  10141. "fogDensity" : { type: "f", value: 0.00025 },
  10142. "fogNear" : { type: "f", value: 1 },
  10143. "fogFar" : { type: "f", value: 2000 },
  10144. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10145. },
  10146. lights: {
  10147. "ambientLightColor" : { type: "fv", value: [] },
  10148. "directionalLightDirection" : { type: "fv", value: [] },
  10149. "directionalLightColor" : { type: "fv", value: [] },
  10150. "hemisphereLightDirection" : { type: "fv", value: [] },
  10151. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  10152. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  10153. "pointLightColor" : { type: "fv", value: [] },
  10154. "pointLightPosition" : { type: "fv", value: [] },
  10155. "pointLightDistance" : { type: "fv1", value: [] },
  10156. "pointLightDecay" : { type: "fv1", value: [] },
  10157. "spotLightColor" : { type: "fv", value: [] },
  10158. "spotLightPosition" : { type: "fv", value: [] },
  10159. "spotLightDirection" : { type: "fv", value: [] },
  10160. "spotLightDistance" : { type: "fv1", value: [] },
  10161. "spotLightAngleCos" : { type: "fv1", value: [] },
  10162. "spotLightExponent" : { type: "fv1", value: [] },
  10163. "spotLightDecay" : { type: "fv1", value: [] }
  10164. },
  10165. particle: {
  10166. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10167. "opacity" : { type: "f", value: 1.0 },
  10168. "size" : { type: "f", value: 1.0 },
  10169. "scale" : { type: "f", value: 1.0 },
  10170. "map" : { type: "t", value: null },
  10171. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10172. "fogDensity" : { type: "f", value: 0.00025 },
  10173. "fogNear" : { type: "f", value: 1 },
  10174. "fogFar" : { type: "f", value: 2000 },
  10175. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10176. },
  10177. shadowmap: {
  10178. "shadowMap": { type: "tv", value: [] },
  10179. "shadowMapSize": { type: "v2v", value: [] },
  10180. "shadowBias" : { type: "fv1", value: [] },
  10181. "shadowDarkness": { type: "fv1", value: [] },
  10182. "shadowMatrix" : { type: "m4v", value: [] }
  10183. }
  10184. };
  10185. // File:src/renderers/shaders/ShaderLib.js
  10186. /**
  10187. * Webgl Shader Library for three.js
  10188. *
  10189. * @author alteredq / http://alteredqualia.com/
  10190. * @author mrdoob / http://mrdoob.com/
  10191. * @author mikael emtinger / http://gomo.se/
  10192. */
  10193. THREE.ShaderLib = {
  10194. 'basic': {
  10195. uniforms: THREE.UniformsUtils.merge( [
  10196. THREE.UniformsLib[ "common" ],
  10197. THREE.UniformsLib[ "fog" ],
  10198. THREE.UniformsLib[ "shadowmap" ]
  10199. ] ),
  10200. vertexShader: [
  10201. THREE.ShaderChunk[ "common" ],
  10202. THREE.ShaderChunk[ "uv_pars_vertex" ],
  10203. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  10204. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10205. THREE.ShaderChunk[ "color_pars_vertex" ],
  10206. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10207. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10208. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10209. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10210. "void main() {",
  10211. THREE.ShaderChunk[ "uv_vertex" ],
  10212. THREE.ShaderChunk[ "uv2_vertex" ],
  10213. THREE.ShaderChunk[ "color_vertex" ],
  10214. THREE.ShaderChunk[ "skinbase_vertex" ],
  10215. " #ifdef USE_ENVMAP",
  10216. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10217. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10218. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10219. " #endif",
  10220. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10221. THREE.ShaderChunk[ "skinning_vertex" ],
  10222. THREE.ShaderChunk[ "default_vertex" ],
  10223. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10224. THREE.ShaderChunk[ "worldpos_vertex" ],
  10225. THREE.ShaderChunk[ "envmap_vertex" ],
  10226. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10227. "}"
  10228. ].join("\n"),
  10229. fragmentShader: [
  10230. "uniform vec3 diffuse;",
  10231. "uniform float opacity;",
  10232. THREE.ShaderChunk[ "common" ],
  10233. THREE.ShaderChunk[ "color_pars_fragment" ],
  10234. THREE.ShaderChunk[ "uv_pars_fragment" ],
  10235. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  10236. THREE.ShaderChunk[ "map_pars_fragment" ],
  10237. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  10238. THREE.ShaderChunk[ "aomap_pars_fragment" ],
  10239. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10240. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10241. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10242. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10243. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10244. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10245. "void main() {",
  10246. " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does
  10247. " vec4 diffuseColor = vec4( diffuse, opacity );",
  10248. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10249. THREE.ShaderChunk[ "map_fragment" ],
  10250. THREE.ShaderChunk[ "color_fragment" ],
  10251. THREE.ShaderChunk[ "alphamap_fragment" ],
  10252. THREE.ShaderChunk[ "alphatest_fragment" ],
  10253. THREE.ShaderChunk[ "specularmap_fragment" ],
  10254. " outgoingLight = diffuseColor.rgb;", // simple shader
  10255. THREE.ShaderChunk[ "aomap_fragment" ],
  10256. THREE.ShaderChunk[ "lightmap_fragment" ],
  10257. THREE.ShaderChunk[ "envmap_fragment" ],
  10258. THREE.ShaderChunk[ "shadowmap_fragment" ], // TODO: Shadows on an otherwise unlit surface doesn't make sense.
  10259. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10260. THREE.ShaderChunk[ "fog_fragment" ],
  10261. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects
  10262. "}"
  10263. ].join("\n")
  10264. },
  10265. 'lambert': {
  10266. uniforms: THREE.UniformsUtils.merge( [
  10267. THREE.UniformsLib[ "common" ],
  10268. THREE.UniformsLib[ "fog" ],
  10269. THREE.UniformsLib[ "lights" ],
  10270. THREE.UniformsLib[ "shadowmap" ],
  10271. {
  10272. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10273. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10274. }
  10275. ] ),
  10276. vertexShader: [
  10277. "#define LAMBERT",
  10278. "varying vec3 vLightFront;",
  10279. "#ifdef DOUBLE_SIDED",
  10280. " varying vec3 vLightBack;",
  10281. "#endif",
  10282. THREE.ShaderChunk[ "common" ],
  10283. THREE.ShaderChunk[ "uv_pars_vertex" ],
  10284. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  10285. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10286. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  10287. THREE.ShaderChunk[ "color_pars_vertex" ],
  10288. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10289. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10290. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10291. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10292. "void main() {",
  10293. THREE.ShaderChunk[ "uv_vertex" ],
  10294. THREE.ShaderChunk[ "uv2_vertex" ],
  10295. THREE.ShaderChunk[ "color_vertex" ],
  10296. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10297. THREE.ShaderChunk[ "skinbase_vertex" ],
  10298. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10299. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10300. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10301. THREE.ShaderChunk[ "skinning_vertex" ],
  10302. THREE.ShaderChunk[ "default_vertex" ],
  10303. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10304. THREE.ShaderChunk[ "worldpos_vertex" ],
  10305. THREE.ShaderChunk[ "envmap_vertex" ],
  10306. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  10307. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10308. "}"
  10309. ].join("\n"),
  10310. fragmentShader: [
  10311. "uniform vec3 diffuse;",
  10312. "uniform vec3 emissive;",
  10313. "uniform float opacity;",
  10314. "varying vec3 vLightFront;",
  10315. "#ifdef DOUBLE_SIDED",
  10316. " varying vec3 vLightBack;",
  10317. "#endif",
  10318. THREE.ShaderChunk[ "common" ],
  10319. THREE.ShaderChunk[ "color_pars_fragment" ],
  10320. THREE.ShaderChunk[ "uv_pars_fragment" ],
  10321. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  10322. THREE.ShaderChunk[ "map_pars_fragment" ],
  10323. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  10324. THREE.ShaderChunk[ "aomap_pars_fragment" ],
  10325. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10326. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10327. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10328. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10329. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10330. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10331. "void main() {",
  10332. " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does
  10333. " vec4 diffuseColor = vec4( diffuse, opacity );",
  10334. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10335. THREE.ShaderChunk[ "map_fragment" ],
  10336. THREE.ShaderChunk[ "color_fragment" ],
  10337. THREE.ShaderChunk[ "alphamap_fragment" ],
  10338. THREE.ShaderChunk[ "alphatest_fragment" ],
  10339. THREE.ShaderChunk[ "specularmap_fragment" ],
  10340. " #ifdef DOUBLE_SIDED",
  10341. //"float isFront = float( gl_FrontFacing );",
  10342. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  10343. " if ( gl_FrontFacing )",
  10344. " outgoingLight += diffuseColor.rgb * vLightFront + emissive;",
  10345. " else",
  10346. " outgoingLight += diffuseColor.rgb * vLightBack + emissive;",
  10347. " #else",
  10348. " outgoingLight += diffuseColor.rgb * vLightFront + emissive;",
  10349. " #endif",
  10350. THREE.ShaderChunk[ "aomap_fragment" ],
  10351. THREE.ShaderChunk[ "lightmap_fragment" ],
  10352. THREE.ShaderChunk[ "envmap_fragment" ],
  10353. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10354. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10355. THREE.ShaderChunk[ "fog_fragment" ],
  10356. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects
  10357. "}"
  10358. ].join("\n")
  10359. },
  10360. 'phong': {
  10361. uniforms: THREE.UniformsUtils.merge( [
  10362. THREE.UniformsLib[ "common" ],
  10363. THREE.UniformsLib[ "bump" ],
  10364. THREE.UniformsLib[ "normalmap" ],
  10365. THREE.UniformsLib[ "fog" ],
  10366. THREE.UniformsLib[ "lights" ],
  10367. THREE.UniformsLib[ "shadowmap" ],
  10368. {
  10369. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10370. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10371. "shininess": { type: "f", value: 30 },
  10372. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10373. }
  10374. ] ),
  10375. vertexShader: [
  10376. "#define PHONG",
  10377. "varying vec3 vViewPosition;",
  10378. "#ifndef FLAT_SHADED",
  10379. " varying vec3 vNormal;",
  10380. "#endif",
  10381. THREE.ShaderChunk[ "common" ],
  10382. THREE.ShaderChunk[ "uv_pars_vertex" ],
  10383. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  10384. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10385. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10386. THREE.ShaderChunk[ "color_pars_vertex" ],
  10387. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10388. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10389. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10390. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10391. "void main() {",
  10392. THREE.ShaderChunk[ "uv_vertex" ],
  10393. THREE.ShaderChunk[ "uv2_vertex" ],
  10394. THREE.ShaderChunk[ "color_vertex" ],
  10395. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10396. THREE.ShaderChunk[ "skinbase_vertex" ],
  10397. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10398. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10399. "#ifndef FLAT_SHADED", // Normal computed with derivatives when FLAT_SHADED
  10400. " vNormal = normalize( transformedNormal );",
  10401. "#endif",
  10402. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10403. THREE.ShaderChunk[ "skinning_vertex" ],
  10404. THREE.ShaderChunk[ "default_vertex" ],
  10405. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10406. " vViewPosition = -mvPosition.xyz;",
  10407. THREE.ShaderChunk[ "worldpos_vertex" ],
  10408. THREE.ShaderChunk[ "envmap_vertex" ],
  10409. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10410. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10411. "}"
  10412. ].join("\n"),
  10413. fragmentShader: [
  10414. "#define PHONG",
  10415. "uniform vec3 diffuse;",
  10416. "uniform vec3 emissive;",
  10417. "uniform vec3 specular;",
  10418. "uniform float shininess;",
  10419. "uniform float opacity;",
  10420. THREE.ShaderChunk[ "common" ],
  10421. THREE.ShaderChunk[ "color_pars_fragment" ],
  10422. THREE.ShaderChunk[ "uv_pars_fragment" ],
  10423. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  10424. THREE.ShaderChunk[ "map_pars_fragment" ],
  10425. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  10426. THREE.ShaderChunk[ "aomap_pars_fragment" ],
  10427. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10428. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10429. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10430. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10431. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10432. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10433. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10434. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10435. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10436. "void main() {",
  10437. " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does
  10438. " vec4 diffuseColor = vec4( diffuse, opacity );",
  10439. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10440. THREE.ShaderChunk[ "map_fragment" ],
  10441. THREE.ShaderChunk[ "color_fragment" ],
  10442. THREE.ShaderChunk[ "alphamap_fragment" ],
  10443. THREE.ShaderChunk[ "alphatest_fragment" ],
  10444. THREE.ShaderChunk[ "specularmap_fragment" ],
  10445. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10446. THREE.ShaderChunk[ "aomap_fragment" ],
  10447. THREE.ShaderChunk[ "lightmap_fragment" ],
  10448. THREE.ShaderChunk[ "envmap_fragment" ],
  10449. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10450. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10451. THREE.ShaderChunk[ "fog_fragment" ],
  10452. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects
  10453. "}"
  10454. ].join("\n")
  10455. },
  10456. 'particle_basic': {
  10457. uniforms: THREE.UniformsUtils.merge( [
  10458. THREE.UniformsLib[ "particle" ],
  10459. THREE.UniformsLib[ "shadowmap" ]
  10460. ] ),
  10461. vertexShader: [
  10462. "uniform float size;",
  10463. "uniform float scale;",
  10464. THREE.ShaderChunk[ "common" ],
  10465. THREE.ShaderChunk[ "color_pars_vertex" ],
  10466. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10467. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10468. "void main() {",
  10469. THREE.ShaderChunk[ "color_vertex" ],
  10470. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10471. " #ifdef USE_SIZEATTENUATION",
  10472. " gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  10473. " #else",
  10474. " gl_PointSize = size;",
  10475. " #endif",
  10476. " gl_Position = projectionMatrix * mvPosition;",
  10477. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10478. THREE.ShaderChunk[ "worldpos_vertex" ],
  10479. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10480. "}"
  10481. ].join("\n"),
  10482. fragmentShader: [
  10483. "uniform vec3 psColor;",
  10484. "uniform float opacity;",
  10485. THREE.ShaderChunk[ "common" ],
  10486. THREE.ShaderChunk[ "color_pars_fragment" ],
  10487. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  10488. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10489. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10490. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10491. "void main() {",
  10492. " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does
  10493. " vec4 diffuseColor = vec4( psColor, opacity );",
  10494. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10495. THREE.ShaderChunk[ "map_particle_fragment" ],
  10496. THREE.ShaderChunk[ "color_fragment" ],
  10497. THREE.ShaderChunk[ "alphatest_fragment" ],
  10498. " outgoingLight = diffuseColor.rgb;", // simple shader
  10499. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10500. THREE.ShaderChunk[ "fog_fragment" ],
  10501. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects
  10502. "}"
  10503. ].join("\n")
  10504. },
  10505. 'dashed': {
  10506. uniforms: THREE.UniformsUtils.merge( [
  10507. THREE.UniformsLib[ "common" ],
  10508. THREE.UniformsLib[ "fog" ],
  10509. {
  10510. "scale" : { type: "f", value: 1 },
  10511. "dashSize" : { type: "f", value: 1 },
  10512. "totalSize": { type: "f", value: 2 }
  10513. }
  10514. ] ),
  10515. vertexShader: [
  10516. "uniform float scale;",
  10517. "attribute float lineDistance;",
  10518. "varying float vLineDistance;",
  10519. THREE.ShaderChunk[ "common" ],
  10520. THREE.ShaderChunk[ "color_pars_vertex" ],
  10521. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10522. "void main() {",
  10523. THREE.ShaderChunk[ "color_vertex" ],
  10524. " vLineDistance = scale * lineDistance;",
  10525. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10526. " gl_Position = projectionMatrix * mvPosition;",
  10527. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10528. "}"
  10529. ].join("\n"),
  10530. fragmentShader: [
  10531. "uniform vec3 diffuse;",
  10532. "uniform float opacity;",
  10533. "uniform float dashSize;",
  10534. "uniform float totalSize;",
  10535. "varying float vLineDistance;",
  10536. THREE.ShaderChunk[ "common" ],
  10537. THREE.ShaderChunk[ "color_pars_fragment" ],
  10538. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10539. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10540. "void main() {",
  10541. " if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  10542. " discard;",
  10543. " }",
  10544. " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does
  10545. " vec4 diffuseColor = vec4( diffuse, opacity );",
  10546. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10547. THREE.ShaderChunk[ "color_fragment" ],
  10548. " outgoingLight = diffuseColor.rgb;", // simple shader
  10549. THREE.ShaderChunk[ "fog_fragment" ],
  10550. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects
  10551. "}"
  10552. ].join("\n")
  10553. },
  10554. 'depth': {
  10555. uniforms: {
  10556. "mNear": { type: "f", value: 1.0 },
  10557. "mFar" : { type: "f", value: 2000.0 },
  10558. "opacity" : { type: "f", value: 1.0 }
  10559. },
  10560. vertexShader: [
  10561. THREE.ShaderChunk[ "common" ],
  10562. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10563. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10564. "void main() {",
  10565. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10566. THREE.ShaderChunk[ "default_vertex" ],
  10567. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10568. "}"
  10569. ].join("\n"),
  10570. fragmentShader: [
  10571. "uniform float mNear;",
  10572. "uniform float mFar;",
  10573. "uniform float opacity;",
  10574. THREE.ShaderChunk[ "common" ],
  10575. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10576. "void main() {",
  10577. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10578. " #ifdef USE_LOGDEPTHBUF_EXT",
  10579. " float depth = gl_FragDepthEXT / gl_FragCoord.w;",
  10580. " #else",
  10581. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10582. " #endif",
  10583. " float color = 1.0 - smoothstep( mNear, mFar, depth );",
  10584. " gl_FragColor = vec4( vec3( color ), opacity );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects
  10585. "}"
  10586. ].join("\n")
  10587. },
  10588. 'normal': {
  10589. uniforms: {
  10590. "opacity" : { type: "f", value: 1.0 }
  10591. },
  10592. vertexShader: [
  10593. "varying vec3 vNormal;",
  10594. THREE.ShaderChunk[ "common" ],
  10595. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10596. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10597. "void main() {",
  10598. " vNormal = normalize( normalMatrix * normal );",
  10599. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10600. THREE.ShaderChunk[ "default_vertex" ],
  10601. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10602. "}"
  10603. ].join("\n"),
  10604. fragmentShader: [
  10605. "uniform float opacity;",
  10606. "varying vec3 vNormal;",
  10607. THREE.ShaderChunk[ "common" ],
  10608. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10609. "void main() {",
  10610. " gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  10611. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10612. "}"
  10613. ].join("\n")
  10614. },
  10615. /* -------------------------------------------------------------------------
  10616. // Cube map shader
  10617. ------------------------------------------------------------------------- */
  10618. 'cube': {
  10619. uniforms: { "tCube": { type: "t", value: null },
  10620. "tFlip": { type: "f", value: - 1 } },
  10621. vertexShader: [
  10622. "varying vec3 vWorldPosition;",
  10623. THREE.ShaderChunk[ "common" ],
  10624. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10625. "void main() {",
  10626. " vWorldPosition = transformDirection( position, modelMatrix );",
  10627. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10628. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10629. "}"
  10630. ].join("\n"),
  10631. fragmentShader: [
  10632. "uniform samplerCube tCube;",
  10633. "uniform float tFlip;",
  10634. "varying vec3 vWorldPosition;",
  10635. THREE.ShaderChunk[ "common" ],
  10636. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10637. "void main() {",
  10638. " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  10639. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10640. "}"
  10641. ].join("\n")
  10642. },
  10643. /* -------------------------------------------------------------------------
  10644. // Cube map shader
  10645. ------------------------------------------------------------------------- */
  10646. 'equirect': {
  10647. uniforms: { "tEquirect": { type: "t", value: null },
  10648. "tFlip": { type: "f", value: - 1 } },
  10649. vertexShader: [
  10650. "varying vec3 vWorldPosition;",
  10651. THREE.ShaderChunk[ "common" ],
  10652. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10653. "void main() {",
  10654. " vWorldPosition = transformDirection( position, modelMatrix );",
  10655. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10656. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10657. "}"
  10658. ].join("\n"),
  10659. fragmentShader: [
  10660. "uniform sampler2D tEquirect;",
  10661. "uniform float tFlip;",
  10662. "varying vec3 vWorldPosition;",
  10663. THREE.ShaderChunk[ "common" ],
  10664. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10665. "void main() {",
  10666. // " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  10667. "vec3 direction = normalize( vWorldPosition );",
  10668. "vec2 sampleUV;",
  10669. "sampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );",
  10670. "sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;",
  10671. "gl_FragColor = texture2D( tEquirect, sampleUV );",
  10672. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10673. "}"
  10674. ].join("\n")
  10675. },
  10676. /* Depth encoding into RGBA texture
  10677. *
  10678. * based on SpiderGL shadow map example
  10679. * http://spidergl.org/example.php?id=6
  10680. *
  10681. * originally from
  10682. * http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  10683. *
  10684. * see also
  10685. * http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  10686. */
  10687. 'depthRGBA': {
  10688. uniforms: {},
  10689. vertexShader: [
  10690. THREE.ShaderChunk[ "common" ],
  10691. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10692. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10693. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10694. "void main() {",
  10695. THREE.ShaderChunk[ "skinbase_vertex" ],
  10696. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10697. THREE.ShaderChunk[ "skinning_vertex" ],
  10698. THREE.ShaderChunk[ "default_vertex" ],
  10699. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10700. "}"
  10701. ].join("\n"),
  10702. fragmentShader: [
  10703. THREE.ShaderChunk[ "common" ],
  10704. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10705. "vec4 pack_depth( const in float depth ) {",
  10706. " const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  10707. " const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  10708. " vec4 res = mod( depth * bit_shift * vec4( 255 ), vec4( 256 ) ) / vec4( 255 );", // " vec4 res = fract( depth * bit_shift );",
  10709. " res -= res.xxyz * bit_mask;",
  10710. " return res;",
  10711. "}",
  10712. "void main() {",
  10713. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10714. " #ifdef USE_LOGDEPTHBUF_EXT",
  10715. " gl_FragData[ 0 ] = pack_depth( gl_FragDepthEXT );",
  10716. " #else",
  10717. " gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  10718. " #endif",
  10719. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  10720. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  10721. //"gl_FragData[ 0 ] = pack_depth( z );",
  10722. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  10723. "}"
  10724. ].join("\n")
  10725. }
  10726. };
  10727. // File:src/renderers/WebGLRenderer.js
  10728. /**
  10729. * @author supereggbert / http://www.paulbrunt.co.uk/
  10730. * @author mrdoob / http://mrdoob.com/
  10731. * @author alteredq / http://alteredqualia.com/
  10732. * @author szimek / https://github.com/szimek/
  10733. */
  10734. THREE.WebGLRenderer = function ( parameters ) {
  10735. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  10736. parameters = parameters || {};
  10737. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  10738. _context = parameters.context !== undefined ? parameters.context : null,
  10739. _width = _canvas.width,
  10740. _height = _canvas.height,
  10741. pixelRatio = 1,
  10742. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  10743. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  10744. _depth = parameters.depth !== undefined ? parameters.depth : true,
  10745. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  10746. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  10747. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  10748. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  10749. _logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false,
  10750. _clearColor = new THREE.Color( 0x000000 ),
  10751. _clearAlpha = 0;
  10752. var lights = [];
  10753. var _webglObjects = {};
  10754. var _webglObjectsImmediate = [];
  10755. var opaqueObjects = [];
  10756. var transparentObjects = [];
  10757. var sprites = [];
  10758. var lensFlares = [];
  10759. // public properties
  10760. this.domElement = _canvas;
  10761. this.context = null;
  10762. // clearing
  10763. this.autoClear = true;
  10764. this.autoClearColor = true;
  10765. this.autoClearDepth = true;
  10766. this.autoClearStencil = true;
  10767. // scene graph
  10768. this.sortObjects = true;
  10769. // physically based shading
  10770. this.gammaFactor = 2.0; // for backwards compatibility
  10771. this.gammaInput = false;
  10772. this.gammaOutput = false;
  10773. // shadow map
  10774. this.shadowMapEnabled = false;
  10775. this.shadowMapType = THREE.PCFShadowMap;
  10776. this.shadowMapCullFace = THREE.CullFaceFront;
  10777. this.shadowMapDebug = false;
  10778. this.shadowMapCascade = false;
  10779. // morphs
  10780. this.maxMorphTargets = 8;
  10781. this.maxMorphNormals = 4;
  10782. // flags
  10783. this.autoScaleCubemaps = true;
  10784. // info
  10785. this.info = {
  10786. memory: {
  10787. programs: 0,
  10788. geometries: 0,
  10789. textures: 0
  10790. },
  10791. render: {
  10792. calls: 0,
  10793. vertices: 0,
  10794. faces: 0,
  10795. points: 0
  10796. }
  10797. };
  10798. // internal properties
  10799. var _this = this,
  10800. _programs = [],
  10801. // internal state cache
  10802. _currentProgram = null,
  10803. _currentFramebuffer = null,
  10804. _currentMaterialId = - 1,
  10805. _currentGeometryProgram = '',
  10806. _currentCamera = null,
  10807. _usedTextureUnits = 0,
  10808. _viewportX = 0,
  10809. _viewportY = 0,
  10810. _viewportWidth = _canvas.width,
  10811. _viewportHeight = _canvas.height,
  10812. _currentWidth = 0,
  10813. _currentHeight = 0,
  10814. // frustum
  10815. _frustum = new THREE.Frustum(),
  10816. // camera matrices cache
  10817. _projScreenMatrix = new THREE.Matrix4(),
  10818. _vector3 = new THREE.Vector3(),
  10819. // light arrays cache
  10820. _direction = new THREE.Vector3(),
  10821. _lightsNeedUpdate = true,
  10822. _lights = {
  10823. ambient: [ 0, 0, 0 ],
  10824. directional: { length: 0, colors:[], positions: [] },
  10825. point: { length: 0, colors: [], positions: [], distances: [], decays: [] },
  10826. spot: { length: 0, colors: [], positions: [], distances: [], directions: [], anglesCos: [], exponents: [], decays: [] },
  10827. hemi: { length: 0, skyColors: [], groundColors: [], positions: [] }
  10828. };
  10829. // initialize
  10830. var _gl;
  10831. try {
  10832. var attributes = {
  10833. alpha: _alpha,
  10834. depth: _depth,
  10835. stencil: _stencil,
  10836. antialias: _antialias,
  10837. premultipliedAlpha: _premultipliedAlpha,
  10838. preserveDrawingBuffer: _preserveDrawingBuffer
  10839. };
  10840. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  10841. if ( _gl === null ) {
  10842. if ( _canvas.getContext( 'webgl') !== null ) {
  10843. throw 'Error creating WebGL context with your selected attributes.';
  10844. } else {
  10845. throw 'Error creating WebGL context.';
  10846. }
  10847. }
  10848. _canvas.addEventListener( 'webglcontextlost', function ( event ) {
  10849. event.preventDefault();
  10850. resetGLState();
  10851. setDefaultGLState();
  10852. _webglObjects = {};
  10853. }, false);
  10854. } catch ( error ) {
  10855. THREE.error( 'THREE.WebGLRenderer: ' + error );
  10856. }
  10857. var state = new THREE.WebGLState( _gl, paramThreeToGL );
  10858. if ( _gl.getShaderPrecisionFormat === undefined ) {
  10859. _gl.getShaderPrecisionFormat = function () {
  10860. return {
  10861. 'rangeMin': 1,
  10862. 'rangeMax': 1,
  10863. 'precision': 1
  10864. };
  10865. }
  10866. }
  10867. var extensions = new THREE.WebGLExtensions( _gl );
  10868. extensions.get( 'OES_texture_float' );
  10869. extensions.get( 'OES_texture_float_linear' );
  10870. extensions.get( 'OES_texture_half_float' );
  10871. extensions.get( 'OES_texture_half_float_linear' );
  10872. extensions.get( 'OES_standard_derivatives' );
  10873. if ( _logarithmicDepthBuffer ) {
  10874. extensions.get( 'EXT_frag_depth' );
  10875. }
  10876. //
  10877. var glClearColor = function ( r, g, b, a ) {
  10878. if ( _premultipliedAlpha === true ) {
  10879. r *= a; g *= a; b *= a;
  10880. }
  10881. _gl.clearColor( r, g, b, a );
  10882. };
  10883. var setDefaultGLState = function () {
  10884. _gl.clearColor( 0, 0, 0, 1 );
  10885. _gl.clearDepth( 1 );
  10886. _gl.clearStencil( 0 );
  10887. _gl.enable( _gl.DEPTH_TEST );
  10888. _gl.depthFunc( _gl.LEQUAL );
  10889. _gl.frontFace( _gl.CCW );
  10890. _gl.cullFace( _gl.BACK );
  10891. _gl.enable( _gl.CULL_FACE );
  10892. _gl.enable( _gl.BLEND );
  10893. _gl.blendEquation( _gl.FUNC_ADD );
  10894. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  10895. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  10896. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10897. };
  10898. var resetGLState = function () {
  10899. _currentProgram = null;
  10900. _currentCamera = null;
  10901. _currentGeometryProgram = '';
  10902. _currentMaterialId = - 1;
  10903. _lightsNeedUpdate = true;
  10904. state.reset();
  10905. };
  10906. setDefaultGLState();
  10907. this.context = _gl;
  10908. this.extensions = extensions;
  10909. this.state = state;
  10910. // GPU capabilities
  10911. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  10912. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  10913. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  10914. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  10915. var _supportsVertexTextures = _maxVertexTextures > 0;
  10916. var _supportsBoneTextures = _supportsVertexTextures && extensions.get( 'OES_texture_float' );
  10917. //
  10918. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  10919. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  10920. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  10921. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  10922. var getCompressedTextureFormats = ( function () {
  10923. var array;
  10924. return function () {
  10925. if ( array !== undefined ) {
  10926. return array;
  10927. }
  10928. array = [];
  10929. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) || extensions.get( 'WEBGL_compressed_texture_s3tc' ) ) {
  10930. var formats = _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS );
  10931. for ( var i = 0; i < formats.length; i ++ ) {
  10932. array.push( formats[ i ] );
  10933. }
  10934. }
  10935. return array;
  10936. };
  10937. } )();
  10938. // clamp precision to maximum available
  10939. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  10940. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  10941. if ( _precision === 'highp' && ! highpAvailable ) {
  10942. if ( mediumpAvailable ) {
  10943. _precision = 'mediump';
  10944. THREE.warn( 'THREE.WebGLRenderer: highp not supported, using mediump.' );
  10945. } else {
  10946. _precision = 'lowp';
  10947. THREE.warn( 'THREE.WebGLRenderer: highp and mediump not supported, using lowp.' );
  10948. }
  10949. }
  10950. if ( _precision === 'mediump' && ! mediumpAvailable ) {
  10951. _precision = 'lowp';
  10952. THREE.warn( 'THREE.WebGLRenderer: mediump not supported, using lowp.' );
  10953. }
  10954. // Plugins
  10955. var shadowMapPlugin = new THREE.ShadowMapPlugin( this, lights, _webglObjects, _webglObjectsImmediate );
  10956. var spritePlugin = new THREE.SpritePlugin( this, sprites );
  10957. var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares );
  10958. // API
  10959. this.getContext = function () {
  10960. return _gl;
  10961. };
  10962. this.forceContextLoss = function () {
  10963. extensions.get( 'WEBGL_lose_context' ).loseContext();
  10964. };
  10965. this.supportsVertexTextures = function () {
  10966. return _supportsVertexTextures;
  10967. };
  10968. this.supportsFloatTextures = function () {
  10969. return extensions.get( 'OES_texture_float' );
  10970. };
  10971. this.supportsHalfFloatTextures = function () {
  10972. return extensions.get( 'OES_texture_half_float' );
  10973. };
  10974. this.supportsStandardDerivatives = function () {
  10975. return extensions.get( 'OES_standard_derivatives' );
  10976. };
  10977. this.supportsCompressedTextureS3TC = function () {
  10978. return extensions.get( 'WEBGL_compressed_texture_s3tc' );
  10979. };
  10980. this.supportsCompressedTexturePVRTC = function () {
  10981. return extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  10982. };
  10983. this.supportsBlendMinMax = function () {
  10984. return extensions.get( 'EXT_blend_minmax' );
  10985. };
  10986. this.getMaxAnisotropy = ( function () {
  10987. var value;
  10988. return function () {
  10989. if ( value !== undefined ) {
  10990. return value;
  10991. }
  10992. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  10993. value = extension !== null ? _gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  10994. return value;
  10995. }
  10996. } )();
  10997. this.getPrecision = function () {
  10998. return _precision;
  10999. };
  11000. this.getPixelRatio = function () {
  11001. return pixelRatio;
  11002. };
  11003. this.setPixelRatio = function ( value ) {
  11004. pixelRatio = value;
  11005. };
  11006. this.getSize = function () {
  11007. return {
  11008. width: _width,
  11009. height: _height
  11010. };
  11011. };
  11012. this.setSize = function ( width, height, updateStyle ) {
  11013. _width = width;
  11014. _height = height;
  11015. _canvas.width = width * pixelRatio;
  11016. _canvas.height = height * pixelRatio;
  11017. if ( updateStyle !== false ) {
  11018. _canvas.style.width = width + 'px';
  11019. _canvas.style.height = height + 'px';
  11020. }
  11021. this.setViewport( 0, 0, width, height );
  11022. };
  11023. this.setViewport = function ( x, y, width, height ) {
  11024. _viewportX = x * pixelRatio;
  11025. _viewportY = y * pixelRatio;
  11026. _viewportWidth = width * pixelRatio;
  11027. _viewportHeight = height * pixelRatio;
  11028. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  11029. };
  11030. this.setScissor = function ( x, y, width, height ) {
  11031. _gl.scissor(
  11032. x * pixelRatio,
  11033. y * pixelRatio,
  11034. width * pixelRatio,
  11035. height * pixelRatio
  11036. );
  11037. };
  11038. this.enableScissorTest = function ( enable ) {
  11039. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  11040. };
  11041. // Clearing
  11042. this.getClearColor = function () {
  11043. return _clearColor;
  11044. };
  11045. this.setClearColor = function ( color, alpha ) {
  11046. _clearColor.set( color );
  11047. _clearAlpha = alpha !== undefined ? alpha : 1;
  11048. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11049. };
  11050. this.getClearAlpha = function () {
  11051. return _clearAlpha;
  11052. };
  11053. this.setClearAlpha = function ( alpha ) {
  11054. _clearAlpha = alpha;
  11055. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11056. };
  11057. this.clear = function ( color, depth, stencil ) {
  11058. var bits = 0;
  11059. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11060. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11061. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11062. _gl.clear( bits );
  11063. };
  11064. this.clearColor = function () {
  11065. _gl.clear( _gl.COLOR_BUFFER_BIT );
  11066. };
  11067. this.clearDepth = function () {
  11068. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  11069. };
  11070. this.clearStencil = function () {
  11071. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  11072. };
  11073. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11074. this.setRenderTarget( renderTarget );
  11075. this.clear( color, depth, stencil );
  11076. };
  11077. // Reset
  11078. this.resetGLState = resetGLState;
  11079. // Buffer allocation
  11080. function createParticleBuffers ( geometry ) {
  11081. geometry.__webglVertexBuffer = _gl.createBuffer();
  11082. geometry.__webglColorBuffer = _gl.createBuffer();
  11083. _this.info.memory.geometries ++;
  11084. };
  11085. function createLineBuffers ( geometry ) {
  11086. geometry.__webglVertexBuffer = _gl.createBuffer();
  11087. geometry.__webglColorBuffer = _gl.createBuffer();
  11088. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  11089. _this.info.memory.geometries ++;
  11090. };
  11091. function createMeshBuffers ( geometryGroup ) {
  11092. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  11093. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  11094. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  11095. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  11096. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  11097. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  11098. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  11099. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  11100. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  11101. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  11102. var numMorphTargets = geometryGroup.numMorphTargets;
  11103. if ( numMorphTargets ) {
  11104. geometryGroup.__webglMorphTargetsBuffers = [];
  11105. for ( var m = 0, ml = numMorphTargets; m < ml; m ++ ) {
  11106. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  11107. }
  11108. }
  11109. var numMorphNormals = geometryGroup.numMorphNormals;
  11110. if ( numMorphNormals ) {
  11111. geometryGroup.__webglMorphNormalsBuffers = [];
  11112. for ( var m = 0, ml = numMorphNormals; m < ml; m ++ ) {
  11113. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  11114. }
  11115. }
  11116. _this.info.memory.geometries ++;
  11117. };
  11118. // Events
  11119. var onObjectRemoved = function ( event ) {
  11120. var object = event.target;
  11121. object.traverse( function ( child ) {
  11122. child.removeEventListener( 'remove', onObjectRemoved );
  11123. removeObject( child );
  11124. } );
  11125. };
  11126. var onGeometryDispose = function ( event ) {
  11127. var geometry = event.target;
  11128. geometry.removeEventListener( 'dispose', onGeometryDispose );
  11129. deallocateGeometry( geometry );
  11130. };
  11131. var onTextureDispose = function ( event ) {
  11132. var texture = event.target;
  11133. texture.removeEventListener( 'dispose', onTextureDispose );
  11134. deallocateTexture( texture );
  11135. _this.info.memory.textures --;
  11136. };
  11137. var onRenderTargetDispose = function ( event ) {
  11138. var renderTarget = event.target;
  11139. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  11140. deallocateRenderTarget( renderTarget );
  11141. _this.info.memory.textures --;
  11142. };
  11143. var onMaterialDispose = function ( event ) {
  11144. var material = event.target;
  11145. material.removeEventListener( 'dispose', onMaterialDispose );
  11146. deallocateMaterial( material );
  11147. };
  11148. // Buffer deallocation
  11149. var deleteBuffers = function ( geometry ) {
  11150. var buffers = [
  11151. '__webglVertexBuffer',
  11152. '__webglNormalBuffer',
  11153. '__webglTangentBuffer',
  11154. '__webglColorBuffer',
  11155. '__webglUVBuffer',
  11156. '__webglUV2Buffer',
  11157. '__webglSkinIndicesBuffer',
  11158. '__webglSkinWeightsBuffer',
  11159. '__webglFaceBuffer',
  11160. '__webglLineBuffer',
  11161. '__webglLineDistanceBuffer'
  11162. ];
  11163. for ( var i = 0, l = buffers.length; i < l; i ++ ) {
  11164. var name = buffers[ i ];
  11165. if ( geometry[ name ] !== undefined ) {
  11166. _gl.deleteBuffer( geometry[ name ] );
  11167. delete geometry[ name ];
  11168. }
  11169. }
  11170. // custom attributes
  11171. if ( geometry.__webglCustomAttributesList !== undefined ) {
  11172. for ( var name in geometry.__webglCustomAttributesList ) {
  11173. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ name ].buffer );
  11174. }
  11175. delete geometry.__webglCustomAttributesList;
  11176. }
  11177. _this.info.memory.geometries --;
  11178. };
  11179. var deallocateGeometry = function ( geometry ) {
  11180. delete geometry.__webglInit;
  11181. if ( geometry instanceof THREE.BufferGeometry ) {
  11182. for ( var name in geometry.attributes ) {
  11183. var attribute = geometry.attributes[ name ];
  11184. if ( attribute.buffer !== undefined ) {
  11185. _gl.deleteBuffer( attribute.buffer );
  11186. delete attribute.buffer;
  11187. }
  11188. }
  11189. _this.info.memory.geometries --;
  11190. } else {
  11191. var geometryGroupsList = geometryGroups[ geometry.id ];
  11192. if ( geometryGroupsList !== undefined ) {
  11193. for ( var i = 0, l = geometryGroupsList.length; i < l; i ++ ) {
  11194. var geometryGroup = geometryGroupsList[ i ];
  11195. if ( geometryGroup.numMorphTargets !== undefined ) {
  11196. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11197. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  11198. }
  11199. delete geometryGroup.__webglMorphTargetsBuffers;
  11200. }
  11201. if ( geometryGroup.numMorphNormals !== undefined ) {
  11202. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11203. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  11204. }
  11205. delete geometryGroup.__webglMorphNormalsBuffers;
  11206. }
  11207. deleteBuffers( geometryGroup );
  11208. }
  11209. delete geometryGroups[ geometry.id ];
  11210. } else {
  11211. deleteBuffers( geometry );
  11212. }
  11213. }
  11214. // TOFIX: Workaround for deleted geometry being currently bound
  11215. _currentGeometryProgram = '';
  11216. };
  11217. var deallocateTexture = function ( texture ) {
  11218. if ( texture.image && texture.image.__webglTextureCube ) {
  11219. // cube texture
  11220. _gl.deleteTexture( texture.image.__webglTextureCube );
  11221. delete texture.image.__webglTextureCube;
  11222. } else {
  11223. // 2D texture
  11224. if ( texture.__webglInit === undefined ) return;
  11225. _gl.deleteTexture( texture.__webglTexture );
  11226. delete texture.__webglTexture;
  11227. delete texture.__webglInit;
  11228. }
  11229. };
  11230. var deallocateRenderTarget = function ( renderTarget ) {
  11231. if ( ! renderTarget || renderTarget.__webglTexture === undefined ) return;
  11232. _gl.deleteTexture( renderTarget.__webglTexture );
  11233. delete renderTarget.__webglTexture;
  11234. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  11235. for ( var i = 0; i < 6; i ++ ) {
  11236. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  11237. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  11238. }
  11239. } else {
  11240. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  11241. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  11242. }
  11243. delete renderTarget.__webglFramebuffer;
  11244. delete renderTarget.__webglRenderbuffer;
  11245. };
  11246. var deallocateMaterial = function ( material ) {
  11247. var program = material.program.program;
  11248. if ( program === undefined ) return;
  11249. material.program = undefined;
  11250. // only deallocate GL program if this was the last use of shared program
  11251. // assumed there is only single copy of any program in the _programs list
  11252. // (that's how it's constructed)
  11253. var i, il, programInfo;
  11254. var deleteProgram = false;
  11255. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11256. programInfo = _programs[ i ];
  11257. if ( programInfo.program === program ) {
  11258. programInfo.usedTimes --;
  11259. if ( programInfo.usedTimes === 0 ) {
  11260. deleteProgram = true;
  11261. }
  11262. break;
  11263. }
  11264. }
  11265. if ( deleteProgram === true ) {
  11266. // avoid using array.splice, this is costlier than creating new array from scratch
  11267. var newPrograms = [];
  11268. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11269. programInfo = _programs[ i ];
  11270. if ( programInfo.program !== program ) {
  11271. newPrograms.push( programInfo );
  11272. }
  11273. }
  11274. _programs = newPrograms;
  11275. _gl.deleteProgram( program );
  11276. _this.info.memory.programs --;
  11277. }
  11278. };
  11279. // Buffer initialization
  11280. function initCustomAttributes ( object ) {
  11281. var geometry = object.geometry;
  11282. var material = object.material;
  11283. var nvertices = geometry.vertices.length;
  11284. if ( material.attributes ) {
  11285. if ( geometry.__webglCustomAttributesList === undefined ) {
  11286. geometry.__webglCustomAttributesList = [];
  11287. }
  11288. for ( var name in material.attributes ) {
  11289. var attribute = material.attributes[ name ];
  11290. if ( ! attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11291. attribute.__webglInitialized = true;
  11292. var size = 1; // "f" and "i"
  11293. if ( attribute.type === 'v2' ) size = 2;
  11294. else if ( attribute.type === 'v3' ) size = 3;
  11295. else if ( attribute.type === 'v4' ) size = 4;
  11296. else if ( attribute.type === 'c' ) size = 3;
  11297. attribute.size = size;
  11298. attribute.array = new Float32Array( nvertices * size );
  11299. attribute.buffer = _gl.createBuffer();
  11300. attribute.buffer.belongsToAttribute = name;
  11301. attribute.needsUpdate = true;
  11302. }
  11303. geometry.__webglCustomAttributesList.push( attribute );
  11304. }
  11305. }
  11306. };
  11307. function initParticleBuffers ( geometry, object ) {
  11308. var nvertices = geometry.vertices.length;
  11309. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11310. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11311. geometry.__webglParticleCount = nvertices;
  11312. initCustomAttributes( object );
  11313. };
  11314. function initLineBuffers ( geometry, object ) {
  11315. var nvertices = geometry.vertices.length;
  11316. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11317. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11318. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  11319. geometry.__webglLineCount = nvertices;
  11320. initCustomAttributes( object );
  11321. };
  11322. function initMeshBuffers ( geometryGroup, object ) {
  11323. var geometry = object.geometry,
  11324. faces3 = geometryGroup.faces3,
  11325. nvertices = faces3.length * 3,
  11326. ntris = faces3.length * 1,
  11327. nlines = faces3.length * 3,
  11328. material = getBufferMaterial( object, geometryGroup );
  11329. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  11330. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  11331. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  11332. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  11333. if ( geometry.faceVertexUvs.length > 1 ) {
  11334. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  11335. }
  11336. if ( geometry.hasTangents ) {
  11337. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  11338. }
  11339. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  11340. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  11341. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  11342. }
  11343. var UintArray = extensions.get( 'OES_element_index_uint' ) !== null && ntris > 21845 ? Uint32Array : Uint16Array; // 65535 / 3
  11344. geometryGroup.__typeArray = UintArray;
  11345. geometryGroup.__faceArray = new UintArray( ntris * 3 );
  11346. geometryGroup.__lineArray = new UintArray( nlines * 2 );
  11347. var numMorphTargets = geometryGroup.numMorphTargets;
  11348. if ( numMorphTargets ) {
  11349. geometryGroup.__morphTargetsArrays = [];
  11350. for ( var m = 0, ml = numMorphTargets; m < ml; m ++ ) {
  11351. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  11352. }
  11353. }
  11354. var numMorphNormals = geometryGroup.numMorphNormals;
  11355. if ( numMorphNormals ) {
  11356. geometryGroup.__morphNormalsArrays = [];
  11357. for ( var m = 0, ml = numMorphNormals; m < ml; m ++ ) {
  11358. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  11359. }
  11360. }
  11361. geometryGroup.__webglFaceCount = ntris * 3;
  11362. geometryGroup.__webglLineCount = nlines * 2;
  11363. // custom attributes
  11364. if ( material.attributes ) {
  11365. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  11366. geometryGroup.__webglCustomAttributesList = [];
  11367. }
  11368. for ( var name in material.attributes ) {
  11369. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  11370. // attribute buffers which are correctly indexed in the setMeshBuffers function
  11371. var originalAttribute = material.attributes[ name ];
  11372. var attribute = {};
  11373. for ( var property in originalAttribute ) {
  11374. attribute[ property ] = originalAttribute[ property ];
  11375. }
  11376. if ( ! attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11377. attribute.__webglInitialized = true;
  11378. var size = 1; // "f" and "i"
  11379. if ( attribute.type === 'v2' ) size = 2;
  11380. else if ( attribute.type === 'v3' ) size = 3;
  11381. else if ( attribute.type === 'v4' ) size = 4;
  11382. else if ( attribute.type === 'c' ) size = 3;
  11383. attribute.size = size;
  11384. attribute.array = new Float32Array( nvertices * size );
  11385. attribute.buffer = _gl.createBuffer();
  11386. attribute.buffer.belongsToAttribute = name;
  11387. originalAttribute.needsUpdate = true;
  11388. attribute.__original = originalAttribute;
  11389. }
  11390. geometryGroup.__webglCustomAttributesList.push( attribute );
  11391. }
  11392. }
  11393. geometryGroup.__inittedArrays = true;
  11394. };
  11395. function getBufferMaterial( object, geometryGroup ) {
  11396. return object.material instanceof THREE.MeshFaceMaterial
  11397. ? object.material.materials[ geometryGroup.materialIndex ]
  11398. : object.material;
  11399. }
  11400. function materialNeedsFaceNormals ( material ) {
  11401. return material instanceof THREE.MeshPhongMaterial === false && material.shading === THREE.FlatShading;
  11402. }
  11403. // Buffer setting
  11404. function setParticleBuffers ( geometry, hint, object ) {
  11405. var v, c, vertex, offset, color,
  11406. vertices = geometry.vertices,
  11407. vl = vertices.length,
  11408. colors = geometry.colors,
  11409. cl = colors.length,
  11410. vertexArray = geometry.__vertexArray,
  11411. colorArray = geometry.__colorArray,
  11412. dirtyVertices = geometry.verticesNeedUpdate,
  11413. dirtyColors = geometry.colorsNeedUpdate,
  11414. customAttributes = geometry.__webglCustomAttributesList,
  11415. i, il,
  11416. ca, cal, value,
  11417. customAttribute;
  11418. if ( dirtyVertices ) {
  11419. for ( v = 0; v < vl; v ++ ) {
  11420. vertex = vertices[ v ];
  11421. offset = v * 3;
  11422. vertexArray[ offset ] = vertex.x;
  11423. vertexArray[ offset + 1 ] = vertex.y;
  11424. vertexArray[ offset + 2 ] = vertex.z;
  11425. }
  11426. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11427. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11428. }
  11429. if ( dirtyColors ) {
  11430. for ( c = 0; c < cl; c ++ ) {
  11431. color = colors[ c ];
  11432. offset = c * 3;
  11433. colorArray[ offset ] = color.r;
  11434. colorArray[ offset + 1 ] = color.g;
  11435. colorArray[ offset + 2 ] = color.b;
  11436. }
  11437. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11438. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11439. }
  11440. if ( customAttributes ) {
  11441. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11442. customAttribute = customAttributes[ i ];
  11443. if ( customAttribute.needsUpdate && ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) ) {
  11444. cal = customAttribute.value.length;
  11445. offset = 0;
  11446. if ( customAttribute.size === 1 ) {
  11447. for ( ca = 0; ca < cal; ca ++ ) {
  11448. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11449. }
  11450. } else if ( customAttribute.size === 2 ) {
  11451. for ( ca = 0; ca < cal; ca ++ ) {
  11452. value = customAttribute.value[ ca ];
  11453. customAttribute.array[ offset ] = value.x;
  11454. customAttribute.array[ offset + 1 ] = value.y;
  11455. offset += 2;
  11456. }
  11457. } else if ( customAttribute.size === 3 ) {
  11458. if ( customAttribute.type === 'c' ) {
  11459. for ( ca = 0; ca < cal; ca ++ ) {
  11460. value = customAttribute.value[ ca ];
  11461. customAttribute.array[ offset ] = value.r;
  11462. customAttribute.array[ offset + 1 ] = value.g;
  11463. customAttribute.array[ offset + 2 ] = value.b;
  11464. offset += 3;
  11465. }
  11466. } else {
  11467. for ( ca = 0; ca < cal; ca ++ ) {
  11468. value = customAttribute.value[ ca ];
  11469. customAttribute.array[ offset ] = value.x;
  11470. customAttribute.array[ offset + 1 ] = value.y;
  11471. customAttribute.array[ offset + 2 ] = value.z;
  11472. offset += 3;
  11473. }
  11474. }
  11475. } else if ( customAttribute.size === 4 ) {
  11476. for ( ca = 0; ca < cal; ca ++ ) {
  11477. value = customAttribute.value[ ca ];
  11478. customAttribute.array[ offset ] = value.x;
  11479. customAttribute.array[ offset + 1 ] = value.y;
  11480. customAttribute.array[ offset + 2 ] = value.z;
  11481. customAttribute.array[ offset + 3 ] = value.w;
  11482. offset += 4;
  11483. }
  11484. }
  11485. }
  11486. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11487. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11488. customAttribute.needsUpdate = false;
  11489. }
  11490. }
  11491. }
  11492. function setLineBuffers ( geometry, hint ) {
  11493. var v, c, d, vertex, offset, color,
  11494. vertices = geometry.vertices,
  11495. colors = geometry.colors,
  11496. lineDistances = geometry.lineDistances,
  11497. vl = vertices.length,
  11498. cl = colors.length,
  11499. dl = lineDistances.length,
  11500. vertexArray = geometry.__vertexArray,
  11501. colorArray = geometry.__colorArray,
  11502. lineDistanceArray = geometry.__lineDistanceArray,
  11503. dirtyVertices = geometry.verticesNeedUpdate,
  11504. dirtyColors = geometry.colorsNeedUpdate,
  11505. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  11506. customAttributes = geometry.__webglCustomAttributesList,
  11507. i, il,
  11508. ca, cal, value,
  11509. customAttribute;
  11510. if ( dirtyVertices ) {
  11511. for ( v = 0; v < vl; v ++ ) {
  11512. vertex = vertices[ v ];
  11513. offset = v * 3;
  11514. vertexArray[ offset ] = vertex.x;
  11515. vertexArray[ offset + 1 ] = vertex.y;
  11516. vertexArray[ offset + 2 ] = vertex.z;
  11517. }
  11518. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11519. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11520. }
  11521. if ( dirtyColors ) {
  11522. for ( c = 0; c < cl; c ++ ) {
  11523. color = colors[ c ];
  11524. offset = c * 3;
  11525. colorArray[ offset ] = color.r;
  11526. colorArray[ offset + 1 ] = color.g;
  11527. colorArray[ offset + 2 ] = color.b;
  11528. }
  11529. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11530. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11531. }
  11532. if ( dirtyLineDistances ) {
  11533. for ( d = 0; d < dl; d ++ ) {
  11534. lineDistanceArray[ d ] = lineDistances[ d ];
  11535. }
  11536. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  11537. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  11538. }
  11539. if ( customAttributes ) {
  11540. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11541. customAttribute = customAttributes[ i ];
  11542. if ( customAttribute.needsUpdate && ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) ) {
  11543. offset = 0;
  11544. cal = customAttribute.value.length;
  11545. if ( customAttribute.size === 1 ) {
  11546. for ( ca = 0; ca < cal; ca ++ ) {
  11547. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11548. }
  11549. } else if ( customAttribute.size === 2 ) {
  11550. for ( ca = 0; ca < cal; ca ++ ) {
  11551. value = customAttribute.value[ ca ];
  11552. customAttribute.array[ offset ] = value.x;
  11553. customAttribute.array[ offset + 1 ] = value.y;
  11554. offset += 2;
  11555. }
  11556. } else if ( customAttribute.size === 3 ) {
  11557. if ( customAttribute.type === 'c' ) {
  11558. for ( ca = 0; ca < cal; ca ++ ) {
  11559. value = customAttribute.value[ ca ];
  11560. customAttribute.array[ offset ] = value.r;
  11561. customAttribute.array[ offset + 1 ] = value.g;
  11562. customAttribute.array[ offset + 2 ] = value.b;
  11563. offset += 3;
  11564. }
  11565. } else {
  11566. for ( ca = 0; ca < cal; ca ++ ) {
  11567. value = customAttribute.value[ ca ];
  11568. customAttribute.array[ offset ] = value.x;
  11569. customAttribute.array[ offset + 1 ] = value.y;
  11570. customAttribute.array[ offset + 2 ] = value.z;
  11571. offset += 3;
  11572. }
  11573. }
  11574. } else if ( customAttribute.size === 4 ) {
  11575. for ( ca = 0; ca < cal; ca ++ ) {
  11576. value = customAttribute.value[ ca ];
  11577. customAttribute.array[ offset ] = value.x;
  11578. customAttribute.array[ offset + 1 ] = value.y;
  11579. customAttribute.array[ offset + 2 ] = value.z;
  11580. customAttribute.array[ offset + 3 ] = value.w;
  11581. offset += 4;
  11582. }
  11583. }
  11584. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11585. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11586. customAttribute.needsUpdate = false;
  11587. }
  11588. }
  11589. }
  11590. }
  11591. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  11592. if ( ! geometryGroup.__inittedArrays ) {
  11593. return;
  11594. }
  11595. var needsFaceNormals = materialNeedsFaceNormals( material );
  11596. var f, fl, fi, face,
  11597. vertexNormals, faceNormal,
  11598. vertexColors, faceColor,
  11599. vertexTangents,
  11600. uv, uv2, v1, v2, v3, t1, t2, t3, n1, n2, n3,
  11601. c1, c2, c3,
  11602. sw1, sw2, sw3,
  11603. si1, si2, si3,
  11604. i, il,
  11605. vn, uvi, uv2i,
  11606. vk, vkl, vka,
  11607. nka, chf, faceVertexNormals,
  11608. vertexIndex = 0,
  11609. offset = 0,
  11610. offset_uv = 0,
  11611. offset_uv2 = 0,
  11612. offset_face = 0,
  11613. offset_normal = 0,
  11614. offset_tangent = 0,
  11615. offset_line = 0,
  11616. offset_color = 0,
  11617. offset_skin = 0,
  11618. offset_morphTarget = 0,
  11619. offset_custom = 0,
  11620. value,
  11621. vertexArray = geometryGroup.__vertexArray,
  11622. uvArray = geometryGroup.__uvArray,
  11623. uv2Array = geometryGroup.__uv2Array,
  11624. normalArray = geometryGroup.__normalArray,
  11625. tangentArray = geometryGroup.__tangentArray,
  11626. colorArray = geometryGroup.__colorArray,
  11627. skinIndexArray = geometryGroup.__skinIndexArray,
  11628. skinWeightArray = geometryGroup.__skinWeightArray,
  11629. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  11630. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  11631. customAttributes = geometryGroup.__webglCustomAttributesList,
  11632. customAttribute,
  11633. faceArray = geometryGroup.__faceArray,
  11634. lineArray = geometryGroup.__lineArray,
  11635. geometry = object.geometry, // this is shared for all chunks
  11636. dirtyVertices = geometry.verticesNeedUpdate,
  11637. dirtyElements = geometry.elementsNeedUpdate,
  11638. dirtyUvs = geometry.uvsNeedUpdate,
  11639. dirtyNormals = geometry.normalsNeedUpdate,
  11640. dirtyTangents = geometry.tangentsNeedUpdate,
  11641. dirtyColors = geometry.colorsNeedUpdate,
  11642. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  11643. vertices = geometry.vertices,
  11644. chunk_faces3 = geometryGroup.faces3,
  11645. obj_faces = geometry.faces,
  11646. obj_uvs = geometry.faceVertexUvs[ 0 ],
  11647. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  11648. obj_skinIndices = geometry.skinIndices,
  11649. obj_skinWeights = geometry.skinWeights,
  11650. morphTargets = geometry.morphTargets,
  11651. morphNormals = geometry.morphNormals;
  11652. if ( dirtyVertices ) {
  11653. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11654. face = obj_faces[ chunk_faces3[ f ] ];
  11655. v1 = vertices[ face.a ];
  11656. v2 = vertices[ face.b ];
  11657. v3 = vertices[ face.c ];
  11658. vertexArray[ offset ] = v1.x;
  11659. vertexArray[ offset + 1 ] = v1.y;
  11660. vertexArray[ offset + 2 ] = v1.z;
  11661. vertexArray[ offset + 3 ] = v2.x;
  11662. vertexArray[ offset + 4 ] = v2.y;
  11663. vertexArray[ offset + 5 ] = v2.z;
  11664. vertexArray[ offset + 6 ] = v3.x;
  11665. vertexArray[ offset + 7 ] = v3.y;
  11666. vertexArray[ offset + 8 ] = v3.z;
  11667. offset += 9;
  11668. }
  11669. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11670. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11671. }
  11672. if ( dirtyMorphTargets ) {
  11673. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  11674. offset_morphTarget = 0;
  11675. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11676. chf = chunk_faces3[ f ];
  11677. face = obj_faces[ chf ];
  11678. // morph positions
  11679. v1 = morphTargets[ vk ].vertices[ face.a ];
  11680. v2 = morphTargets[ vk ].vertices[ face.b ];
  11681. v3 = morphTargets[ vk ].vertices[ face.c ];
  11682. vka = morphTargetsArrays[ vk ];
  11683. vka[ offset_morphTarget ] = v1.x;
  11684. vka[ offset_morphTarget + 1 ] = v1.y;
  11685. vka[ offset_morphTarget + 2 ] = v1.z;
  11686. vka[ offset_morphTarget + 3 ] = v2.x;
  11687. vka[ offset_morphTarget + 4 ] = v2.y;
  11688. vka[ offset_morphTarget + 5 ] = v2.z;
  11689. vka[ offset_morphTarget + 6 ] = v3.x;
  11690. vka[ offset_morphTarget + 7 ] = v3.y;
  11691. vka[ offset_morphTarget + 8 ] = v3.z;
  11692. // morph normals
  11693. if ( material.morphNormals ) {
  11694. if ( needsFaceNormals ) {
  11695. n1 = morphNormals[ vk ].faceNormals[ chf ];
  11696. n2 = n1;
  11697. n3 = n1;
  11698. } else {
  11699. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  11700. n1 = faceVertexNormals.a;
  11701. n2 = faceVertexNormals.b;
  11702. n3 = faceVertexNormals.c;
  11703. }
  11704. nka = morphNormalsArrays[ vk ];
  11705. nka[ offset_morphTarget ] = n1.x;
  11706. nka[ offset_morphTarget + 1 ] = n1.y;
  11707. nka[ offset_morphTarget + 2 ] = n1.z;
  11708. nka[ offset_morphTarget + 3 ] = n2.x;
  11709. nka[ offset_morphTarget + 4 ] = n2.y;
  11710. nka[ offset_morphTarget + 5 ] = n2.z;
  11711. nka[ offset_morphTarget + 6 ] = n3.x;
  11712. nka[ offset_morphTarget + 7 ] = n3.y;
  11713. nka[ offset_morphTarget + 8 ] = n3.z;
  11714. }
  11715. //
  11716. offset_morphTarget += 9;
  11717. }
  11718. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  11719. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  11720. if ( material.morphNormals ) {
  11721. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  11722. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  11723. }
  11724. }
  11725. }
  11726. if ( obj_skinWeights.length ) {
  11727. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11728. face = obj_faces[ chunk_faces3[ f ] ];
  11729. // weights
  11730. sw1 = obj_skinWeights[ face.a ];
  11731. sw2 = obj_skinWeights[ face.b ];
  11732. sw3 = obj_skinWeights[ face.c ];
  11733. skinWeightArray[ offset_skin ] = sw1.x;
  11734. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  11735. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  11736. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  11737. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  11738. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  11739. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  11740. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  11741. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  11742. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  11743. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  11744. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  11745. // indices
  11746. si1 = obj_skinIndices[ face.a ];
  11747. si2 = obj_skinIndices[ face.b ];
  11748. si3 = obj_skinIndices[ face.c ];
  11749. skinIndexArray[ offset_skin ] = si1.x;
  11750. skinIndexArray[ offset_skin + 1 ] = si1.y;
  11751. skinIndexArray[ offset_skin + 2 ] = si1.z;
  11752. skinIndexArray[ offset_skin + 3 ] = si1.w;
  11753. skinIndexArray[ offset_skin + 4 ] = si2.x;
  11754. skinIndexArray[ offset_skin + 5 ] = si2.y;
  11755. skinIndexArray[ offset_skin + 6 ] = si2.z;
  11756. skinIndexArray[ offset_skin + 7 ] = si2.w;
  11757. skinIndexArray[ offset_skin + 8 ] = si3.x;
  11758. skinIndexArray[ offset_skin + 9 ] = si3.y;
  11759. skinIndexArray[ offset_skin + 10 ] = si3.z;
  11760. skinIndexArray[ offset_skin + 11 ] = si3.w;
  11761. offset_skin += 12;
  11762. }
  11763. if ( offset_skin > 0 ) {
  11764. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  11765. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  11766. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  11767. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  11768. }
  11769. }
  11770. if ( dirtyColors ) {
  11771. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11772. face = obj_faces[ chunk_faces3[ f ] ];
  11773. vertexColors = face.vertexColors;
  11774. faceColor = face.color;
  11775. if ( vertexColors.length === 3 && material.vertexColors === THREE.VertexColors ) {
  11776. c1 = vertexColors[ 0 ];
  11777. c2 = vertexColors[ 1 ];
  11778. c3 = vertexColors[ 2 ];
  11779. } else {
  11780. c1 = faceColor;
  11781. c2 = faceColor;
  11782. c3 = faceColor;
  11783. }
  11784. colorArray[ offset_color ] = c1.r;
  11785. colorArray[ offset_color + 1 ] = c1.g;
  11786. colorArray[ offset_color + 2 ] = c1.b;
  11787. colorArray[ offset_color + 3 ] = c2.r;
  11788. colorArray[ offset_color + 4 ] = c2.g;
  11789. colorArray[ offset_color + 5 ] = c2.b;
  11790. colorArray[ offset_color + 6 ] = c3.r;
  11791. colorArray[ offset_color + 7 ] = c3.g;
  11792. colorArray[ offset_color + 8 ] = c3.b;
  11793. offset_color += 9;
  11794. }
  11795. if ( offset_color > 0 ) {
  11796. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  11797. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11798. }
  11799. }
  11800. if ( dirtyTangents && geometry.hasTangents ) {
  11801. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11802. face = obj_faces[ chunk_faces3[ f ] ];
  11803. vertexTangents = face.vertexTangents;
  11804. t1 = vertexTangents[ 0 ];
  11805. t2 = vertexTangents[ 1 ];
  11806. t3 = vertexTangents[ 2 ];
  11807. tangentArray[ offset_tangent ] = t1.x;
  11808. tangentArray[ offset_tangent + 1 ] = t1.y;
  11809. tangentArray[ offset_tangent + 2 ] = t1.z;
  11810. tangentArray[ offset_tangent + 3 ] = t1.w;
  11811. tangentArray[ offset_tangent + 4 ] = t2.x;
  11812. tangentArray[ offset_tangent + 5 ] = t2.y;
  11813. tangentArray[ offset_tangent + 6 ] = t2.z;
  11814. tangentArray[ offset_tangent + 7 ] = t2.w;
  11815. tangentArray[ offset_tangent + 8 ] = t3.x;
  11816. tangentArray[ offset_tangent + 9 ] = t3.y;
  11817. tangentArray[ offset_tangent + 10 ] = t3.z;
  11818. tangentArray[ offset_tangent + 11 ] = t3.w;
  11819. offset_tangent += 12;
  11820. }
  11821. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  11822. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  11823. }
  11824. if ( dirtyNormals ) {
  11825. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11826. face = obj_faces[ chunk_faces3[ f ] ];
  11827. vertexNormals = face.vertexNormals;
  11828. faceNormal = face.normal;
  11829. if ( vertexNormals.length === 3 && needsFaceNormals === false ) {
  11830. for ( i = 0; i < 3; i ++ ) {
  11831. vn = vertexNormals[ i ];
  11832. normalArray[ offset_normal ] = vn.x;
  11833. normalArray[ offset_normal + 1 ] = vn.y;
  11834. normalArray[ offset_normal + 2 ] = vn.z;
  11835. offset_normal += 3;
  11836. }
  11837. } else {
  11838. for ( i = 0; i < 3; i ++ ) {
  11839. normalArray[ offset_normal ] = faceNormal.x;
  11840. normalArray[ offset_normal + 1 ] = faceNormal.y;
  11841. normalArray[ offset_normal + 2 ] = faceNormal.z;
  11842. offset_normal += 3;
  11843. }
  11844. }
  11845. }
  11846. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  11847. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  11848. }
  11849. if ( dirtyUvs && obj_uvs ) {
  11850. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11851. fi = chunk_faces3[ f ];
  11852. uv = obj_uvs[ fi ];
  11853. if ( uv === undefined ) continue;
  11854. for ( i = 0; i < 3; i ++ ) {
  11855. uvi = uv[ i ];
  11856. uvArray[ offset_uv ] = uvi.x;
  11857. uvArray[ offset_uv + 1 ] = uvi.y;
  11858. offset_uv += 2;
  11859. }
  11860. }
  11861. if ( offset_uv > 0 ) {
  11862. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  11863. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  11864. }
  11865. }
  11866. if ( dirtyUvs && obj_uvs2 ) {
  11867. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11868. fi = chunk_faces3[ f ];
  11869. uv2 = obj_uvs2[ fi ];
  11870. if ( uv2 === undefined ) continue;
  11871. for ( i = 0; i < 3; i ++ ) {
  11872. uv2i = uv2[ i ];
  11873. uv2Array[ offset_uv2 ] = uv2i.x;
  11874. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  11875. offset_uv2 += 2;
  11876. }
  11877. }
  11878. if ( offset_uv2 > 0 ) {
  11879. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  11880. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  11881. }
  11882. }
  11883. if ( dirtyElements ) {
  11884. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11885. faceArray[ offset_face ] = vertexIndex;
  11886. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  11887. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  11888. offset_face += 3;
  11889. lineArray[ offset_line ] = vertexIndex;
  11890. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  11891. lineArray[ offset_line + 2 ] = vertexIndex;
  11892. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  11893. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  11894. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  11895. offset_line += 6;
  11896. vertexIndex += 3;
  11897. }
  11898. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  11899. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  11900. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  11901. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  11902. }
  11903. if ( customAttributes ) {
  11904. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11905. customAttribute = customAttributes[ i ];
  11906. if ( ! customAttribute.__original.needsUpdate ) continue;
  11907. offset_custom = 0;
  11908. if ( customAttribute.size === 1 ) {
  11909. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  11910. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11911. face = obj_faces[ chunk_faces3[ f ] ];
  11912. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  11913. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  11914. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  11915. offset_custom += 3;
  11916. }
  11917. } else if ( customAttribute.boundTo === 'faces' ) {
  11918. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11919. value = customAttribute.value[ chunk_faces3[ f ] ];
  11920. customAttribute.array[ offset_custom ] = value;
  11921. customAttribute.array[ offset_custom + 1 ] = value;
  11922. customAttribute.array[ offset_custom + 2 ] = value;
  11923. offset_custom += 3;
  11924. }
  11925. }
  11926. } else if ( customAttribute.size === 2 ) {
  11927. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  11928. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11929. face = obj_faces[ chunk_faces3[ f ] ];
  11930. v1 = customAttribute.value[ face.a ];
  11931. v2 = customAttribute.value[ face.b ];
  11932. v3 = customAttribute.value[ face.c ];
  11933. customAttribute.array[ offset_custom ] = v1.x;
  11934. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11935. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11936. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11937. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11938. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11939. offset_custom += 6;
  11940. }
  11941. } else if ( customAttribute.boundTo === 'faces' ) {
  11942. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11943. value = customAttribute.value[ chunk_faces3[ f ] ];
  11944. v1 = value;
  11945. v2 = value;
  11946. v3 = value;
  11947. customAttribute.array[ offset_custom ] = v1.x;
  11948. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11949. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11950. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11951. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11952. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11953. offset_custom += 6;
  11954. }
  11955. }
  11956. } else if ( customAttribute.size === 3 ) {
  11957. var pp;
  11958. if ( customAttribute.type === 'c' ) {
  11959. pp = [ 'r', 'g', 'b' ];
  11960. } else {
  11961. pp = [ 'x', 'y', 'z' ];
  11962. }
  11963. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  11964. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11965. face = obj_faces[ chunk_faces3[ f ] ];
  11966. v1 = customAttribute.value[ face.a ];
  11967. v2 = customAttribute.value[ face.b ];
  11968. v3 = customAttribute.value[ face.c ];
  11969. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11970. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11971. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11972. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11973. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11974. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11975. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11976. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11977. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11978. offset_custom += 9;
  11979. }
  11980. } else if ( customAttribute.boundTo === 'faces' ) {
  11981. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11982. value = customAttribute.value[ chunk_faces3[ f ] ];
  11983. v1 = value;
  11984. v2 = value;
  11985. v3 = value;
  11986. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11987. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11988. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11989. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11990. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11991. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11992. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11993. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11994. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11995. offset_custom += 9;
  11996. }
  11997. } else if ( customAttribute.boundTo === 'faceVertices' ) {
  11998. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11999. value = customAttribute.value[ chunk_faces3[ f ] ];
  12000. v1 = value[ 0 ];
  12001. v2 = value[ 1 ];
  12002. v3 = value[ 2 ];
  12003. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12004. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12005. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12006. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12007. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12008. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12009. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12010. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12011. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12012. offset_custom += 9;
  12013. }
  12014. }
  12015. } else if ( customAttribute.size === 4 ) {
  12016. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  12017. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12018. face = obj_faces[ chunk_faces3[ f ] ];
  12019. v1 = customAttribute.value[ face.a ];
  12020. v2 = customAttribute.value[ face.b ];
  12021. v3 = customAttribute.value[ face.c ];
  12022. customAttribute.array[ offset_custom ] = v1.x;
  12023. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12024. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12025. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12026. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12027. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12028. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12029. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12030. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12031. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12032. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12033. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12034. offset_custom += 12;
  12035. }
  12036. } else if ( customAttribute.boundTo === 'faces' ) {
  12037. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12038. value = customAttribute.value[ chunk_faces3[ f ] ];
  12039. v1 = value;
  12040. v2 = value;
  12041. v3 = value;
  12042. customAttribute.array[ offset_custom ] = v1.x;
  12043. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12044. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12045. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12046. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12047. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12048. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12049. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12050. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12051. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12052. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12053. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12054. offset_custom += 12;
  12055. }
  12056. } else if ( customAttribute.boundTo === 'faceVertices' ) {
  12057. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12058. value = customAttribute.value[ chunk_faces3[ f ] ];
  12059. v1 = value[ 0 ];
  12060. v2 = value[ 1 ];
  12061. v3 = value[ 2 ];
  12062. customAttribute.array[ offset_custom ] = v1.x;
  12063. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12064. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12065. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12066. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12067. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12068. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12069. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12070. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12071. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12072. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12073. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12074. offset_custom += 12;
  12075. }
  12076. }
  12077. }
  12078. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12079. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12080. }
  12081. }
  12082. if ( dispose ) {
  12083. delete geometryGroup.__inittedArrays;
  12084. delete geometryGroup.__colorArray;
  12085. delete geometryGroup.__normalArray;
  12086. delete geometryGroup.__tangentArray;
  12087. delete geometryGroup.__uvArray;
  12088. delete geometryGroup.__uv2Array;
  12089. delete geometryGroup.__faceArray;
  12090. delete geometryGroup.__vertexArray;
  12091. delete geometryGroup.__lineArray;
  12092. delete geometryGroup.__skinIndexArray;
  12093. delete geometryGroup.__skinWeightArray;
  12094. }
  12095. };
  12096. // Buffer rendering
  12097. this.renderBufferImmediate = function ( object, program, material ) {
  12098. state.initAttributes();
  12099. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  12100. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  12101. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  12102. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  12103. if ( object.hasPositions ) {
  12104. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  12105. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12106. state.enableAttribute( program.attributes.position );
  12107. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12108. }
  12109. if ( object.hasNormals ) {
  12110. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  12111. if ( material instanceof THREE.MeshPhongMaterial === false &&
  12112. material.shading === THREE.FlatShading ) {
  12113. var nx, ny, nz,
  12114. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  12115. normalArray,
  12116. i, il = object.count * 3;
  12117. for ( i = 0; i < il; i += 9 ) {
  12118. normalArray = object.normalArray;
  12119. nax = normalArray[ i ];
  12120. nay = normalArray[ i + 1 ];
  12121. naz = normalArray[ i + 2 ];
  12122. nbx = normalArray[ i + 3 ];
  12123. nby = normalArray[ i + 4 ];
  12124. nbz = normalArray[ i + 5 ];
  12125. ncx = normalArray[ i + 6 ];
  12126. ncy = normalArray[ i + 7 ];
  12127. ncz = normalArray[ i + 8 ];
  12128. nx = ( nax + nbx + ncx ) / 3;
  12129. ny = ( nay + nby + ncy ) / 3;
  12130. nz = ( naz + nbz + ncz ) / 3;
  12131. normalArray[ i ] = nx;
  12132. normalArray[ i + 1 ] = ny;
  12133. normalArray[ i + 2 ] = nz;
  12134. normalArray[ i + 3 ] = nx;
  12135. normalArray[ i + 4 ] = ny;
  12136. normalArray[ i + 5 ] = nz;
  12137. normalArray[ i + 6 ] = nx;
  12138. normalArray[ i + 7 ] = ny;
  12139. normalArray[ i + 8 ] = nz;
  12140. }
  12141. }
  12142. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  12143. state.enableAttribute( program.attributes.normal );
  12144. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12145. }
  12146. if ( object.hasUvs && material.map ) {
  12147. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  12148. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  12149. state.enableAttribute( program.attributes.uv );
  12150. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12151. }
  12152. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  12153. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  12154. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  12155. state.enableAttribute( program.attributes.color );
  12156. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12157. }
  12158. state.disableUnusedAttributes();
  12159. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  12160. object.count = 0;
  12161. };
  12162. function setupVertexAttributes( material, program, geometry, startIndex ) {
  12163. var geometryAttributes = geometry.attributes;
  12164. var programAttributes = program.attributes;
  12165. var programAttributesKeys = program.attributesKeys;
  12166. for ( var i = 0, l = programAttributesKeys.length; i < l; i ++ ) {
  12167. var key = programAttributesKeys[ i ];
  12168. var programAttribute = programAttributes[ key ];
  12169. if ( programAttribute >= 0 ) {
  12170. var geometryAttribute = geometryAttributes[ key ];
  12171. if ( geometryAttribute !== undefined ) {
  12172. var size = geometryAttribute.itemSize;
  12173. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryAttribute.buffer );
  12174. state.enableAttribute( programAttribute );
  12175. _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, 0, startIndex * size * 4 ); // 4 bytes per Float32
  12176. } else if ( material.defaultAttributeValues !== undefined ) {
  12177. if ( material.defaultAttributeValues[ key ].length === 2 ) {
  12178. _gl.vertexAttrib2fv( programAttribute, material.defaultAttributeValues[ key ] );
  12179. } else if ( material.defaultAttributeValues[ key ].length === 3 ) {
  12180. _gl.vertexAttrib3fv( programAttribute, material.defaultAttributeValues[ key ] );
  12181. }
  12182. }
  12183. }
  12184. }
  12185. state.disableUnusedAttributes();
  12186. }
  12187. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  12188. if ( material.visible === false ) return;
  12189. updateObject( object );
  12190. var program = setProgram( camera, lights, fog, material, object );
  12191. var updateBuffers = false,
  12192. wireframeBit = material.wireframe ? 1 : 0,
  12193. geometryProgram = 'direct_' + geometry.id + '_' + program.id + '_' + wireframeBit;
  12194. if ( geometryProgram !== _currentGeometryProgram ) {
  12195. _currentGeometryProgram = geometryProgram;
  12196. updateBuffers = true;
  12197. }
  12198. if ( updateBuffers ) {
  12199. state.initAttributes();
  12200. }
  12201. // render mesh
  12202. if ( object instanceof THREE.Mesh ) {
  12203. var mode = material.wireframe === true ? _gl.LINES : _gl.TRIANGLES;
  12204. var index = geometry.attributes.index;
  12205. if ( index ) {
  12206. // indexed triangles
  12207. var type, size;
  12208. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  12209. type = _gl.UNSIGNED_INT;
  12210. size = 4;
  12211. } else {
  12212. type = _gl.UNSIGNED_SHORT;
  12213. size = 2;
  12214. }
  12215. var offsets = geometry.offsets;
  12216. if ( offsets.length === 0 ) {
  12217. if ( updateBuffers ) {
  12218. setupVertexAttributes( material, program, geometry, 0 );
  12219. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12220. }
  12221. _gl.drawElements( mode, index.array.length, type, 0 );
  12222. _this.info.render.calls ++;
  12223. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  12224. _this.info.render.faces += index.array.length / 3;
  12225. } else {
  12226. // if there is more than 1 chunk
  12227. // must set attribute pointers to use new offsets for each chunk
  12228. // even if geometry and materials didn't change
  12229. updateBuffers = true;
  12230. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12231. var startIndex = offsets[ i ].index;
  12232. if ( updateBuffers ) {
  12233. setupVertexAttributes( material, program, geometry, startIndex );
  12234. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12235. }
  12236. // render indexed triangles
  12237. _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size );
  12238. _this.info.render.calls ++;
  12239. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  12240. _this.info.render.faces += offsets[ i ].count / 3;
  12241. }
  12242. }
  12243. } else {
  12244. // non-indexed triangles
  12245. if ( updateBuffers ) {
  12246. setupVertexAttributes( material, program, geometry, 0 );
  12247. }
  12248. var position = geometry.attributes[ 'position' ];
  12249. // render non-indexed triangles
  12250. _gl.drawArrays( mode, 0, position.array.length / position.itemSize );
  12251. _this.info.render.calls ++;
  12252. _this.info.render.vertices += position.array.length / position.itemSize;
  12253. _this.info.render.faces += position.array.length / ( 3 * position.itemSize );
  12254. }
  12255. } else if ( object instanceof THREE.PointCloud ) {
  12256. // render particles
  12257. var mode = _gl.POINTS;
  12258. var index = geometry.attributes.index;
  12259. if ( index ) {
  12260. // indexed points
  12261. var type, size;
  12262. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  12263. type = _gl.UNSIGNED_INT;
  12264. size = 4;
  12265. } else {
  12266. type = _gl.UNSIGNED_SHORT;
  12267. size = 2;
  12268. }
  12269. var offsets = geometry.offsets;
  12270. if ( offsets.length === 0 ) {
  12271. if ( updateBuffers ) {
  12272. setupVertexAttributes( material, program, geometry, 0 );
  12273. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12274. }
  12275. _gl.drawElements( mode, index.array.length, type, 0);
  12276. _this.info.render.calls ++;
  12277. _this.info.render.points += index.array.length;
  12278. } else {
  12279. // if there is more than 1 chunk
  12280. // must set attribute pointers to use new offsets for each chunk
  12281. // even if geometry and materials didn't change
  12282. if ( offsets.length > 1 ) updateBuffers = true;
  12283. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12284. var startIndex = offsets[ i ].index;
  12285. if ( updateBuffers ) {
  12286. setupVertexAttributes( material, program, geometry, startIndex );
  12287. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12288. }
  12289. // render indexed points
  12290. _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size );
  12291. _this.info.render.calls ++;
  12292. _this.info.render.points += offsets[ i ].count;
  12293. }
  12294. }
  12295. } else {
  12296. // non-indexed points
  12297. if ( updateBuffers ) {
  12298. setupVertexAttributes( material, program, geometry, 0 );
  12299. }
  12300. var position = geometry.attributes.position;
  12301. var offsets = geometry.offsets;
  12302. if ( offsets.length === 0 ) {
  12303. _gl.drawArrays( mode, 0, position.array.length / 3 );
  12304. _this.info.render.calls ++;
  12305. _this.info.render.points += position.array.length / 3;
  12306. } else {
  12307. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12308. _gl.drawArrays( mode, offsets[ i ].index, offsets[ i ].count );
  12309. _this.info.render.calls ++;
  12310. _this.info.render.points += offsets[ i ].count;
  12311. }
  12312. }
  12313. }
  12314. } else if ( object instanceof THREE.Line ) {
  12315. var mode = ( object.mode === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  12316. state.setLineWidth( material.linewidth * pixelRatio );
  12317. var index = geometry.attributes.index;
  12318. if ( index ) {
  12319. // indexed lines
  12320. var type, size;
  12321. if ( index.array instanceof Uint32Array ) {
  12322. type = _gl.UNSIGNED_INT;
  12323. size = 4;
  12324. } else {
  12325. type = _gl.UNSIGNED_SHORT;
  12326. size = 2;
  12327. }
  12328. var offsets = geometry.offsets;
  12329. if ( offsets.length === 0 ) {
  12330. if ( updateBuffers ) {
  12331. setupVertexAttributes( material, program, geometry, 0 );
  12332. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12333. }
  12334. _gl.drawElements( mode, index.array.length, type, 0 ); // 2 bytes per Uint16Array
  12335. _this.info.render.calls ++;
  12336. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  12337. } else {
  12338. // if there is more than 1 chunk
  12339. // must set attribute pointers to use new offsets for each chunk
  12340. // even if geometry and materials didn't change
  12341. if ( offsets.length > 1 ) updateBuffers = true;
  12342. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12343. var startIndex = offsets[ i ].index;
  12344. if ( updateBuffers ) {
  12345. setupVertexAttributes( material, program, geometry, startIndex );
  12346. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12347. }
  12348. // render indexed lines
  12349. _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size ); // 2 bytes per Uint16Array
  12350. _this.info.render.calls ++;
  12351. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  12352. }
  12353. }
  12354. } else {
  12355. // non-indexed lines
  12356. if ( updateBuffers ) {
  12357. setupVertexAttributes( material, program, geometry, 0 );
  12358. }
  12359. var position = geometry.attributes.position;
  12360. var offsets = geometry.offsets;
  12361. if ( offsets.length === 0 ) {
  12362. _gl.drawArrays( mode, 0, position.array.length / 3 );
  12363. _this.info.render.calls ++;
  12364. _this.info.render.vertices += position.array.length / 3;
  12365. } else {
  12366. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12367. _gl.drawArrays( mode, offsets[ i ].index, offsets[ i ].count );
  12368. _this.info.render.calls ++;
  12369. _this.info.render.vertices += offsets[ i ].count;
  12370. }
  12371. }
  12372. }
  12373. }
  12374. };
  12375. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  12376. if ( material.visible === false ) return;
  12377. updateObject( object );
  12378. var program = setProgram( camera, lights, fog, material, object );
  12379. var attributes = program.attributes;
  12380. var updateBuffers = false,
  12381. wireframeBit = material.wireframe ? 1 : 0,
  12382. geometryProgram = geometryGroup.id + '_' + program.id + '_' + wireframeBit;
  12383. if ( geometryProgram !== _currentGeometryProgram ) {
  12384. _currentGeometryProgram = geometryProgram;
  12385. updateBuffers = true;
  12386. }
  12387. if ( updateBuffers ) {
  12388. state.initAttributes();
  12389. }
  12390. // vertices
  12391. if ( ! material.morphTargets && attributes.position >= 0 ) {
  12392. if ( updateBuffers ) {
  12393. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12394. state.enableAttribute( attributes.position );
  12395. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12396. }
  12397. } else {
  12398. if ( object.morphTargetBase ) {
  12399. setupMorphTargets( material, geometryGroup, object );
  12400. }
  12401. }
  12402. if ( updateBuffers ) {
  12403. // custom attributes
  12404. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  12405. if ( geometryGroup.__webglCustomAttributesList ) {
  12406. for ( var i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  12407. var attribute = geometryGroup.__webglCustomAttributesList[ i ];
  12408. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  12409. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  12410. state.enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  12411. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  12412. }
  12413. }
  12414. }
  12415. // colors
  12416. if ( attributes.color >= 0 ) {
  12417. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  12418. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12419. state.enableAttribute( attributes.color );
  12420. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12421. } else if ( material.defaultAttributeValues !== undefined ) {
  12422. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  12423. }
  12424. }
  12425. // normals
  12426. if ( attributes.normal >= 0 ) {
  12427. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12428. state.enableAttribute( attributes.normal );
  12429. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12430. }
  12431. // tangents
  12432. if ( attributes.tangent >= 0 ) {
  12433. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12434. state.enableAttribute( attributes.tangent );
  12435. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  12436. }
  12437. // uvs
  12438. if ( attributes.uv >= 0 ) {
  12439. if ( object.geometry.faceVertexUvs[ 0 ] ) {
  12440. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12441. state.enableAttribute( attributes.uv );
  12442. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12443. } else if ( material.defaultAttributeValues !== undefined ) {
  12444. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  12445. }
  12446. }
  12447. if ( attributes.uv2 >= 0 ) {
  12448. if ( object.geometry.faceVertexUvs[ 1 ] ) {
  12449. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12450. state.enableAttribute( attributes.uv2 );
  12451. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  12452. } else if ( material.defaultAttributeValues !== undefined ) {
  12453. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  12454. }
  12455. }
  12456. if ( material.skinning &&
  12457. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  12458. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12459. state.enableAttribute( attributes.skinIndex );
  12460. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  12461. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12462. state.enableAttribute( attributes.skinWeight );
  12463. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  12464. }
  12465. // line distances
  12466. if ( attributes.lineDistance >= 0 ) {
  12467. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  12468. state.enableAttribute( attributes.lineDistance );
  12469. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  12470. }
  12471. }
  12472. state.disableUnusedAttributes();
  12473. // render mesh
  12474. if ( object instanceof THREE.Mesh ) {
  12475. var type = geometryGroup.__typeArray === Uint32Array ? _gl.UNSIGNED_INT : _gl.UNSIGNED_SHORT;
  12476. // wireframe
  12477. if ( material.wireframe ) {
  12478. state.setLineWidth( material.wireframeLinewidth * pixelRatio );
  12479. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12480. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, type, 0 );
  12481. // triangles
  12482. } else {
  12483. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12484. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, type, 0 );
  12485. }
  12486. _this.info.render.calls ++;
  12487. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  12488. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  12489. // render lines
  12490. } else if ( object instanceof THREE.Line ) {
  12491. var mode = ( object.mode === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  12492. state.setLineWidth( material.linewidth * pixelRatio );
  12493. _gl.drawArrays( mode, 0, geometryGroup.__webglLineCount );
  12494. _this.info.render.calls ++;
  12495. // render particles
  12496. } else if ( object instanceof THREE.PointCloud ) {
  12497. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  12498. _this.info.render.calls ++;
  12499. _this.info.render.points += geometryGroup.__webglParticleCount;
  12500. }
  12501. };
  12502. function setupMorphTargets ( material, geometryGroup, object ) {
  12503. // set base
  12504. var attributes = material.program.attributes;
  12505. if ( object.morphTargetBase !== - 1 && attributes.position >= 0 ) {
  12506. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  12507. state.enableAttribute( attributes.position );
  12508. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12509. } else if ( attributes.position >= 0 ) {
  12510. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12511. state.enableAttribute( attributes.position );
  12512. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12513. }
  12514. if ( object.morphTargetForcedOrder.length ) {
  12515. // set forced order
  12516. var m = 0;
  12517. var order = object.morphTargetForcedOrder;
  12518. var influences = object.morphTargetInfluences;
  12519. var attribute;
  12520. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  12521. attribute = attributes[ 'morphTarget' + m ];
  12522. if ( attribute >= 0 ) {
  12523. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  12524. state.enableAttribute( attribute );
  12525. _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 );
  12526. }
  12527. attribute = attributes[ 'morphNormal' + m ];
  12528. if ( attribute >= 0 && material.morphNormals ) {
  12529. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  12530. state.enableAttribute( attribute );
  12531. _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 );
  12532. }
  12533. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  12534. m ++;
  12535. }
  12536. } else {
  12537. // find the most influencing
  12538. var activeInfluenceIndices = [];
  12539. var influences = object.morphTargetInfluences;
  12540. var morphTargets = object.geometry.morphTargets;
  12541. if ( influences.length > morphTargets.length ) {
  12542. THREE.warn( 'THREE.WebGLRenderer: Influences array is bigger than morphTargets array.' );
  12543. influences.length = morphTargets.length;
  12544. }
  12545. for ( var i = 0, il = influences.length; i < il; i ++ ) {
  12546. var influence = influences[ i ];
  12547. activeInfluenceIndices.push( [ influence, i ] );
  12548. }
  12549. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  12550. activeInfluenceIndices.sort( numericalSort );
  12551. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  12552. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  12553. activeInfluenceIndices.sort( numericalSort );
  12554. } else if ( activeInfluenceIndices.length === 0 ) {
  12555. activeInfluenceIndices.push( [ 0, 0 ] );
  12556. }
  12557. var attribute;
  12558. for ( var m = 0, ml = material.numSupportedMorphTargets; m < ml; m ++ ) {
  12559. if ( activeInfluenceIndices[ m ] ) {
  12560. var influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  12561. attribute = attributes[ 'morphTarget' + m ];
  12562. if ( attribute >= 0 ) {
  12563. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  12564. state.enableAttribute( attribute );
  12565. _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 );
  12566. }
  12567. attribute = attributes[ 'morphNormal' + m ];
  12568. if ( attribute >= 0 && material.morphNormals ) {
  12569. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  12570. state.enableAttribute( attribute );
  12571. _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 );
  12572. }
  12573. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  12574. } else {
  12575. /*
  12576. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12577. if ( material.morphNormals ) {
  12578. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12579. }
  12580. */
  12581. object.__webglMorphTargetInfluences[ m ] = 0;
  12582. }
  12583. }
  12584. }
  12585. // load updated influences uniform
  12586. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  12587. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  12588. }
  12589. }
  12590. // Sorting
  12591. function painterSortStable ( a, b ) {
  12592. if ( a.object.renderOrder !== b.object.renderOrder ) {
  12593. return a.object.renderOrder - b.object.renderOrder;
  12594. } else if ( a.material.id !== b.material.id ) {
  12595. return a.material.id - b.material.id;
  12596. } else if ( a.z !== b.z ) {
  12597. return a.z - b.z;
  12598. } else {
  12599. return a.id - b.id;
  12600. }
  12601. }
  12602. function reversePainterSortStable ( a, b ) {
  12603. if ( a.object.renderOrder !== b.object.renderOrder ) {
  12604. return a.object.renderOrder - b.object.renderOrder;
  12605. } if ( a.z !== b.z ) {
  12606. return b.z - a.z;
  12607. } else {
  12608. return a.id - b.id;
  12609. }
  12610. }
  12611. function numericalSort ( a, b ) {
  12612. return b[ 0 ] - a[ 0 ];
  12613. }
  12614. // Rendering
  12615. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12616. if ( camera instanceof THREE.Camera === false ) {
  12617. THREE.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12618. return;
  12619. }
  12620. var fog = scene.fog;
  12621. // reset caching for this frame
  12622. _currentGeometryProgram = '';
  12623. _currentMaterialId = - 1;
  12624. _currentCamera = null;
  12625. _lightsNeedUpdate = true;
  12626. // update scene graph
  12627. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  12628. // update camera matrices and frustum
  12629. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  12630. // update Skeleton objects
  12631. scene.traverse( function ( object ) {
  12632. if ( object instanceof THREE.SkinnedMesh ) {
  12633. object.skeleton.update();
  12634. }
  12635. } );
  12636. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  12637. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  12638. _frustum.setFromMatrix( _projScreenMatrix );
  12639. lights.length = 0;
  12640. opaqueObjects.length = 0;
  12641. transparentObjects.length = 0;
  12642. sprites.length = 0;
  12643. lensFlares.length = 0;
  12644. projectObject( scene );
  12645. if ( _this.sortObjects === true ) {
  12646. opaqueObjects.sort( painterSortStable );
  12647. transparentObjects.sort( reversePainterSortStable );
  12648. }
  12649. // custom render plugins (pre pass)
  12650. shadowMapPlugin.render( scene, camera );
  12651. //
  12652. _this.info.render.calls = 0;
  12653. _this.info.render.vertices = 0;
  12654. _this.info.render.faces = 0;
  12655. _this.info.render.points = 0;
  12656. this.setRenderTarget( renderTarget );
  12657. if ( this.autoClear || forceClear ) {
  12658. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  12659. }
  12660. // set matrices for immediate objects
  12661. for ( var i = 0, il = _webglObjectsImmediate.length; i < il; i ++ ) {
  12662. var webglObject = _webglObjectsImmediate[ i ];
  12663. var object = webglObject.object;
  12664. if ( object.visible ) {
  12665. setupMatrices( object, camera );
  12666. unrollImmediateBufferMaterial( webglObject );
  12667. }
  12668. }
  12669. if ( scene.overrideMaterial ) {
  12670. var overrideMaterial = scene.overrideMaterial;
  12671. setMaterial( overrideMaterial );
  12672. renderObjects( opaqueObjects, camera, lights, fog, overrideMaterial );
  12673. renderObjects( transparentObjects, camera, lights, fog, overrideMaterial );
  12674. renderObjectsImmediate( _webglObjectsImmediate, '', camera, lights, fog, overrideMaterial );
  12675. } else {
  12676. // opaque pass (front-to-back order)
  12677. state.setBlending( THREE.NoBlending );
  12678. renderObjects( opaqueObjects, camera, lights, fog, null );
  12679. renderObjectsImmediate( _webglObjectsImmediate, 'opaque', camera, lights, fog, null );
  12680. // transparent pass (back-to-front order)
  12681. renderObjects( transparentObjects, camera, lights, fog, null );
  12682. renderObjectsImmediate( _webglObjectsImmediate, 'transparent', camera, lights, fog, null );
  12683. }
  12684. // custom render plugins (post pass)
  12685. spritePlugin.render( scene, camera );
  12686. lensFlarePlugin.render( scene, camera, _currentWidth, _currentHeight );
  12687. // Generate mipmap if we're using any kind of mipmap filtering
  12688. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  12689. updateRenderTargetMipmap( renderTarget );
  12690. }
  12691. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12692. state.setDepthTest( true );
  12693. state.setDepthWrite( true );
  12694. state.setColorWrite( true );
  12695. // _gl.finish();
  12696. };
  12697. function projectObject( object ) {
  12698. if ( object.visible === false ) return;
  12699. if ( object instanceof THREE.Scene || object instanceof THREE.Group ) {
  12700. // skip
  12701. } else {
  12702. initObject( object );
  12703. if ( object instanceof THREE.Light ) {
  12704. lights.push( object );
  12705. } else if ( object instanceof THREE.Sprite ) {
  12706. sprites.push( object );
  12707. } else if ( object instanceof THREE.LensFlare ) {
  12708. lensFlares.push( object );
  12709. } else {
  12710. var webglObjects = _webglObjects[ object.id ];
  12711. if ( webglObjects && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  12712. for ( var i = 0, l = webglObjects.length; i < l; i ++ ) {
  12713. var webglObject = webglObjects[ i ];
  12714. unrollBufferMaterial( webglObject );
  12715. webglObject.render = true;
  12716. if ( _this.sortObjects === true ) {
  12717. _vector3.setFromMatrixPosition( object.matrixWorld );
  12718. _vector3.applyProjection( _projScreenMatrix );
  12719. webglObject.z = _vector3.z;
  12720. }
  12721. }
  12722. }
  12723. }
  12724. }
  12725. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  12726. projectObject( object.children[ i ] );
  12727. }
  12728. }
  12729. function renderObjects( renderList, camera, lights, fog, overrideMaterial ) {
  12730. var material;
  12731. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  12732. var webglObject = renderList[ i ];
  12733. var object = webglObject.object;
  12734. var buffer = webglObject.buffer;
  12735. setupMatrices( object, camera );
  12736. if ( overrideMaterial ) {
  12737. material = overrideMaterial;
  12738. } else {
  12739. material = webglObject.material;
  12740. if ( ! material ) continue;
  12741. setMaterial( material );
  12742. }
  12743. _this.setMaterialFaces( material );
  12744. if ( buffer instanceof THREE.BufferGeometry ) {
  12745. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  12746. } else {
  12747. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  12748. }
  12749. }
  12750. }
  12751. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, overrideMaterial ) {
  12752. var material;
  12753. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  12754. var webglObject = renderList[ i ];
  12755. var object = webglObject.object;
  12756. if ( object.visible ) {
  12757. if ( overrideMaterial ) {
  12758. material = overrideMaterial;
  12759. } else {
  12760. material = webglObject[ materialType ];
  12761. if ( ! material ) continue;
  12762. setMaterial( material );
  12763. }
  12764. _this.renderImmediateObject( camera, lights, fog, material, object );
  12765. }
  12766. }
  12767. }
  12768. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  12769. var program = setProgram( camera, lights, fog, material, object );
  12770. _currentGeometryProgram = '';
  12771. _this.setMaterialFaces( material );
  12772. if ( object.immediateRenderCallback ) {
  12773. object.immediateRenderCallback( program, _gl, _frustum );
  12774. } else {
  12775. object.render( function ( object ) { _this.renderBufferImmediate( object, program, material ); } );
  12776. }
  12777. };
  12778. function unrollImmediateBufferMaterial ( globject ) {
  12779. var object = globject.object,
  12780. material = object.material;
  12781. if ( material.transparent ) {
  12782. globject.transparent = material;
  12783. globject.opaque = null;
  12784. } else {
  12785. globject.opaque = material;
  12786. globject.transparent = null;
  12787. }
  12788. }
  12789. function unrollBufferMaterial ( globject ) {
  12790. var object = globject.object;
  12791. var buffer = globject.buffer;
  12792. var geometry = object.geometry;
  12793. var material = object.material;
  12794. if ( material instanceof THREE.MeshFaceMaterial ) {
  12795. var materialIndex = geometry instanceof THREE.BufferGeometry ? 0 : buffer.materialIndex;
  12796. material = material.materials[ materialIndex ];
  12797. globject.material = material;
  12798. if ( material.transparent ) {
  12799. transparentObjects.push( globject );
  12800. } else {
  12801. opaqueObjects.push( globject );
  12802. }
  12803. } else if ( material ) {
  12804. globject.material = material;
  12805. if ( material.transparent ) {
  12806. transparentObjects.push( globject );
  12807. } else {
  12808. opaqueObjects.push( globject );
  12809. }
  12810. }
  12811. }
  12812. function initObject( object ) {
  12813. if ( object.__webglInit === undefined ) {
  12814. object.__webglInit = true;
  12815. object._modelViewMatrix = new THREE.Matrix4();
  12816. object._normalMatrix = new THREE.Matrix3();
  12817. object.addEventListener( 'removed', onObjectRemoved );
  12818. }
  12819. var geometry = object.geometry;
  12820. if ( geometry === undefined ) {
  12821. // ImmediateRenderObject
  12822. } else if ( geometry.__webglInit === undefined ) {
  12823. geometry.__webglInit = true;
  12824. geometry.addEventListener( 'dispose', onGeometryDispose );
  12825. if ( geometry instanceof THREE.BufferGeometry ) {
  12826. _this.info.memory.geometries ++;
  12827. } else if ( object instanceof THREE.Mesh ) {
  12828. initGeometryGroups( object, geometry );
  12829. } else if ( object instanceof THREE.Line ) {
  12830. if ( geometry.__webglVertexBuffer === undefined ) {
  12831. createLineBuffers( geometry );
  12832. initLineBuffers( geometry, object );
  12833. geometry.verticesNeedUpdate = true;
  12834. geometry.colorsNeedUpdate = true;
  12835. geometry.lineDistancesNeedUpdate = true;
  12836. }
  12837. } else if ( object instanceof THREE.PointCloud ) {
  12838. if ( geometry.__webglVertexBuffer === undefined ) {
  12839. createParticleBuffers( geometry );
  12840. initParticleBuffers( geometry, object );
  12841. geometry.verticesNeedUpdate = true;
  12842. geometry.colorsNeedUpdate = true;
  12843. }
  12844. }
  12845. }
  12846. if ( object.__webglActive === undefined) {
  12847. object.__webglActive = true;
  12848. if ( object instanceof THREE.Mesh ) {
  12849. if ( geometry instanceof THREE.BufferGeometry ) {
  12850. addBuffer( _webglObjects, geometry, object );
  12851. } else if ( geometry instanceof THREE.Geometry ) {
  12852. var geometryGroupsList = geometryGroups[ geometry.id ];
  12853. for ( var i = 0,l = geometryGroupsList.length; i < l; i ++ ) {
  12854. addBuffer( _webglObjects, geometryGroupsList[ i ], object );
  12855. }
  12856. }
  12857. } else if ( object instanceof THREE.Line || object instanceof THREE.PointCloud ) {
  12858. addBuffer( _webglObjects, geometry, object );
  12859. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12860. addBufferImmediate( _webglObjectsImmediate, object );
  12861. }
  12862. }
  12863. }
  12864. // Geometry splitting
  12865. var geometryGroups = {};
  12866. var geometryGroupCounter = 0;
  12867. function makeGroups( geometry, usesFaceMaterial ) {
  12868. var maxVerticesInGroup = extensions.get( 'OES_element_index_uint' ) ? 4294967296 : 65535;
  12869. var groupHash, hash_map = {};
  12870. var numMorphTargets = geometry.morphTargets.length;
  12871. var numMorphNormals = geometry.morphNormals.length;
  12872. var group;
  12873. var groups = {};
  12874. var groupsList = [];
  12875. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  12876. var face = geometry.faces[ f ];
  12877. var materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  12878. if ( ! ( materialIndex in hash_map ) ) {
  12879. hash_map[ materialIndex ] = { hash: materialIndex, counter: 0 };
  12880. }
  12881. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  12882. if ( ! ( groupHash in groups ) ) {
  12883. group = {
  12884. id: geometryGroupCounter ++,
  12885. faces3: [],
  12886. materialIndex: materialIndex,
  12887. vertices: 0,
  12888. numMorphTargets: numMorphTargets,
  12889. numMorphNormals: numMorphNormals
  12890. };
  12891. groups[ groupHash ] = group;
  12892. groupsList.push( group );
  12893. }
  12894. if ( groups[ groupHash ].vertices + 3 > maxVerticesInGroup ) {
  12895. hash_map[ materialIndex ].counter += 1;
  12896. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  12897. if ( ! ( groupHash in groups ) ) {
  12898. group = {
  12899. id: geometryGroupCounter ++,
  12900. faces3: [],
  12901. materialIndex: materialIndex,
  12902. vertices: 0,
  12903. numMorphTargets: numMorphTargets,
  12904. numMorphNormals: numMorphNormals
  12905. };
  12906. groups[ groupHash ] = group;
  12907. groupsList.push( group );
  12908. }
  12909. }
  12910. groups[ groupHash ].faces3.push( f );
  12911. groups[ groupHash ].vertices += 3;
  12912. }
  12913. return groupsList;
  12914. }
  12915. function initGeometryGroups( object, geometry ) {
  12916. var material = object.material, addBuffers = false;
  12917. if ( geometryGroups[ geometry.id ] === undefined || geometry.groupsNeedUpdate === true ) {
  12918. delete _webglObjects[ object.id ];
  12919. geometryGroups[ geometry.id ] = makeGroups( geometry, material instanceof THREE.MeshFaceMaterial );
  12920. geometry.groupsNeedUpdate = false;
  12921. }
  12922. var geometryGroupsList = geometryGroups[ geometry.id ];
  12923. // create separate VBOs per geometry chunk
  12924. for ( var i = 0, il = geometryGroupsList.length; i < il; i ++ ) {
  12925. var geometryGroup = geometryGroupsList[ i ];
  12926. // initialise VBO on the first access
  12927. if ( geometryGroup.__webglVertexBuffer === undefined ) {
  12928. createMeshBuffers( geometryGroup );
  12929. initMeshBuffers( geometryGroup, object );
  12930. geometry.verticesNeedUpdate = true;
  12931. geometry.morphTargetsNeedUpdate = true;
  12932. geometry.elementsNeedUpdate = true;
  12933. geometry.uvsNeedUpdate = true;
  12934. geometry.normalsNeedUpdate = true;
  12935. geometry.tangentsNeedUpdate = true;
  12936. geometry.colorsNeedUpdate = true;
  12937. addBuffers = true;
  12938. } else {
  12939. addBuffers = false;
  12940. }
  12941. if ( addBuffers || object.__webglActive === undefined ) {
  12942. addBuffer( _webglObjects, geometryGroup, object );
  12943. }
  12944. }
  12945. object.__webglActive = true;
  12946. }
  12947. function addBuffer( objlist, buffer, object ) {
  12948. var id = object.id;
  12949. objlist[id] = objlist[id] || [];
  12950. objlist[id].push(
  12951. {
  12952. id: id,
  12953. buffer: buffer,
  12954. object: object,
  12955. material: null,
  12956. z: 0
  12957. }
  12958. );
  12959. };
  12960. function addBufferImmediate( objlist, object ) {
  12961. objlist.push(
  12962. {
  12963. id: null,
  12964. object: object,
  12965. opaque: null,
  12966. transparent: null,
  12967. z: 0
  12968. }
  12969. );
  12970. };
  12971. // Objects updates
  12972. function updateObject( object ) {
  12973. var geometry = object.geometry;
  12974. if ( geometry instanceof THREE.BufferGeometry ) {
  12975. var attributes = geometry.attributes;
  12976. var attributesKeys = geometry.attributesKeys;
  12977. for ( var i = 0, l = attributesKeys.length; i < l; i ++ ) {
  12978. var key = attributesKeys[ i ];
  12979. var attribute = attributes[ key ];
  12980. var bufferType = ( key === 'index' ) ? _gl.ELEMENT_ARRAY_BUFFER : _gl.ARRAY_BUFFER;
  12981. if ( attribute.buffer === undefined ) {
  12982. attribute.buffer = _gl.createBuffer();
  12983. _gl.bindBuffer( bufferType, attribute.buffer );
  12984. _gl.bufferData( bufferType, attribute.array, ( attribute instanceof THREE.DynamicBufferAttribute ) ? _gl.DYNAMIC_DRAW : _gl.STATIC_DRAW );
  12985. attribute.needsUpdate = false;
  12986. } else if ( attribute.needsUpdate === true ) {
  12987. _gl.bindBuffer( bufferType, attribute.buffer );
  12988. if ( attribute.updateRange === undefined || attribute.updateRange.count === -1 ) { // Not using update ranges
  12989. _gl.bufferSubData( bufferType, 0, attribute.array );
  12990. } else if ( attribute.updateRange.count === 0 ) {
  12991. THREE.error( 'THREE.WebGLRenderer.updateObject: using updateRange for THREE.DynamicBufferAttribute and marked as needsUpdate but count is 0, ensure you are using set methods or updating manually.' );
  12992. } else {
  12993. _gl.bufferSubData( bufferType, attribute.updateRange.offset * attribute.array.BYTES_PER_ELEMENT,
  12994. attribute.array.subarray( attribute.updateRange.offset, attribute.updateRange.offset + attribute.updateRange.count ) );
  12995. attribute.updateRange.count = 0; // reset range
  12996. }
  12997. attribute.needsUpdate = false;
  12998. }
  12999. }
  13000. } else if ( object instanceof THREE.Mesh ) {
  13001. // check all geometry groups
  13002. if ( geometry.groupsNeedUpdate === true ) {
  13003. initGeometryGroups( object, geometry );
  13004. }
  13005. var geometryGroupsList = geometryGroups[ geometry.id ];
  13006. for ( var i = 0, il = geometryGroupsList.length; i < il; i ++ ) {
  13007. var geometryGroup = geometryGroupsList[ i ];
  13008. var material = getBufferMaterial( object, geometryGroup );
  13009. var customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13010. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  13011. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  13012. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  13013. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, ! geometry.dynamic, material );
  13014. }
  13015. }
  13016. geometry.verticesNeedUpdate = false;
  13017. geometry.morphTargetsNeedUpdate = false;
  13018. geometry.elementsNeedUpdate = false;
  13019. geometry.uvsNeedUpdate = false;
  13020. geometry.normalsNeedUpdate = false;
  13021. geometry.colorsNeedUpdate = false;
  13022. geometry.tangentsNeedUpdate = false;
  13023. material.attributes && clearCustomAttributes( material );
  13024. } else if ( object instanceof THREE.Line ) {
  13025. var material = getBufferMaterial( object, geometry );
  13026. var customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13027. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  13028. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  13029. }
  13030. geometry.verticesNeedUpdate = false;
  13031. geometry.colorsNeedUpdate = false;
  13032. geometry.lineDistancesNeedUpdate = false;
  13033. material.attributes && clearCustomAttributes( material );
  13034. } else if ( object instanceof THREE.PointCloud ) {
  13035. var material = getBufferMaterial( object, geometry );
  13036. var customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13037. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || customAttributesDirty ) {
  13038. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  13039. }
  13040. geometry.verticesNeedUpdate = false;
  13041. geometry.colorsNeedUpdate = false;
  13042. material.attributes && clearCustomAttributes( material );
  13043. }
  13044. }
  13045. // Objects updates - custom attributes check
  13046. function areCustomAttributesDirty( material ) {
  13047. for ( var name in material.attributes ) {
  13048. if ( material.attributes[ name ].needsUpdate ) return true;
  13049. }
  13050. return false;
  13051. }
  13052. function clearCustomAttributes( material ) {
  13053. for ( var name in material.attributes ) {
  13054. material.attributes[ name ].needsUpdate = false;
  13055. }
  13056. }
  13057. // Objects removal
  13058. function removeObject( object ) {
  13059. if ( object instanceof THREE.Mesh ||
  13060. object instanceof THREE.PointCloud ||
  13061. object instanceof THREE.Line ) {
  13062. delete _webglObjects[ object.id ];
  13063. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13064. removeInstances( _webglObjectsImmediate, object );
  13065. }
  13066. delete object.__webglInit;
  13067. delete object._modelViewMatrix;
  13068. delete object._normalMatrix;
  13069. delete object.__webglActive;
  13070. }
  13071. function removeInstances( objlist, object ) {
  13072. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13073. if ( objlist[ o ].object === object ) {
  13074. objlist.splice( o, 1 );
  13075. }
  13076. }
  13077. }
  13078. // Materials
  13079. var shaderIDs = {
  13080. MeshDepthMaterial: 'depth',
  13081. MeshNormalMaterial: 'normal',
  13082. MeshBasicMaterial: 'basic',
  13083. MeshLambertMaterial: 'lambert',
  13084. MeshPhongMaterial: 'phong',
  13085. LineBasicMaterial: 'basic',
  13086. LineDashedMaterial: 'dashed',
  13087. PointCloudMaterial: 'particle_basic'
  13088. };
  13089. function initMaterial( material, lights, fog, object ) {
  13090. material.addEventListener( 'dispose', onMaterialDispose );
  13091. var shaderID = shaderIDs[ material.type ];
  13092. if ( shaderID ) {
  13093. var shader = THREE.ShaderLib[ shaderID ];
  13094. material.__webglShader = {
  13095. uniforms: THREE.UniformsUtils.clone( shader.uniforms ),
  13096. vertexShader: shader.vertexShader,
  13097. fragmentShader: shader.fragmentShader
  13098. }
  13099. } else {
  13100. material.__webglShader = {
  13101. uniforms: material.uniforms,
  13102. vertexShader: material.vertexShader,
  13103. fragmentShader: material.fragmentShader
  13104. }
  13105. }
  13106. // heuristics to create shader parameters according to lights in the scene
  13107. // (not to blow over maxLights budget)
  13108. var maxLightCount = allocateLights( lights );
  13109. var maxShadows = allocateShadows( lights );
  13110. var maxBones = allocateBones( object );
  13111. var parameters = {
  13112. precision: _precision,
  13113. supportsVertexTextures: _supportsVertexTextures,
  13114. map: !! material.map,
  13115. envMap: !! material.envMap,
  13116. envMapMode: material.envMap && material.envMap.mapping,
  13117. lightMap: !! material.lightMap,
  13118. aoMap: !! material.aoMap,
  13119. bumpMap: !! material.bumpMap,
  13120. normalMap: !! material.normalMap,
  13121. specularMap: !! material.specularMap,
  13122. alphaMap: !! material.alphaMap,
  13123. combine: material.combine,
  13124. vertexColors: material.vertexColors,
  13125. fog: fog,
  13126. useFog: material.fog,
  13127. fogExp: fog instanceof THREE.FogExp2,
  13128. flatShading: material.shading === THREE.FlatShading,
  13129. sizeAttenuation: material.sizeAttenuation,
  13130. logarithmicDepthBuffer: _logarithmicDepthBuffer,
  13131. skinning: material.skinning,
  13132. maxBones: maxBones,
  13133. useVertexTexture: _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  13134. morphTargets: material.morphTargets,
  13135. morphNormals: material.morphNormals,
  13136. maxMorphTargets: _this.maxMorphTargets,
  13137. maxMorphNormals: _this.maxMorphNormals,
  13138. maxDirLights: maxLightCount.directional,
  13139. maxPointLights: maxLightCount.point,
  13140. maxSpotLights: maxLightCount.spot,
  13141. maxHemiLights: maxLightCount.hemi,
  13142. maxShadows: maxShadows,
  13143. shadowMapEnabled: _this.shadowMapEnabled && object.receiveShadow && maxShadows > 0,
  13144. shadowMapType: _this.shadowMapType,
  13145. shadowMapDebug: _this.shadowMapDebug,
  13146. shadowMapCascade: _this.shadowMapCascade,
  13147. alphaTest: material.alphaTest,
  13148. metal: material.metal,
  13149. wrapAround: material.wrapAround,
  13150. doubleSided: material.side === THREE.DoubleSide,
  13151. flipSided: material.side === THREE.BackSide
  13152. };
  13153. // Generate code
  13154. var chunks = [];
  13155. if ( shaderID ) {
  13156. chunks.push( shaderID );
  13157. } else {
  13158. chunks.push( material.fragmentShader );
  13159. chunks.push( material.vertexShader );
  13160. }
  13161. if ( material.defines !== undefined ) {
  13162. for ( var name in material.defines ) {
  13163. chunks.push( name );
  13164. chunks.push( material.defines[ name ] );
  13165. }
  13166. }
  13167. for ( var name in parameters ) {
  13168. chunks.push( name );
  13169. chunks.push( parameters[ name ] );
  13170. }
  13171. var code = chunks.join();
  13172. var program;
  13173. // Check if code has been already compiled
  13174. for ( var p = 0, pl = _programs.length; p < pl; p ++ ) {
  13175. var programInfo = _programs[ p ];
  13176. if ( programInfo.code === code ) {
  13177. program = programInfo;
  13178. program.usedTimes ++;
  13179. break;
  13180. }
  13181. }
  13182. if ( program === undefined ) {
  13183. program = new THREE.WebGLProgram( _this, code, material, parameters );
  13184. _programs.push( program );
  13185. _this.info.memory.programs = _programs.length;
  13186. }
  13187. material.program = program;
  13188. var attributes = program.attributes;
  13189. if ( material.morphTargets ) {
  13190. material.numSupportedMorphTargets = 0;
  13191. var id, base = 'morphTarget';
  13192. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  13193. id = base + i;
  13194. if ( attributes[ id ] >= 0 ) {
  13195. material.numSupportedMorphTargets ++;
  13196. }
  13197. }
  13198. }
  13199. if ( material.morphNormals ) {
  13200. material.numSupportedMorphNormals = 0;
  13201. var id, base = 'morphNormal';
  13202. for ( i = 0; i < _this.maxMorphNormals; i ++ ) {
  13203. id = base + i;
  13204. if ( attributes[ id ] >= 0 ) {
  13205. material.numSupportedMorphNormals ++;
  13206. }
  13207. }
  13208. }
  13209. material.uniformsList = [];
  13210. for ( var u in material.__webglShader.uniforms ) {
  13211. var location = material.program.uniforms[ u ];
  13212. if ( location ) {
  13213. material.uniformsList.push( [ material.__webglShader.uniforms[ u ], location ] );
  13214. }
  13215. }
  13216. }
  13217. function setMaterial( material ) {
  13218. if ( material.transparent === true ) {
  13219. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha );
  13220. } else {
  13221. state.setBlending( THREE.NoBlending );
  13222. }
  13223. state.setDepthTest( material.depthTest );
  13224. state.setDepthWrite( material.depthWrite );
  13225. state.setColorWrite( material.colorWrite );
  13226. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13227. }
  13228. function setProgram( camera, lights, fog, material, object ) {
  13229. _usedTextureUnits = 0;
  13230. if ( material.needsUpdate ) {
  13231. if ( material.program ) deallocateMaterial( material );
  13232. initMaterial( material, lights, fog, object );
  13233. material.needsUpdate = false;
  13234. }
  13235. if ( material.morphTargets ) {
  13236. if ( ! object.__webglMorphTargetInfluences ) {
  13237. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  13238. }
  13239. }
  13240. var refreshProgram = false;
  13241. var refreshMaterial = false;
  13242. var refreshLights = false;
  13243. var program = material.program,
  13244. p_uniforms = program.uniforms,
  13245. m_uniforms = material.__webglShader.uniforms;
  13246. if ( program.id !== _currentProgram ) {
  13247. _gl.useProgram( program.program );
  13248. _currentProgram = program.id;
  13249. refreshProgram = true;
  13250. refreshMaterial = true;
  13251. refreshLights = true;
  13252. }
  13253. if ( material.id !== _currentMaterialId ) {
  13254. if ( _currentMaterialId === -1 ) refreshLights = true;
  13255. _currentMaterialId = material.id;
  13256. refreshMaterial = true;
  13257. }
  13258. if ( refreshProgram || camera !== _currentCamera ) {
  13259. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  13260. if ( _logarithmicDepthBuffer ) {
  13261. _gl.uniform1f( p_uniforms.logDepthBufFC, 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  13262. }
  13263. if ( camera !== _currentCamera ) _currentCamera = camera;
  13264. // load material specific uniforms
  13265. // (shader material also gets them for the sake of genericity)
  13266. if ( material instanceof THREE.ShaderMaterial ||
  13267. material instanceof THREE.MeshPhongMaterial ||
  13268. material.envMap ) {
  13269. if ( p_uniforms.cameraPosition !== null ) {
  13270. _vector3.setFromMatrixPosition( camera.matrixWorld );
  13271. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  13272. }
  13273. }
  13274. if ( material instanceof THREE.MeshPhongMaterial ||
  13275. material instanceof THREE.MeshLambertMaterial ||
  13276. material instanceof THREE.MeshBasicMaterial ||
  13277. material instanceof THREE.ShaderMaterial ||
  13278. material.skinning ) {
  13279. if ( p_uniforms.viewMatrix !== null ) {
  13280. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  13281. }
  13282. }
  13283. }
  13284. // skinning uniforms must be set even if material didn't change
  13285. // auto-setting of texture unit for bone texture must go before other textures
  13286. // not sure why, but otherwise weird things happen
  13287. if ( material.skinning ) {
  13288. if ( object.bindMatrix && p_uniforms.bindMatrix !== null ) {
  13289. _gl.uniformMatrix4fv( p_uniforms.bindMatrix, false, object.bindMatrix.elements );
  13290. }
  13291. if ( object.bindMatrixInverse && p_uniforms.bindMatrixInverse !== null ) {
  13292. _gl.uniformMatrix4fv( p_uniforms.bindMatrixInverse, false, object.bindMatrixInverse.elements );
  13293. }
  13294. if ( _supportsBoneTextures && object.skeleton && object.skeleton.useVertexTexture ) {
  13295. if ( p_uniforms.boneTexture !== null ) {
  13296. var textureUnit = getTextureUnit();
  13297. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  13298. _this.setTexture( object.skeleton.boneTexture, textureUnit );
  13299. }
  13300. if ( p_uniforms.boneTextureWidth !== null ) {
  13301. _gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth );
  13302. }
  13303. if ( p_uniforms.boneTextureHeight !== null ) {
  13304. _gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight );
  13305. }
  13306. } else if ( object.skeleton && object.skeleton.boneMatrices ) {
  13307. if ( p_uniforms.boneGlobalMatrices !== null ) {
  13308. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices );
  13309. }
  13310. }
  13311. }
  13312. if ( refreshMaterial ) {
  13313. // refresh uniforms common to several materials
  13314. if ( fog && material.fog ) {
  13315. refreshUniformsFog( m_uniforms, fog );
  13316. }
  13317. if ( material instanceof THREE.MeshPhongMaterial ||
  13318. material instanceof THREE.MeshLambertMaterial ||
  13319. material.lights ) {
  13320. if ( _lightsNeedUpdate ) {
  13321. refreshLights = true;
  13322. setupLights( lights );
  13323. _lightsNeedUpdate = false;
  13324. }
  13325. if ( refreshLights ) {
  13326. refreshUniformsLights( m_uniforms, _lights );
  13327. markUniformsLightsNeedsUpdate( m_uniforms, true );
  13328. } else {
  13329. markUniformsLightsNeedsUpdate( m_uniforms, false );
  13330. }
  13331. }
  13332. if ( material instanceof THREE.MeshBasicMaterial ||
  13333. material instanceof THREE.MeshLambertMaterial ||
  13334. material instanceof THREE.MeshPhongMaterial ) {
  13335. refreshUniformsCommon( m_uniforms, material );
  13336. }
  13337. // refresh single material specific uniforms
  13338. if ( material instanceof THREE.LineBasicMaterial ) {
  13339. refreshUniformsLine( m_uniforms, material );
  13340. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13341. refreshUniformsLine( m_uniforms, material );
  13342. refreshUniformsDash( m_uniforms, material );
  13343. } else if ( material instanceof THREE.PointCloudMaterial ) {
  13344. refreshUniformsParticle( m_uniforms, material );
  13345. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13346. refreshUniformsPhong( m_uniforms, material );
  13347. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13348. refreshUniformsLambert( m_uniforms, material );
  13349. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  13350. m_uniforms.mNear.value = camera.near;
  13351. m_uniforms.mFar.value = camera.far;
  13352. m_uniforms.opacity.value = material.opacity;
  13353. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13354. m_uniforms.opacity.value = material.opacity;
  13355. }
  13356. if ( object.receiveShadow && ! material._shadowPass ) {
  13357. refreshUniformsShadow( m_uniforms, lights );
  13358. }
  13359. // load common uniforms
  13360. loadUniformsGeneric( material.uniformsList );
  13361. }
  13362. loadUniformsMatrices( p_uniforms, object );
  13363. if ( p_uniforms.modelMatrix !== null ) {
  13364. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  13365. }
  13366. return program;
  13367. }
  13368. // Uniforms (refresh uniforms objects)
  13369. function refreshUniformsCommon ( uniforms, material ) {
  13370. uniforms.opacity.value = material.opacity;
  13371. uniforms.diffuse.value = material.color;
  13372. uniforms.map.value = material.map;
  13373. uniforms.lightMap.value = material.lightMap;
  13374. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  13375. uniforms.aoMap.value = material.aoMap;
  13376. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  13377. uniforms.specularMap.value = material.specularMap;
  13378. uniforms.alphaMap.value = material.alphaMap;
  13379. if ( material.bumpMap ) {
  13380. uniforms.bumpMap.value = material.bumpMap;
  13381. uniforms.bumpScale.value = material.bumpScale;
  13382. }
  13383. if ( material.normalMap ) {
  13384. uniforms.normalMap.value = material.normalMap;
  13385. uniforms.normalScale.value.copy( material.normalScale );
  13386. }
  13387. // uv repeat and offset setting priorities
  13388. // 1. color map
  13389. // 2. specular map
  13390. // 3. normal map
  13391. // 4. bump map
  13392. // 5. alpha map
  13393. var uvScaleMap;
  13394. if ( material.map ) {
  13395. uvScaleMap = material.map;
  13396. } else if ( material.specularMap ) {
  13397. uvScaleMap = material.specularMap;
  13398. } else if ( material.normalMap ) {
  13399. uvScaleMap = material.normalMap;
  13400. } else if ( material.bumpMap ) {
  13401. uvScaleMap = material.bumpMap;
  13402. } else if ( material.alphaMap ) {
  13403. uvScaleMap = material.alphaMap;
  13404. }
  13405. if ( uvScaleMap !== undefined ) {
  13406. var offset = uvScaleMap.offset;
  13407. var repeat = uvScaleMap.repeat;
  13408. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13409. }
  13410. uniforms.envMap.value = material.envMap;
  13411. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1;
  13412. uniforms.reflectivity.value = material.reflectivity;
  13413. uniforms.refractionRatio.value = material.refractionRatio;
  13414. }
  13415. function refreshUniformsLine ( uniforms, material ) {
  13416. uniforms.diffuse.value = material.color;
  13417. uniforms.opacity.value = material.opacity;
  13418. }
  13419. function refreshUniformsDash ( uniforms, material ) {
  13420. uniforms.dashSize.value = material.dashSize;
  13421. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13422. uniforms.scale.value = material.scale;
  13423. }
  13424. function refreshUniformsParticle ( uniforms, material ) {
  13425. uniforms.psColor.value = material.color;
  13426. uniforms.opacity.value = material.opacity;
  13427. uniforms.size.value = material.size;
  13428. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  13429. uniforms.map.value = material.map;
  13430. if ( material.map !== null ) {
  13431. var offset = material.map.offset;
  13432. var repeat = material.map.repeat;
  13433. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13434. }
  13435. }
  13436. function refreshUniformsFog ( uniforms, fog ) {
  13437. uniforms.fogColor.value = fog.color;
  13438. if ( fog instanceof THREE.Fog ) {
  13439. uniforms.fogNear.value = fog.near;
  13440. uniforms.fogFar.value = fog.far;
  13441. } else if ( fog instanceof THREE.FogExp2 ) {
  13442. uniforms.fogDensity.value = fog.density;
  13443. }
  13444. }
  13445. function refreshUniformsPhong ( uniforms, material ) {
  13446. uniforms.shininess.value = material.shininess;
  13447. uniforms.emissive.value = material.emissive;
  13448. uniforms.specular.value = material.specular;
  13449. if ( material.wrapAround ) {
  13450. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13451. }
  13452. }
  13453. function refreshUniformsLambert ( uniforms, material ) {
  13454. uniforms.emissive.value = material.emissive;
  13455. if ( material.wrapAround ) {
  13456. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13457. }
  13458. }
  13459. function refreshUniformsLights ( uniforms, lights ) {
  13460. uniforms.ambientLightColor.value = lights.ambient;
  13461. uniforms.directionalLightColor.value = lights.directional.colors;
  13462. uniforms.directionalLightDirection.value = lights.directional.positions;
  13463. uniforms.pointLightColor.value = lights.point.colors;
  13464. uniforms.pointLightPosition.value = lights.point.positions;
  13465. uniforms.pointLightDistance.value = lights.point.distances;
  13466. uniforms.pointLightDecay.value = lights.point.decays;
  13467. uniforms.spotLightColor.value = lights.spot.colors;
  13468. uniforms.spotLightPosition.value = lights.spot.positions;
  13469. uniforms.spotLightDistance.value = lights.spot.distances;
  13470. uniforms.spotLightDirection.value = lights.spot.directions;
  13471. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  13472. uniforms.spotLightExponent.value = lights.spot.exponents;
  13473. uniforms.spotLightDecay.value = lights.spot.decays;
  13474. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  13475. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  13476. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  13477. }
  13478. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  13479. function markUniformsLightsNeedsUpdate ( uniforms, value ) {
  13480. uniforms.ambientLightColor.needsUpdate = value;
  13481. uniforms.directionalLightColor.needsUpdate = value;
  13482. uniforms.directionalLightDirection.needsUpdate = value;
  13483. uniforms.pointLightColor.needsUpdate = value;
  13484. uniforms.pointLightPosition.needsUpdate = value;
  13485. uniforms.pointLightDistance.needsUpdate = value;
  13486. uniforms.pointLightDecay.needsUpdate = value;
  13487. uniforms.spotLightColor.needsUpdate = value;
  13488. uniforms.spotLightPosition.needsUpdate = value;
  13489. uniforms.spotLightDistance.needsUpdate = value;
  13490. uniforms.spotLightDirection.needsUpdate = value;
  13491. uniforms.spotLightAngleCos.needsUpdate = value;
  13492. uniforms.spotLightExponent.needsUpdate = value;
  13493. uniforms.spotLightDecay.needsUpdate = value;
  13494. uniforms.hemisphereLightSkyColor.needsUpdate = value;
  13495. uniforms.hemisphereLightGroundColor.needsUpdate = value;
  13496. uniforms.hemisphereLightDirection.needsUpdate = value;
  13497. }
  13498. function refreshUniformsShadow ( uniforms, lights ) {
  13499. if ( uniforms.shadowMatrix ) {
  13500. var j = 0;
  13501. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  13502. var light = lights[ i ];
  13503. if ( ! light.castShadow ) continue;
  13504. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  13505. uniforms.shadowMap.value[ j ] = light.shadowMap;
  13506. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  13507. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  13508. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  13509. uniforms.shadowBias.value[ j ] = light.shadowBias;
  13510. j ++;
  13511. }
  13512. }
  13513. }
  13514. }
  13515. // Uniforms (load to GPU)
  13516. function loadUniformsMatrices ( uniforms, object ) {
  13517. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  13518. if ( uniforms.normalMatrix ) {
  13519. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  13520. }
  13521. }
  13522. function getTextureUnit() {
  13523. var textureUnit = _usedTextureUnits;
  13524. if ( textureUnit >= _maxTextures ) {
  13525. THREE.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + _maxTextures );
  13526. }
  13527. _usedTextureUnits += 1;
  13528. return textureUnit;
  13529. }
  13530. function loadUniformsGeneric ( uniforms ) {
  13531. var texture, textureUnit, offset;
  13532. for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) {
  13533. var uniform = uniforms[ j ][ 0 ];
  13534. // needsUpdate property is not added to all uniforms.
  13535. if ( uniform.needsUpdate === false ) continue;
  13536. var type = uniform.type;
  13537. var value = uniform.value;
  13538. var location = uniforms[ j ][ 1 ];
  13539. switch ( type ) {
  13540. case '1i':
  13541. _gl.uniform1i( location, value );
  13542. break;
  13543. case '1f':
  13544. _gl.uniform1f( location, value );
  13545. break;
  13546. case '2f':
  13547. _gl.uniform2f( location, value[ 0 ], value[ 1 ] );
  13548. break;
  13549. case '3f':
  13550. _gl.uniform3f( location, value[ 0 ], value[ 1 ], value[ 2 ] );
  13551. break;
  13552. case '4f':
  13553. _gl.uniform4f( location, value[ 0 ], value[ 1 ], value[ 2 ], value[ 3 ] );
  13554. break;
  13555. case '1iv':
  13556. _gl.uniform1iv( location, value );
  13557. break;
  13558. case '3iv':
  13559. _gl.uniform3iv( location, value );
  13560. break;
  13561. case '1fv':
  13562. _gl.uniform1fv( location, value );
  13563. break;
  13564. case '2fv':
  13565. _gl.uniform2fv( location, value );
  13566. break;
  13567. case '3fv':
  13568. _gl.uniform3fv( location, value );
  13569. break;
  13570. case '4fv':
  13571. _gl.uniform4fv( location, value );
  13572. break;
  13573. case 'Matrix3fv':
  13574. _gl.uniformMatrix3fv( location, false, value );
  13575. break;
  13576. case 'Matrix4fv':
  13577. _gl.uniformMatrix4fv( location, false, value );
  13578. break;
  13579. //
  13580. case 'i':
  13581. // single integer
  13582. _gl.uniform1i( location, value );
  13583. break;
  13584. case 'f':
  13585. // single float
  13586. _gl.uniform1f( location, value );
  13587. break;
  13588. case 'v2':
  13589. // single THREE.Vector2
  13590. _gl.uniform2f( location, value.x, value.y );
  13591. break;
  13592. case 'v3':
  13593. // single THREE.Vector3
  13594. _gl.uniform3f( location, value.x, value.y, value.z );
  13595. break;
  13596. case 'v4':
  13597. // single THREE.Vector4
  13598. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  13599. break;
  13600. case 'c':
  13601. // single THREE.Color
  13602. _gl.uniform3f( location, value.r, value.g, value.b );
  13603. break;
  13604. case 'iv1':
  13605. // flat array of integers (JS or typed array)
  13606. _gl.uniform1iv( location, value );
  13607. break;
  13608. case 'iv':
  13609. // flat array of integers with 3 x N size (JS or typed array)
  13610. _gl.uniform3iv( location, value );
  13611. break;
  13612. case 'fv1':
  13613. // flat array of floats (JS or typed array)
  13614. _gl.uniform1fv( location, value );
  13615. break;
  13616. case 'fv':
  13617. // flat array of floats with 3 x N size (JS or typed array)
  13618. _gl.uniform3fv( location, value );
  13619. break;
  13620. case 'v2v':
  13621. // array of THREE.Vector2
  13622. if ( uniform._array === undefined ) {
  13623. uniform._array = new Float32Array( 2 * value.length );
  13624. }
  13625. for ( var i = 0, il = value.length; i < il; i ++ ) {
  13626. offset = i * 2;
  13627. uniform._array[ offset ] = value[ i ].x;
  13628. uniform._array[ offset + 1 ] = value[ i ].y;
  13629. }
  13630. _gl.uniform2fv( location, uniform._array );
  13631. break;
  13632. case 'v3v':
  13633. // array of THREE.Vector3
  13634. if ( uniform._array === undefined ) {
  13635. uniform._array = new Float32Array( 3 * value.length );
  13636. }
  13637. for ( var i = 0, il = value.length; i < il; i ++ ) {
  13638. offset = i * 3;
  13639. uniform._array[ offset ] = value[ i ].x;
  13640. uniform._array[ offset + 1 ] = value[ i ].y;
  13641. uniform._array[ offset + 2 ] = value[ i ].z;
  13642. }
  13643. _gl.uniform3fv( location, uniform._array );
  13644. break;
  13645. case 'v4v':
  13646. // array of THREE.Vector4
  13647. if ( uniform._array === undefined ) {
  13648. uniform._array = new Float32Array( 4 * value.length );
  13649. }
  13650. for ( var i = 0, il = value.length; i < il; i ++ ) {
  13651. offset = i * 4;
  13652. uniform._array[ offset ] = value[ i ].x;
  13653. uniform._array[ offset + 1 ] = value[ i ].y;
  13654. uniform._array[ offset + 2 ] = value[ i ].z;
  13655. uniform._array[ offset + 3 ] = value[ i ].w;
  13656. }
  13657. _gl.uniform4fv( location, uniform._array );
  13658. break;
  13659. case 'm3':
  13660. // single THREE.Matrix3
  13661. _gl.uniformMatrix3fv( location, false, value.elements );
  13662. break;
  13663. case 'm3v':
  13664. // array of THREE.Matrix3
  13665. if ( uniform._array === undefined ) {
  13666. uniform._array = new Float32Array( 9 * value.length );
  13667. }
  13668. for ( var i = 0, il = value.length; i < il; i ++ ) {
  13669. value[ i ].flattenToArrayOffset( uniform._array, i * 9 );
  13670. }
  13671. _gl.uniformMatrix3fv( location, false, uniform._array );
  13672. break;
  13673. case 'm4':
  13674. // single THREE.Matrix4
  13675. _gl.uniformMatrix4fv( location, false, value.elements );
  13676. break;
  13677. case 'm4v':
  13678. // array of THREE.Matrix4
  13679. if ( uniform._array === undefined ) {
  13680. uniform._array = new Float32Array( 16 * value.length );
  13681. }
  13682. for ( var i = 0, il = value.length; i < il; i ++ ) {
  13683. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  13684. }
  13685. _gl.uniformMatrix4fv( location, false, uniform._array );
  13686. break;
  13687. case 't':
  13688. // single THREE.Texture (2d or cube)
  13689. texture = value;
  13690. textureUnit = getTextureUnit();
  13691. _gl.uniform1i( location, textureUnit );
  13692. if ( ! texture ) continue;
  13693. if ( texture instanceof THREE.CubeTexture ||
  13694. ( texture.image instanceof Array && texture.image.length === 6 ) ) { // CompressedTexture can have Array in image :/
  13695. setCubeTexture( texture, textureUnit );
  13696. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  13697. setCubeTextureDynamic( texture, textureUnit );
  13698. } else {
  13699. _this.setTexture( texture, textureUnit );
  13700. }
  13701. break;
  13702. case 'tv':
  13703. // array of THREE.Texture (2d)
  13704. if ( uniform._array === undefined ) {
  13705. uniform._array = [];
  13706. }
  13707. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  13708. uniform._array[ i ] = getTextureUnit();
  13709. }
  13710. _gl.uniform1iv( location, uniform._array );
  13711. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  13712. texture = uniform.value[ i ];
  13713. textureUnit = uniform._array[ i ];
  13714. if ( ! texture ) continue;
  13715. _this.setTexture( texture, textureUnit );
  13716. }
  13717. break;
  13718. default:
  13719. THREE.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  13720. }
  13721. }
  13722. }
  13723. function setupMatrices ( object, camera ) {
  13724. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  13725. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  13726. }
  13727. function setColorLinear( array, offset, color, intensity ) {
  13728. array[ offset ] = color.r * intensity;
  13729. array[ offset + 1 ] = color.g * intensity;
  13730. array[ offset + 2 ] = color.b * intensity;
  13731. }
  13732. function setupLights ( lights ) {
  13733. var l, ll, light,
  13734. r = 0, g = 0, b = 0,
  13735. color, skyColor, groundColor,
  13736. intensity,
  13737. distance,
  13738. zlights = _lights,
  13739. dirColors = zlights.directional.colors,
  13740. dirPositions = zlights.directional.positions,
  13741. pointColors = zlights.point.colors,
  13742. pointPositions = zlights.point.positions,
  13743. pointDistances = zlights.point.distances,
  13744. pointDecays = zlights.point.decays,
  13745. spotColors = zlights.spot.colors,
  13746. spotPositions = zlights.spot.positions,
  13747. spotDistances = zlights.spot.distances,
  13748. spotDirections = zlights.spot.directions,
  13749. spotAnglesCos = zlights.spot.anglesCos,
  13750. spotExponents = zlights.spot.exponents,
  13751. spotDecays = zlights.spot.decays,
  13752. hemiSkyColors = zlights.hemi.skyColors,
  13753. hemiGroundColors = zlights.hemi.groundColors,
  13754. hemiPositions = zlights.hemi.positions,
  13755. dirLength = 0,
  13756. pointLength = 0,
  13757. spotLength = 0,
  13758. hemiLength = 0,
  13759. dirCount = 0,
  13760. pointCount = 0,
  13761. spotCount = 0,
  13762. hemiCount = 0,
  13763. dirOffset = 0,
  13764. pointOffset = 0,
  13765. spotOffset = 0,
  13766. hemiOffset = 0;
  13767. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  13768. light = lights[ l ];
  13769. if ( light.onlyShadow ) continue;
  13770. color = light.color;
  13771. intensity = light.intensity;
  13772. distance = light.distance;
  13773. if ( light instanceof THREE.AmbientLight ) {
  13774. if ( ! light.visible ) continue;
  13775. r += color.r;
  13776. g += color.g;
  13777. b += color.b;
  13778. } else if ( light instanceof THREE.DirectionalLight ) {
  13779. dirCount += 1;
  13780. if ( ! light.visible ) continue;
  13781. _direction.setFromMatrixPosition( light.matrixWorld );
  13782. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  13783. _direction.sub( _vector3 );
  13784. _direction.normalize();
  13785. dirOffset = dirLength * 3;
  13786. dirPositions[ dirOffset ] = _direction.x;
  13787. dirPositions[ dirOffset + 1 ] = _direction.y;
  13788. dirPositions[ dirOffset + 2 ] = _direction.z;
  13789. setColorLinear( dirColors, dirOffset, color, intensity );
  13790. dirLength += 1;
  13791. } else if ( light instanceof THREE.PointLight ) {
  13792. pointCount += 1;
  13793. if ( ! light.visible ) continue;
  13794. pointOffset = pointLength * 3;
  13795. setColorLinear( pointColors, pointOffset, color, intensity );
  13796. _vector3.setFromMatrixPosition( light.matrixWorld );
  13797. pointPositions[ pointOffset ] = _vector3.x;
  13798. pointPositions[ pointOffset + 1 ] = _vector3.y;
  13799. pointPositions[ pointOffset + 2 ] = _vector3.z;
  13800. // distance is 0 if decay is 0, because there is no attenuation at all.
  13801. pointDistances[ pointLength ] = distance;
  13802. pointDecays[ pointLength ] = ( light.distance === 0 ) ? 0.0 : light.decay;
  13803. pointLength += 1;
  13804. } else if ( light instanceof THREE.SpotLight ) {
  13805. spotCount += 1;
  13806. if ( ! light.visible ) continue;
  13807. spotOffset = spotLength * 3;
  13808. setColorLinear( spotColors, spotOffset, color, intensity );
  13809. _direction.setFromMatrixPosition( light.matrixWorld );
  13810. spotPositions[ spotOffset ] = _direction.x;
  13811. spotPositions[ spotOffset + 1 ] = _direction.y;
  13812. spotPositions[ spotOffset + 2 ] = _direction.z;
  13813. spotDistances[ spotLength ] = distance;
  13814. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  13815. _direction.sub( _vector3 );
  13816. _direction.normalize();
  13817. spotDirections[ spotOffset ] = _direction.x;
  13818. spotDirections[ spotOffset + 1 ] = _direction.y;
  13819. spotDirections[ spotOffset + 2 ] = _direction.z;
  13820. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  13821. spotExponents[ spotLength ] = light.exponent;
  13822. spotDecays[ spotLength ] = ( light.distance === 0 ) ? 0.0 : light.decay;
  13823. spotLength += 1;
  13824. } else if ( light instanceof THREE.HemisphereLight ) {
  13825. hemiCount += 1;
  13826. if ( ! light.visible ) continue;
  13827. _direction.setFromMatrixPosition( light.matrixWorld );
  13828. _direction.normalize();
  13829. hemiOffset = hemiLength * 3;
  13830. hemiPositions[ hemiOffset ] = _direction.x;
  13831. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  13832. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  13833. skyColor = light.color;
  13834. groundColor = light.groundColor;
  13835. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  13836. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  13837. hemiLength += 1;
  13838. }
  13839. }
  13840. // null eventual remains from removed lights
  13841. // (this is to avoid if in shader)
  13842. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  13843. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  13844. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  13845. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  13846. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  13847. zlights.directional.length = dirLength;
  13848. zlights.point.length = pointLength;
  13849. zlights.spot.length = spotLength;
  13850. zlights.hemi.length = hemiLength;
  13851. zlights.ambient[ 0 ] = r;
  13852. zlights.ambient[ 1 ] = g;
  13853. zlights.ambient[ 2 ] = b;
  13854. }
  13855. // GL state setting
  13856. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  13857. if ( cullFace === THREE.CullFaceNone ) {
  13858. _gl.disable( _gl.CULL_FACE );
  13859. } else {
  13860. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  13861. _gl.frontFace( _gl.CW );
  13862. } else {
  13863. _gl.frontFace( _gl.CCW );
  13864. }
  13865. if ( cullFace === THREE.CullFaceBack ) {
  13866. _gl.cullFace( _gl.BACK );
  13867. } else if ( cullFace === THREE.CullFaceFront ) {
  13868. _gl.cullFace( _gl.FRONT );
  13869. } else {
  13870. _gl.cullFace( _gl.FRONT_AND_BACK );
  13871. }
  13872. _gl.enable( _gl.CULL_FACE );
  13873. }
  13874. };
  13875. this.setMaterialFaces = function ( material ) {
  13876. state.setDoubleSided( material.side === THREE.DoubleSide );
  13877. state.setFlipSided( material.side === THREE.BackSide );
  13878. };
  13879. // Textures
  13880. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  13881. var extension;
  13882. if ( isImagePowerOfTwo ) {
  13883. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  13884. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  13885. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  13886. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  13887. } else {
  13888. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  13889. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  13890. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) {
  13891. THREE.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping. ( ' + texture.sourceFile + ' )' );
  13892. }
  13893. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  13894. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  13895. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) {
  13896. THREE.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter. ( ' + texture.sourceFile + ' )' );
  13897. }
  13898. }
  13899. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  13900. if ( extension && texture.type !== THREE.FloatType && texture.type !== THREE.HalfFloatType ) {
  13901. if ( texture.anisotropy > 1 || texture.__currentAnisotropy ) {
  13902. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _this.getMaxAnisotropy() ) );
  13903. texture.__currentAnisotropy = texture.anisotropy;
  13904. }
  13905. }
  13906. }
  13907. this.uploadTexture = function ( texture, slot ) {
  13908. if ( texture.__webglInit === undefined ) {
  13909. texture.__webglInit = true;
  13910. texture.addEventListener( 'dispose', onTextureDispose );
  13911. texture.__webglTexture = _gl.createTexture();
  13912. _this.info.memory.textures ++;
  13913. }
  13914. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13915. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13916. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13917. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  13918. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  13919. texture.image = clampToMaxSize( texture.image, _maxTextureSize );
  13920. var image = texture.image,
  13921. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  13922. glFormat = paramThreeToGL( texture.format ),
  13923. glType = paramThreeToGL( texture.type );
  13924. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  13925. var mipmap, mipmaps = texture.mipmaps;
  13926. if ( texture instanceof THREE.DataTexture ) {
  13927. // use manually created mipmaps if available
  13928. // if there are no manual mipmaps
  13929. // set 0 level mipmap and then use GL to generate other mipmap levels
  13930. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  13931. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13932. mipmap = mipmaps[ i ];
  13933. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13934. }
  13935. texture.generateMipmaps = false;
  13936. } else {
  13937. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13938. }
  13939. } else if ( texture instanceof THREE.CompressedTexture ) {
  13940. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13941. mipmap = mipmaps[ i ];
  13942. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  13943. if ( getCompressedTextureFormats().indexOf( glFormat ) > -1 ) {
  13944. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13945. } else {
  13946. THREE.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  13947. }
  13948. } else {
  13949. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13950. }
  13951. }
  13952. } else { // regular Texture (image, video, canvas)
  13953. // use manually created mipmaps if available
  13954. // if there are no manual mipmaps
  13955. // set 0 level mipmap and then use GL to generate other mipmap levels
  13956. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  13957. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13958. mipmap = mipmaps[ i ];
  13959. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  13960. }
  13961. texture.generateMipmaps = false;
  13962. } else {
  13963. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  13964. }
  13965. }
  13966. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13967. texture.needsUpdate = false;
  13968. if ( texture.onUpdate ) texture.onUpdate( texture );
  13969. };
  13970. this.setTexture = function ( texture, slot ) {
  13971. if ( texture.needsUpdate === true ) {
  13972. var image = texture.image;
  13973. if ( image.complete === false ) {
  13974. THREE.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  13975. return;
  13976. }
  13977. _this.uploadTexture( texture, slot );
  13978. return;
  13979. }
  13980. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13981. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13982. };
  13983. function clampToMaxSize ( image, maxSize ) {
  13984. if ( image.width > maxSize || image.height > maxSize ) {
  13985. // Warning: Scaling through the canvas will only work with images that use
  13986. // premultiplied alpha.
  13987. var scale = maxSize / Math.max( image.width, image.height );
  13988. var canvas = document.createElement( 'canvas' );
  13989. canvas.width = Math.floor( image.width * scale );
  13990. canvas.height = Math.floor( image.height * scale );
  13991. var context = canvas.getContext( '2d' );
  13992. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  13993. THREE.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  13994. return canvas;
  13995. }
  13996. return image;
  13997. }
  13998. function setCubeTexture ( texture, slot ) {
  13999. if ( texture.image.length === 6 ) {
  14000. if ( texture.needsUpdate ) {
  14001. if ( ! texture.image.__webglTextureCube ) {
  14002. texture.addEventListener( 'dispose', onTextureDispose );
  14003. texture.image.__webglTextureCube = _gl.createTexture();
  14004. _this.info.memory.textures ++;
  14005. }
  14006. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14007. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14008. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14009. var isCompressed = texture instanceof THREE.CompressedTexture;
  14010. var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture;
  14011. var cubeImage = [];
  14012. for ( var i = 0; i < 6; i ++ ) {
  14013. if ( _this.autoScaleCubemaps && ! isCompressed && ! isDataTexture ) {
  14014. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  14015. } else {
  14016. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  14017. }
  14018. }
  14019. var image = cubeImage[ 0 ],
  14020. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  14021. glFormat = paramThreeToGL( texture.format ),
  14022. glType = paramThreeToGL( texture.type );
  14023. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  14024. for ( var i = 0; i < 6; i ++ ) {
  14025. if ( ! isCompressed ) {
  14026. if ( isDataTexture ) {
  14027. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  14028. } else {
  14029. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  14030. }
  14031. } else {
  14032. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  14033. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  14034. mipmap = mipmaps[ j ];
  14035. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  14036. if ( getCompressedTextureFormats().indexOf( glFormat ) > -1 ) {
  14037. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14038. } else {
  14039. THREE.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setCubeTexture()" );
  14040. }
  14041. } else {
  14042. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14043. }
  14044. }
  14045. }
  14046. }
  14047. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  14048. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14049. }
  14050. texture.needsUpdate = false;
  14051. if ( texture.onUpdate ) texture.onUpdate( texture );
  14052. } else {
  14053. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14054. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14055. }
  14056. }
  14057. }
  14058. function setCubeTextureDynamic ( texture, slot ) {
  14059. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14060. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  14061. }
  14062. // Render targets
  14063. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  14064. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14065. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  14066. }
  14067. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  14068. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  14069. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14070. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  14071. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14072. /* For some reason this is not working. Defaulting to RGBA4.
  14073. } else if ( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14074. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  14075. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14076. */
  14077. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14078. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  14079. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14080. } else {
  14081. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  14082. }
  14083. }
  14084. this.setRenderTarget = function ( renderTarget ) {
  14085. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  14086. if ( renderTarget && renderTarget.__webglFramebuffer === undefined ) {
  14087. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  14088. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  14089. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14090. renderTarget.__webglTexture = _gl.createTexture();
  14091. _this.info.memory.textures ++;
  14092. // Setup texture, create render and frame buffers
  14093. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ),
  14094. glFormat = paramThreeToGL( renderTarget.format ),
  14095. glType = paramThreeToGL( renderTarget.type );
  14096. if ( isCube ) {
  14097. renderTarget.__webglFramebuffer = [];
  14098. renderTarget.__webglRenderbuffer = [];
  14099. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14100. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  14101. for ( var i = 0; i < 6; i ++ ) {
  14102. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14103. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  14104. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14105. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  14106. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  14107. }
  14108. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14109. } else {
  14110. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  14111. if ( renderTarget.shareDepthFrom ) {
  14112. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  14113. } else {
  14114. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  14115. }
  14116. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14117. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  14118. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14119. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  14120. if ( renderTarget.shareDepthFrom ) {
  14121. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14122. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14123. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14124. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14125. }
  14126. } else {
  14127. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  14128. }
  14129. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14130. }
  14131. // Release everything
  14132. if ( isCube ) {
  14133. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14134. } else {
  14135. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14136. }
  14137. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14138. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14139. }
  14140. var framebuffer, width, height, vx, vy;
  14141. if ( renderTarget ) {
  14142. if ( isCube ) {
  14143. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  14144. } else {
  14145. framebuffer = renderTarget.__webglFramebuffer;
  14146. }
  14147. width = renderTarget.width;
  14148. height = renderTarget.height;
  14149. vx = 0;
  14150. vy = 0;
  14151. } else {
  14152. framebuffer = null;
  14153. width = _viewportWidth;
  14154. height = _viewportHeight;
  14155. vx = _viewportX;
  14156. vy = _viewportY;
  14157. }
  14158. if ( framebuffer !== _currentFramebuffer ) {
  14159. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14160. _gl.viewport( vx, vy, width, height );
  14161. _currentFramebuffer = framebuffer;
  14162. }
  14163. _currentWidth = width;
  14164. _currentHeight = height;
  14165. };
  14166. this.readRenderTargetPixels = function( renderTarget, x, y, width, height, buffer ) {
  14167. if ( ! ( renderTarget instanceof THREE.WebGLRenderTarget ) ) {
  14168. THREE.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  14169. return;
  14170. }
  14171. if ( renderTarget.__webglFramebuffer ) {
  14172. if ( renderTarget.format !== THREE.RGBAFormat ) {
  14173. THREE.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA format. readPixels can read only RGBA format.' );
  14174. return;
  14175. }
  14176. var restore = false;
  14177. if ( renderTarget.__webglFramebuffer !== _currentFramebuffer ) {
  14178. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTarget.__webglFramebuffer );
  14179. restore = true;
  14180. }
  14181. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  14182. _gl.readPixels( x, y, width, height, _gl.RGBA, _gl.UNSIGNED_BYTE, buffer );
  14183. } else {
  14184. THREE.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  14185. }
  14186. if ( restore ) {
  14187. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  14188. }
  14189. }
  14190. };
  14191. function updateRenderTargetMipmap ( renderTarget ) {
  14192. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  14193. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14194. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14195. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14196. } else {
  14197. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14198. _gl.generateMipmap( _gl.TEXTURE_2D );
  14199. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14200. }
  14201. }
  14202. // Fallback filters for non-power-of-2 textures
  14203. function filterFallback ( f ) {
  14204. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  14205. return _gl.NEAREST;
  14206. }
  14207. return _gl.LINEAR;
  14208. }
  14209. // Map three.js constants to WebGL constants
  14210. function paramThreeToGL ( p ) {
  14211. var extension;
  14212. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  14213. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  14214. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  14215. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  14216. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  14217. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  14218. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  14219. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  14220. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  14221. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  14222. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  14223. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  14224. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  14225. if ( p === THREE.ByteType ) return _gl.BYTE;
  14226. if ( p === THREE.ShortType ) return _gl.SHORT;
  14227. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  14228. if ( p === THREE.IntType ) return _gl.INT;
  14229. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  14230. if ( p === THREE.FloatType ) return _gl.FLOAT;
  14231. extension = extensions.get( 'OES_texture_half_float' );
  14232. if ( extension !== null ) {
  14233. if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES;
  14234. }
  14235. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  14236. if ( p === THREE.RGBFormat ) return _gl.RGB;
  14237. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  14238. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  14239. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  14240. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  14241. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  14242. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  14243. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  14244. if ( p === THREE.OneFactor ) return _gl.ONE;
  14245. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  14246. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  14247. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  14248. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  14249. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  14250. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  14251. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  14252. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  14253. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  14254. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  14255. if ( extension !== null ) {
  14256. if ( p === THREE.RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14257. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14258. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14259. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14260. }
  14261. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  14262. if ( extension !== null ) {
  14263. if ( p === THREE.RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14264. if ( p === THREE.RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14265. if ( p === THREE.RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14266. if ( p === THREE.RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14267. }
  14268. extension = extensions.get( 'EXT_blend_minmax' );
  14269. if ( extension !== null ) {
  14270. if ( p === THREE.MinEquation ) return extension.MIN_EXT;
  14271. if ( p === THREE.MaxEquation ) return extension.MAX_EXT;
  14272. }
  14273. return 0;
  14274. }
  14275. // Allocations
  14276. function allocateBones ( object ) {
  14277. if ( _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  14278. return 1024;
  14279. } else {
  14280. // default for when object is not specified
  14281. // ( for example when prebuilding shader
  14282. // to be used with multiple objects )
  14283. //
  14284. // - leave some extra space for other uniforms
  14285. // - limit here is ANGLE's 254 max uniform vectors
  14286. // (up to 54 should be safe)
  14287. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  14288. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  14289. var maxBones = nVertexMatrices;
  14290. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  14291. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  14292. if ( maxBones < object.skeleton.bones.length ) {
  14293. THREE.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  14294. }
  14295. }
  14296. return maxBones;
  14297. }
  14298. }
  14299. function allocateLights( lights ) {
  14300. var dirLights = 0;
  14301. var pointLights = 0;
  14302. var spotLights = 0;
  14303. var hemiLights = 0;
  14304. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  14305. var light = lights[ l ];
  14306. if ( light.onlyShadow || light.visible === false ) continue;
  14307. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  14308. if ( light instanceof THREE.PointLight ) pointLights ++;
  14309. if ( light instanceof THREE.SpotLight ) spotLights ++;
  14310. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  14311. }
  14312. return { 'directional': dirLights, 'point': pointLights, 'spot': spotLights, 'hemi': hemiLights };
  14313. }
  14314. function allocateShadows( lights ) {
  14315. var maxShadows = 0;
  14316. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  14317. var light = lights[ l ];
  14318. if ( ! light.castShadow ) continue;
  14319. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  14320. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  14321. }
  14322. return maxShadows;
  14323. }
  14324. // DEPRECATED
  14325. this.initMaterial = function () {
  14326. THREE.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  14327. };
  14328. this.addPrePlugin = function () {
  14329. THREE.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  14330. };
  14331. this.addPostPlugin = function () {
  14332. THREE.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  14333. };
  14334. this.updateShadowMap = function () {
  14335. THREE.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  14336. };
  14337. };
  14338. // File:src/renderers/WebGLRenderTarget.js
  14339. /**
  14340. * @author szimek / https://github.com/szimek/
  14341. * @author alteredq / http://alteredqualia.com/
  14342. */
  14343. THREE.WebGLRenderTarget = function ( width, height, options ) {
  14344. this.width = width;
  14345. this.height = height;
  14346. options = options || {};
  14347. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  14348. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  14349. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  14350. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  14351. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  14352. this.offset = new THREE.Vector2( 0, 0 );
  14353. this.repeat = new THREE.Vector2( 1, 1 );
  14354. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  14355. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  14356. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  14357. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  14358. this.generateMipmaps = true;
  14359. this.shareDepthFrom = options.shareDepthFrom !== undefined ? options.shareDepthFrom : null;
  14360. };
  14361. THREE.WebGLRenderTarget.prototype = {
  14362. constructor: THREE.WebGLRenderTarget,
  14363. setSize: function ( width, height ) {
  14364. this.width = width;
  14365. this.height = height;
  14366. },
  14367. clone: function () {
  14368. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  14369. tmp.wrapS = this.wrapS;
  14370. tmp.wrapT = this.wrapT;
  14371. tmp.magFilter = this.magFilter;
  14372. tmp.minFilter = this.minFilter;
  14373. tmp.anisotropy = this.anisotropy;
  14374. tmp.offset.copy( this.offset );
  14375. tmp.repeat.copy( this.repeat );
  14376. tmp.format = this.format;
  14377. tmp.type = this.type;
  14378. tmp.depthBuffer = this.depthBuffer;
  14379. tmp.stencilBuffer = this.stencilBuffer;
  14380. tmp.generateMipmaps = this.generateMipmaps;
  14381. tmp.shareDepthFrom = this.shareDepthFrom;
  14382. return tmp;
  14383. },
  14384. dispose: function () {
  14385. this.dispatchEvent( { type: 'dispose' } );
  14386. }
  14387. };
  14388. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  14389. // File:src/renderers/WebGLRenderTargetCube.js
  14390. /**
  14391. * @author alteredq / http://alteredqualia.com
  14392. */
  14393. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  14394. THREE.WebGLRenderTarget.call( this, width, height, options );
  14395. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  14396. };
  14397. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  14398. THREE.WebGLRenderTargetCube.prototype.constructor = THREE.WebGLRenderTargetCube;
  14399. // File:src/renderers/webgl/WebGLExtensions.js
  14400. /**
  14401. * @author mrdoob / http://mrdoob.com/
  14402. */
  14403. THREE.WebGLExtensions = function ( gl ) {
  14404. var extensions = {};
  14405. this.get = function ( name ) {
  14406. if ( extensions[ name ] !== undefined ) {
  14407. return extensions[ name ];
  14408. }
  14409. var extension;
  14410. switch ( name ) {
  14411. case 'EXT_texture_filter_anisotropic':
  14412. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  14413. break;
  14414. case 'WEBGL_compressed_texture_s3tc':
  14415. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  14416. break;
  14417. case 'WEBGL_compressed_texture_pvrtc':
  14418. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  14419. break;
  14420. default:
  14421. extension = gl.getExtension( name );
  14422. }
  14423. if ( extension === null ) {
  14424. THREE.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  14425. }
  14426. extensions[ name ] = extension;
  14427. return extension;
  14428. };
  14429. };
  14430. // File:src/renderers/webgl/WebGLProgram.js
  14431. THREE.WebGLProgram = ( function () {
  14432. var programIdCount = 0;
  14433. var generateDefines = function ( defines ) {
  14434. var value, chunk, chunks = [];
  14435. for ( var d in defines ) {
  14436. value = defines[ d ];
  14437. if ( value === false ) continue;
  14438. chunk = '#define ' + d + ' ' + value;
  14439. chunks.push( chunk );
  14440. }
  14441. return chunks.join( '\n' );
  14442. };
  14443. var cacheUniformLocations = function ( gl, program, identifiers ) {
  14444. var uniforms = {};
  14445. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  14446. var id = identifiers[ i ];
  14447. uniforms[ id ] = gl.getUniformLocation( program, id );
  14448. }
  14449. return uniforms;
  14450. };
  14451. var cacheAttributeLocations = function ( gl, program, identifiers ) {
  14452. var attributes = {};
  14453. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  14454. var id = identifiers[ i ];
  14455. attributes[ id ] = gl.getAttribLocation( program, id );
  14456. }
  14457. return attributes;
  14458. };
  14459. return function ( renderer, code, material, parameters ) {
  14460. var _this = renderer;
  14461. var _gl = _this.context;
  14462. var defines = material.defines;
  14463. var uniforms = material.__webglShader.uniforms;
  14464. var attributes = material.attributes;
  14465. var vertexShader = material.__webglShader.vertexShader;
  14466. var fragmentShader = material.__webglShader.fragmentShader;
  14467. var index0AttributeName = material.index0AttributeName;
  14468. if ( index0AttributeName === undefined && parameters.morphTargets === true ) {
  14469. // programs with morphTargets displace position out of attribute 0
  14470. index0AttributeName = 'position';
  14471. }
  14472. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  14473. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  14474. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  14475. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  14476. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  14477. }
  14478. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  14479. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  14480. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  14481. if ( parameters.envMap ) {
  14482. switch ( material.envMap.mapping ) {
  14483. case THREE.CubeReflectionMapping:
  14484. case THREE.CubeRefractionMapping:
  14485. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  14486. break;
  14487. case THREE.EquirectangularReflectionMapping:
  14488. case THREE.EquirectangularRefractionMapping:
  14489. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  14490. break;
  14491. case THREE.SphericalReflectionMapping:
  14492. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  14493. break;
  14494. }
  14495. switch ( material.envMap.mapping ) {
  14496. case THREE.CubeRefractionMapping:
  14497. case THREE.EquirectangularRefractionMapping:
  14498. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  14499. break;
  14500. }
  14501. switch ( material.combine ) {
  14502. case THREE.MultiplyOperation:
  14503. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  14504. break;
  14505. case THREE.MixOperation:
  14506. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  14507. break;
  14508. case THREE.AddOperation:
  14509. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  14510. break;
  14511. }
  14512. }
  14513. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  14514. // THREE.log( 'building new program ' );
  14515. //
  14516. var customDefines = generateDefines( defines );
  14517. //
  14518. var program = _gl.createProgram();
  14519. var prefix_vertex, prefix_fragment;
  14520. if ( material instanceof THREE.RawShaderMaterial ) {
  14521. prefix_vertex = '';
  14522. prefix_fragment = '';
  14523. } else {
  14524. prefix_vertex = [
  14525. 'precision ' + parameters.precision + ' float;',
  14526. 'precision ' + parameters.precision + ' int;',
  14527. customDefines,
  14528. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  14529. _this.gammaInput ? '#define GAMMA_INPUT' : '',
  14530. _this.gammaOutput ? '#define GAMMA_OUTPUT' : '',
  14531. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  14532. '#define MAX_DIR_LIGHTS ' + parameters.maxDirLights,
  14533. '#define MAX_POINT_LIGHTS ' + parameters.maxPointLights,
  14534. '#define MAX_SPOT_LIGHTS ' + parameters.maxSpotLights,
  14535. '#define MAX_HEMI_LIGHTS ' + parameters.maxHemiLights,
  14536. '#define MAX_SHADOWS ' + parameters.maxShadows,
  14537. '#define MAX_BONES ' + parameters.maxBones,
  14538. parameters.map ? '#define USE_MAP' : '',
  14539. parameters.envMap ? '#define USE_ENVMAP' : '',
  14540. parameters.envMap ? '#define ' + envMapModeDefine : '',
  14541. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  14542. parameters.aoMap ? '#define USE_AOMAP' : '',
  14543. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  14544. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  14545. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  14546. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  14547. parameters.vertexColors ? '#define USE_COLOR' : '',
  14548. parameters.flatShading ? '#define FLAT_SHADED': '',
  14549. parameters.skinning ? '#define USE_SKINNING' : '',
  14550. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  14551. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  14552. parameters.morphNormals ? '#define USE_MORPHNORMALS' : '',
  14553. parameters.wrapAround ? '#define WRAP_AROUND' : '',
  14554. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  14555. parameters.flipSided ? '#define FLIP_SIDED' : '',
  14556. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  14557. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  14558. parameters.shadowMapDebug ? '#define SHADOWMAP_DEBUG' : '',
  14559. parameters.shadowMapCascade ? '#define SHADOWMAP_CASCADE' : '',
  14560. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  14561. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  14562. //_this._glExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '',
  14563. 'uniform mat4 modelMatrix;',
  14564. 'uniform mat4 modelViewMatrix;',
  14565. 'uniform mat4 projectionMatrix;',
  14566. 'uniform mat4 viewMatrix;',
  14567. 'uniform mat3 normalMatrix;',
  14568. 'uniform vec3 cameraPosition;',
  14569. 'attribute vec3 position;',
  14570. 'attribute vec3 normal;',
  14571. 'attribute vec2 uv;',
  14572. '#ifdef USE_COLOR',
  14573. ' attribute vec3 color;',
  14574. '#endif',
  14575. '#ifdef USE_MORPHTARGETS',
  14576. ' attribute vec3 morphTarget0;',
  14577. ' attribute vec3 morphTarget1;',
  14578. ' attribute vec3 morphTarget2;',
  14579. ' attribute vec3 morphTarget3;',
  14580. ' #ifdef USE_MORPHNORMALS',
  14581. ' attribute vec3 morphNormal0;',
  14582. ' attribute vec3 morphNormal1;',
  14583. ' attribute vec3 morphNormal2;',
  14584. ' attribute vec3 morphNormal3;',
  14585. ' #else',
  14586. ' attribute vec3 morphTarget4;',
  14587. ' attribute vec3 morphTarget5;',
  14588. ' attribute vec3 morphTarget6;',
  14589. ' attribute vec3 morphTarget7;',
  14590. ' #endif',
  14591. '#endif',
  14592. '#ifdef USE_SKINNING',
  14593. ' attribute vec4 skinIndex;',
  14594. ' attribute vec4 skinWeight;',
  14595. '#endif',
  14596. ''
  14597. ].join( '\n' );
  14598. prefix_fragment = [
  14599. 'precision ' + parameters.precision + ' float;',
  14600. 'precision ' + parameters.precision + ' int;',
  14601. ( parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  14602. customDefines,
  14603. '#define MAX_DIR_LIGHTS ' + parameters.maxDirLights,
  14604. '#define MAX_POINT_LIGHTS ' + parameters.maxPointLights,
  14605. '#define MAX_SPOT_LIGHTS ' + parameters.maxSpotLights,
  14606. '#define MAX_HEMI_LIGHTS ' + parameters.maxHemiLights,
  14607. '#define MAX_SHADOWS ' + parameters.maxShadows,
  14608. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  14609. _this.gammaInput ? '#define GAMMA_INPUT' : '',
  14610. _this.gammaOutput ? '#define GAMMA_OUTPUT' : '',
  14611. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  14612. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  14613. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  14614. parameters.map ? '#define USE_MAP' : '',
  14615. parameters.envMap ? '#define USE_ENVMAP' : '',
  14616. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  14617. parameters.envMap ? '#define ' + envMapModeDefine : '',
  14618. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  14619. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  14620. parameters.aoMap ? '#define USE_AOMAP' : '',
  14621. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  14622. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  14623. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  14624. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  14625. parameters.vertexColors ? '#define USE_COLOR' : '',
  14626. parameters.flatShading ? '#define FLAT_SHADED': '',
  14627. parameters.metal ? '#define METAL' : '',
  14628. parameters.wrapAround ? '#define WRAP_AROUND' : '',
  14629. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  14630. parameters.flipSided ? '#define FLIP_SIDED' : '',
  14631. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  14632. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  14633. parameters.shadowMapDebug ? '#define SHADOWMAP_DEBUG' : '',
  14634. parameters.shadowMapCascade ? '#define SHADOWMAP_CASCADE' : '',
  14635. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  14636. //_this._glExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '',
  14637. 'uniform mat4 viewMatrix;',
  14638. 'uniform vec3 cameraPosition;',
  14639. ''
  14640. ].join( '\n' );
  14641. }
  14642. var glVertexShader = new THREE.WebGLShader( _gl, _gl.VERTEX_SHADER, prefix_vertex + vertexShader );
  14643. var glFragmentShader = new THREE.WebGLShader( _gl, _gl.FRAGMENT_SHADER, prefix_fragment + fragmentShader );
  14644. _gl.attachShader( program, glVertexShader );
  14645. _gl.attachShader( program, glFragmentShader );
  14646. if ( index0AttributeName !== undefined ) {
  14647. // Force a particular attribute to index 0.
  14648. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  14649. // And, color, for example is often automatically bound to index 0 so disabling it
  14650. _gl.bindAttribLocation( program, 0, index0AttributeName );
  14651. }
  14652. _gl.linkProgram( program );
  14653. var programLogInfo = _gl.getProgramInfoLog( program );
  14654. var vertexErrorLogInfo = _gl.getShaderInfoLog( glVertexShader );
  14655. var fragmentErrorLogInfo = _gl.getShaderInfoLog( glFragmentShader );
  14656. if ( _gl.getProgramParameter( program, _gl.LINK_STATUS ) === false ) {
  14657. THREE.error( 'THREE.WebGLProgram: shader error: ', _gl.getError(), 'gl.VALIDATE_STATUS', _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLogInfo, vertexErrorLogInfo, fragmentErrorLogInfo );
  14658. }
  14659. if ( programLogInfo !== '' ) {
  14660. THREE.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLogInfo );
  14661. }
  14662. // clean up
  14663. _gl.deleteShader( glVertexShader );
  14664. _gl.deleteShader( glFragmentShader );
  14665. // cache uniform locations
  14666. var identifiers = [
  14667. 'viewMatrix',
  14668. 'modelViewMatrix',
  14669. 'projectionMatrix',
  14670. 'normalMatrix',
  14671. 'modelMatrix',
  14672. 'cameraPosition',
  14673. 'morphTargetInfluences',
  14674. 'bindMatrix',
  14675. 'bindMatrixInverse'
  14676. ];
  14677. if ( parameters.useVertexTexture ) {
  14678. identifiers.push( 'boneTexture' );
  14679. identifiers.push( 'boneTextureWidth' );
  14680. identifiers.push( 'boneTextureHeight' );
  14681. } else {
  14682. identifiers.push( 'boneGlobalMatrices' );
  14683. }
  14684. if ( parameters.logarithmicDepthBuffer ) {
  14685. identifiers.push('logDepthBufFC');
  14686. }
  14687. for ( var u in uniforms ) {
  14688. identifiers.push( u );
  14689. }
  14690. this.uniforms = cacheUniformLocations( _gl, program, identifiers );
  14691. // cache attributes locations
  14692. identifiers = [
  14693. 'position',
  14694. 'normal',
  14695. 'uv',
  14696. 'uv2',
  14697. 'tangent',
  14698. 'color',
  14699. 'skinIndex',
  14700. 'skinWeight',
  14701. 'lineDistance'
  14702. ];
  14703. for ( var i = 0; i < parameters.maxMorphTargets; i ++ ) {
  14704. identifiers.push( 'morphTarget' + i );
  14705. }
  14706. for ( var i = 0; i < parameters.maxMorphNormals; i ++ ) {
  14707. identifiers.push( 'morphNormal' + i );
  14708. }
  14709. for ( var a in attributes ) {
  14710. identifiers.push( a );
  14711. }
  14712. this.attributes = cacheAttributeLocations( _gl, program, identifiers );
  14713. this.attributesKeys = Object.keys( this.attributes );
  14714. //
  14715. this.id = programIdCount ++;
  14716. this.code = code;
  14717. this.usedTimes = 1;
  14718. this.program = program;
  14719. this.vertexShader = glVertexShader;
  14720. this.fragmentShader = glFragmentShader;
  14721. return this;
  14722. };
  14723. } )();
  14724. // File:src/renderers/webgl/WebGLShader.js
  14725. THREE.WebGLShader = ( function () {
  14726. var addLineNumbers = function ( string ) {
  14727. var lines = string.split( '\n' );
  14728. for ( var i = 0; i < lines.length; i ++ ) {
  14729. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  14730. }
  14731. return lines.join( '\n' );
  14732. };
  14733. return function ( gl, type, string ) {
  14734. var shader = gl.createShader( type );
  14735. gl.shaderSource( shader, string );
  14736. gl.compileShader( shader );
  14737. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  14738. THREE.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  14739. }
  14740. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  14741. THREE.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  14742. }
  14743. // --enable-privileged-webgl-extension
  14744. // THREE.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  14745. return shader;
  14746. };
  14747. } )();
  14748. // File:src/renderers/webgl/WebGLState.js
  14749. /**
  14750. * @author mrdoob / http://mrdoob.com/
  14751. */
  14752. THREE.WebGLState = function ( gl, paramThreeToGL ) {
  14753. var newAttributes = new Uint8Array( 16 );
  14754. var enabledAttributes = new Uint8Array( 16 );
  14755. var currentBlending = null;
  14756. var currentBlendEquation = null;
  14757. var currentBlendSrc = null;
  14758. var currentBlendDst = null;
  14759. var currentBlendEquationAlpha = null;
  14760. var currentBlendSrcAlpha = null;
  14761. var currentBlendDstAlpha = null;
  14762. var currentDepthTest = null;
  14763. var currentDepthWrite = null;
  14764. var currentColorWrite = null;
  14765. var currentDoubleSided = null;
  14766. var currentFlipSided = null;
  14767. var currentLineWidth = null;
  14768. var currentPolygonOffset = null;
  14769. var currentPolygonOffsetFactor = null;
  14770. var currentPolygonOffsetUnits = null;
  14771. this.initAttributes = function () {
  14772. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  14773. newAttributes[ i ] = 0;
  14774. }
  14775. };
  14776. this.enableAttribute = function ( attribute ) {
  14777. newAttributes[ attribute ] = 1;
  14778. if ( enabledAttributes[ attribute ] === 0 ) {
  14779. gl.enableVertexAttribArray( attribute );
  14780. enabledAttributes[ attribute ] = 1;
  14781. }
  14782. };
  14783. this.disableUnusedAttributes = function () {
  14784. for ( var i = 0, l = enabledAttributes.length; i < l; i ++ ) {
  14785. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  14786. gl.disableVertexAttribArray( i );
  14787. enabledAttributes[ i ] = 0;
  14788. }
  14789. }
  14790. };
  14791. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha ) {
  14792. if ( blending !== currentBlending ) {
  14793. if ( blending === THREE.NoBlending ) {
  14794. gl.disable( gl.BLEND );
  14795. } else if ( blending === THREE.AdditiveBlending ) {
  14796. gl.enable( gl.BLEND );
  14797. gl.blendEquation( gl.FUNC_ADD );
  14798. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  14799. } else if ( blending === THREE.SubtractiveBlending ) {
  14800. // TODO: Find blendFuncSeparate() combination
  14801. gl.enable( gl.BLEND );
  14802. gl.blendEquation( gl.FUNC_ADD );
  14803. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  14804. } else if ( blending === THREE.MultiplyBlending ) {
  14805. // TODO: Find blendFuncSeparate() combination
  14806. gl.enable( gl.BLEND );
  14807. gl.blendEquation( gl.FUNC_ADD );
  14808. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  14809. } else if ( blending === THREE.CustomBlending ) {
  14810. gl.enable( gl.BLEND );
  14811. } else {
  14812. gl.enable( gl.BLEND );
  14813. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  14814. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  14815. }
  14816. currentBlending = blending;
  14817. }
  14818. if ( blending === THREE.CustomBlending ) {
  14819. blendEquationAlpha = blendEquationAlpha || blendEquation;
  14820. blendSrcAlpha = blendSrcAlpha || blendSrc;
  14821. blendDstAlpha = blendDstAlpha || blendDst;
  14822. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  14823. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  14824. currentBlendEquation = blendEquation;
  14825. currentBlendEquationAlpha = blendEquationAlpha;
  14826. }
  14827. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  14828. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  14829. currentBlendSrc = blendSrc;
  14830. currentBlendDst = blendDst;
  14831. currentBlendSrcAlpha = blendSrcAlpha;
  14832. currentBlendDstAlpha = blendDstAlpha;
  14833. }
  14834. } else {
  14835. currentBlendEquation = null;
  14836. currentBlendSrc = null;
  14837. currentBlendDst = null;
  14838. currentBlendEquationAlpha = null;
  14839. currentBlendSrcAlpha = null;
  14840. currentBlendDstAlpha = null;
  14841. }
  14842. };
  14843. this.setDepthTest = function ( depthTest ) {
  14844. if ( currentDepthTest !== depthTest ) {
  14845. if ( depthTest ) {
  14846. gl.enable( gl.DEPTH_TEST );
  14847. } else {
  14848. gl.disable( gl.DEPTH_TEST );
  14849. }
  14850. currentDepthTest = depthTest;
  14851. }
  14852. };
  14853. this.setDepthWrite = function ( depthWrite ) {
  14854. if ( currentDepthWrite !== depthWrite ) {
  14855. gl.depthMask( depthWrite );
  14856. currentDepthWrite = depthWrite;
  14857. }
  14858. };
  14859. this.setColorWrite = function ( colorWrite ) {
  14860. if ( currentColorWrite !== colorWrite ) {
  14861. gl.colorMask( colorWrite, colorWrite, colorWrite, colorWrite );
  14862. currentColorWrite = colorWrite;
  14863. }
  14864. };
  14865. this.setDoubleSided = function ( doubleSided ) {
  14866. if ( currentDoubleSided !== doubleSided ) {
  14867. if ( doubleSided ) {
  14868. gl.disable( gl.CULL_FACE );
  14869. } else {
  14870. gl.enable( gl.CULL_FACE );
  14871. }
  14872. currentDoubleSided = doubleSided;
  14873. }
  14874. };
  14875. this.setFlipSided = function ( flipSided ) {
  14876. if ( currentFlipSided !== flipSided ) {
  14877. if ( flipSided ) {
  14878. gl.frontFace( gl.CW );
  14879. } else {
  14880. gl.frontFace( gl.CCW );
  14881. }
  14882. currentFlipSided = flipSided;
  14883. }
  14884. };
  14885. this.setLineWidth = function ( width ) {
  14886. if ( width !== currentLineWidth ) {
  14887. gl.lineWidth( width );
  14888. currentLineWidth = width;
  14889. }
  14890. };
  14891. this.setPolygonOffset = function ( polygonoffset, factor, units ) {
  14892. if ( currentPolygonOffset !== polygonoffset ) {
  14893. if ( polygonoffset ) {
  14894. gl.enable( gl.POLYGON_OFFSET_FILL );
  14895. } else {
  14896. gl.disable( gl.POLYGON_OFFSET_FILL );
  14897. }
  14898. currentPolygonOffset = polygonoffset;
  14899. }
  14900. if ( polygonoffset && ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) ) {
  14901. gl.polygonOffset( factor, units );
  14902. currentPolygonOffsetFactor = factor;
  14903. currentPolygonOffsetUnits = units;
  14904. }
  14905. };
  14906. this.reset = function () {
  14907. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  14908. enabledAttributes[ i ] = 0;
  14909. }
  14910. currentBlending = null;
  14911. currentDepthTest = null;
  14912. currentDepthWrite = null;
  14913. currentColorWrite = null;
  14914. currentDoubleSided = null;
  14915. currentFlipSided = null;
  14916. };
  14917. };
  14918. // File:src/renderers/webgl/plugins/LensFlarePlugin.js
  14919. /**
  14920. * @author mikael emtinger / http://gomo.se/
  14921. * @author alteredq / http://alteredqualia.com/
  14922. */
  14923. THREE.LensFlarePlugin = function ( renderer, flares ) {
  14924. var gl = renderer.context;
  14925. var vertexBuffer, elementBuffer;
  14926. var program, attributes, uniforms;
  14927. var hasVertexTexture;
  14928. var tempTexture, occlusionTexture;
  14929. var init = function () {
  14930. var vertices = new Float32Array( [
  14931. -1, -1, 0, 0,
  14932. 1, -1, 1, 0,
  14933. 1, 1, 1, 1,
  14934. -1, 1, 0, 1
  14935. ] );
  14936. var faces = new Uint16Array( [
  14937. 0, 1, 2,
  14938. 0, 2, 3
  14939. ] );
  14940. // buffers
  14941. vertexBuffer = gl.createBuffer();
  14942. elementBuffer = gl.createBuffer();
  14943. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  14944. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  14945. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  14946. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  14947. // textures
  14948. tempTexture = gl.createTexture();
  14949. occlusionTexture = gl.createTexture();
  14950. gl.bindTexture( gl.TEXTURE_2D, tempTexture );
  14951. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  14952. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  14953. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  14954. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  14955. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  14956. gl.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  14957. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  14958. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  14959. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  14960. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  14961. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  14962. hasVertexTexture = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) > 0;
  14963. var shader;
  14964. if ( hasVertexTexture ) {
  14965. shader = {
  14966. vertexShader: [
  14967. "uniform lowp int renderType;",
  14968. "uniform vec3 screenPosition;",
  14969. "uniform vec2 scale;",
  14970. "uniform float rotation;",
  14971. "uniform sampler2D occlusionMap;",
  14972. "attribute vec2 position;",
  14973. "attribute vec2 uv;",
  14974. "varying vec2 vUV;",
  14975. "varying float vVisibility;",
  14976. "void main() {",
  14977. "vUV = uv;",
  14978. "vec2 pos = position;",
  14979. "if( renderType == 2 ) {",
  14980. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  14981. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  14982. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  14983. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  14984. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  14985. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  14986. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  14987. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  14988. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  14989. "vVisibility = visibility.r / 9.0;",
  14990. "vVisibility *= 1.0 - visibility.g / 9.0;",
  14991. "vVisibility *= visibility.b / 9.0;",
  14992. "vVisibility *= 1.0 - visibility.a / 9.0;",
  14993. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  14994. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  14995. "}",
  14996. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  14997. "}"
  14998. ].join( "\n" ),
  14999. fragmentShader: [
  15000. "uniform lowp int renderType;",
  15001. "uniform sampler2D map;",
  15002. "uniform float opacity;",
  15003. "uniform vec3 color;",
  15004. "varying vec2 vUV;",
  15005. "varying float vVisibility;",
  15006. "void main() {",
  15007. // pink square
  15008. "if( renderType == 0 ) {",
  15009. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  15010. // restore
  15011. "} else if( renderType == 1 ) {",
  15012. "gl_FragColor = texture2D( map, vUV );",
  15013. // flare
  15014. "} else {",
  15015. "vec4 texture = texture2D( map, vUV );",
  15016. "texture.a *= opacity * vVisibility;",
  15017. "gl_FragColor = texture;",
  15018. "gl_FragColor.rgb *= color;",
  15019. "}",
  15020. "}"
  15021. ].join( "\n" )
  15022. };
  15023. } else {
  15024. shader = {
  15025. vertexShader: [
  15026. "uniform lowp int renderType;",
  15027. "uniform vec3 screenPosition;",
  15028. "uniform vec2 scale;",
  15029. "uniform float rotation;",
  15030. "attribute vec2 position;",
  15031. "attribute vec2 uv;",
  15032. "varying vec2 vUV;",
  15033. "void main() {",
  15034. "vUV = uv;",
  15035. "vec2 pos = position;",
  15036. "if( renderType == 2 ) {",
  15037. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  15038. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  15039. "}",
  15040. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  15041. "}"
  15042. ].join( "\n" ),
  15043. fragmentShader: [
  15044. "precision mediump float;",
  15045. "uniform lowp int renderType;",
  15046. "uniform sampler2D map;",
  15047. "uniform sampler2D occlusionMap;",
  15048. "uniform float opacity;",
  15049. "uniform vec3 color;",
  15050. "varying vec2 vUV;",
  15051. "void main() {",
  15052. // pink square
  15053. "if( renderType == 0 ) {",
  15054. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  15055. // restore
  15056. "} else if( renderType == 1 ) {",
  15057. "gl_FragColor = texture2D( map, vUV );",
  15058. // flare
  15059. "} else {",
  15060. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  15061. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  15062. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  15063. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  15064. "visibility = ( 1.0 - visibility / 4.0 );",
  15065. "vec4 texture = texture2D( map, vUV );",
  15066. "texture.a *= opacity * visibility;",
  15067. "gl_FragColor = texture;",
  15068. "gl_FragColor.rgb *= color;",
  15069. "}",
  15070. "}"
  15071. ].join( "\n" )
  15072. };
  15073. }
  15074. program = createProgram( shader );
  15075. attributes = {
  15076. vertex: gl.getAttribLocation ( program, "position" ),
  15077. uv: gl.getAttribLocation ( program, "uv" )
  15078. }
  15079. uniforms = {
  15080. renderType: gl.getUniformLocation( program, "renderType" ),
  15081. map: gl.getUniformLocation( program, "map" ),
  15082. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  15083. opacity: gl.getUniformLocation( program, "opacity" ),
  15084. color: gl.getUniformLocation( program, "color" ),
  15085. scale: gl.getUniformLocation( program, "scale" ),
  15086. rotation: gl.getUniformLocation( program, "rotation" ),
  15087. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  15088. };
  15089. };
  15090. /*
  15091. * Render lens flares
  15092. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  15093. * reads these back and calculates occlusion.
  15094. */
  15095. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  15096. if ( flares.length === 0 ) return;
  15097. var tempPosition = new THREE.Vector3();
  15098. var invAspect = viewportHeight / viewportWidth,
  15099. halfViewportWidth = viewportWidth * 0.5,
  15100. halfViewportHeight = viewportHeight * 0.5;
  15101. var size = 16 / viewportHeight,
  15102. scale = new THREE.Vector2( size * invAspect, size );
  15103. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  15104. screenPositionPixels = new THREE.Vector2( 1, 1 );
  15105. if ( program === undefined ) {
  15106. init();
  15107. }
  15108. gl.useProgram( program );
  15109. gl.enableVertexAttribArray( attributes.vertex );
  15110. gl.enableVertexAttribArray( attributes.uv );
  15111. // loop through all lens flares to update their occlusion and positions
  15112. // setup gl and common used attribs/unforms
  15113. gl.uniform1i( uniforms.occlusionMap, 0 );
  15114. gl.uniform1i( uniforms.map, 1 );
  15115. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  15116. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  15117. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  15118. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  15119. gl.disable( gl.CULL_FACE );
  15120. gl.depthMask( false );
  15121. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  15122. size = 16 / viewportHeight;
  15123. scale.set( size * invAspect, size );
  15124. // calc object screen position
  15125. var flare = flares[ i ];
  15126. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  15127. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  15128. tempPosition.applyProjection( camera.projectionMatrix );
  15129. // setup arrays for gl programs
  15130. screenPosition.copy( tempPosition )
  15131. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  15132. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  15133. // screen cull
  15134. if ( hasVertexTexture || (
  15135. screenPositionPixels.x > 0 &&
  15136. screenPositionPixels.x < viewportWidth &&
  15137. screenPositionPixels.y > 0 &&
  15138. screenPositionPixels.y < viewportHeight ) ) {
  15139. // save current RGB to temp texture
  15140. gl.activeTexture( gl.TEXTURE1 );
  15141. gl.bindTexture( gl.TEXTURE_2D, tempTexture );
  15142. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  15143. // render pink quad
  15144. gl.uniform1i( uniforms.renderType, 0 );
  15145. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  15146. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  15147. gl.disable( gl.BLEND );
  15148. gl.enable( gl.DEPTH_TEST );
  15149. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  15150. // copy result to occlusionMap
  15151. gl.activeTexture( gl.TEXTURE0 );
  15152. gl.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  15153. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  15154. // restore graphics
  15155. gl.uniform1i( uniforms.renderType, 1 );
  15156. gl.disable( gl.DEPTH_TEST );
  15157. gl.activeTexture( gl.TEXTURE1 );
  15158. gl.bindTexture( gl.TEXTURE_2D, tempTexture );
  15159. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  15160. // update object positions
  15161. flare.positionScreen.copy( screenPosition )
  15162. if ( flare.customUpdateCallback ) {
  15163. flare.customUpdateCallback( flare );
  15164. } else {
  15165. flare.updateLensFlares();
  15166. }
  15167. // render flares
  15168. gl.uniform1i( uniforms.renderType, 2 );
  15169. gl.enable( gl.BLEND );
  15170. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  15171. var sprite = flare.lensFlares[ j ];
  15172. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  15173. screenPosition.x = sprite.x;
  15174. screenPosition.y = sprite.y;
  15175. screenPosition.z = sprite.z;
  15176. size = sprite.size * sprite.scale / viewportHeight;
  15177. scale.x = size * invAspect;
  15178. scale.y = size;
  15179. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  15180. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  15181. gl.uniform1f( uniforms.rotation, sprite.rotation );
  15182. gl.uniform1f( uniforms.opacity, sprite.opacity );
  15183. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  15184. renderer.state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  15185. renderer.setTexture( sprite.texture, 1 );
  15186. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  15187. }
  15188. }
  15189. }
  15190. }
  15191. // restore gl
  15192. gl.enable( gl.CULL_FACE );
  15193. gl.enable( gl.DEPTH_TEST );
  15194. gl.depthMask( true );
  15195. renderer.resetGLState();
  15196. };
  15197. function createProgram ( shader ) {
  15198. var program = gl.createProgram();
  15199. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  15200. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  15201. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  15202. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  15203. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  15204. gl.compileShader( fragmentShader );
  15205. gl.compileShader( vertexShader );
  15206. gl.attachShader( program, fragmentShader );
  15207. gl.attachShader( program, vertexShader );
  15208. gl.linkProgram( program );
  15209. return program;
  15210. }
  15211. };
  15212. // File:src/renderers/webgl/plugins/ShadowMapPlugin.js
  15213. /**
  15214. * @author alteredq / http://alteredqualia.com/
  15215. */
  15216. THREE.ShadowMapPlugin = function ( _renderer, _lights, _webglObjects, _webglObjectsImmediate ) {
  15217. var _gl = _renderer.context;
  15218. var _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  15219. _frustum = new THREE.Frustum(),
  15220. _projScreenMatrix = new THREE.Matrix4(),
  15221. _min = new THREE.Vector3(),
  15222. _max = new THREE.Vector3(),
  15223. _matrixPosition = new THREE.Vector3(),
  15224. _renderList = [];
  15225. // init
  15226. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  15227. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  15228. _depthMaterial = new THREE.ShaderMaterial( {
  15229. uniforms: depthUniforms,
  15230. vertexShader: depthShader.vertexShader,
  15231. fragmentShader: depthShader.fragmentShader
  15232. } );
  15233. _depthMaterialMorph = new THREE.ShaderMaterial( {
  15234. uniforms: depthUniforms,
  15235. vertexShader: depthShader.vertexShader,
  15236. fragmentShader: depthShader.fragmentShader,
  15237. morphTargets: true
  15238. } );
  15239. _depthMaterialSkin = new THREE.ShaderMaterial( {
  15240. uniforms: depthUniforms,
  15241. vertexShader: depthShader.vertexShader,
  15242. fragmentShader: depthShader.fragmentShader,
  15243. skinning: true
  15244. } );
  15245. _depthMaterialMorphSkin = new THREE.ShaderMaterial( {
  15246. uniforms: depthUniforms,
  15247. vertexShader: depthShader.vertexShader,
  15248. fragmentShader: depthShader.fragmentShader,
  15249. morphTargets: true,
  15250. skinning: true
  15251. } );
  15252. _depthMaterial._shadowPass = true;
  15253. _depthMaterialMorph._shadowPass = true;
  15254. _depthMaterialSkin._shadowPass = true;
  15255. _depthMaterialMorphSkin._shadowPass = true;
  15256. this.render = function ( scene, camera ) {
  15257. if ( _renderer.shadowMapEnabled === false ) return;
  15258. var i, il, j, jl, n,
  15259. shadowMap, shadowMatrix, shadowCamera,
  15260. buffer, material,
  15261. webglObject, object, light,
  15262. lights = [],
  15263. k = 0,
  15264. fog = null;
  15265. // set GL state for depth map
  15266. _gl.clearColor( 1, 1, 1, 1 );
  15267. _gl.disable( _gl.BLEND );
  15268. _gl.enable( _gl.CULL_FACE );
  15269. _gl.frontFace( _gl.CCW );
  15270. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  15271. _gl.cullFace( _gl.FRONT );
  15272. } else {
  15273. _gl.cullFace( _gl.BACK );
  15274. }
  15275. _renderer.state.setDepthTest( true );
  15276. // preprocess lights
  15277. // - skip lights that are not casting shadows
  15278. // - create virtual lights for cascaded shadow maps
  15279. for ( i = 0, il = _lights.length; i < il; i ++ ) {
  15280. light = _lights[ i ];
  15281. if ( ! light.castShadow ) continue;
  15282. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  15283. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  15284. var virtualLight;
  15285. if ( ! light.shadowCascadeArray[ n ] ) {
  15286. virtualLight = createVirtualLight( light, n );
  15287. virtualLight.originalCamera = camera;
  15288. var gyro = new THREE.Gyroscope();
  15289. gyro.position.copy( light.shadowCascadeOffset );
  15290. gyro.add( virtualLight );
  15291. gyro.add( virtualLight.target );
  15292. camera.add( gyro );
  15293. light.shadowCascadeArray[ n ] = virtualLight;
  15294. //THREE.log( "Created virtualLight", virtualLight );
  15295. } else {
  15296. virtualLight = light.shadowCascadeArray[ n ];
  15297. }
  15298. updateVirtualLight( light, n );
  15299. lights[ k ] = virtualLight;
  15300. k ++;
  15301. }
  15302. } else {
  15303. lights[ k ] = light;
  15304. k ++;
  15305. }
  15306. }
  15307. // render depth map
  15308. for ( i = 0, il = lights.length; i < il; i ++ ) {
  15309. light = lights[ i ];
  15310. if ( ! light.shadowMap ) {
  15311. var shadowFilter = THREE.LinearFilter;
  15312. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  15313. shadowFilter = THREE.NearestFilter;
  15314. }
  15315. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  15316. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  15317. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  15318. light.shadowMatrix = new THREE.Matrix4();
  15319. }
  15320. if ( ! light.shadowCamera ) {
  15321. if ( light instanceof THREE.SpotLight ) {
  15322. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  15323. } else if ( light instanceof THREE.DirectionalLight ) {
  15324. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  15325. } else {
  15326. THREE.error( "THREE.ShadowMapPlugin: Unsupported light type for shadow", light );
  15327. continue;
  15328. }
  15329. scene.add( light.shadowCamera );
  15330. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  15331. }
  15332. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  15333. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  15334. scene.add( light.cameraHelper );
  15335. }
  15336. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  15337. updateShadowCamera( camera, light );
  15338. }
  15339. shadowMap = light.shadowMap;
  15340. shadowMatrix = light.shadowMatrix;
  15341. shadowCamera = light.shadowCamera;
  15342. //
  15343. shadowCamera.position.setFromMatrixPosition( light.matrixWorld );
  15344. _matrixPosition.setFromMatrixPosition( light.target.matrixWorld );
  15345. shadowCamera.lookAt( _matrixPosition );
  15346. shadowCamera.updateMatrixWorld();
  15347. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  15348. //
  15349. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  15350. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  15351. // compute shadow matrix
  15352. shadowMatrix.set(
  15353. 0.5, 0.0, 0.0, 0.5,
  15354. 0.0, 0.5, 0.0, 0.5,
  15355. 0.0, 0.0, 0.5, 0.5,
  15356. 0.0, 0.0, 0.0, 1.0
  15357. );
  15358. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  15359. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  15360. // update camera matrices and frustum
  15361. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  15362. _frustum.setFromMatrix( _projScreenMatrix );
  15363. // render shadow map
  15364. _renderer.setRenderTarget( shadowMap );
  15365. _renderer.clear();
  15366. // set object matrices & frustum culling
  15367. _renderList.length = 0;
  15368. projectObject( scene, scene, shadowCamera );
  15369. // render regular objects
  15370. var objectMaterial, useMorphing, useSkinning;
  15371. for ( j = 0, jl = _renderList.length; j < jl; j ++ ) {
  15372. webglObject = _renderList[ j ];
  15373. object = webglObject.object;
  15374. buffer = webglObject.buffer;
  15375. // culling is overriden globally for all objects
  15376. // while rendering depth map
  15377. // need to deal with MeshFaceMaterial somehow
  15378. // in that case just use the first of material.materials for now
  15379. // (proper solution would require to break objects by materials
  15380. // similarly to regular rendering and then set corresponding
  15381. // depth materials per each chunk instead of just once per object)
  15382. objectMaterial = getObjectMaterial( object );
  15383. useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  15384. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  15385. if ( object.customDepthMaterial ) {
  15386. material = object.customDepthMaterial;
  15387. } else if ( useSkinning ) {
  15388. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  15389. } else if ( useMorphing ) {
  15390. material = _depthMaterialMorph;
  15391. } else {
  15392. material = _depthMaterial;
  15393. }
  15394. _renderer.setMaterialFaces( objectMaterial );
  15395. if ( buffer instanceof THREE.BufferGeometry ) {
  15396. _renderer.renderBufferDirect( shadowCamera, _lights, fog, material, buffer, object );
  15397. } else {
  15398. _renderer.renderBuffer( shadowCamera, _lights, fog, material, buffer, object );
  15399. }
  15400. }
  15401. // set matrices and render immediate objects
  15402. for ( j = 0, jl = _webglObjectsImmediate.length; j < jl; j ++ ) {
  15403. webglObject = _webglObjectsImmediate[ j ];
  15404. object = webglObject.object;
  15405. if ( object.visible && object.castShadow ) {
  15406. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  15407. _renderer.renderImmediateObject( shadowCamera, _lights, fog, _depthMaterial, object );
  15408. }
  15409. }
  15410. }
  15411. // restore GL state
  15412. var clearColor = _renderer.getClearColor(),
  15413. clearAlpha = _renderer.getClearAlpha();
  15414. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  15415. _gl.enable( _gl.BLEND );
  15416. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  15417. _gl.cullFace( _gl.BACK );
  15418. }
  15419. _renderer.resetGLState();
  15420. };
  15421. function projectObject( scene, object, shadowCamera ) {
  15422. if ( object.visible ) {
  15423. var webglObjects = _webglObjects[ object.id ];
  15424. if ( webglObjects && object.castShadow && (object.frustumCulled === false || _frustum.intersectsObject( object ) === true) ) {
  15425. for ( var i = 0, l = webglObjects.length; i < l; i ++ ) {
  15426. var webglObject = webglObjects[ i ];
  15427. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  15428. _renderList.push( webglObject );
  15429. }
  15430. }
  15431. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  15432. projectObject( scene, object.children[ i ], shadowCamera );
  15433. }
  15434. }
  15435. }
  15436. function createVirtualLight( light, cascade ) {
  15437. var virtualLight = new THREE.DirectionalLight();
  15438. virtualLight.isVirtual = true;
  15439. virtualLight.onlyShadow = true;
  15440. virtualLight.castShadow = true;
  15441. virtualLight.shadowCameraNear = light.shadowCameraNear;
  15442. virtualLight.shadowCameraFar = light.shadowCameraFar;
  15443. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  15444. virtualLight.shadowCameraRight = light.shadowCameraRight;
  15445. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  15446. virtualLight.shadowCameraTop = light.shadowCameraTop;
  15447. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  15448. virtualLight.shadowDarkness = light.shadowDarkness;
  15449. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  15450. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  15451. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  15452. virtualLight.pointsWorld = [];
  15453. virtualLight.pointsFrustum = [];
  15454. var pointsWorld = virtualLight.pointsWorld,
  15455. pointsFrustum = virtualLight.pointsFrustum;
  15456. for ( var i = 0; i < 8; i ++ ) {
  15457. pointsWorld[ i ] = new THREE.Vector3();
  15458. pointsFrustum[ i ] = new THREE.Vector3();
  15459. }
  15460. var nearZ = light.shadowCascadeNearZ[ cascade ];
  15461. var farZ = light.shadowCascadeFarZ[ cascade ];
  15462. pointsFrustum[ 0 ].set( - 1, - 1, nearZ );
  15463. pointsFrustum[ 1 ].set( 1, - 1, nearZ );
  15464. pointsFrustum[ 2 ].set( - 1, 1, nearZ );
  15465. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  15466. pointsFrustum[ 4 ].set( - 1, - 1, farZ );
  15467. pointsFrustum[ 5 ].set( 1, - 1, farZ );
  15468. pointsFrustum[ 6 ].set( - 1, 1, farZ );
  15469. pointsFrustum[ 7 ].set( 1, 1, farZ );
  15470. return virtualLight;
  15471. }
  15472. // Synchronize virtual light with the original light
  15473. function updateVirtualLight( light, cascade ) {
  15474. var virtualLight = light.shadowCascadeArray[ cascade ];
  15475. virtualLight.position.copy( light.position );
  15476. virtualLight.target.position.copy( light.target.position );
  15477. virtualLight.lookAt( virtualLight.target );
  15478. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  15479. virtualLight.shadowDarkness = light.shadowDarkness;
  15480. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  15481. var nearZ = light.shadowCascadeNearZ[ cascade ];
  15482. var farZ = light.shadowCascadeFarZ[ cascade ];
  15483. var pointsFrustum = virtualLight.pointsFrustum;
  15484. pointsFrustum[ 0 ].z = nearZ;
  15485. pointsFrustum[ 1 ].z = nearZ;
  15486. pointsFrustum[ 2 ].z = nearZ;
  15487. pointsFrustum[ 3 ].z = nearZ;
  15488. pointsFrustum[ 4 ].z = farZ;
  15489. pointsFrustum[ 5 ].z = farZ;
  15490. pointsFrustum[ 6 ].z = farZ;
  15491. pointsFrustum[ 7 ].z = farZ;
  15492. }
  15493. // Fit shadow camera's ortho frustum to camera frustum
  15494. function updateShadowCamera( camera, light ) {
  15495. var shadowCamera = light.shadowCamera,
  15496. pointsFrustum = light.pointsFrustum,
  15497. pointsWorld = light.pointsWorld;
  15498. _min.set( Infinity, Infinity, Infinity );
  15499. _max.set( - Infinity, - Infinity, - Infinity );
  15500. for ( var i = 0; i < 8; i ++ ) {
  15501. var p = pointsWorld[ i ];
  15502. p.copy( pointsFrustum[ i ] );
  15503. p.unproject( camera );
  15504. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  15505. if ( p.x < _min.x ) _min.x = p.x;
  15506. if ( p.x > _max.x ) _max.x = p.x;
  15507. if ( p.y < _min.y ) _min.y = p.y;
  15508. if ( p.y > _max.y ) _max.y = p.y;
  15509. if ( p.z < _min.z ) _min.z = p.z;
  15510. if ( p.z > _max.z ) _max.z = p.z;
  15511. }
  15512. shadowCamera.left = _min.x;
  15513. shadowCamera.right = _max.x;
  15514. shadowCamera.top = _max.y;
  15515. shadowCamera.bottom = _min.y;
  15516. // can't really fit near/far
  15517. //shadowCamera.near = _min.z;
  15518. //shadowCamera.far = _max.z;
  15519. shadowCamera.updateProjectionMatrix();
  15520. }
  15521. // For the moment just ignore objects that have multiple materials with different animation methods
  15522. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  15523. function getObjectMaterial( object ) {
  15524. return object.material instanceof THREE.MeshFaceMaterial
  15525. ? object.material.materials[ 0 ]
  15526. : object.material;
  15527. };
  15528. };
  15529. // File:src/renderers/webgl/plugins/SpritePlugin.js
  15530. /**
  15531. * @author mikael emtinger / http://gomo.se/
  15532. * @author alteredq / http://alteredqualia.com/
  15533. */
  15534. THREE.SpritePlugin = function ( renderer, sprites ) {
  15535. var gl = renderer.context;
  15536. var vertexBuffer, elementBuffer;
  15537. var program, attributes, uniforms;
  15538. var texture;
  15539. // decompose matrixWorld
  15540. var spritePosition = new THREE.Vector3();
  15541. var spriteRotation = new THREE.Quaternion();
  15542. var spriteScale = new THREE.Vector3();
  15543. var init = function () {
  15544. var vertices = new Float32Array( [
  15545. - 0.5, - 0.5, 0, 0,
  15546. 0.5, - 0.5, 1, 0,
  15547. 0.5, 0.5, 1, 1,
  15548. - 0.5, 0.5, 0, 1
  15549. ] );
  15550. var faces = new Uint16Array( [
  15551. 0, 1, 2,
  15552. 0, 2, 3
  15553. ] );
  15554. vertexBuffer = gl.createBuffer();
  15555. elementBuffer = gl.createBuffer();
  15556. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  15557. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  15558. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  15559. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  15560. program = createProgram();
  15561. attributes = {
  15562. position: gl.getAttribLocation ( program, 'position' ),
  15563. uv: gl.getAttribLocation ( program, 'uv' )
  15564. };
  15565. uniforms = {
  15566. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  15567. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  15568. rotation: gl.getUniformLocation( program, 'rotation' ),
  15569. scale: gl.getUniformLocation( program, 'scale' ),
  15570. color: gl.getUniformLocation( program, 'color' ),
  15571. map: gl.getUniformLocation( program, 'map' ),
  15572. opacity: gl.getUniformLocation( program, 'opacity' ),
  15573. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  15574. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  15575. fogType: gl.getUniformLocation( program, 'fogType' ),
  15576. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  15577. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  15578. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  15579. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  15580. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  15581. };
  15582. var canvas = document.createElement( 'canvas' );
  15583. canvas.width = 8;
  15584. canvas.height = 8;
  15585. var context = canvas.getContext( '2d' );
  15586. context.fillStyle = 'white';
  15587. context.fillRect( 0, 0, 8, 8 );
  15588. texture = new THREE.Texture( canvas );
  15589. texture.needsUpdate = true;
  15590. };
  15591. this.render = function ( scene, camera ) {
  15592. if ( sprites.length === 0 ) return;
  15593. // setup gl
  15594. if ( program === undefined ) {
  15595. init();
  15596. }
  15597. gl.useProgram( program );
  15598. gl.enableVertexAttribArray( attributes.position );
  15599. gl.enableVertexAttribArray( attributes.uv );
  15600. gl.disable( gl.CULL_FACE );
  15601. gl.enable( gl.BLEND );
  15602. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  15603. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  15604. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  15605. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  15606. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  15607. gl.activeTexture( gl.TEXTURE0 );
  15608. gl.uniform1i( uniforms.map, 0 );
  15609. var oldFogType = 0;
  15610. var sceneFogType = 0;
  15611. var fog = scene.fog;
  15612. if ( fog ) {
  15613. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  15614. if ( fog instanceof THREE.Fog ) {
  15615. gl.uniform1f( uniforms.fogNear, fog.near );
  15616. gl.uniform1f( uniforms.fogFar, fog.far );
  15617. gl.uniform1i( uniforms.fogType, 1 );
  15618. oldFogType = 1;
  15619. sceneFogType = 1;
  15620. } else if ( fog instanceof THREE.FogExp2 ) {
  15621. gl.uniform1f( uniforms.fogDensity, fog.density );
  15622. gl.uniform1i( uniforms.fogType, 2 );
  15623. oldFogType = 2;
  15624. sceneFogType = 2;
  15625. }
  15626. } else {
  15627. gl.uniform1i( uniforms.fogType, 0 );
  15628. oldFogType = 0;
  15629. sceneFogType = 0;
  15630. }
  15631. // update positions and sort
  15632. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  15633. var sprite = sprites[ i ];
  15634. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  15635. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  15636. }
  15637. sprites.sort( painterSortStable );
  15638. // render all sprites
  15639. var scale = [];
  15640. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  15641. var sprite = sprites[ i ];
  15642. var material = sprite.material;
  15643. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  15644. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  15645. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  15646. scale[ 0 ] = spriteScale.x;
  15647. scale[ 1 ] = spriteScale.y;
  15648. var fogType = 0;
  15649. if ( scene.fog && material.fog ) {
  15650. fogType = sceneFogType;
  15651. }
  15652. if ( oldFogType !== fogType ) {
  15653. gl.uniform1i( uniforms.fogType, fogType );
  15654. oldFogType = fogType;
  15655. }
  15656. if ( material.map !== null ) {
  15657. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  15658. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  15659. } else {
  15660. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  15661. gl.uniform2f( uniforms.uvScale, 1, 1 );
  15662. }
  15663. gl.uniform1f( uniforms.opacity, material.opacity );
  15664. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  15665. gl.uniform1f( uniforms.rotation, material.rotation );
  15666. gl.uniform2fv( uniforms.scale, scale );
  15667. renderer.state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  15668. renderer.state.setDepthTest( material.depthTest );
  15669. renderer.state.setDepthWrite( material.depthWrite );
  15670. if ( material.map && material.map.image && material.map.image.width ) {
  15671. renderer.setTexture( material.map, 0 );
  15672. } else {
  15673. renderer.setTexture( texture, 0 );
  15674. }
  15675. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  15676. }
  15677. // restore gl
  15678. gl.enable( gl.CULL_FACE );
  15679. renderer.resetGLState();
  15680. };
  15681. function createProgram () {
  15682. var program = gl.createProgram();
  15683. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  15684. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  15685. gl.shaderSource( vertexShader, [
  15686. 'precision ' + renderer.getPrecision() + ' float;',
  15687. 'uniform mat4 modelViewMatrix;',
  15688. 'uniform mat4 projectionMatrix;',
  15689. 'uniform float rotation;',
  15690. 'uniform vec2 scale;',
  15691. 'uniform vec2 uvOffset;',
  15692. 'uniform vec2 uvScale;',
  15693. 'attribute vec2 position;',
  15694. 'attribute vec2 uv;',
  15695. 'varying vec2 vUV;',
  15696. 'void main() {',
  15697. 'vUV = uvOffset + uv * uvScale;',
  15698. 'vec2 alignedPosition = position * scale;',
  15699. 'vec2 rotatedPosition;',
  15700. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  15701. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  15702. 'vec4 finalPosition;',
  15703. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  15704. 'finalPosition.xy += rotatedPosition;',
  15705. 'finalPosition = projectionMatrix * finalPosition;',
  15706. 'gl_Position = finalPosition;',
  15707. '}'
  15708. ].join( '\n' ) );
  15709. gl.shaderSource( fragmentShader, [
  15710. 'precision ' + renderer.getPrecision() + ' float;',
  15711. 'uniform vec3 color;',
  15712. 'uniform sampler2D map;',
  15713. 'uniform float opacity;',
  15714. 'uniform int fogType;',
  15715. 'uniform vec3 fogColor;',
  15716. 'uniform float fogDensity;',
  15717. 'uniform float fogNear;',
  15718. 'uniform float fogFar;',
  15719. 'uniform float alphaTest;',
  15720. 'varying vec2 vUV;',
  15721. 'void main() {',
  15722. 'vec4 texture = texture2D( map, vUV );',
  15723. 'if ( texture.a < alphaTest ) discard;',
  15724. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  15725. 'if ( fogType > 0 ) {',
  15726. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  15727. 'float fogFactor = 0.0;',
  15728. 'if ( fogType == 1 ) {',
  15729. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  15730. '} else {',
  15731. 'const float LOG2 = 1.442695;',
  15732. 'float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  15733. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  15734. '}',
  15735. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  15736. '}',
  15737. '}'
  15738. ].join( '\n' ) );
  15739. gl.compileShader( vertexShader );
  15740. gl.compileShader( fragmentShader );
  15741. gl.attachShader( program, vertexShader );
  15742. gl.attachShader( program, fragmentShader );
  15743. gl.linkProgram( program );
  15744. return program;
  15745. };
  15746. function painterSortStable ( a, b ) {
  15747. if ( a.z !== b.z ) {
  15748. return b.z - a.z;
  15749. } else {
  15750. return b.id - a.id;
  15751. }
  15752. };
  15753. };
  15754. // File:src/extras/GeometryUtils.js
  15755. /**
  15756. * @author mrdoob / http://mrdoob.com/
  15757. */
  15758. THREE.GeometryUtils = {
  15759. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  15760. THREE.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  15761. var matrix;
  15762. if ( geometry2 instanceof THREE.Mesh ) {
  15763. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  15764. matrix = geometry2.matrix;
  15765. geometry2 = geometry2.geometry;
  15766. }
  15767. geometry1.merge( geometry2, matrix, materialIndexOffset );
  15768. },
  15769. center: function ( geometry ) {
  15770. THREE.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  15771. return geometry.center();
  15772. }
  15773. };
  15774. // File:src/extras/ImageUtils.js
  15775. /**
  15776. * @author alteredq / http://alteredqualia.com/
  15777. * @author mrdoob / http://mrdoob.com/
  15778. * @author Daosheng Mu / https://github.com/DaoshengMu/
  15779. */
  15780. THREE.ImageUtils = {
  15781. crossOrigin: undefined,
  15782. loadTexture: function ( url, mapping, onLoad, onError ) {
  15783. var loader = new THREE.ImageLoader();
  15784. loader.crossOrigin = this.crossOrigin;
  15785. var texture = new THREE.Texture( undefined, mapping );
  15786. loader.load( url, function ( image ) {
  15787. texture.image = image;
  15788. texture.needsUpdate = true;
  15789. if ( onLoad ) onLoad( texture );
  15790. }, undefined, function ( event ) {
  15791. if ( onError ) onError( event );
  15792. } );
  15793. texture.sourceFile = url;
  15794. return texture;
  15795. },
  15796. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15797. var images = [];
  15798. var loader = new THREE.ImageLoader();
  15799. loader.crossOrigin = this.crossOrigin;
  15800. var texture = new THREE.CubeTexture( images, mapping );
  15801. // no flipping needed for cube textures
  15802. texture.flipY = false;
  15803. var loaded = 0;
  15804. var loadTexture = function ( i ) {
  15805. loader.load( array[ i ], function ( image ) {
  15806. texture.images[ i ] = image;
  15807. loaded += 1;
  15808. if ( loaded === 6 ) {
  15809. texture.needsUpdate = true;
  15810. if ( onLoad ) onLoad( texture );
  15811. }
  15812. }, undefined, onError );
  15813. }
  15814. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15815. loadTexture( i );
  15816. }
  15817. return texture;
  15818. },
  15819. loadCompressedTexture: function () {
  15820. THREE.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' )
  15821. },
  15822. loadCompressedTextureCube: function () {
  15823. THREE.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' )
  15824. },
  15825. getNormalMap: function ( image, depth ) {
  15826. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  15827. var cross = function ( a, b ) {
  15828. 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 ] ];
  15829. }
  15830. var subtract = function ( a, b ) {
  15831. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  15832. }
  15833. var normalize = function ( a ) {
  15834. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  15835. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  15836. }
  15837. depth = depth | 1;
  15838. var width = image.width;
  15839. var height = image.height;
  15840. var canvas = document.createElement( 'canvas' );
  15841. canvas.width = width;
  15842. canvas.height = height;
  15843. var context = canvas.getContext( '2d' );
  15844. context.drawImage( image, 0, 0 );
  15845. var data = context.getImageData( 0, 0, width, height ).data;
  15846. var imageData = context.createImageData( width, height );
  15847. var output = imageData.data;
  15848. for ( var x = 0; x < width; x ++ ) {
  15849. for ( var y = 0; y < height; y ++ ) {
  15850. var ly = y - 1 < 0 ? 0 : y - 1;
  15851. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  15852. var lx = x - 1 < 0 ? 0 : x - 1;
  15853. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  15854. var points = [];
  15855. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  15856. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  15857. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  15858. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  15859. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  15860. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  15861. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  15862. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  15863. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  15864. var normals = [];
  15865. var num_points = points.length;
  15866. for ( var i = 0; i < num_points; i ++ ) {
  15867. var v1 = points[ i ];
  15868. var v2 = points[ ( i + 1 ) % num_points ];
  15869. v1 = subtract( v1, origin );
  15870. v2 = subtract( v2, origin );
  15871. normals.push( normalize( cross( v1, v2 ) ) );
  15872. }
  15873. var normal = [ 0, 0, 0 ];
  15874. for ( var i = 0; i < normals.length; i ++ ) {
  15875. normal[ 0 ] += normals[ i ][ 0 ];
  15876. normal[ 1 ] += normals[ i ][ 1 ];
  15877. normal[ 2 ] += normals[ i ][ 2 ];
  15878. }
  15879. normal[ 0 ] /= normals.length;
  15880. normal[ 1 ] /= normals.length;
  15881. normal[ 2 ] /= normals.length;
  15882. var idx = ( y * width + x ) * 4;
  15883. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15884. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15885. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  15886. output[ idx + 3 ] = 255;
  15887. }
  15888. }
  15889. context.putImageData( imageData, 0, 0 );
  15890. return canvas;
  15891. },
  15892. generateDataTexture: function ( width, height, color ) {
  15893. var size = width * height;
  15894. var data = new Uint8Array( 3 * size );
  15895. var r = Math.floor( color.r * 255 );
  15896. var g = Math.floor( color.g * 255 );
  15897. var b = Math.floor( color.b * 255 );
  15898. for ( var i = 0; i < size; i ++ ) {
  15899. data[ i * 3 ] = r;
  15900. data[ i * 3 + 1 ] = g;
  15901. data[ i * 3 + 2 ] = b;
  15902. }
  15903. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  15904. texture.needsUpdate = true;
  15905. return texture;
  15906. }
  15907. };
  15908. // File:src/extras/SceneUtils.js
  15909. /**
  15910. * @author alteredq / http://alteredqualia.com/
  15911. */
  15912. THREE.SceneUtils = {
  15913. createMultiMaterialObject: function ( geometry, materials ) {
  15914. var group = new THREE.Object3D();
  15915. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  15916. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  15917. }
  15918. return group;
  15919. },
  15920. detach: function ( child, parent, scene ) {
  15921. child.applyMatrix( parent.matrixWorld );
  15922. parent.remove( child );
  15923. scene.add( child );
  15924. },
  15925. attach: function ( child, scene, parent ) {
  15926. var matrixWorldInverse = new THREE.Matrix4();
  15927. matrixWorldInverse.getInverse( parent.matrixWorld );
  15928. child.applyMatrix( matrixWorldInverse );
  15929. scene.remove( child );
  15930. parent.add( child );
  15931. }
  15932. };
  15933. // File:src/extras/FontUtils.js
  15934. /**
  15935. * @author zz85 / http://www.lab4games.net/zz85/blog
  15936. * @author alteredq / http://alteredqualia.com/
  15937. *
  15938. * For Text operations in three.js (See TextGeometry)
  15939. *
  15940. * It uses techniques used in:
  15941. *
  15942. * typeface.js and canvastext
  15943. * For converting fonts and rendering with javascript
  15944. * http://typeface.neocracy.org
  15945. *
  15946. * Triangulation ported from AS3
  15947. * Simple Polygon Triangulation
  15948. * http://actionsnippet.com/?p=1462
  15949. *
  15950. * A Method to triangulate shapes with holes
  15951. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  15952. *
  15953. */
  15954. THREE.FontUtils = {
  15955. faces: {},
  15956. // Just for now. face[weight][style]
  15957. face: 'helvetiker',
  15958. weight: 'normal',
  15959. style: 'normal',
  15960. size: 150,
  15961. divisions: 10,
  15962. getFace: function () {
  15963. try {
  15964. return this.faces[ this.face ][ this.weight ][ this.style ];
  15965. } catch (e) {
  15966. throw "The font " + this.face + " with " + this.weight + " weight and " + this.style + " style is missing."
  15967. };
  15968. },
  15969. loadFace: function ( data ) {
  15970. var family = data.familyName.toLowerCase();
  15971. var ThreeFont = this;
  15972. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  15973. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  15974. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15975. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15976. return data;
  15977. },
  15978. drawText: function ( text ) {
  15979. // RenderText
  15980. var i,
  15981. face = this.getFace(),
  15982. scale = this.size / face.resolution,
  15983. offset = 0,
  15984. chars = String( text ).split( '' ),
  15985. length = chars.length;
  15986. var fontPaths = [];
  15987. for ( i = 0; i < length; i ++ ) {
  15988. var path = new THREE.Path();
  15989. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  15990. offset += ret.offset;
  15991. fontPaths.push( ret.path );
  15992. }
  15993. // get the width
  15994. var width = offset / 2;
  15995. //
  15996. // for ( p = 0; p < allPts.length; p++ ) {
  15997. //
  15998. // allPts[ p ].x -= width;
  15999. //
  16000. // }
  16001. //var extract = this.extractPoints( allPts, characterPts );
  16002. //extract.contour = allPts;
  16003. //extract.paths = fontPaths;
  16004. //extract.offset = width;
  16005. return { paths: fontPaths, offset: width };
  16006. },
  16007. extractGlyphPoints: function ( c, face, scale, offset, path ) {
  16008. var pts = [];
  16009. var i, i2, divisions,
  16010. outline, action, length,
  16011. scaleX, scaleY,
  16012. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16013. laste,
  16014. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16015. if ( ! glyph ) return;
  16016. if ( glyph.o ) {
  16017. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16018. length = outline.length;
  16019. scaleX = scale;
  16020. scaleY = scale;
  16021. for ( i = 0; i < length; ) {
  16022. action = outline[ i ++ ];
  16023. //THREE.log( action );
  16024. switch ( action ) {
  16025. case 'm':
  16026. // Move To
  16027. x = outline[ i ++ ] * scaleX + offset;
  16028. y = outline[ i ++ ] * scaleY;
  16029. path.moveTo( x, y );
  16030. break;
  16031. case 'l':
  16032. // Line To
  16033. x = outline[ i ++ ] * scaleX + offset;
  16034. y = outline[ i ++ ] * scaleY;
  16035. path.lineTo( x, y );
  16036. break;
  16037. case 'q':
  16038. // QuadraticCurveTo
  16039. cpx = outline[ i ++ ] * scaleX + offset;
  16040. cpy = outline[ i ++ ] * scaleY;
  16041. cpx1 = outline[ i ++ ] * scaleX + offset;
  16042. cpy1 = outline[ i ++ ] * scaleY;
  16043. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  16044. laste = pts[ pts.length - 1 ];
  16045. if ( laste ) {
  16046. cpx0 = laste.x;
  16047. cpy0 = laste.y;
  16048. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16049. var t = i2 / divisions;
  16050. THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16051. THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16052. }
  16053. }
  16054. break;
  16055. case 'b':
  16056. // Cubic Bezier Curve
  16057. cpx = outline[ i ++ ] * scaleX + offset;
  16058. cpy = outline[ i ++ ] * scaleY;
  16059. cpx1 = outline[ i ++ ] * scaleX + offset;
  16060. cpy1 = outline[ i ++ ] * scaleY;
  16061. cpx2 = outline[ i ++ ] * scaleX + offset;
  16062. cpy2 = outline[ i ++ ] * scaleY;
  16063. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  16064. laste = pts[ pts.length - 1 ];
  16065. if ( laste ) {
  16066. cpx0 = laste.x;
  16067. cpy0 = laste.y;
  16068. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16069. var t = i2 / divisions;
  16070. THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16071. THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16072. }
  16073. }
  16074. break;
  16075. }
  16076. }
  16077. }
  16078. return { offset: glyph.ha * scale, path:path };
  16079. }
  16080. };
  16081. THREE.FontUtils.generateShapes = function ( text, parameters ) {
  16082. // Parameters
  16083. parameters = parameters || {};
  16084. var size = parameters.size !== undefined ? parameters.size : 100;
  16085. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments : 4;
  16086. var font = parameters.font !== undefined ? parameters.font : 'helvetiker';
  16087. var weight = parameters.weight !== undefined ? parameters.weight : 'normal';
  16088. var style = parameters.style !== undefined ? parameters.style : 'normal';
  16089. THREE.FontUtils.size = size;
  16090. THREE.FontUtils.divisions = curveSegments;
  16091. THREE.FontUtils.face = font;
  16092. THREE.FontUtils.weight = weight;
  16093. THREE.FontUtils.style = style;
  16094. // Get a Font data json object
  16095. var data = THREE.FontUtils.drawText( text );
  16096. var paths = data.paths;
  16097. var shapes = [];
  16098. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16099. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16100. }
  16101. return shapes;
  16102. };
  16103. /**
  16104. * This code is a quick port of code written in C++ which was submitted to
  16105. * flipcode.com by John W. Ratcliff // July 22, 2000
  16106. * See original code and more information here:
  16107. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16108. *
  16109. * ported to actionscript by Zevan Rosser
  16110. * www.actionsnippet.com
  16111. *
  16112. * ported to javascript by Joshua Koo
  16113. * http://www.lab4games.net/zz85/blog
  16114. *
  16115. */
  16116. ( function ( namespace ) {
  16117. var EPSILON = 0.0000000001;
  16118. // takes in an contour array and returns
  16119. var process = function ( contour, indices ) {
  16120. var n = contour.length;
  16121. if ( n < 3 ) return null;
  16122. var result = [],
  16123. verts = [],
  16124. vertIndices = [];
  16125. /* we want a counter-clockwise polygon in verts */
  16126. var u, v, w;
  16127. if ( area( contour ) > 0.0 ) {
  16128. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  16129. } else {
  16130. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  16131. }
  16132. var nv = n;
  16133. /* remove nv - 2 vertices, creating 1 triangle every time */
  16134. var count = 2 * nv; /* error detection */
  16135. for ( v = nv - 1; nv > 2; ) {
  16136. /* if we loop, it is probably a non-simple polygon */
  16137. if ( ( count -- ) <= 0 ) {
  16138. //** Triangulate: ERROR - probable bad polygon!
  16139. //throw ( "Warning, unable to triangulate polygon!" );
  16140. //return null;
  16141. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16142. THREE.warn( 'THREE.FontUtils: Warning, unable to triangulate polygon! in Triangulate.process()' );
  16143. if ( indices ) return vertIndices;
  16144. return result;
  16145. }
  16146. /* three consecutive vertices in current polygon, <u,v,w> */
  16147. u = v; if ( nv <= u ) u = 0; /* previous */
  16148. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16149. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16150. if ( snip( contour, u, v, w, nv, verts ) ) {
  16151. var a, b, c, s, t;
  16152. /* true names of the vertices */
  16153. a = verts[ u ];
  16154. b = verts[ v ];
  16155. c = verts[ w ];
  16156. /* output Triangle */
  16157. result.push( [ contour[ a ],
  16158. contour[ b ],
  16159. contour[ c ] ] );
  16160. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16161. /* remove v from the remaining polygon */
  16162. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  16163. verts[ s ] = verts[ t ];
  16164. }
  16165. nv --;
  16166. /* reset error detection counter */
  16167. count = 2 * nv;
  16168. }
  16169. }
  16170. if ( indices ) return vertIndices;
  16171. return result;
  16172. };
  16173. // calculate area of the contour polygon
  16174. var area = function ( contour ) {
  16175. var n = contour.length;
  16176. var a = 0.0;
  16177. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  16178. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16179. }
  16180. return a * 0.5;
  16181. };
  16182. var snip = function ( contour, u, v, w, n, verts ) {
  16183. var p;
  16184. var ax, ay, bx, by;
  16185. var cx, cy, px, py;
  16186. ax = contour[ verts[ u ] ].x;
  16187. ay = contour[ verts[ u ] ].y;
  16188. bx = contour[ verts[ v ] ].x;
  16189. by = contour[ verts[ v ] ].y;
  16190. cx = contour[ verts[ w ] ].x;
  16191. cy = contour[ verts[ w ] ].y;
  16192. if ( EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false;
  16193. var aX, aY, bX, bY, cX, cY;
  16194. var apx, apy, bpx, bpy, cpx, cpy;
  16195. var cCROSSap, bCROSScp, aCROSSbp;
  16196. aX = cx - bx; aY = cy - by;
  16197. bX = ax - cx; bY = ay - cy;
  16198. cX = bx - ax; cY = by - ay;
  16199. for ( p = 0; p < n; p ++ ) {
  16200. px = contour[ verts[ p ] ].x
  16201. py = contour[ verts[ p ] ].y
  16202. if ( ( ( px === ax ) && ( py === ay ) ) ||
  16203. ( ( px === bx ) && ( py === by ) ) ||
  16204. ( ( px === cx ) && ( py === cy ) ) ) continue;
  16205. apx = px - ax; apy = py - ay;
  16206. bpx = px - bx; bpy = py - by;
  16207. cpx = px - cx; cpy = py - cy;
  16208. // see if p is inside triangle abc
  16209. aCROSSbp = aX * bpy - aY * bpx;
  16210. cCROSSap = cX * apy - cY * apx;
  16211. bCROSScp = bX * cpy - bY * cpx;
  16212. if ( ( aCROSSbp >= - EPSILON ) && ( bCROSScp >= - EPSILON ) && ( cCROSSap >= - EPSILON ) ) return false;
  16213. }
  16214. return true;
  16215. };
  16216. namespace.Triangulate = process;
  16217. namespace.Triangulate.area = area;
  16218. return namespace;
  16219. } )( THREE.FontUtils );
  16220. // To use the typeface.js face files, hook up the API
  16221. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  16222. THREE.typeface_js = self._typeface_js;
  16223. // File:src/extras/audio/Audio.js
  16224. /**
  16225. * @author mrdoob / http://mrdoob.com/
  16226. */
  16227. THREE.Audio = function ( listener ) {
  16228. THREE.Object3D.call( this );
  16229. this.type = 'Audio';
  16230. this.context = listener.context;
  16231. this.source = this.context.createBufferSource();
  16232. this.source.onended = this.onEnded.bind(this);
  16233. this.gain = this.context.createGain();
  16234. this.gain.connect( this.context.destination );
  16235. this.panner = this.context.createPanner();
  16236. this.panner.connect( this.gain );
  16237. this.autoplay = false;
  16238. this.startTime = 0;
  16239. this.isPlaying = false;
  16240. };
  16241. THREE.Audio.prototype = Object.create( THREE.Object3D.prototype );
  16242. THREE.Audio.prototype.constructor = THREE.Audio;
  16243. THREE.Audio.prototype.load = function ( file ) {
  16244. var scope = this;
  16245. var request = new XMLHttpRequest();
  16246. request.open( 'GET', file, true );
  16247. request.responseType = 'arraybuffer';
  16248. request.onload = function ( e ) {
  16249. scope.context.decodeAudioData( this.response, function ( buffer ) {
  16250. scope.source.buffer = buffer;
  16251. if( scope.autoplay ) scope.play();
  16252. } );
  16253. };
  16254. request.send();
  16255. return this;
  16256. };
  16257. THREE.Audio.prototype.play = function () {
  16258. if ( this.isPlaying === true ) {
  16259. THREE.warn( 'THREE.Audio: Audio is already playing.' );
  16260. return;
  16261. }
  16262. var source = this.context.createBufferSource();
  16263. source.buffer = this.source.buffer;
  16264. source.loop = this.source.loop;
  16265. source.onended = this.source.onended;
  16266. source.connect( this.panner );
  16267. source.start( 0, this.startTime );
  16268. this.isPlaying = true;
  16269. this.source = source;
  16270. };
  16271. THREE.Audio.prototype.pause = function () {
  16272. this.source.stop();
  16273. this.startTime = this.context.currentTime;
  16274. };
  16275. THREE.Audio.prototype.stop = function () {
  16276. this.source.stop();
  16277. this.startTime = 0;
  16278. };
  16279. THREE.Audio.prototype.onEnded = function() {
  16280. this.isPlaying = false;
  16281. };
  16282. THREE.Audio.prototype.setLoop = function ( value ) {
  16283. this.source.loop = value;
  16284. };
  16285. THREE.Audio.prototype.setRefDistance = function ( value ) {
  16286. this.panner.refDistance = value;
  16287. };
  16288. THREE.Audio.prototype.setRolloffFactor = function ( value ) {
  16289. this.panner.rolloffFactor = value;
  16290. };
  16291. THREE.Audio.prototype.setVolume = function ( value ) {
  16292. this.gain.gain.value = value;
  16293. };
  16294. THREE.Audio.prototype.updateMatrixWorld = ( function () {
  16295. var position = new THREE.Vector3();
  16296. return function ( force ) {
  16297. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  16298. position.setFromMatrixPosition( this.matrixWorld );
  16299. this.panner.setPosition( position.x, position.y, position.z );
  16300. };
  16301. } )();
  16302. // File:src/extras/audio/AudioListener.js
  16303. /**
  16304. * @author mrdoob / http://mrdoob.com/
  16305. */
  16306. THREE.AudioListener = function () {
  16307. THREE.Object3D.call( this );
  16308. this.type = 'AudioListener';
  16309. this.context = new ( window.AudioContext || window.webkitAudioContext )();
  16310. };
  16311. THREE.AudioListener.prototype = Object.create( THREE.Object3D.prototype );
  16312. THREE.AudioListener.prototype.constructor = THREE.AudioListener;
  16313. THREE.AudioListener.prototype.updateMatrixWorld = ( function () {
  16314. var position = new THREE.Vector3();
  16315. var quaternion = new THREE.Quaternion();
  16316. var scale = new THREE.Vector3();
  16317. var orientation = new THREE.Vector3();
  16318. return function ( force ) {
  16319. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  16320. var listener = this.context.listener;
  16321. var up = this.up;
  16322. this.matrixWorld.decompose( position, quaternion, scale );
  16323. orientation.set( 0, 0, -1 ).applyQuaternion( quaternion );
  16324. listener.setPosition( position.x, position.y, position.z );
  16325. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  16326. };
  16327. } )();
  16328. // File:src/extras/core/Curve.js
  16329. /**
  16330. * @author zz85 / http://www.lab4games.net/zz85/blog
  16331. * Extensible curve object
  16332. *
  16333. * Some common of Curve methods
  16334. * .getPoint(t), getTangent(t)
  16335. * .getPointAt(u), getTagentAt(u)
  16336. * .getPoints(), .getSpacedPoints()
  16337. * .getLength()
  16338. * .updateArcLengths()
  16339. *
  16340. * This following classes subclasses THREE.Curve:
  16341. *
  16342. * -- 2d classes --
  16343. * THREE.LineCurve
  16344. * THREE.QuadraticBezierCurve
  16345. * THREE.CubicBezierCurve
  16346. * THREE.SplineCurve
  16347. * THREE.ArcCurve
  16348. * THREE.EllipseCurve
  16349. *
  16350. * -- 3d classes --
  16351. * THREE.LineCurve3
  16352. * THREE.QuadraticBezierCurve3
  16353. * THREE.CubicBezierCurve3
  16354. * THREE.SplineCurve3
  16355. * THREE.ClosedSplineCurve3
  16356. *
  16357. * A series of curves can be represented as a THREE.CurvePath
  16358. *
  16359. **/
  16360. /**************************************************************
  16361. * Abstract Curve base class
  16362. **************************************************************/
  16363. THREE.Curve = function () {
  16364. };
  16365. // Virtual base class method to overwrite and implement in subclasses
  16366. // - t [0 .. 1]
  16367. THREE.Curve.prototype.getPoint = function ( t ) {
  16368. THREE.warn( "THREE.Curve: Warning, getPoint() not implemented!" );
  16369. return null;
  16370. };
  16371. // Get point at relative position in curve according to arc length
  16372. // - u [0 .. 1]
  16373. THREE.Curve.prototype.getPointAt = function ( u ) {
  16374. var t = this.getUtoTmapping( u );
  16375. return this.getPoint( t );
  16376. };
  16377. // Get sequence of points using getPoint( t )
  16378. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16379. if ( ! divisions ) divisions = 5;
  16380. var d, pts = [];
  16381. for ( d = 0; d <= divisions; d ++ ) {
  16382. pts.push( this.getPoint( d / divisions ) );
  16383. }
  16384. return pts;
  16385. };
  16386. // Get sequence of points using getPointAt( u )
  16387. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16388. if ( ! divisions ) divisions = 5;
  16389. var d, pts = [];
  16390. for ( d = 0; d <= divisions; d ++ ) {
  16391. pts.push( this.getPointAt( d / divisions ) );
  16392. }
  16393. return pts;
  16394. };
  16395. // Get total curve arc length
  16396. THREE.Curve.prototype.getLength = function () {
  16397. var lengths = this.getLengths();
  16398. return lengths[ lengths.length - 1 ];
  16399. };
  16400. // Get list of cumulative segment lengths
  16401. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16402. if ( ! divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions) : 200;
  16403. if ( this.cacheArcLengths
  16404. && ( this.cacheArcLengths.length == divisions + 1 )
  16405. && ! this.needsUpdate) {
  16406. //THREE.log( "cached", this.cacheArcLengths );
  16407. return this.cacheArcLengths;
  16408. }
  16409. this.needsUpdate = false;
  16410. var cache = [];
  16411. var current, last = this.getPoint( 0 );
  16412. var p, sum = 0;
  16413. cache.push( 0 );
  16414. for ( p = 1; p <= divisions; p ++ ) {
  16415. current = this.getPoint ( p / divisions );
  16416. sum += current.distanceTo( last );
  16417. cache.push( sum );
  16418. last = current;
  16419. }
  16420. this.cacheArcLengths = cache;
  16421. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16422. };
  16423. THREE.Curve.prototype.updateArcLengths = function() {
  16424. this.needsUpdate = true;
  16425. this.getLengths();
  16426. };
  16427. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16428. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16429. var arcLengths = this.getLengths();
  16430. var i = 0, il = arcLengths.length;
  16431. var targetArcLength; // The targeted u distance value to get
  16432. if ( distance ) {
  16433. targetArcLength = distance;
  16434. } else {
  16435. targetArcLength = u * arcLengths[ il - 1 ];
  16436. }
  16437. //var time = Date.now();
  16438. // binary search for the index with largest value smaller than target u distance
  16439. var low = 0, high = il - 1, comparison;
  16440. while ( low <= high ) {
  16441. 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
  16442. comparison = arcLengths[ i ] - targetArcLength;
  16443. if ( comparison < 0 ) {
  16444. low = i + 1;
  16445. } else if ( comparison > 0 ) {
  16446. high = i - 1;
  16447. } else {
  16448. high = i;
  16449. break;
  16450. // DONE
  16451. }
  16452. }
  16453. i = high;
  16454. //THREE.log('b' , i, low, high, Date.now()- time);
  16455. if ( arcLengths[ i ] == targetArcLength ) {
  16456. var t = i / ( il - 1 );
  16457. return t;
  16458. }
  16459. // we could get finer grain at lengths, or use simple interpolatation between two points
  16460. var lengthBefore = arcLengths[ i ];
  16461. var lengthAfter = arcLengths[ i + 1 ];
  16462. var segmentLength = lengthAfter - lengthBefore;
  16463. // determine where we are between the 'before' and 'after' points
  16464. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16465. // add that fractional amount to t
  16466. var t = ( i + segmentFraction ) / ( il - 1 );
  16467. return t;
  16468. };
  16469. // Returns a unit vector tangent at t
  16470. // In case any sub curve does not implement its tangent derivation,
  16471. // 2 points a small delta apart will be used to find its gradient
  16472. // which seems to give a reasonable approximation
  16473. THREE.Curve.prototype.getTangent = function( t ) {
  16474. var delta = 0.0001;
  16475. var t1 = t - delta;
  16476. var t2 = t + delta;
  16477. // Capping in case of danger
  16478. if ( t1 < 0 ) t1 = 0;
  16479. if ( t2 > 1 ) t2 = 1;
  16480. var pt1 = this.getPoint( t1 );
  16481. var pt2 = this.getPoint( t2 );
  16482. var vec = pt2.clone().sub(pt1);
  16483. return vec.normalize();
  16484. };
  16485. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16486. var t = this.getUtoTmapping( u );
  16487. return this.getTangent( t );
  16488. };
  16489. /**************************************************************
  16490. * Utils
  16491. **************************************************************/
  16492. THREE.Curve.Utils = {
  16493. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16494. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16495. },
  16496. // Puay Bing, thanks for helping with this derivative!
  16497. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16498. return - 3 * p0 * (1 - t) * (1 - t) +
  16499. 3 * p1 * (1 - t) * (1 - t) - 6 * t * p1 * (1 - t) +
  16500. 6 * t * p2 * (1 - t) - 3 * t * t * p2 +
  16501. 3 * t * t * p3;
  16502. },
  16503. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16504. // To check if my formulas are correct
  16505. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16506. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16507. var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2
  16508. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16509. return h00 + h10 + h01 + h11;
  16510. },
  16511. // Catmull-Rom
  16512. interpolate: function( p0, p1, p2, p3, t ) {
  16513. var v0 = ( p2 - p0 ) * 0.5;
  16514. var v1 = ( p3 - p1 ) * 0.5;
  16515. var t2 = t * t;
  16516. var t3 = t * t2;
  16517. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16518. }
  16519. };
  16520. // TODO: Transformation for Curves?
  16521. /**************************************************************
  16522. * 3D Curves
  16523. **************************************************************/
  16524. // A Factory method for creating new curve subclasses
  16525. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16526. constructor.prototype = Object.create( THREE.Curve.prototype );
  16527. constructor.prototype.constructor = constructor;
  16528. constructor.prototype.getPoint = getPointFunc;
  16529. return constructor;
  16530. };
  16531. // File:src/extras/core/CurvePath.js
  16532. /**
  16533. * @author zz85 / http://www.lab4games.net/zz85/blog
  16534. *
  16535. **/
  16536. /**************************************************************
  16537. * Curved Path - a curve path is simply a array of connected
  16538. * curves, but retains the api of a curve
  16539. **************************************************************/
  16540. THREE.CurvePath = function () {
  16541. this.curves = [];
  16542. this.bends = [];
  16543. this.autoClose = false; // Automatically closes the path
  16544. };
  16545. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16546. THREE.CurvePath.prototype.constructor = THREE.CurvePath;
  16547. THREE.CurvePath.prototype.add = function ( curve ) {
  16548. this.curves.push( curve );
  16549. };
  16550. THREE.CurvePath.prototype.checkConnection = function() {
  16551. // TODO
  16552. // If the ending of curve is not connected to the starting
  16553. // or the next curve, then, this is not a real path
  16554. };
  16555. THREE.CurvePath.prototype.closePath = function() {
  16556. // TODO Test
  16557. // and verify for vector3 (needs to implement equals)
  16558. // Add a line curve if start and end of lines are not connected
  16559. var startPoint = this.curves[0].getPoint(0);
  16560. var endPoint = this.curves[this.curves.length - 1].getPoint(1);
  16561. if (! startPoint.equals(endPoint)) {
  16562. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16563. }
  16564. };
  16565. // To get accurate point with reference to
  16566. // entire path distance at time t,
  16567. // following has to be done:
  16568. // 1. Length of each sub path have to be known
  16569. // 2. Locate and identify type of curve
  16570. // 3. Get t for the curve
  16571. // 4. Return curve.getPointAt(t')
  16572. THREE.CurvePath.prototype.getPoint = function( t ) {
  16573. var d = t * this.getLength();
  16574. var curveLengths = this.getCurveLengths();
  16575. var i = 0, diff, curve;
  16576. // To think about boundaries points.
  16577. while ( i < curveLengths.length ) {
  16578. if ( curveLengths[ i ] >= d ) {
  16579. diff = curveLengths[ i ] - d;
  16580. curve = this.curves[ i ];
  16581. var u = 1 - diff / curve.getLength();
  16582. return curve.getPointAt( u );
  16583. }
  16584. i ++;
  16585. }
  16586. return null;
  16587. // loop where sum != 0, sum > d , sum+1 <d
  16588. };
  16589. /*
  16590. THREE.CurvePath.prototype.getTangent = function( t ) {
  16591. };*/
  16592. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16593. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16594. // getPoint() depends on getLength
  16595. THREE.CurvePath.prototype.getLength = function() {
  16596. var lens = this.getCurveLengths();
  16597. return lens[ lens.length - 1 ];
  16598. };
  16599. // Compute lengths and cache them
  16600. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16601. THREE.CurvePath.prototype.getCurveLengths = function() {
  16602. // We use cache values if curves and cache array are same length
  16603. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16604. return this.cacheLengths;
  16605. };
  16606. // Get length of subsurve
  16607. // Push sums into cached array
  16608. var lengths = [], sums = 0;
  16609. var i, il = this.curves.length;
  16610. for ( i = 0; i < il; i ++ ) {
  16611. sums += this.curves[ i ].getLength();
  16612. lengths.push( sums );
  16613. }
  16614. this.cacheLengths = lengths;
  16615. return lengths;
  16616. };
  16617. // Returns min and max coordinates
  16618. THREE.CurvePath.prototype.getBoundingBox = function () {
  16619. var points = this.getPoints();
  16620. var maxX, maxY, maxZ;
  16621. var minX, minY, minZ;
  16622. maxX = maxY = Number.NEGATIVE_INFINITY;
  16623. minX = minY = Number.POSITIVE_INFINITY;
  16624. var p, i, il, sum;
  16625. var v3 = points[0] instanceof THREE.Vector3;
  16626. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16627. for ( i = 0, il = points.length; i < il; i ++ ) {
  16628. p = points[ i ];
  16629. if ( p.x > maxX ) maxX = p.x;
  16630. else if ( p.x < minX ) minX = p.x;
  16631. if ( p.y > maxY ) maxY = p.y;
  16632. else if ( p.y < minY ) minY = p.y;
  16633. if ( v3 ) {
  16634. if ( p.z > maxZ ) maxZ = p.z;
  16635. else if ( p.z < minZ ) minZ = p.z;
  16636. }
  16637. sum.add( p );
  16638. }
  16639. var ret = {
  16640. minX: minX,
  16641. minY: minY,
  16642. maxX: maxX,
  16643. maxY: maxY
  16644. };
  16645. if ( v3 ) {
  16646. ret.maxZ = maxZ;
  16647. ret.minZ = minZ;
  16648. }
  16649. return ret;
  16650. };
  16651. /**************************************************************
  16652. * Create Geometries Helpers
  16653. **************************************************************/
  16654. /// Generate geometry from path points (for Line or Points objects)
  16655. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16656. var pts = this.getPoints( divisions, true );
  16657. return this.createGeometry( pts );
  16658. };
  16659. // Generate geometry from equidistance sampling along the path
  16660. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16661. var pts = this.getSpacedPoints( divisions, true );
  16662. return this.createGeometry( pts );
  16663. };
  16664. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16665. var geometry = new THREE.Geometry();
  16666. for ( var i = 0; i < points.length; i ++ ) {
  16667. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16668. }
  16669. return geometry;
  16670. };
  16671. /**************************************************************
  16672. * Bend / Wrap Helper Methods
  16673. **************************************************************/
  16674. // Wrap path / Bend modifiers?
  16675. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16676. this.bends.push( bendpath );
  16677. };
  16678. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16679. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16680. var i, il;
  16681. if ( ! bends ) {
  16682. bends = this.bends;
  16683. }
  16684. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16685. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16686. }
  16687. return oldPts;
  16688. };
  16689. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16690. var oldPts = this.getSpacedPoints( segments );
  16691. var i, il;
  16692. if ( ! bends ) {
  16693. bends = this.bends;
  16694. }
  16695. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16696. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16697. }
  16698. return oldPts;
  16699. };
  16700. // This returns getPoints() bend/wrapped around the contour of a path.
  16701. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16702. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16703. var bounds = this.getBoundingBox();
  16704. var i, il, p, oldX, oldY, xNorm;
  16705. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16706. p = oldPts[ i ];
  16707. oldX = p.x;
  16708. oldY = p.y;
  16709. xNorm = oldX / bounds.maxX;
  16710. // If using actual distance, for length > path, requires line extrusions
  16711. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16712. xNorm = path.getUtoTmapping( xNorm, oldX );
  16713. // check for out of bounds?
  16714. var pathPt = path.getPoint( xNorm );
  16715. var normal = path.getTangent( xNorm );
  16716. normal.set( - normal.y, normal.x ).multiplyScalar( oldY );
  16717. p.x = pathPt.x + normal.x;
  16718. p.y = pathPt.y + normal.y;
  16719. }
  16720. return oldPts;
  16721. };
  16722. // File:src/extras/core/Gyroscope.js
  16723. /**
  16724. * @author alteredq / http://alteredqualia.com/
  16725. */
  16726. THREE.Gyroscope = function () {
  16727. THREE.Object3D.call( this );
  16728. };
  16729. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16730. THREE.Gyroscope.prototype.constructor = THREE.Gyroscope;
  16731. THREE.Gyroscope.prototype.updateMatrixWorld = ( function () {
  16732. var translationObject = new THREE.Vector3();
  16733. var quaternionObject = new THREE.Quaternion();
  16734. var scaleObject = new THREE.Vector3();
  16735. var translationWorld = new THREE.Vector3();
  16736. var quaternionWorld = new THREE.Quaternion();
  16737. var scaleWorld = new THREE.Vector3();
  16738. return function ( force ) {
  16739. this.matrixAutoUpdate && this.updateMatrix();
  16740. // update matrixWorld
  16741. if ( this.matrixWorldNeedsUpdate || force ) {
  16742. if ( this.parent ) {
  16743. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  16744. this.matrixWorld.decompose( translationWorld, quaternionWorld, scaleWorld );
  16745. this.matrix.decompose( translationObject, quaternionObject, scaleObject );
  16746. this.matrixWorld.compose( translationWorld, quaternionObject, scaleWorld );
  16747. } else {
  16748. this.matrixWorld.copy( this.matrix );
  16749. }
  16750. this.matrixWorldNeedsUpdate = false;
  16751. force = true;
  16752. }
  16753. // update children
  16754. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16755. this.children[ i ].updateMatrixWorld( force );
  16756. }
  16757. };
  16758. }() );
  16759. // File:src/extras/core/Path.js
  16760. /**
  16761. * @author zz85 / http://www.lab4games.net/zz85/blog
  16762. * Creates free form 2d path using series of points, lines or curves.
  16763. *
  16764. **/
  16765. THREE.Path = function ( points ) {
  16766. THREE.CurvePath.call(this);
  16767. this.actions = [];
  16768. if ( points ) {
  16769. this.fromPoints( points );
  16770. }
  16771. };
  16772. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16773. THREE.Path.prototype.constructor = THREE.Path;
  16774. THREE.PathActions = {
  16775. MOVE_TO: 'moveTo',
  16776. LINE_TO: 'lineTo',
  16777. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16778. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16779. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16780. ARC: 'arc', // Circle
  16781. ELLIPSE: 'ellipse'
  16782. };
  16783. // TODO Clean up PATH API
  16784. // Create path using straight lines to connect all points
  16785. // - vectors: array of Vector2
  16786. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16787. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16788. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16789. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16790. };
  16791. };
  16792. // startPath() endPath()?
  16793. THREE.Path.prototype.moveTo = function ( x, y ) {
  16794. var args = Array.prototype.slice.call( arguments );
  16795. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16796. };
  16797. THREE.Path.prototype.lineTo = function ( x, y ) {
  16798. var args = Array.prototype.slice.call( arguments );
  16799. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16800. var x0 = lastargs[ lastargs.length - 2 ];
  16801. var y0 = lastargs[ lastargs.length - 1 ];
  16802. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16803. this.curves.push( curve );
  16804. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16805. };
  16806. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16807. var args = Array.prototype.slice.call( arguments );
  16808. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16809. var x0 = lastargs[ lastargs.length - 2 ];
  16810. var y0 = lastargs[ lastargs.length - 1 ];
  16811. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16812. new THREE.Vector2( aCPx, aCPy ),
  16813. new THREE.Vector2( aX, aY ) );
  16814. this.curves.push( curve );
  16815. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16816. };
  16817. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16818. aCP2x, aCP2y,
  16819. aX, aY ) {
  16820. var args = Array.prototype.slice.call( arguments );
  16821. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16822. var x0 = lastargs[ lastargs.length - 2 ];
  16823. var y0 = lastargs[ lastargs.length - 1 ];
  16824. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16825. new THREE.Vector2( aCP1x, aCP1y ),
  16826. new THREE.Vector2( aCP2x, aCP2y ),
  16827. new THREE.Vector2( aX, aY ) );
  16828. this.curves.push( curve );
  16829. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16830. };
  16831. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16832. var args = Array.prototype.slice.call( arguments );
  16833. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16834. var x0 = lastargs[ lastargs.length - 2 ];
  16835. var y0 = lastargs[ lastargs.length - 1 ];
  16836. //---
  16837. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16838. Array.prototype.push.apply( npts, pts );
  16839. var curve = new THREE.SplineCurve( npts );
  16840. this.curves.push( curve );
  16841. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16842. };
  16843. // FUTURE: Change the API or follow canvas API?
  16844. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16845. aStartAngle, aEndAngle, aClockwise ) {
  16846. var lastargs = this.actions[ this.actions.length - 1].args;
  16847. var x0 = lastargs[ lastargs.length - 2 ];
  16848. var y0 = lastargs[ lastargs.length - 1 ];
  16849. this.absarc(aX + x0, aY + y0, aRadius,
  16850. aStartAngle, aEndAngle, aClockwise );
  16851. };
  16852. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16853. aStartAngle, aEndAngle, aClockwise ) {
  16854. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16855. };
  16856. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16857. aStartAngle, aEndAngle, aClockwise ) {
  16858. var lastargs = this.actions[ this.actions.length - 1].args;
  16859. var x0 = lastargs[ lastargs.length - 2 ];
  16860. var y0 = lastargs[ lastargs.length - 1 ];
  16861. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16862. aStartAngle, aEndAngle, aClockwise );
  16863. };
  16864. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16865. aStartAngle, aEndAngle, aClockwise ) {
  16866. var args = Array.prototype.slice.call( arguments );
  16867. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16868. aStartAngle, aEndAngle, aClockwise );
  16869. this.curves.push( curve );
  16870. var lastPoint = curve.getPoint(1);
  16871. args.push(lastPoint.x);
  16872. args.push(lastPoint.y);
  16873. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16874. };
  16875. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16876. if ( ! divisions ) divisions = 40;
  16877. var points = [];
  16878. for ( var i = 0; i < divisions; i ++ ) {
  16879. points.push( this.getPoint( i / divisions ) );
  16880. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16881. }
  16882. // if ( closedPath ) {
  16883. //
  16884. // points.push( points[ 0 ] );
  16885. //
  16886. // }
  16887. return points;
  16888. };
  16889. /* Return an array of vectors based on contour of the path */
  16890. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  16891. if (this.useSpacedPoints) {
  16892. THREE.log('tata');
  16893. return this.getSpacedPoints( divisions, closedPath );
  16894. }
  16895. divisions = divisions || 12;
  16896. var points = [];
  16897. var i, il, item, action, args;
  16898. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  16899. laste, j,
  16900. t, tx, ty;
  16901. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16902. item = this.actions[ i ];
  16903. action = item.action;
  16904. args = item.args;
  16905. switch ( action ) {
  16906. case THREE.PathActions.MOVE_TO:
  16907. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16908. break;
  16909. case THREE.PathActions.LINE_TO:
  16910. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16911. break;
  16912. case THREE.PathActions.QUADRATIC_CURVE_TO:
  16913. cpx = args[ 2 ];
  16914. cpy = args[ 3 ];
  16915. cpx1 = args[ 0 ];
  16916. cpy1 = args[ 1 ];
  16917. if ( points.length > 0 ) {
  16918. laste = points[ points.length - 1 ];
  16919. cpx0 = laste.x;
  16920. cpy0 = laste.y;
  16921. } else {
  16922. laste = this.actions[ i - 1 ].args;
  16923. cpx0 = laste[ laste.length - 2 ];
  16924. cpy0 = laste[ laste.length - 1 ];
  16925. }
  16926. for ( j = 1; j <= divisions; j ++ ) {
  16927. t = j / divisions;
  16928. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16929. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16930. points.push( new THREE.Vector2( tx, ty ) );
  16931. }
  16932. break;
  16933. case THREE.PathActions.BEZIER_CURVE_TO:
  16934. cpx = args[ 4 ];
  16935. cpy = args[ 5 ];
  16936. cpx1 = args[ 0 ];
  16937. cpy1 = args[ 1 ];
  16938. cpx2 = args[ 2 ];
  16939. cpy2 = args[ 3 ];
  16940. if ( points.length > 0 ) {
  16941. laste = points[ points.length - 1 ];
  16942. cpx0 = laste.x;
  16943. cpy0 = laste.y;
  16944. } else {
  16945. laste = this.actions[ i - 1 ].args;
  16946. cpx0 = laste[ laste.length - 2 ];
  16947. cpy0 = laste[ laste.length - 1 ];
  16948. }
  16949. for ( j = 1; j <= divisions; j ++ ) {
  16950. t = j / divisions;
  16951. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16952. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16953. points.push( new THREE.Vector2( tx, ty ) );
  16954. }
  16955. break;
  16956. case THREE.PathActions.CSPLINE_THRU:
  16957. laste = this.actions[ i - 1 ].args;
  16958. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  16959. var spts = [ last ];
  16960. var n = divisions * args[ 0 ].length;
  16961. spts = spts.concat( args[ 0 ] );
  16962. var spline = new THREE.SplineCurve( spts );
  16963. for ( j = 1; j <= n; j ++ ) {
  16964. points.push( spline.getPointAt( j / n ) ) ;
  16965. }
  16966. break;
  16967. case THREE.PathActions.ARC:
  16968. var aX = args[ 0 ], aY = args[ 1 ],
  16969. aRadius = args[ 2 ],
  16970. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  16971. aClockwise = !! args[ 5 ];
  16972. var deltaAngle = aEndAngle - aStartAngle;
  16973. var angle;
  16974. var tdivisions = divisions * 2;
  16975. for ( j = 1; j <= tdivisions; j ++ ) {
  16976. t = j / tdivisions;
  16977. if ( ! aClockwise ) {
  16978. t = 1 - t;
  16979. }
  16980. angle = aStartAngle + t * deltaAngle;
  16981. tx = aX + aRadius * Math.cos( angle );
  16982. ty = aY + aRadius * Math.sin( angle );
  16983. //THREE.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16984. points.push( new THREE.Vector2( tx, ty ) );
  16985. }
  16986. //THREE.log(points);
  16987. break;
  16988. case THREE.PathActions.ELLIPSE:
  16989. var aX = args[ 0 ], aY = args[ 1 ],
  16990. xRadius = args[ 2 ],
  16991. yRadius = args[ 3 ],
  16992. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  16993. aClockwise = !! args[ 6 ];
  16994. var deltaAngle = aEndAngle - aStartAngle;
  16995. var angle;
  16996. var tdivisions = divisions * 2;
  16997. for ( j = 1; j <= tdivisions; j ++ ) {
  16998. t = j / tdivisions;
  16999. if ( ! aClockwise ) {
  17000. t = 1 - t;
  17001. }
  17002. angle = aStartAngle + t * deltaAngle;
  17003. tx = aX + xRadius * Math.cos( angle );
  17004. ty = aY + yRadius * Math.sin( angle );
  17005. //THREE.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17006. points.push( new THREE.Vector2( tx, ty ) );
  17007. }
  17008. //THREE.log(points);
  17009. break;
  17010. } // end switch
  17011. }
  17012. // Normalize to remove the closing point by default.
  17013. var lastPoint = points[ points.length - 1];
  17014. var EPSILON = 0.0000000001;
  17015. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17016. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17017. points.splice( points.length - 1, 1);
  17018. if ( closedPath ) {
  17019. points.push( points[ 0 ] );
  17020. }
  17021. return points;
  17022. };
  17023. //
  17024. // Breaks path into shapes
  17025. //
  17026. // Assumptions (if parameter isCCW==true the opposite holds):
  17027. // - solid shapes are defined clockwise (CW)
  17028. // - holes are defined counterclockwise (CCW)
  17029. //
  17030. // If parameter noHoles==true:
  17031. // - all subPaths are regarded as solid shapes
  17032. // - definition order CW/CCW has no relevance
  17033. //
  17034. THREE.Path.prototype.toShapes = function( isCCW, noHoles ) {
  17035. function extractSubpaths( inActions ) {
  17036. var i, il, item, action, args;
  17037. var subPaths = [], lastPath = new THREE.Path();
  17038. for ( i = 0, il = inActions.length; i < il; i ++ ) {
  17039. item = inActions[ i ];
  17040. args = item.args;
  17041. action = item.action;
  17042. if ( action == THREE.PathActions.MOVE_TO ) {
  17043. if ( lastPath.actions.length != 0 ) {
  17044. subPaths.push( lastPath );
  17045. lastPath = new THREE.Path();
  17046. }
  17047. }
  17048. lastPath[ action ].apply( lastPath, args );
  17049. }
  17050. if ( lastPath.actions.length != 0 ) {
  17051. subPaths.push( lastPath );
  17052. }
  17053. // THREE.log(subPaths);
  17054. return subPaths;
  17055. }
  17056. function toShapesNoHoles( inSubpaths ) {
  17057. var shapes = [];
  17058. for ( var i = 0, il = inSubpaths.length; i < il; i ++ ) {
  17059. var tmpPath = inSubpaths[ i ];
  17060. var tmpShape = new THREE.Shape();
  17061. tmpShape.actions = tmpPath.actions;
  17062. tmpShape.curves = tmpPath.curves;
  17063. shapes.push( tmpShape );
  17064. }
  17065. //THREE.log("shape", shapes);
  17066. return shapes;
  17067. };
  17068. function isPointInsidePolygon( inPt, inPolygon ) {
  17069. var EPSILON = 0.0000000001;
  17070. var polyLen = inPolygon.length;
  17071. // inPt on polygon contour => immediate success or
  17072. // toggling of inside/outside at every single! intersection point of an edge
  17073. // with the horizontal line through inPt, left of inPt
  17074. // not counting lowerY endpoints of edges and whole edges on that line
  17075. var inside = false;
  17076. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  17077. var edgeLowPt = inPolygon[ p ];
  17078. var edgeHighPt = inPolygon[ q ];
  17079. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  17080. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  17081. if ( Math.abs(edgeDy) > EPSILON ) { // not parallel
  17082. if ( edgeDy < 0 ) {
  17083. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  17084. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  17085. }
  17086. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  17087. if ( inPt.y == edgeLowPt.y ) {
  17088. if ( inPt.x == edgeLowPt.x ) return true; // inPt is on contour ?
  17089. // continue; // no intersection or edgeLowPt => doesn't count !!!
  17090. } else {
  17091. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  17092. if ( perpEdge == 0 ) return true; // inPt is on contour ?
  17093. if ( perpEdge < 0 ) continue;
  17094. inside = ! inside; // true intersection left of inPt
  17095. }
  17096. } else { // parallel or colinear
  17097. if ( inPt.y != edgeLowPt.y ) continue; // parallel
  17098. // egde lies on the same horizontal line as inPt
  17099. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  17100. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  17101. // continue;
  17102. }
  17103. }
  17104. return inside;
  17105. }
  17106. var subPaths = extractSubpaths( this.actions );
  17107. if ( subPaths.length == 0 ) return [];
  17108. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  17109. var solid, tmpPath, tmpShape, shapes = [];
  17110. if ( subPaths.length == 1) {
  17111. tmpPath = subPaths[0];
  17112. tmpShape = new THREE.Shape();
  17113. tmpShape.actions = tmpPath.actions;
  17114. tmpShape.curves = tmpPath.curves;
  17115. shapes.push( tmpShape );
  17116. return shapes;
  17117. }
  17118. var holesFirst = ! THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17119. holesFirst = isCCW ? ! holesFirst : holesFirst;
  17120. // THREE.log("Holes first", holesFirst);
  17121. var betterShapeHoles = [];
  17122. var newShapes = [];
  17123. var newShapeHoles = [];
  17124. var mainIdx = 0;
  17125. var tmpPoints;
  17126. newShapes[mainIdx] = undefined;
  17127. newShapeHoles[mainIdx] = [];
  17128. var i, il;
  17129. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17130. tmpPath = subPaths[ i ];
  17131. tmpPoints = tmpPath.getPoints();
  17132. solid = THREE.Shape.Utils.isClockWise( tmpPoints );
  17133. solid = isCCW ? ! solid : solid;
  17134. if ( solid ) {
  17135. if ( (! holesFirst ) && ( newShapes[mainIdx] ) ) mainIdx ++;
  17136. newShapes[mainIdx] = { s: new THREE.Shape(), p: tmpPoints };
  17137. newShapes[mainIdx].s.actions = tmpPath.actions;
  17138. newShapes[mainIdx].s.curves = tmpPath.curves;
  17139. if ( holesFirst ) mainIdx ++;
  17140. newShapeHoles[mainIdx] = [];
  17141. //THREE.log('cw', i);
  17142. } else {
  17143. newShapeHoles[mainIdx].push( { h: tmpPath, p: tmpPoints[0] } );
  17144. //THREE.log('ccw', i);
  17145. }
  17146. }
  17147. // only Holes? -> probably all Shapes with wrong orientation
  17148. if ( ! newShapes[0] ) return toShapesNoHoles( subPaths );
  17149. if ( newShapes.length > 1 ) {
  17150. var ambigious = false;
  17151. var toChange = [];
  17152. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  17153. betterShapeHoles[sIdx] = [];
  17154. }
  17155. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  17156. var sho = newShapeHoles[sIdx];
  17157. for (var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  17158. var ho = sho[hIdx];
  17159. var hole_unassigned = true;
  17160. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  17161. if ( isPointInsidePolygon( ho.p, newShapes[s2Idx].p ) ) {
  17162. if ( sIdx != s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  17163. if ( hole_unassigned ) {
  17164. hole_unassigned = false;
  17165. betterShapeHoles[s2Idx].push( ho );
  17166. } else {
  17167. ambigious = true;
  17168. }
  17169. }
  17170. }
  17171. if ( hole_unassigned ) { betterShapeHoles[sIdx].push( ho ); }
  17172. }
  17173. }
  17174. // THREE.log("ambigious: ", ambigious);
  17175. if ( toChange.length > 0 ) {
  17176. // THREE.log("to change: ", toChange);
  17177. if (! ambigious) newShapeHoles = betterShapeHoles;
  17178. }
  17179. }
  17180. var tmpHoles, j, jl;
  17181. for ( i = 0, il = newShapes.length; i < il; i ++ ) {
  17182. tmpShape = newShapes[i].s;
  17183. shapes.push( tmpShape );
  17184. tmpHoles = newShapeHoles[i];
  17185. for ( j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  17186. tmpShape.holes.push( tmpHoles[j].h );
  17187. }
  17188. }
  17189. //THREE.log("shape", shapes);
  17190. return shapes;
  17191. };
  17192. // File:src/extras/core/Shape.js
  17193. /**
  17194. * @author zz85 / http://www.lab4games.net/zz85/blog
  17195. * Defines a 2d shape plane using paths.
  17196. **/
  17197. // STEP 1 Create a path.
  17198. // STEP 2 Turn path into shape.
  17199. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17200. // STEP 3a - Extract points from each shape, turn to vertices
  17201. // STEP 3b - Triangulate each shape, add faces.
  17202. THREE.Shape = function () {
  17203. THREE.Path.apply( this, arguments );
  17204. this.holes = [];
  17205. };
  17206. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17207. THREE.Shape.prototype.constructor = THREE.Shape;
  17208. // Convenience method to return ExtrudeGeometry
  17209. THREE.Shape.prototype.extrude = function ( options ) {
  17210. var extruded = new THREE.ExtrudeGeometry( this, options );
  17211. return extruded;
  17212. };
  17213. // Convenience method to return ShapeGeometry
  17214. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17215. var geometry = new THREE.ShapeGeometry( this, options );
  17216. return geometry;
  17217. };
  17218. // Get points of holes
  17219. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17220. var i, il = this.holes.length, holesPts = [];
  17221. for ( i = 0; i < il; i ++ ) {
  17222. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17223. }
  17224. return holesPts;
  17225. };
  17226. // Get points of holes (spaced by regular distance)
  17227. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17228. var i, il = this.holes.length, holesPts = [];
  17229. for ( i = 0; i < il; i ++ ) {
  17230. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17231. }
  17232. return holesPts;
  17233. };
  17234. // Get points of shape and holes (keypoints based on segments parameter)
  17235. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17236. return {
  17237. shape: this.getTransformedPoints( divisions ),
  17238. holes: this.getPointsHoles( divisions )
  17239. };
  17240. };
  17241. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17242. if (this.useSpacedPoints) {
  17243. return this.extractAllSpacedPoints(divisions);
  17244. }
  17245. return this.extractAllPoints(divisions);
  17246. };
  17247. //
  17248. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17249. //
  17250. // return {
  17251. //
  17252. // shape: this.transform( bend, divisions ),
  17253. // holes: this.getPointsHoles( divisions, bend )
  17254. //
  17255. // };
  17256. //
  17257. // };
  17258. // Get points of shape and holes (spaced by regular distance)
  17259. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17260. return {
  17261. shape: this.getTransformedSpacedPoints( divisions ),
  17262. holes: this.getSpacedPointsHoles( divisions )
  17263. };
  17264. };
  17265. /**************************************************************
  17266. * Utils
  17267. **************************************************************/
  17268. THREE.Shape.Utils = {
  17269. triangulateShape: function ( contour, holes ) {
  17270. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  17271. // inOtherPt needs to be colinear to the inSegment
  17272. if ( inSegPt1.x != inSegPt2.x ) {
  17273. if ( inSegPt1.x < inSegPt2.x ) {
  17274. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  17275. } else {
  17276. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  17277. }
  17278. } else {
  17279. if ( inSegPt1.y < inSegPt2.y ) {
  17280. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  17281. } else {
  17282. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  17283. }
  17284. }
  17285. }
  17286. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  17287. var EPSILON = 0.0000000001;
  17288. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  17289. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  17290. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  17291. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  17292. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  17293. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  17294. if ( Math.abs(limit) > EPSILON ) { // not parallel
  17295. var perpSeg2;
  17296. if ( limit > 0 ) {
  17297. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  17298. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17299. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  17300. } else {
  17301. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  17302. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17303. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  17304. }
  17305. // i.e. to reduce rounding errors
  17306. // intersection at endpoint of segment#1?
  17307. if ( perpSeg2 == 0 ) {
  17308. if ( ( inExcludeAdjacentSegs ) &&
  17309. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17310. return [ inSeg1Pt1 ];
  17311. }
  17312. if ( perpSeg2 == limit ) {
  17313. if ( ( inExcludeAdjacentSegs ) &&
  17314. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17315. return [ inSeg1Pt2 ];
  17316. }
  17317. // intersection at endpoint of segment#2?
  17318. if ( perpSeg1 == 0 ) return [ inSeg2Pt1 ];
  17319. if ( perpSeg1 == limit ) return [ inSeg2Pt2 ];
  17320. // return real intersection point
  17321. var factorSeg1 = perpSeg2 / limit;
  17322. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  17323. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  17324. } else { // parallel or colinear
  17325. if ( ( perpSeg1 != 0 ) ||
  17326. ( seg2dy * seg1seg2dx != seg2dx * seg1seg2dy ) ) return [];
  17327. // they are collinear or degenerate
  17328. var seg1Pt = ( (seg1dx == 0) && (seg1dy == 0) ); // segment1 ist just a point?
  17329. var seg2Pt = ( (seg2dx == 0) && (seg2dy == 0) ); // segment2 ist just a point?
  17330. // both segments are points
  17331. if ( seg1Pt && seg2Pt ) {
  17332. if ( (inSeg1Pt1.x != inSeg2Pt1.x) ||
  17333. (inSeg1Pt1.y != inSeg2Pt1.y) ) return []; // they are distinct points
  17334. return [ inSeg1Pt1 ]; // they are the same point
  17335. }
  17336. // segment#1 is a single point
  17337. if ( seg1Pt ) {
  17338. if (! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  17339. return [ inSeg1Pt1 ];
  17340. }
  17341. // segment#2 is a single point
  17342. if ( seg2Pt ) {
  17343. if (! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  17344. return [ inSeg2Pt1 ];
  17345. }
  17346. // they are collinear segments, which might overlap
  17347. var seg1min, seg1max, seg1minVal, seg1maxVal;
  17348. var seg2min, seg2max, seg2minVal, seg2maxVal;
  17349. if (seg1dx != 0) { // the segments are NOT on a vertical line
  17350. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  17351. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  17352. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  17353. } else {
  17354. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  17355. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  17356. }
  17357. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  17358. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  17359. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  17360. } else {
  17361. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  17362. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  17363. }
  17364. } else { // the segments are on a vertical line
  17365. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  17366. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  17367. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  17368. } else {
  17369. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  17370. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  17371. }
  17372. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  17373. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  17374. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  17375. } else {
  17376. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  17377. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  17378. }
  17379. }
  17380. if ( seg1minVal <= seg2minVal ) {
  17381. if ( seg1maxVal < seg2minVal ) return [];
  17382. if ( seg1maxVal == seg2minVal ) {
  17383. if ( inExcludeAdjacentSegs ) return [];
  17384. return [ seg2min ];
  17385. }
  17386. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  17387. return [ seg2min, seg2max ];
  17388. } else {
  17389. if ( seg1minVal > seg2maxVal ) return [];
  17390. if ( seg1minVal == seg2maxVal ) {
  17391. if ( inExcludeAdjacentSegs ) return [];
  17392. return [ seg1min ];
  17393. }
  17394. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  17395. return [ seg1min, seg2max ];
  17396. }
  17397. }
  17398. }
  17399. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  17400. // The order of legs is important
  17401. var EPSILON = 0.0000000001;
  17402. // translation of all points, so that Vertex is at (0,0)
  17403. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  17404. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  17405. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  17406. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  17407. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  17408. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  17409. if ( Math.abs(from2toAngle) > EPSILON ) { // angle != 180 deg.
  17410. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  17411. // THREE.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  17412. if ( from2toAngle > 0 ) { // main angle < 180 deg.
  17413. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  17414. } else { // main angle > 180 deg.
  17415. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  17416. }
  17417. } else { // angle == 180 deg.
  17418. // THREE.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  17419. return ( from2otherAngle > 0 );
  17420. }
  17421. }
  17422. function removeHoles( contour, holes ) {
  17423. var shape = contour.concat(); // work on this shape
  17424. var hole;
  17425. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  17426. // Check if hole point lies within angle around shape point
  17427. var lastShapeIdx = shape.length - 1;
  17428. var prevShapeIdx = inShapeIdx - 1;
  17429. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  17430. var nextShapeIdx = inShapeIdx + 1;
  17431. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  17432. var insideAngle = isPointInsideAngle( shape[inShapeIdx], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[inHoleIdx] );
  17433. if (! insideAngle ) {
  17434. // THREE.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  17435. return false;
  17436. }
  17437. // Check if shape point lies within angle around hole point
  17438. var lastHoleIdx = hole.length - 1;
  17439. var prevHoleIdx = inHoleIdx - 1;
  17440. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  17441. var nextHoleIdx = inHoleIdx + 1;
  17442. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  17443. insideAngle = isPointInsideAngle( hole[inHoleIdx], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[inShapeIdx] );
  17444. if (! insideAngle ) {
  17445. // THREE.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  17446. return false;
  17447. }
  17448. return true;
  17449. }
  17450. function intersectsShapeEdge( inShapePt, inHolePt ) {
  17451. // checks for intersections with shape edges
  17452. var sIdx, nextIdx, intersection;
  17453. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  17454. nextIdx = sIdx + 1; nextIdx %= shape.length;
  17455. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[sIdx], shape[nextIdx], true );
  17456. if ( intersection.length > 0 ) return true;
  17457. }
  17458. return false;
  17459. }
  17460. var indepHoles = [];
  17461. function intersectsHoleEdge( inShapePt, inHolePt ) {
  17462. // checks for intersections with hole edges
  17463. var ihIdx, chkHole,
  17464. hIdx, nextIdx, intersection;
  17465. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  17466. chkHole = holes[indepHoles[ihIdx]];
  17467. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  17468. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  17469. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[hIdx], chkHole[nextIdx], true );
  17470. if ( intersection.length > 0 ) return true;
  17471. }
  17472. }
  17473. return false;
  17474. }
  17475. var holeIndex, shapeIndex,
  17476. shapePt, holePt,
  17477. holeIdx, cutKey, failedCuts = [],
  17478. tmpShape1, tmpShape2,
  17479. tmpHole1, tmpHole2;
  17480. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17481. indepHoles.push( h );
  17482. }
  17483. var minShapeIndex = 0;
  17484. var counter = indepHoles.length * 2;
  17485. while ( indepHoles.length > 0 ) {
  17486. counter --;
  17487. if ( counter < 0 ) {
  17488. THREE.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  17489. break;
  17490. }
  17491. // search for shape-vertex and hole-vertex,
  17492. // which can be connected without intersections
  17493. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  17494. shapePt = shape[ shapeIndex ];
  17495. holeIndex = - 1;
  17496. // search for hole which can be reached without intersections
  17497. for ( var h = 0; h < indepHoles.length; h ++ ) {
  17498. holeIdx = indepHoles[h];
  17499. // prevent multiple checks
  17500. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  17501. if ( failedCuts[cutKey] !== undefined ) continue;
  17502. hole = holes[holeIdx];
  17503. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  17504. holePt = hole[ h2 ];
  17505. if (! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  17506. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  17507. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  17508. holeIndex = h2;
  17509. indepHoles.splice(h, 1);
  17510. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  17511. tmpShape2 = shape.slice( shapeIndex );
  17512. tmpHole1 = hole.slice( holeIndex );
  17513. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  17514. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17515. minShapeIndex = shapeIndex;
  17516. // Debug only, to show the selected cuts
  17517. // glob_CutLines.push( [ shapePt, holePt ] );
  17518. break;
  17519. }
  17520. if ( holeIndex >= 0 ) break; // hole-vertex found
  17521. failedCuts[cutKey] = true; // remember failure
  17522. }
  17523. if ( holeIndex >= 0 ) break; // hole-vertex found
  17524. }
  17525. }
  17526. return shape; /* shape with no holes */
  17527. }
  17528. var i, il, f, face,
  17529. key, index,
  17530. allPointsMap = {};
  17531. // 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.
  17532. var allpoints = contour.concat();
  17533. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17534. Array.prototype.push.apply( allpoints, holes[h] );
  17535. }
  17536. //THREE.log( "allpoints",allpoints, allpoints.length );
  17537. // prepare all points map
  17538. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17539. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17540. if ( allPointsMap[ key ] !== undefined ) {
  17541. THREE.warn( "THREE.Shape: Duplicate point", key );
  17542. }
  17543. allPointsMap[ key ] = i;
  17544. }
  17545. // remove holes by cutting paths to holes and adding them to the shape
  17546. var shapeWithoutHoles = removeHoles( contour, holes );
  17547. var triangles = THREE.FontUtils.Triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  17548. //THREE.log( "triangles",triangles, triangles.length );
  17549. // check all face vertices against all points map
  17550. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17551. face = triangles[ i ];
  17552. for ( f = 0; f < 3; f ++ ) {
  17553. key = face[ f ].x + ":" + face[ f ].y;
  17554. index = allPointsMap[ key ];
  17555. if ( index !== undefined ) {
  17556. face[ f ] = index;
  17557. }
  17558. }
  17559. }
  17560. return triangles.concat();
  17561. },
  17562. isClockWise: function ( pts ) {
  17563. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17564. },
  17565. // Bezier Curves formulas obtained from
  17566. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17567. // Quad Bezier Functions
  17568. b2p0: function ( t, p ) {
  17569. var k = 1 - t;
  17570. return k * k * p;
  17571. },
  17572. b2p1: function ( t, p ) {
  17573. return 2 * ( 1 - t ) * t * p;
  17574. },
  17575. b2p2: function ( t, p ) {
  17576. return t * t * p;
  17577. },
  17578. b2: function ( t, p0, p1, p2 ) {
  17579. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17580. },
  17581. // Cubic Bezier Functions
  17582. b3p0: function ( t, p ) {
  17583. var k = 1 - t;
  17584. return k * k * k * p;
  17585. },
  17586. b3p1: function ( t, p ) {
  17587. var k = 1 - t;
  17588. return 3 * k * k * t * p;
  17589. },
  17590. b3p2: function ( t, p ) {
  17591. var k = 1 - t;
  17592. return 3 * k * t * t * p;
  17593. },
  17594. b3p3: function ( t, p ) {
  17595. return t * t * t * p;
  17596. },
  17597. b3: function ( t, p0, p1, p2, p3 ) {
  17598. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17599. }
  17600. };
  17601. // File:src/extras/curves/LineCurve.js
  17602. /**************************************************************
  17603. * Line
  17604. **************************************************************/
  17605. THREE.LineCurve = function ( v1, v2 ) {
  17606. this.v1 = v1;
  17607. this.v2 = v2;
  17608. };
  17609. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  17610. THREE.LineCurve.prototype.constructor = THREE.LineCurve;
  17611. THREE.LineCurve.prototype.getPoint = function ( t ) {
  17612. var point = this.v2.clone().sub(this.v1);
  17613. point.multiplyScalar( t ).add( this.v1 );
  17614. return point;
  17615. };
  17616. // Line curve is linear, so we can overwrite default getPointAt
  17617. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  17618. return this.getPoint( u );
  17619. };
  17620. THREE.LineCurve.prototype.getTangent = function( t ) {
  17621. var tangent = this.v2.clone().sub(this.v1);
  17622. return tangent.normalize();
  17623. };
  17624. // File:src/extras/curves/QuadraticBezierCurve.js
  17625. /**************************************************************
  17626. * Quadratic Bezier curve
  17627. **************************************************************/
  17628. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  17629. this.v0 = v0;
  17630. this.v1 = v1;
  17631. this.v2 = v2;
  17632. };
  17633. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17634. THREE.QuadraticBezierCurve.prototype.constructor = THREE.QuadraticBezierCurve;
  17635. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  17636. var vector = new THREE.Vector2();
  17637. vector.x = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17638. vector.y = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17639. return vector;
  17640. };
  17641. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  17642. var vector = new THREE.Vector2();
  17643. vector.x = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  17644. vector.y = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  17645. // returns unit vector
  17646. return vector.normalize();
  17647. };
  17648. // File:src/extras/curves/CubicBezierCurve.js
  17649. /**************************************************************
  17650. * Cubic Bezier curve
  17651. **************************************************************/
  17652. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  17653. this.v0 = v0;
  17654. this.v1 = v1;
  17655. this.v2 = v2;
  17656. this.v3 = v3;
  17657. };
  17658. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17659. THREE.CubicBezierCurve.prototype.constructor = THREE.CubicBezierCurve;
  17660. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  17661. var tx, ty;
  17662. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17663. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17664. return new THREE.Vector2( tx, ty );
  17665. };
  17666. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  17667. var tx, ty;
  17668. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17669. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17670. var tangent = new THREE.Vector2( tx, ty );
  17671. tangent.normalize();
  17672. return tangent;
  17673. };
  17674. // File:src/extras/curves/SplineCurve.js
  17675. /**************************************************************
  17676. * Spline curve
  17677. **************************************************************/
  17678. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  17679. this.points = ( points == undefined ) ? [] : points;
  17680. };
  17681. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  17682. THREE.SplineCurve.prototype.constructor = THREE.SplineCurve;
  17683. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  17684. var points = this.points;
  17685. var point = ( points.length - 1 ) * t;
  17686. var intPoint = Math.floor( point );
  17687. var weight = point - intPoint;
  17688. var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ]
  17689. var point1 = points[ intPoint ]
  17690. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]
  17691. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]
  17692. var vector = new THREE.Vector2();
  17693. vector.x = THREE.Curve.Utils.interpolate( point0.x, point1.x, point2.x, point3.x, weight );
  17694. vector.y = THREE.Curve.Utils.interpolate( point0.y, point1.y, point2.y, point3.y, weight );
  17695. return vector;
  17696. };
  17697. // File:src/extras/curves/EllipseCurve.js
  17698. /**************************************************************
  17699. * Ellipse curve
  17700. **************************************************************/
  17701. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) {
  17702. this.aX = aX;
  17703. this.aY = aY;
  17704. this.xRadius = xRadius;
  17705. this.yRadius = yRadius;
  17706. this.aStartAngle = aStartAngle;
  17707. this.aEndAngle = aEndAngle;
  17708. this.aClockwise = aClockwise;
  17709. };
  17710. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  17711. THREE.EllipseCurve.prototype.constructor = THREE.EllipseCurve;
  17712. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  17713. var deltaAngle = this.aEndAngle - this.aStartAngle;
  17714. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  17715. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  17716. var angle;
  17717. if ( this.aClockwise === true ) {
  17718. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  17719. } else {
  17720. angle = this.aStartAngle + t * deltaAngle;
  17721. }
  17722. var vector = new THREE.Vector2();
  17723. vector.x = this.aX + this.xRadius * Math.cos( angle );
  17724. vector.y = this.aY + this.yRadius * Math.sin( angle );
  17725. return vector;
  17726. };
  17727. // File:src/extras/curves/ArcCurve.js
  17728. /**************************************************************
  17729. * Arc curve
  17730. **************************************************************/
  17731. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  17732. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  17733. };
  17734. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  17735. THREE.ArcCurve.prototype.constructor = THREE.ArcCurve;
  17736. // File:src/extras/curves/LineCurve3.js
  17737. /**************************************************************
  17738. * Line3D
  17739. **************************************************************/
  17740. THREE.LineCurve3 = THREE.Curve.create(
  17741. function ( v1, v2 ) {
  17742. this.v1 = v1;
  17743. this.v2 = v2;
  17744. },
  17745. function ( t ) {
  17746. var vector = new THREE.Vector3();
  17747. vector.subVectors( this.v2, this.v1 ); // diff
  17748. vector.multiplyScalar( t );
  17749. vector.add( this.v1 );
  17750. return vector;
  17751. }
  17752. );
  17753. // File:src/extras/curves/QuadraticBezierCurve3.js
  17754. /**************************************************************
  17755. * Quadratic Bezier 3D curve
  17756. **************************************************************/
  17757. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  17758. function ( v0, v1, v2 ) {
  17759. this.v0 = v0;
  17760. this.v1 = v1;
  17761. this.v2 = v2;
  17762. },
  17763. function ( t ) {
  17764. var vector = new THREE.Vector3();
  17765. vector.x = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17766. vector.y = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17767. vector.z = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  17768. return vector;
  17769. }
  17770. );
  17771. // File:src/extras/curves/CubicBezierCurve3.js
  17772. /**************************************************************
  17773. * Cubic Bezier 3D curve
  17774. **************************************************************/
  17775. THREE.CubicBezierCurve3 = THREE.Curve.create(
  17776. function ( v0, v1, v2, v3 ) {
  17777. this.v0 = v0;
  17778. this.v1 = v1;
  17779. this.v2 = v2;
  17780. this.v3 = v3;
  17781. },
  17782. function ( t ) {
  17783. var vector = new THREE.Vector3();
  17784. vector.x = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17785. vector.y = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17786. vector.z = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  17787. return vector;
  17788. }
  17789. );
  17790. // File:src/extras/curves/SplineCurve3.js
  17791. /**************************************************************
  17792. * Spline 3D curve
  17793. **************************************************************/
  17794. THREE.SplineCurve3 = THREE.Curve.create(
  17795. function ( points /* array of Vector3 */) {
  17796. this.points = ( points == undefined ) ? [] : points;
  17797. },
  17798. function ( t ) {
  17799. var points = this.points;
  17800. var point = ( points.length - 1 ) * t;
  17801. var intPoint = Math.floor( point );
  17802. var weight = point - intPoint;
  17803. var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ];
  17804. var point1 = points[ intPoint ];
  17805. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  17806. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  17807. var vector = new THREE.Vector3();
  17808. vector.x = THREE.Curve.Utils.interpolate( point0.x, point1.x, point2.x, point3.x, weight );
  17809. vector.y = THREE.Curve.Utils.interpolate( point0.y, point1.y, point2.y, point3.y, weight );
  17810. vector.z = THREE.Curve.Utils.interpolate( point0.z, point1.z, point2.z, point3.z, weight );
  17811. return vector;
  17812. }
  17813. );
  17814. // File:src/extras/curves/ClosedSplineCurve3.js
  17815. /**************************************************************
  17816. * Closed Spline 3D curve
  17817. **************************************************************/
  17818. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  17819. function ( points /* array of Vector3 */) {
  17820. this.points = ( points == undefined ) ? [] : points;
  17821. },
  17822. function ( t ) {
  17823. var points = this.points;
  17824. var point = ( points.length - 0 ) * t; // This needs to be from 0-length +1
  17825. var intPoint = Math.floor( point );
  17826. var weight = point - intPoint;
  17827. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  17828. var point0 = points[ ( intPoint - 1 ) % points.length ];
  17829. var point1 = points[ ( intPoint ) % points.length ];
  17830. var point2 = points[ ( intPoint + 1 ) % points.length ];
  17831. var point3 = points[ ( intPoint + 2 ) % points.length ];
  17832. var vector = new THREE.Vector3();
  17833. vector.x = THREE.Curve.Utils.interpolate( point0.x, point1.x, point2.x, point3.x, weight );
  17834. vector.y = THREE.Curve.Utils.interpolate( point0.y, point1.y, point2.y, point3.y, weight );
  17835. vector.z = THREE.Curve.Utils.interpolate( point0.z, point1.z, point2.z, point3.z, weight );
  17836. return vector;
  17837. }
  17838. );
  17839. // File:src/extras/animation/AnimationHandler.js
  17840. /**
  17841. * @author mikael emtinger / http://gomo.se/
  17842. */
  17843. THREE.AnimationHandler = {
  17844. LINEAR: 0,
  17845. CATMULLROM: 1,
  17846. CATMULLROM_FORWARD: 2,
  17847. //
  17848. add: function () { THREE.warn( 'THREE.AnimationHandler.add() has been deprecated.' ); },
  17849. get: function () { THREE.warn( 'THREE.AnimationHandler.get() has been deprecated.' ); },
  17850. remove: function () { THREE.warn( 'THREE.AnimationHandler.remove() has been deprecated.' ); },
  17851. //
  17852. animations: [],
  17853. init: function ( data ) {
  17854. if ( data.initialized === true ) return data;
  17855. // loop through all keys
  17856. for ( var h = 0; h < data.hierarchy.length; h ++ ) {
  17857. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17858. // remove minus times
  17859. if ( data.hierarchy[ h ].keys[ k ].time < 0 ) {
  17860. data.hierarchy[ h ].keys[ k ].time = 0;
  17861. }
  17862. // create quaternions
  17863. if ( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17864. ! ( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17865. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17866. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion().fromArray( quat );
  17867. }
  17868. }
  17869. // prepare morph target keys
  17870. if ( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17871. // get all used
  17872. var usedMorphTargets = {};
  17873. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17874. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17875. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17876. usedMorphTargets[ morphTargetName ] = - 1;
  17877. }
  17878. }
  17879. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17880. // set all used on all frames
  17881. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17882. var influences = {};
  17883. for ( var morphTargetName in usedMorphTargets ) {
  17884. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17885. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17886. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17887. break;
  17888. }
  17889. }
  17890. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17891. influences[ morphTargetName ] = 0;
  17892. }
  17893. }
  17894. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17895. }
  17896. }
  17897. // remove all keys that are on the same time
  17898. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17899. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17900. data.hierarchy[ h ].keys.splice( k, 1 );
  17901. k --;
  17902. }
  17903. }
  17904. // set index
  17905. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17906. data.hierarchy[ h ].keys[ k ].index = k;
  17907. }
  17908. }
  17909. data.initialized = true;
  17910. return data;
  17911. },
  17912. parse: function ( root ) {
  17913. var parseRecurseHierarchy = function ( root, hierarchy ) {
  17914. hierarchy.push( root );
  17915. for ( var c = 0; c < root.children.length; c ++ )
  17916. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17917. };
  17918. // setup hierarchy
  17919. var hierarchy = [];
  17920. if ( root instanceof THREE.SkinnedMesh ) {
  17921. for ( var b = 0; b < root.skeleton.bones.length; b ++ ) {
  17922. hierarchy.push( root.skeleton.bones[ b ] );
  17923. }
  17924. } else {
  17925. parseRecurseHierarchy( root, hierarchy );
  17926. }
  17927. return hierarchy;
  17928. },
  17929. play: function ( animation ) {
  17930. if ( this.animations.indexOf( animation ) === - 1 ) {
  17931. this.animations.push( animation );
  17932. }
  17933. },
  17934. stop: function ( animation ) {
  17935. var index = this.animations.indexOf( animation );
  17936. if ( index !== - 1 ) {
  17937. this.animations.splice( index, 1 );
  17938. }
  17939. },
  17940. update: function ( deltaTimeMS ) {
  17941. for ( var i = 0; i < this.animations.length; i ++ ) {
  17942. this.animations[ i ].resetBlendWeights( );
  17943. }
  17944. for ( var i = 0; i < this.animations.length; i ++ ) {
  17945. this.animations[ i ].update( deltaTimeMS );
  17946. }
  17947. }
  17948. };
  17949. // File:src/extras/animation/Animation.js
  17950. /**
  17951. * @author mikael emtinger / http://gomo.se/
  17952. * @author mrdoob / http://mrdoob.com/
  17953. * @author alteredq / http://alteredqualia.com/
  17954. */
  17955. THREE.Animation = function ( root, data ) {
  17956. this.root = root;
  17957. this.data = THREE.AnimationHandler.init( data );
  17958. this.hierarchy = THREE.AnimationHandler.parse( root );
  17959. this.currentTime = 0;
  17960. this.timeScale = 1;
  17961. this.isPlaying = false;
  17962. this.loop = true;
  17963. this.weight = 0;
  17964. this.interpolationType = THREE.AnimationHandler.LINEAR;
  17965. };
  17966. THREE.Animation.prototype = {
  17967. constructor: THREE.Animation,
  17968. keyTypes: [ "pos", "rot", "scl" ],
  17969. play: function ( startTime, weight ) {
  17970. this.currentTime = startTime !== undefined ? startTime : 0;
  17971. this.weight = weight !== undefined ? weight : 1;
  17972. this.isPlaying = true;
  17973. this.reset();
  17974. THREE.AnimationHandler.play( this );
  17975. },
  17976. stop: function() {
  17977. this.isPlaying = false;
  17978. THREE.AnimationHandler.stop( this );
  17979. },
  17980. reset: function () {
  17981. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17982. var object = this.hierarchy[ h ];
  17983. if ( object.animationCache === undefined ) {
  17984. object.animationCache = {
  17985. animations: {},
  17986. blending: {
  17987. positionWeight: 0.0,
  17988. quaternionWeight: 0.0,
  17989. scaleWeight: 0.0
  17990. }
  17991. };
  17992. }
  17993. var name = this.data.name;
  17994. var animations = object.animationCache.animations;
  17995. var animationCache = animations[ name ];
  17996. if ( animationCache === undefined ) {
  17997. animationCache = {
  17998. prevKey: { pos: 0, rot: 0, scl: 0 },
  17999. nextKey: { pos: 0, rot: 0, scl: 0 },
  18000. originalMatrix: object.matrix
  18001. };
  18002. animations[ name ] = animationCache;
  18003. }
  18004. // Get keys to match our current time
  18005. for ( var t = 0; t < 3; t ++ ) {
  18006. var type = this.keyTypes[ t ];
  18007. var prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18008. var nextKey = this.getNextKeyWith( type, h, 1 );
  18009. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18010. prevKey = nextKey;
  18011. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18012. }
  18013. animationCache.prevKey[ type ] = prevKey;
  18014. animationCache.nextKey[ type ] = nextKey;
  18015. }
  18016. }
  18017. },
  18018. resetBlendWeights: function () {
  18019. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18020. var object = this.hierarchy[ h ];
  18021. var animationCache = object.animationCache;
  18022. if ( animationCache !== undefined ) {
  18023. var blending = animationCache.blending;
  18024. blending.positionWeight = 0.0;
  18025. blending.quaternionWeight = 0.0;
  18026. blending.scaleWeight = 0.0;
  18027. }
  18028. }
  18029. },
  18030. update: ( function() {
  18031. var points = [];
  18032. var target = new THREE.Vector3();
  18033. var newVector = new THREE.Vector3();
  18034. var newQuat = new THREE.Quaternion();
  18035. // Catmull-Rom spline
  18036. var interpolateCatmullRom = function ( points, scale ) {
  18037. var c = [], v3 = [],
  18038. point, intPoint, weight, w2, w3,
  18039. pa, pb, pc, pd;
  18040. point = ( points.length - 1 ) * scale;
  18041. intPoint = Math.floor( point );
  18042. weight = point - intPoint;
  18043. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18044. c[ 1 ] = intPoint;
  18045. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18046. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18047. pa = points[ c[ 0 ] ];
  18048. pb = points[ c[ 1 ] ];
  18049. pc = points[ c[ 2 ] ];
  18050. pd = points[ c[ 3 ] ];
  18051. w2 = weight * weight;
  18052. w3 = weight * w2;
  18053. v3[ 0 ] = interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18054. v3[ 1 ] = interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18055. v3[ 2 ] = interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18056. return v3;
  18057. };
  18058. var interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18059. var v0 = ( p2 - p0 ) * 0.5,
  18060. v1 = ( p3 - p1 ) * 0.5;
  18061. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18062. };
  18063. return function ( delta ) {
  18064. if ( this.isPlaying === false ) return;
  18065. this.currentTime += delta * this.timeScale;
  18066. if ( this.weight === 0 )
  18067. return;
  18068. //
  18069. var duration = this.data.length;
  18070. if ( this.currentTime > duration || this.currentTime < 0 ) {
  18071. if ( this.loop ) {
  18072. this.currentTime %= duration;
  18073. if ( this.currentTime < 0 )
  18074. this.currentTime += duration;
  18075. this.reset();
  18076. } else {
  18077. this.stop();
  18078. }
  18079. }
  18080. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18081. var object = this.hierarchy[ h ];
  18082. var animationCache = object.animationCache.animations[this.data.name];
  18083. var blending = object.animationCache.blending;
  18084. // loop through pos/rot/scl
  18085. for ( var t = 0; t < 3; t ++ ) {
  18086. // get keys
  18087. var type = this.keyTypes[ t ];
  18088. var prevKey = animationCache.prevKey[ type ];
  18089. var nextKey = animationCache.nextKey[ type ];
  18090. if ( ( this.timeScale > 0 && nextKey.time <= this.currentTime ) ||
  18091. ( this.timeScale < 0 && prevKey.time >= this.currentTime ) ) {
  18092. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18093. nextKey = this.getNextKeyWith( type, h, 1 );
  18094. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18095. prevKey = nextKey;
  18096. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18097. }
  18098. animationCache.prevKey[ type ] = prevKey;
  18099. animationCache.nextKey[ type ] = nextKey;
  18100. }
  18101. var scale = ( this.currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18102. var prevXYZ = prevKey[ type ];
  18103. var nextXYZ = nextKey[ type ];
  18104. if ( scale < 0 ) scale = 0;
  18105. if ( scale > 1 ) scale = 1;
  18106. // interpolate
  18107. if ( type === "pos" ) {
  18108. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18109. newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18110. newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18111. newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18112. // blend
  18113. var proportionalWeight = this.weight / ( this.weight + blending.positionWeight );
  18114. object.position.lerp( newVector, proportionalWeight );
  18115. blending.positionWeight += this.weight;
  18116. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18117. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18118. points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18119. points[ 1 ] = prevXYZ;
  18120. points[ 2 ] = nextXYZ;
  18121. points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18122. scale = scale * 0.33 + 0.33;
  18123. var currentPoint = interpolateCatmullRom( points, scale );
  18124. var proportionalWeight = this.weight / ( this.weight + blending.positionWeight );
  18125. blending.positionWeight += this.weight;
  18126. // blend
  18127. var vector = object.position;
  18128. vector.x = vector.x + ( currentPoint[ 0 ] - vector.x ) * proportionalWeight;
  18129. vector.y = vector.y + ( currentPoint[ 1 ] - vector.y ) * proportionalWeight;
  18130. vector.z = vector.z + ( currentPoint[ 2 ] - vector.z ) * proportionalWeight;
  18131. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18132. var forwardPoint = interpolateCatmullRom( points, scale * 1.01 );
  18133. target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18134. target.sub( vector );
  18135. target.y = 0;
  18136. target.normalize();
  18137. var angle = Math.atan2( target.x, target.z );
  18138. object.rotation.set( 0, angle, 0 );
  18139. }
  18140. }
  18141. } else if ( type === "rot" ) {
  18142. THREE.Quaternion.slerp( prevXYZ, nextXYZ, newQuat, scale );
  18143. // Avoid paying the cost of an additional slerp if we don't have to
  18144. if ( blending.quaternionWeight === 0 ) {
  18145. object.quaternion.copy(newQuat);
  18146. blending.quaternionWeight = this.weight;
  18147. } else {
  18148. var proportionalWeight = this.weight / ( this.weight + blending.quaternionWeight );
  18149. THREE.Quaternion.slerp( object.quaternion, newQuat, object.quaternion, proportionalWeight );
  18150. blending.quaternionWeight += this.weight;
  18151. }
  18152. } else if ( type === "scl" ) {
  18153. newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18154. newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18155. newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18156. var proportionalWeight = this.weight / ( this.weight + blending.scaleWeight );
  18157. object.scale.lerp( newVector, proportionalWeight );
  18158. blending.scaleWeight += this.weight;
  18159. }
  18160. }
  18161. }
  18162. return true;
  18163. };
  18164. } )(),
  18165. getNextKeyWith: function ( type, h, key ) {
  18166. var keys = this.data.hierarchy[ h ].keys;
  18167. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18168. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18169. key = key < keys.length - 1 ? key : keys.length - 1;
  18170. } else {
  18171. key = key % keys.length;
  18172. }
  18173. for ( ; key < keys.length; key ++ ) {
  18174. if ( keys[ key ][ type ] !== undefined ) {
  18175. return keys[ key ];
  18176. }
  18177. }
  18178. return this.data.hierarchy[ h ].keys[ 0 ];
  18179. },
  18180. getPrevKeyWith: function ( type, h, key ) {
  18181. var keys = this.data.hierarchy[ h ].keys;
  18182. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18183. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18184. key = key > 0 ? key : 0;
  18185. } else {
  18186. key = key >= 0 ? key : key + keys.length;
  18187. }
  18188. for ( ; key >= 0; key -- ) {
  18189. if ( keys[ key ][ type ] !== undefined ) {
  18190. return keys[ key ];
  18191. }
  18192. }
  18193. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18194. }
  18195. };
  18196. // File:src/extras/animation/KeyFrameAnimation.js
  18197. /**
  18198. * @author mikael emtinger / http://gomo.se/
  18199. * @author mrdoob / http://mrdoob.com/
  18200. * @author alteredq / http://alteredqualia.com/
  18201. * @author khang duong
  18202. * @author erik kitson
  18203. */
  18204. THREE.KeyFrameAnimation = function ( data ) {
  18205. this.root = data.node;
  18206. this.data = THREE.AnimationHandler.init( data );
  18207. this.hierarchy = THREE.AnimationHandler.parse( this.root );
  18208. this.currentTime = 0;
  18209. this.timeScale = 0.001;
  18210. this.isPlaying = false;
  18211. this.isPaused = true;
  18212. this.loop = true;
  18213. // initialize to first keyframes
  18214. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18215. var keys = this.data.hierarchy[h].keys,
  18216. sids = this.data.hierarchy[h].sids,
  18217. obj = this.hierarchy[h];
  18218. if ( keys.length && sids ) {
  18219. for ( var s = 0; s < sids.length; s ++ ) {
  18220. var sid = sids[ s ],
  18221. next = this.getNextKeyWith( sid, h, 0 );
  18222. if ( next ) {
  18223. next.apply( sid );
  18224. }
  18225. }
  18226. obj.matrixAutoUpdate = false;
  18227. this.data.hierarchy[h].node.updateMatrix();
  18228. obj.matrixWorldNeedsUpdate = true;
  18229. }
  18230. }
  18231. };
  18232. THREE.KeyFrameAnimation.prototype = {
  18233. constructor: THREE.KeyFrameAnimation,
  18234. play: function ( startTime ) {
  18235. this.currentTime = startTime !== undefined ? startTime : 0;
  18236. if ( this.isPlaying === false ) {
  18237. this.isPlaying = true;
  18238. // reset key cache
  18239. var h, hl = this.hierarchy.length,
  18240. object,
  18241. node;
  18242. for ( h = 0; h < hl; h ++ ) {
  18243. object = this.hierarchy[ h ];
  18244. node = this.data.hierarchy[ h ];
  18245. if ( node.animationCache === undefined ) {
  18246. node.animationCache = {};
  18247. node.animationCache.prevKey = null;
  18248. node.animationCache.nextKey = null;
  18249. node.animationCache.originalMatrix = object.matrix;
  18250. }
  18251. var keys = this.data.hierarchy[h].keys;
  18252. if (keys.length) {
  18253. node.animationCache.prevKey = keys[ 0 ];
  18254. node.animationCache.nextKey = keys[ 1 ];
  18255. this.startTime = Math.min( keys[0].time, this.startTime );
  18256. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18257. }
  18258. }
  18259. this.update( 0 );
  18260. }
  18261. this.isPaused = false;
  18262. THREE.AnimationHandler.play( this );
  18263. },
  18264. stop: function () {
  18265. this.isPlaying = false;
  18266. this.isPaused = false;
  18267. THREE.AnimationHandler.stop( this );
  18268. // reset JIT matrix and remove cache
  18269. for ( var h = 0; h < this.data.hierarchy.length; h ++ ) {
  18270. var obj = this.hierarchy[ h ];
  18271. var node = this.data.hierarchy[ h ];
  18272. if ( node.animationCache !== undefined ) {
  18273. var original = node.animationCache.originalMatrix;
  18274. original.copy( obj.matrix );
  18275. obj.matrix = original;
  18276. delete node.animationCache;
  18277. }
  18278. }
  18279. },
  18280. update: function ( delta ) {
  18281. if ( this.isPlaying === false ) return;
  18282. this.currentTime += delta * this.timeScale;
  18283. //
  18284. var duration = this.data.length;
  18285. if ( this.loop === true && this.currentTime > duration ) {
  18286. this.currentTime %= duration;
  18287. }
  18288. this.currentTime = Math.min( this.currentTime, duration );
  18289. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18290. var object = this.hierarchy[ h ];
  18291. var node = this.data.hierarchy[ h ];
  18292. var keys = node.keys,
  18293. animationCache = node.animationCache;
  18294. if ( keys.length ) {
  18295. var prevKey = animationCache.prevKey;
  18296. var nextKey = animationCache.nextKey;
  18297. if ( nextKey.time <= this.currentTime ) {
  18298. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18299. prevKey = nextKey;
  18300. nextKey = keys[ prevKey.index + 1 ];
  18301. }
  18302. animationCache.prevKey = prevKey;
  18303. animationCache.nextKey = nextKey;
  18304. }
  18305. if ( nextKey.time >= this.currentTime ) {
  18306. prevKey.interpolate( nextKey, this.currentTime );
  18307. } else {
  18308. prevKey.interpolate( nextKey, nextKey.time );
  18309. }
  18310. this.data.hierarchy[ h ].node.updateMatrix();
  18311. object.matrixWorldNeedsUpdate = true;
  18312. }
  18313. }
  18314. },
  18315. getNextKeyWith: function ( sid, h, key ) {
  18316. var keys = this.data.hierarchy[ h ].keys;
  18317. key = key % keys.length;
  18318. for ( ; key < keys.length; key ++ ) {
  18319. if ( keys[ key ].hasTarget( sid ) ) {
  18320. return keys[ key ];
  18321. }
  18322. }
  18323. return keys[ 0 ];
  18324. },
  18325. getPrevKeyWith: function ( sid, h, key ) {
  18326. var keys = this.data.hierarchy[ h ].keys;
  18327. key = key >= 0 ? key : key + keys.length;
  18328. for ( ; key >= 0; key -- ) {
  18329. if ( keys[ key ].hasTarget( sid ) ) {
  18330. return keys[ key ];
  18331. }
  18332. }
  18333. return keys[ keys.length - 1 ];
  18334. }
  18335. };
  18336. // File:src/extras/animation/MorphAnimation.js
  18337. /**
  18338. * @author mrdoob / http://mrdoob.com
  18339. * @author willy-vvu / http://willy-vvu.github.io
  18340. */
  18341. THREE.MorphAnimation = function ( mesh ) {
  18342. this.mesh = mesh;
  18343. this.frames = mesh.morphTargetInfluences.length;
  18344. this.currentTime = 0;
  18345. this.duration = 1000;
  18346. this.loop = true;
  18347. this.lastFrame = 0;
  18348. this.currentFrame = 0;
  18349. this.isPlaying = false;
  18350. };
  18351. THREE.MorphAnimation.prototype = {
  18352. constructor: THREE.MorphAnimation,
  18353. play: function () {
  18354. this.isPlaying = true;
  18355. },
  18356. pause: function () {
  18357. this.isPlaying = false;
  18358. },
  18359. update: function ( delta ) {
  18360. if ( this.isPlaying === false ) return;
  18361. this.currentTime += delta;
  18362. if ( this.loop === true && this.currentTime > this.duration ) {
  18363. this.currentTime %= this.duration;
  18364. }
  18365. this.currentTime = Math.min( this.currentTime, this.duration );
  18366. var interpolation = this.duration / this.frames;
  18367. var frame = Math.floor( this.currentTime / interpolation );
  18368. var influences = this.mesh.morphTargetInfluences;
  18369. if ( frame != this.currentFrame ) {
  18370. influences[ this.lastFrame ] = 0;
  18371. influences[ this.currentFrame ] = 1;
  18372. influences[ frame ] = 0;
  18373. this.lastFrame = this.currentFrame;
  18374. this.currentFrame = frame;
  18375. }
  18376. influences[ frame ] = ( this.currentTime % interpolation ) / interpolation;
  18377. influences[ this.lastFrame ] = 1 - influences[ frame ];
  18378. }
  18379. };
  18380. // File:src/extras/geometries/BoxGeometry.js
  18381. /**
  18382. * @author mrdoob / http://mrdoob.com/
  18383. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18384. */
  18385. THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18386. THREE.Geometry.call( this );
  18387. this.type = 'BoxGeometry';
  18388. this.parameters = {
  18389. width: width,
  18390. height: height,
  18391. depth: depth,
  18392. widthSegments: widthSegments,
  18393. heightSegments: heightSegments,
  18394. depthSegments: depthSegments
  18395. };
  18396. this.widthSegments = widthSegments || 1;
  18397. this.heightSegments = heightSegments || 1;
  18398. this.depthSegments = depthSegments || 1;
  18399. var scope = this;
  18400. var width_half = width / 2;
  18401. var height_half = height / 2;
  18402. var depth_half = depth / 2;
  18403. buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, 0 ); // px
  18404. buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, 1 ); // nx
  18405. buildPlane( 'x', 'z', 1, 1, width, depth, height_half, 2 ); // py
  18406. buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, 3 ); // ny
  18407. buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, 4 ); // pz
  18408. buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, 5 ); // nz
  18409. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18410. var w, ix, iy,
  18411. gridX = scope.widthSegments,
  18412. gridY = scope.heightSegments,
  18413. width_half = width / 2,
  18414. height_half = height / 2,
  18415. offset = scope.vertices.length;
  18416. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18417. w = 'z';
  18418. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18419. w = 'y';
  18420. gridY = scope.depthSegments;
  18421. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18422. w = 'x';
  18423. gridX = scope.depthSegments;
  18424. }
  18425. var gridX1 = gridX + 1,
  18426. gridY1 = gridY + 1,
  18427. segment_width = width / gridX,
  18428. segment_height = height / gridY,
  18429. normal = new THREE.Vector3();
  18430. normal[ w ] = depth > 0 ? 1 : - 1;
  18431. for ( iy = 0; iy < gridY1; iy ++ ) {
  18432. for ( ix = 0; ix < gridX1; ix ++ ) {
  18433. var vector = new THREE.Vector3();
  18434. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18435. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18436. vector[ w ] = depth;
  18437. scope.vertices.push( vector );
  18438. }
  18439. }
  18440. for ( iy = 0; iy < gridY; iy ++ ) {
  18441. for ( ix = 0; ix < gridX; ix ++ ) {
  18442. var a = ix + gridX1 * iy;
  18443. var b = ix + gridX1 * ( iy + 1 );
  18444. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18445. var d = ( ix + 1 ) + gridX1 * iy;
  18446. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  18447. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  18448. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  18449. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  18450. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  18451. face.normal.copy( normal );
  18452. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18453. face.materialIndex = materialIndex;
  18454. scope.faces.push( face );
  18455. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  18456. face = new THREE.Face3( b + offset, c + offset, d + offset );
  18457. face.normal.copy( normal );
  18458. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18459. face.materialIndex = materialIndex;
  18460. scope.faces.push( face );
  18461. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  18462. }
  18463. }
  18464. }
  18465. this.mergeVertices();
  18466. };
  18467. THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18468. THREE.BoxGeometry.prototype.constructor = THREE.BoxGeometry;
  18469. THREE.CubeGeometry = THREE.BoxGeometry; // backwards compatibility
  18470. // File:src/extras/geometries/CircleGeometry.js
  18471. /**
  18472. * @author hughes
  18473. */
  18474. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18475. THREE.Geometry.call( this );
  18476. this.type = 'CircleGeometry';
  18477. this.parameters = {
  18478. radius: radius,
  18479. segments: segments,
  18480. thetaStart: thetaStart,
  18481. thetaLength: thetaLength
  18482. };
  18483. radius = radius || 50;
  18484. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18485. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18486. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18487. var i, uvs = [],
  18488. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18489. this.vertices.push(center);
  18490. uvs.push( centerUV );
  18491. for ( i = 0; i <= segments; i ++ ) {
  18492. var vertex = new THREE.Vector3();
  18493. var segment = thetaStart + i / segments * thetaLength;
  18494. vertex.x = radius * Math.cos( segment );
  18495. vertex.y = radius * Math.sin( segment );
  18496. this.vertices.push( vertex );
  18497. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  18498. }
  18499. var n = new THREE.Vector3( 0, 0, 1 );
  18500. for ( i = 1; i <= segments; i ++ ) {
  18501. this.faces.push( new THREE.Face3( i, i + 1, 0, [ n.clone(), n.clone(), n.clone() ] ) );
  18502. this.faceVertexUvs[ 0 ].push( [ uvs[ i ].clone(), uvs[ i + 1 ].clone(), centerUV.clone() ] );
  18503. }
  18504. this.computeFaceNormals();
  18505. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18506. };
  18507. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18508. THREE.CircleGeometry.prototype.constructor = THREE.CircleGeometry;
  18509. // File:src/extras/geometries/CylinderGeometry.js
  18510. /**
  18511. * @author mrdoob / http://mrdoob.com/
  18512. */
  18513. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  18514. THREE.Geometry.call( this );
  18515. this.type = 'CylinderGeometry';
  18516. this.parameters = {
  18517. radiusTop: radiusTop,
  18518. radiusBottom: radiusBottom,
  18519. height: height,
  18520. radialSegments: radialSegments,
  18521. heightSegments: heightSegments,
  18522. openEnded: openEnded,
  18523. thetaStart: thetaStart,
  18524. thetaLength: thetaLength
  18525. };
  18526. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18527. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18528. height = height !== undefined ? height : 100;
  18529. radialSegments = radialSegments || 8;
  18530. heightSegments = heightSegments || 1;
  18531. openEnded = openEnded !== undefined ? openEnded : false;
  18532. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18533. thetaLength = thetaLength !== undefined ? thetaLength : 2 * Math.PI;
  18534. var heightHalf = height / 2;
  18535. var x, y, vertices = [], uvs = [];
  18536. for ( y = 0; y <= heightSegments; y ++ ) {
  18537. var verticesRow = [];
  18538. var uvsRow = [];
  18539. var v = y / heightSegments;
  18540. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18541. for ( x = 0; x <= radialSegments; x ++ ) {
  18542. var u = x / radialSegments;
  18543. var vertex = new THREE.Vector3();
  18544. vertex.x = radius * Math.sin( u * thetaLength + thetaStart );
  18545. vertex.y = - v * height + heightHalf;
  18546. vertex.z = radius * Math.cos( u * thetaLength + thetaStart );
  18547. this.vertices.push( vertex );
  18548. verticesRow.push( this.vertices.length - 1 );
  18549. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18550. }
  18551. vertices.push( verticesRow );
  18552. uvs.push( uvsRow );
  18553. }
  18554. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18555. var na, nb;
  18556. for ( x = 0; x < radialSegments; x ++ ) {
  18557. if ( radiusTop !== 0 ) {
  18558. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18559. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18560. } else {
  18561. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18562. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18563. }
  18564. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18565. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18566. for ( y = 0; y < heightSegments; y ++ ) {
  18567. var v1 = vertices[ y ][ x ];
  18568. var v2 = vertices[ y + 1 ][ x ];
  18569. var v3 = vertices[ y + 1 ][ x + 1 ];
  18570. var v4 = vertices[ y ][ x + 1 ];
  18571. var n1 = na.clone();
  18572. var n2 = na.clone();
  18573. var n3 = nb.clone();
  18574. var n4 = nb.clone();
  18575. var uv1 = uvs[ y ][ x ].clone();
  18576. var uv2 = uvs[ y + 1 ][ x ].clone();
  18577. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18578. var uv4 = uvs[ y ][ x + 1 ].clone();
  18579. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  18580. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  18581. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  18582. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  18583. }
  18584. }
  18585. // top cap
  18586. if ( openEnded === false && radiusTop > 0 ) {
  18587. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18588. for ( x = 0; x < radialSegments; x ++ ) {
  18589. var v1 = vertices[ 0 ][ x ];
  18590. var v2 = vertices[ 0 ][ x + 1 ];
  18591. var v3 = this.vertices.length - 1;
  18592. var n1 = new THREE.Vector3( 0, 1, 0 );
  18593. var n2 = new THREE.Vector3( 0, 1, 0 );
  18594. var n3 = new THREE.Vector3( 0, 1, 0 );
  18595. var uv1 = uvs[ 0 ][ x ].clone();
  18596. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18597. var uv3 = new THREE.Vector2( uv2.x, 0 );
  18598. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18599. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18600. }
  18601. }
  18602. // bottom cap
  18603. if ( openEnded === false && radiusBottom > 0 ) {
  18604. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18605. for ( x = 0; x < radialSegments; x ++ ) {
  18606. var v1 = vertices[ heightSegments ][ x + 1 ];
  18607. var v2 = vertices[ heightSegments ][ x ];
  18608. var v3 = this.vertices.length - 1;
  18609. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18610. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18611. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18612. var uv1 = uvs[ heightSegments ][ x + 1 ].clone();
  18613. var uv2 = uvs[ heightSegments ][ x ].clone();
  18614. var uv3 = new THREE.Vector2( uv2.x, 1 );
  18615. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18616. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18617. }
  18618. }
  18619. this.computeFaceNormals();
  18620. };
  18621. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18622. THREE.CylinderGeometry.prototype.constructor = THREE.CylinderGeometry;
  18623. // File:src/extras/geometries/ExtrudeGeometry.js
  18624. /**
  18625. * @author zz85 / http://www.lab4games.net/zz85/blog
  18626. *
  18627. * Creates extruded geometry from a path shape.
  18628. *
  18629. * parameters = {
  18630. *
  18631. * curveSegments: <int>, // number of points on the curves
  18632. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18633. * amount: <int>, // Depth to extrude the shape
  18634. *
  18635. * bevelEnabled: <bool>, // turn on bevel
  18636. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18637. * bevelSize: <float>, // how far from shape outline is bevel
  18638. * bevelSegments: <int>, // number of bevel layers
  18639. *
  18640. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18641. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18642. *
  18643. * material: <int> // material index for front and back faces
  18644. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18645. * uvGenerator: <Object> // object that provides UV generator functions
  18646. *
  18647. * }
  18648. **/
  18649. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18650. if ( typeof( shapes ) === "undefined" ) {
  18651. shapes = [];
  18652. return;
  18653. }
  18654. THREE.Geometry.call( this );
  18655. this.type = 'ExtrudeGeometry';
  18656. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18657. this.addShapeList( shapes, options );
  18658. this.computeFaceNormals();
  18659. // can't really use automatic vertex normals
  18660. // as then front and back sides get smoothed too
  18661. // should do separate smoothing just for sides
  18662. //this.computeVertexNormals();
  18663. //THREE.log( "took", ( Date.now() - startTime ) );
  18664. };
  18665. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18666. THREE.ExtrudeGeometry.prototype.constructor = THREE.ExtrudeGeometry;
  18667. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18668. var sl = shapes.length;
  18669. for ( var s = 0; s < sl; s ++ ) {
  18670. var shape = shapes[ s ];
  18671. this.addShape( shape, options );
  18672. }
  18673. };
  18674. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18675. var amount = options.amount !== undefined ? options.amount : 100;
  18676. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18677. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18678. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18679. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18680. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18681. var steps = options.steps !== undefined ? options.steps : 1;
  18682. var extrudePath = options.extrudePath;
  18683. var extrudePts, extrudeByPath = false;
  18684. var material = options.material;
  18685. var extrudeMaterial = options.extrudeMaterial;
  18686. // Use default WorldUVGenerator if no UV generators are specified.
  18687. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18688. var splineTube, binormal, normal, position2;
  18689. if ( extrudePath ) {
  18690. extrudePts = extrudePath.getSpacedPoints( steps );
  18691. extrudeByPath = true;
  18692. bevelEnabled = false; // bevels not supported for path extrusion
  18693. // SETUP TNB variables
  18694. // Reuse TNB from TubeGeomtry for now.
  18695. // TODO1 - have a .isClosed in spline?
  18696. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18697. // THREE.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18698. binormal = new THREE.Vector3();
  18699. normal = new THREE.Vector3();
  18700. position2 = new THREE.Vector3();
  18701. }
  18702. // Safeguards if bevels are not enabled
  18703. if ( ! bevelEnabled ) {
  18704. bevelSegments = 0;
  18705. bevelThickness = 0;
  18706. bevelSize = 0;
  18707. }
  18708. // Variables initalization
  18709. var ahole, h, hl; // looping of holes
  18710. var scope = this;
  18711. var shapesOffset = this.vertices.length;
  18712. var shapePoints = shape.extractPoints( curveSegments );
  18713. var vertices = shapePoints.shape;
  18714. var holes = shapePoints.holes;
  18715. var reverse = ! THREE.Shape.Utils.isClockWise( vertices ) ;
  18716. if ( reverse ) {
  18717. vertices = vertices.reverse();
  18718. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18719. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18720. ahole = holes[ h ];
  18721. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18722. holes[ h ] = ahole.reverse();
  18723. }
  18724. }
  18725. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18726. }
  18727. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18728. /* Vertices */
  18729. var contour = vertices; // vertices has all points but contour has only points of circumference
  18730. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18731. ahole = holes[ h ];
  18732. vertices = vertices.concat( ahole );
  18733. }
  18734. function scalePt2 ( pt, vec, size ) {
  18735. if ( ! vec ) THREE.error( "THREE.ExtrudeGeometry: vec does not exist" );
  18736. return vec.clone().multiplyScalar( size ).add( pt );
  18737. }
  18738. var b, bs, t, z,
  18739. vert, vlen = vertices.length,
  18740. face, flen = faces.length;
  18741. // Find directions for point movement
  18742. function getBevelVec( inPt, inPrev, inNext ) {
  18743. var EPSILON = 0.0000000001;
  18744. // computes for inPt the corresponding point inPt' on a new contour
  18745. // shiftet by 1 unit (length of normalized vector) to the left
  18746. // if we walk along contour clockwise, this new contour is outside the old one
  18747. //
  18748. // inPt' is the intersection of the two lines parallel to the two
  18749. // adjacent edges of inPt at a distance of 1 unit on the left side.
  18750. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  18751. // good reading for geometry algorithms (here: line-line intersection)
  18752. // http://geomalgorithms.com/a05-_intersect-1.html
  18753. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  18754. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  18755. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  18756. // check for colinear edges
  18757. var colinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18758. if ( Math.abs( colinear0 ) > EPSILON ) { // not colinear
  18759. // length of vectors for normalizing
  18760. var v_prev_len = Math.sqrt( v_prev_lensq );
  18761. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  18762. // shift adjacent points by unit vectors to the left
  18763. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  18764. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  18765. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  18766. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  18767. // scaling factor for v_prev to intersection point
  18768. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  18769. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  18770. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18771. // vector from inPt to intersection point
  18772. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  18773. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  18774. // Don't normalize!, otherwise sharp corners become ugly
  18775. // but prevent crazy spikes
  18776. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y )
  18777. if ( v_trans_lensq <= 2 ) {
  18778. return new THREE.Vector2( v_trans_x, v_trans_y );
  18779. } else {
  18780. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  18781. }
  18782. } else { // handle special case of colinear edges
  18783. var direction_eq = false; // assumes: opposite
  18784. if ( v_prev_x > EPSILON ) {
  18785. if ( v_next_x > EPSILON ) { direction_eq = true; }
  18786. } else {
  18787. if ( v_prev_x < - EPSILON ) {
  18788. if ( v_next_x < - EPSILON ) { direction_eq = true; }
  18789. } else {
  18790. if ( Math.sign(v_prev_y) == Math.sign(v_next_y) ) { direction_eq = true; }
  18791. }
  18792. }
  18793. if ( direction_eq ) {
  18794. // THREE.log("Warning: lines are a straight sequence");
  18795. v_trans_x = - v_prev_y;
  18796. v_trans_y = v_prev_x;
  18797. shrink_by = Math.sqrt( v_prev_lensq );
  18798. } else {
  18799. // THREE.log("Warning: lines are a straight spike");
  18800. v_trans_x = v_prev_x;
  18801. v_trans_y = v_prev_y;
  18802. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  18803. }
  18804. }
  18805. return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  18806. }
  18807. var contourMovements = [];
  18808. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18809. if ( j === il ) j = 0;
  18810. if ( k === il ) k = 0;
  18811. // (j)---(i)---(k)
  18812. // THREE.log('i,j,k', i, j , k)
  18813. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18814. }
  18815. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18816. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18817. ahole = holes[ h ];
  18818. oneHoleMovements = [];
  18819. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18820. if ( j === il ) j = 0;
  18821. if ( k === il ) k = 0;
  18822. // (j)---(i)---(k)
  18823. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18824. }
  18825. holesMovements.push( oneHoleMovements );
  18826. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18827. }
  18828. // Loop bevelSegments, 1 for the front, 1 for the back
  18829. for ( b = 0; b < bevelSegments; b ++ ) {
  18830. //for ( b = bevelSegments; b > 0; b -- ) {
  18831. t = b / bevelSegments;
  18832. z = bevelThickness * ( 1 - t );
  18833. //z = bevelThickness * t;
  18834. bs = bevelSize * ( Math.sin ( t * Math.PI / 2 ) ) ; // curved
  18835. //bs = bevelSize * t ; // linear
  18836. // contract shape
  18837. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18838. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18839. v( vert.x, vert.y, - z );
  18840. }
  18841. // expand holes
  18842. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18843. ahole = holes[ h ];
  18844. oneHoleMovements = holesMovements[ h ];
  18845. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18846. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18847. v( vert.x, vert.y, - z );
  18848. }
  18849. }
  18850. }
  18851. bs = bevelSize;
  18852. // Back facing vertices
  18853. for ( i = 0; i < vlen; i ++ ) {
  18854. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18855. if ( ! extrudeByPath ) {
  18856. v( vert.x, vert.y, 0 );
  18857. } else {
  18858. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18859. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18860. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18861. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  18862. v( position2.x, position2.y, position2.z );
  18863. }
  18864. }
  18865. // Add stepped vertices...
  18866. // Including front facing vertices
  18867. var s;
  18868. for ( s = 1; s <= steps; s ++ ) {
  18869. for ( i = 0; i < vlen; i ++ ) {
  18870. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18871. if ( ! extrudeByPath ) {
  18872. v( vert.x, vert.y, amount / steps * s );
  18873. } else {
  18874. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18875. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18876. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18877. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  18878. v( position2.x, position2.y, position2.z );
  18879. }
  18880. }
  18881. }
  18882. // Add bevel segments planes
  18883. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18884. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18885. t = b / bevelSegments;
  18886. z = bevelThickness * ( 1 - t );
  18887. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18888. bs = bevelSize * Math.sin ( t * Math.PI / 2 ) ;
  18889. // contract shape
  18890. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18891. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18892. v( vert.x, vert.y, amount + z );
  18893. }
  18894. // expand holes
  18895. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18896. ahole = holes[ h ];
  18897. oneHoleMovements = holesMovements[ h ];
  18898. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18899. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18900. if ( ! extrudeByPath ) {
  18901. v( vert.x, vert.y, amount + z );
  18902. } else {
  18903. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18904. }
  18905. }
  18906. }
  18907. }
  18908. /* Faces */
  18909. // Top and bottom faces
  18910. buildLidFaces();
  18911. // Sides faces
  18912. buildSideFaces();
  18913. ///// Internal functions
  18914. function buildLidFaces() {
  18915. if ( bevelEnabled ) {
  18916. var layer = 0 ; // steps + 1
  18917. var offset = vlen * layer;
  18918. // Bottom faces
  18919. for ( i = 0; i < flen; i ++ ) {
  18920. face = faces[ i ];
  18921. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  18922. }
  18923. layer = steps + bevelSegments * 2;
  18924. offset = vlen * layer;
  18925. // Top faces
  18926. for ( i = 0; i < flen; i ++ ) {
  18927. face = faces[ i ];
  18928. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  18929. }
  18930. } else {
  18931. // Bottom faces
  18932. for ( i = 0; i < flen; i ++ ) {
  18933. face = faces[ i ];
  18934. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  18935. }
  18936. // Top faces
  18937. for ( i = 0; i < flen; i ++ ) {
  18938. face = faces[ i ];
  18939. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  18940. }
  18941. }
  18942. }
  18943. // Create faces for the z-sides of the shape
  18944. function buildSideFaces() {
  18945. var layeroffset = 0;
  18946. sidewalls( contour, layeroffset );
  18947. layeroffset += contour.length;
  18948. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18949. ahole = holes[ h ];
  18950. sidewalls( ahole, layeroffset );
  18951. //, true
  18952. layeroffset += ahole.length;
  18953. }
  18954. }
  18955. function sidewalls( contour, layeroffset ) {
  18956. var j, k;
  18957. i = contour.length;
  18958. while ( -- i >= 0 ) {
  18959. j = i;
  18960. k = i - 1;
  18961. if ( k < 0 ) k = contour.length - 1;
  18962. //THREE.log('b', i,j, i-1, k,vertices.length);
  18963. var s = 0, sl = steps + bevelSegments * 2;
  18964. for ( s = 0; s < sl; s ++ ) {
  18965. var slen1 = vlen * s;
  18966. var slen2 = vlen * ( s + 1 );
  18967. var a = layeroffset + j + slen1,
  18968. b = layeroffset + k + slen1,
  18969. c = layeroffset + k + slen2,
  18970. d = layeroffset + j + slen2;
  18971. f4( a, b, c, d, contour, s, sl, j, k );
  18972. }
  18973. }
  18974. }
  18975. function v( x, y, z ) {
  18976. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  18977. }
  18978. function f3( a, b, c ) {
  18979. a += shapesOffset;
  18980. b += shapesOffset;
  18981. c += shapesOffset;
  18982. // normal, color, material
  18983. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18984. var uvs = uvgen.generateTopUV( scope, a, b, c );
  18985. scope.faceVertexUvs[ 0 ].push( uvs );
  18986. }
  18987. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18988. a += shapesOffset;
  18989. b += shapesOffset;
  18990. c += shapesOffset;
  18991. d += shapesOffset;
  18992. scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) );
  18993. scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) );
  18994. var uvs = uvgen.generateSideWallUV( scope, a, b, c, d );
  18995. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  18996. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  18997. }
  18998. };
  18999. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19000. generateTopUV: function ( geometry, indexA, indexB, indexC ) {
  19001. var vertices = geometry.vertices;
  19002. var a = vertices[ indexA ];
  19003. var b = vertices[ indexB ];
  19004. var c = vertices[ indexC ];
  19005. return [
  19006. new THREE.Vector2( a.x, a.y ),
  19007. new THREE.Vector2( b.x, b.y ),
  19008. new THREE.Vector2( c.x, c.y )
  19009. ];
  19010. },
  19011. generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) {
  19012. var vertices = geometry.vertices;
  19013. var a = vertices[ indexA ];
  19014. var b = vertices[ indexB ];
  19015. var c = vertices[ indexC ];
  19016. var d = vertices[ indexD ];
  19017. if ( Math.abs( a.y - b.y ) < 0.01 ) {
  19018. return [
  19019. new THREE.Vector2( a.x, 1 - a.z ),
  19020. new THREE.Vector2( b.x, 1 - b.z ),
  19021. new THREE.Vector2( c.x, 1 - c.z ),
  19022. new THREE.Vector2( d.x, 1 - d.z )
  19023. ];
  19024. } else {
  19025. return [
  19026. new THREE.Vector2( a.y, 1 - a.z ),
  19027. new THREE.Vector2( b.y, 1 - b.z ),
  19028. new THREE.Vector2( c.y, 1 - c.z ),
  19029. new THREE.Vector2( d.y, 1 - d.z )
  19030. ];
  19031. }
  19032. }
  19033. };
  19034. // File:src/extras/geometries/ShapeGeometry.js
  19035. /**
  19036. * @author jonobr1 / http://jonobr1.com
  19037. *
  19038. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19039. * ExtrudeGeometry.
  19040. *
  19041. * parameters = {
  19042. *
  19043. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19044. *
  19045. * material: <int> // material index for front and back faces
  19046. * uvGenerator: <Object> // object that provides UV generator functions
  19047. *
  19048. * }
  19049. **/
  19050. THREE.ShapeGeometry = function ( shapes, options ) {
  19051. THREE.Geometry.call( this );
  19052. this.type = 'ShapeGeometry';
  19053. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19054. this.addShapeList( shapes, options );
  19055. this.computeFaceNormals();
  19056. };
  19057. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19058. THREE.ShapeGeometry.prototype.constructor = THREE.ShapeGeometry;
  19059. /**
  19060. * Add an array of shapes to THREE.ShapeGeometry.
  19061. */
  19062. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19063. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  19064. this.addShape( shapes[ i ], options );
  19065. }
  19066. return this;
  19067. };
  19068. /**
  19069. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19070. */
  19071. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19072. if ( options === undefined ) options = {};
  19073. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19074. var material = options.material;
  19075. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19076. //
  19077. var i, l, hole;
  19078. var shapesOffset = this.vertices.length;
  19079. var shapePoints = shape.extractPoints( curveSegments );
  19080. var vertices = shapePoints.shape;
  19081. var holes = shapePoints.holes;
  19082. var reverse = ! THREE.Shape.Utils.isClockWise( vertices );
  19083. if ( reverse ) {
  19084. vertices = vertices.reverse();
  19085. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19086. for ( i = 0, l = holes.length; i < l; i ++ ) {
  19087. hole = holes[ i ];
  19088. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19089. holes[ i ] = hole.reverse();
  19090. }
  19091. }
  19092. reverse = false;
  19093. }
  19094. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19095. // Vertices
  19096. var contour = vertices;
  19097. for ( i = 0, l = holes.length; i < l; i ++ ) {
  19098. hole = holes[ i ];
  19099. vertices = vertices.concat( hole );
  19100. }
  19101. //
  19102. var vert, vlen = vertices.length;
  19103. var face, flen = faces.length;
  19104. for ( i = 0; i < vlen; i ++ ) {
  19105. vert = vertices[ i ];
  19106. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19107. }
  19108. for ( i = 0; i < flen; i ++ ) {
  19109. face = faces[ i ];
  19110. var a = face[ 0 ] + shapesOffset;
  19111. var b = face[ 1 ] + shapesOffset;
  19112. var c = face[ 2 ] + shapesOffset;
  19113. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19114. this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) );
  19115. }
  19116. };
  19117. // File:src/extras/geometries/LatheGeometry.js
  19118. /**
  19119. * @author astrodud / http://astrodud.isgreat.org/
  19120. * @author zz85 / https://github.com/zz85
  19121. * @author bhouston / http://exocortex.com
  19122. */
  19123. // points - to create a closed torus, one must use a set of points
  19124. // like so: [ a, b, c, d, a ], see first is the same as last.
  19125. // segments - the number of circumference segments to create
  19126. // phiStart - the starting radian
  19127. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19128. // 2*pi is a closed lathe, less than 2PI is a portion.
  19129. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19130. THREE.Geometry.call( this );
  19131. this.type = 'LatheGeometry';
  19132. this.parameters = {
  19133. points: points,
  19134. segments: segments,
  19135. phiStart: phiStart,
  19136. phiLength: phiLength
  19137. };
  19138. segments = segments || 12;
  19139. phiStart = phiStart || 0;
  19140. phiLength = phiLength || 2 * Math.PI;
  19141. var inversePointLength = 1.0 / ( points.length - 1 );
  19142. var inverseSegments = 1.0 / segments;
  19143. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19144. var phi = phiStart + i * inverseSegments * phiLength;
  19145. var c = Math.cos( phi ),
  19146. s = Math.sin( phi );
  19147. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19148. var pt = points[ j ];
  19149. var vertex = new THREE.Vector3();
  19150. vertex.x = c * pt.x - s * pt.y;
  19151. vertex.y = s * pt.x + c * pt.y;
  19152. vertex.z = pt.z;
  19153. this.vertices.push( vertex );
  19154. }
  19155. }
  19156. var np = points.length;
  19157. for ( var i = 0, il = segments; i < il; i ++ ) {
  19158. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19159. var base = j + np * i;
  19160. var a = base;
  19161. var b = base + np;
  19162. var c = base + 1 + np;
  19163. var d = base + 1;
  19164. var u0 = i * inverseSegments;
  19165. var v0 = j * inversePointLength;
  19166. var u1 = u0 + inverseSegments;
  19167. var v1 = v0 + inversePointLength;
  19168. this.faces.push( new THREE.Face3( a, b, d ) );
  19169. this.faceVertexUvs[ 0 ].push( [
  19170. new THREE.Vector2( u0, v0 ),
  19171. new THREE.Vector2( u1, v0 ),
  19172. new THREE.Vector2( u0, v1 )
  19173. ] );
  19174. this.faces.push( new THREE.Face3( b, c, d ) );
  19175. this.faceVertexUvs[ 0 ].push( [
  19176. new THREE.Vector2( u1, v0 ),
  19177. new THREE.Vector2( u1, v1 ),
  19178. new THREE.Vector2( u0, v1 )
  19179. ] );
  19180. }
  19181. }
  19182. this.mergeVertices();
  19183. this.computeFaceNormals();
  19184. this.computeVertexNormals();
  19185. };
  19186. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19187. THREE.LatheGeometry.prototype.constructor = THREE.LatheGeometry;
  19188. // File:src/extras/geometries/PlaneGeometry.js
  19189. /**
  19190. * @author mrdoob / http://mrdoob.com/
  19191. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19192. */
  19193. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19194. THREE.log( 'THREE.PlaneGeometry: Consider using THREE.PlaneBufferGeometry for lower memory footprint.' );
  19195. THREE.Geometry.call( this );
  19196. this.type = 'PlaneGeometry';
  19197. this.parameters = {
  19198. width: width,
  19199. height: height,
  19200. widthSegments: widthSegments,
  19201. heightSegments: heightSegments
  19202. };
  19203. this.fromBufferGeometry( new THREE.PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  19204. };
  19205. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19206. THREE.PlaneGeometry.prototype.constructor = THREE.PlaneGeometry;
  19207. // File:src/extras/geometries/PlaneBufferGeometry.js
  19208. /**
  19209. * @author mrdoob / http://mrdoob.com/
  19210. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19211. */
  19212. THREE.PlaneBufferGeometry = function ( width, height, widthSegments, heightSegments ) {
  19213. THREE.BufferGeometry.call( this );
  19214. this.type = 'PlaneBufferGeometry';
  19215. this.parameters = {
  19216. width: width,
  19217. height: height,
  19218. widthSegments: widthSegments,
  19219. heightSegments: heightSegments
  19220. };
  19221. var width_half = width / 2;
  19222. var height_half = height / 2;
  19223. var gridX = widthSegments || 1;
  19224. var gridY = heightSegments || 1;
  19225. var gridX1 = gridX + 1;
  19226. var gridY1 = gridY + 1;
  19227. var segment_width = width / gridX;
  19228. var segment_height = height / gridY;
  19229. var vertices = new Float32Array( gridX1 * gridY1 * 3 );
  19230. var normals = new Float32Array( gridX1 * gridY1 * 3 );
  19231. var uvs = new Float32Array( gridX1 * gridY1 * 2 );
  19232. var offset = 0;
  19233. var offset2 = 0;
  19234. for ( var iy = 0; iy < gridY1; iy ++ ) {
  19235. var y = iy * segment_height - height_half;
  19236. for ( var ix = 0; ix < gridX1; ix ++ ) {
  19237. var x = ix * segment_width - width_half;
  19238. vertices[ offset ] = x;
  19239. vertices[ offset + 1 ] = - y;
  19240. normals[ offset + 2 ] = 1;
  19241. uvs[ offset2 ] = ix / gridX;
  19242. uvs[ offset2 + 1 ] = 1 - ( iy / gridY );
  19243. offset += 3;
  19244. offset2 += 2;
  19245. }
  19246. }
  19247. offset = 0;
  19248. var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 );
  19249. for ( var iy = 0; iy < gridY; iy ++ ) {
  19250. for ( var ix = 0; ix < gridX; ix ++ ) {
  19251. var a = ix + gridX1 * iy;
  19252. var b = ix + gridX1 * ( iy + 1 );
  19253. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  19254. var d = ( ix + 1 ) + gridX1 * iy;
  19255. indices[ offset ] = a;
  19256. indices[ offset + 1 ] = b;
  19257. indices[ offset + 2 ] = d;
  19258. indices[ offset + 3 ] = b;
  19259. indices[ offset + 4 ] = c;
  19260. indices[ offset + 5 ] = d;
  19261. offset += 6;
  19262. }
  19263. }
  19264. this.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) );
  19265. this.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  19266. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  19267. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  19268. };
  19269. THREE.PlaneBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  19270. THREE.PlaneBufferGeometry.prototype.constructor = THREE.PlaneBufferGeometry;
  19271. // File:src/extras/geometries/RingGeometry.js
  19272. /**
  19273. * @author Kaleb Murphy
  19274. */
  19275. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19276. THREE.Geometry.call( this );
  19277. this.type = 'RingGeometry';
  19278. this.parameters = {
  19279. innerRadius: innerRadius,
  19280. outerRadius: outerRadius,
  19281. thetaSegments: thetaSegments,
  19282. phiSegments: phiSegments,
  19283. thetaStart: thetaStart,
  19284. thetaLength: thetaLength
  19285. };
  19286. innerRadius = innerRadius || 0;
  19287. outerRadius = outerRadius || 50;
  19288. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19289. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19290. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19291. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 8;
  19292. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19293. for ( i = 0; i < phiSegments + 1; i ++ ) { // concentric circles inside ring
  19294. for ( o = 0; o < thetaSegments + 1; o ++ ) { // number of segments per circle
  19295. var vertex = new THREE.Vector3();
  19296. var segment = thetaStart + o / thetaSegments * thetaLength;
  19297. vertex.x = radius * Math.cos( segment );
  19298. vertex.y = radius * Math.sin( segment );
  19299. this.vertices.push( vertex );
  19300. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  19301. }
  19302. radius += radiusStep;
  19303. }
  19304. var n = new THREE.Vector3( 0, 0, 1 );
  19305. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19306. var thetaSegment = i * (thetaSegments + 1);
  19307. for ( o = 0; o < thetaSegments ; o ++ ) { // number of segments per circle
  19308. var segment = o + thetaSegment;
  19309. var v1 = segment;
  19310. var v2 = segment + thetaSegments + 1;
  19311. var v3 = segment + thetaSegments + 2;
  19312. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19313. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19314. v1 = segment;
  19315. v2 = segment + thetaSegments + 2;
  19316. v3 = segment + 1;
  19317. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19318. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19319. }
  19320. }
  19321. this.computeFaceNormals();
  19322. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19323. };
  19324. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19325. THREE.RingGeometry.prototype.constructor = THREE.RingGeometry;
  19326. // File:src/extras/geometries/SphereGeometry.js
  19327. /**
  19328. * @author mrdoob / http://mrdoob.com/
  19329. */
  19330. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19331. THREE.Geometry.call( this );
  19332. this.type = 'SphereGeometry';
  19333. this.parameters = {
  19334. radius: radius,
  19335. widthSegments: widthSegments,
  19336. heightSegments: heightSegments,
  19337. phiStart: phiStart,
  19338. phiLength: phiLength,
  19339. thetaStart: thetaStart,
  19340. thetaLength: thetaLength
  19341. };
  19342. radius = radius || 50;
  19343. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19344. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19345. phiStart = phiStart !== undefined ? phiStart : 0;
  19346. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19347. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19348. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19349. var x, y, vertices = [], uvs = [];
  19350. for ( y = 0; y <= heightSegments; y ++ ) {
  19351. var verticesRow = [];
  19352. var uvsRow = [];
  19353. for ( x = 0; x <= widthSegments; x ++ ) {
  19354. var u = x / widthSegments;
  19355. var v = y / heightSegments;
  19356. var vertex = new THREE.Vector3();
  19357. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19358. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19359. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19360. this.vertices.push( vertex );
  19361. verticesRow.push( this.vertices.length - 1 );
  19362. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19363. }
  19364. vertices.push( verticesRow );
  19365. uvs.push( uvsRow );
  19366. }
  19367. for ( y = 0; y < heightSegments; y ++ ) {
  19368. for ( x = 0; x < widthSegments; x ++ ) {
  19369. var v1 = vertices[ y ][ x + 1 ];
  19370. var v2 = vertices[ y ][ x ];
  19371. var v3 = vertices[ y + 1 ][ x ];
  19372. var v4 = vertices[ y + 1 ][ x + 1 ];
  19373. var n1 = this.vertices[ v1 ].clone().normalize();
  19374. var n2 = this.vertices[ v2 ].clone().normalize();
  19375. var n3 = this.vertices[ v3 ].clone().normalize();
  19376. var n4 = this.vertices[ v4 ].clone().normalize();
  19377. var uv1 = uvs[ y ][ x + 1 ].clone();
  19378. var uv2 = uvs[ y ][ x ].clone();
  19379. var uv3 = uvs[ y + 1 ][ x ].clone();
  19380. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19381. if ( Math.abs( this.vertices[ v1 ].y ) === radius ) {
  19382. uv1.x = ( uv1.x + uv2.x ) / 2;
  19383. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19384. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19385. } else if ( Math.abs( this.vertices[ v3 ].y ) === radius ) {
  19386. uv3.x = ( uv3.x + uv4.x ) / 2;
  19387. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19388. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19389. } else {
  19390. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19391. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19392. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  19393. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  19394. }
  19395. }
  19396. }
  19397. this.computeFaceNormals();
  19398. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19399. };
  19400. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19401. THREE.SphereGeometry.prototype.constructor = THREE.SphereGeometry;
  19402. // File:src/extras/geometries/TextGeometry.js
  19403. /**
  19404. * @author zz85 / http://www.lab4games.net/zz85/blog
  19405. * @author alteredq / http://alteredqualia.com/
  19406. *
  19407. * For creating 3D text geometry in three.js
  19408. *
  19409. * Text = 3D Text
  19410. *
  19411. * parameters = {
  19412. * size: <float>, // size of the text
  19413. * height: <float>, // thickness to extrude text
  19414. * curveSegments: <int>, // number of points on the curves
  19415. *
  19416. * font: <string>, // font name
  19417. * weight: <string>, // font weight (normal, bold)
  19418. * style: <string>, // font style (normal, italics)
  19419. *
  19420. * bevelEnabled: <bool>, // turn on bevel
  19421. * bevelThickness: <float>, // how deep into text bevel goes
  19422. * bevelSize: <float>, // how far from text outline is bevel
  19423. * }
  19424. *
  19425. */
  19426. /* Usage Examples
  19427. // TextGeometry wrapper
  19428. var text3d = new TextGeometry( text, options );
  19429. // Complete manner
  19430. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19431. var text3d = new ExtrudeGeometry( textShapes, options );
  19432. */
  19433. THREE.TextGeometry = function ( text, parameters ) {
  19434. parameters = parameters || {};
  19435. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19436. // translate parameters to ExtrudeGeometry API
  19437. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19438. // defaults
  19439. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19440. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19441. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19442. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19443. this.type = 'TextGeometry';
  19444. };
  19445. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19446. THREE.TextGeometry.prototype.constructor = THREE.TextGeometry;
  19447. // File:src/extras/geometries/TorusGeometry.js
  19448. /**
  19449. * @author oosmoxiecode
  19450. * @author mrdoob / http://mrdoob.com/
  19451. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19452. */
  19453. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19454. THREE.Geometry.call( this );
  19455. this.type = 'TorusGeometry';
  19456. this.parameters = {
  19457. radius: radius,
  19458. tube: tube,
  19459. radialSegments: radialSegments,
  19460. tubularSegments: tubularSegments,
  19461. arc: arc
  19462. };
  19463. radius = radius || 100;
  19464. tube = tube || 40;
  19465. radialSegments = radialSegments || 8;
  19466. tubularSegments = tubularSegments || 6;
  19467. arc = arc || Math.PI * 2;
  19468. var center = new THREE.Vector3(), uvs = [], normals = [];
  19469. for ( var j = 0; j <= radialSegments; j ++ ) {
  19470. for ( var i = 0; i <= tubularSegments; i ++ ) {
  19471. var u = i / tubularSegments * arc;
  19472. var v = j / radialSegments * Math.PI * 2;
  19473. center.x = radius * Math.cos( u );
  19474. center.y = radius * Math.sin( u );
  19475. var vertex = new THREE.Vector3();
  19476. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  19477. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  19478. vertex.z = tube * Math.sin( v );
  19479. this.vertices.push( vertex );
  19480. uvs.push( new THREE.Vector2( i / tubularSegments, j / radialSegments ) );
  19481. normals.push( vertex.clone().sub( center ).normalize() );
  19482. }
  19483. }
  19484. for ( var j = 1; j <= radialSegments; j ++ ) {
  19485. for ( var i = 1; i <= tubularSegments; i ++ ) {
  19486. var a = ( tubularSegments + 1 ) * j + i - 1;
  19487. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19488. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  19489. var d = ( tubularSegments + 1 ) * j + i;
  19490. var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
  19491. this.faces.push( face );
  19492. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  19493. face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
  19494. this.faces.push( face );
  19495. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19496. }
  19497. }
  19498. this.computeFaceNormals();
  19499. };
  19500. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19501. THREE.TorusGeometry.prototype.constructor = THREE.TorusGeometry;
  19502. // File:src/extras/geometries/TorusKnotGeometry.js
  19503. /**
  19504. * @author oosmoxiecode
  19505. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19506. */
  19507. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19508. THREE.Geometry.call( this );
  19509. this.type = 'TorusKnotGeometry';
  19510. this.parameters = {
  19511. radius: radius,
  19512. tube: tube,
  19513. radialSegments: radialSegments,
  19514. tubularSegments: tubularSegments,
  19515. p: p,
  19516. q: q,
  19517. heightScale: heightScale
  19518. };
  19519. radius = radius || 100;
  19520. tube = tube || 40;
  19521. radialSegments = radialSegments || 64;
  19522. tubularSegments = tubularSegments || 8;
  19523. p = p || 2;
  19524. q = q || 3;
  19525. heightScale = heightScale || 1;
  19526. var grid = new Array( radialSegments );
  19527. var tang = new THREE.Vector3();
  19528. var n = new THREE.Vector3();
  19529. var bitan = new THREE.Vector3();
  19530. for ( var i = 0; i < radialSegments; ++ i ) {
  19531. grid[ i ] = new Array( tubularSegments );
  19532. var u = i / radialSegments * 2 * p * Math.PI;
  19533. var p1 = getPos( u, q, p, radius, heightScale );
  19534. var p2 = getPos( u + 0.01, q, p, radius, heightScale );
  19535. tang.subVectors( p2, p1 );
  19536. n.addVectors( p2, p1 );
  19537. bitan.crossVectors( tang, n );
  19538. n.crossVectors( bitan, tang );
  19539. bitan.normalize();
  19540. n.normalize();
  19541. for ( var j = 0; j < tubularSegments; ++ j ) {
  19542. var v = j / tubularSegments * 2 * Math.PI;
  19543. var cx = - tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19544. var cy = tube * Math.sin( v );
  19545. var pos = new THREE.Vector3();
  19546. pos.x = p1.x + cx * n.x + cy * bitan.x;
  19547. pos.y = p1.y + cx * n.y + cy * bitan.y;
  19548. pos.z = p1.z + cx * n.z + cy * bitan.z;
  19549. grid[ i ][ j ] = this.vertices.push( pos ) - 1;
  19550. }
  19551. }
  19552. for ( var i = 0; i < radialSegments; ++ i ) {
  19553. for ( var j = 0; j < tubularSegments; ++ j ) {
  19554. var ip = ( i + 1 ) % radialSegments;
  19555. var jp = ( j + 1 ) % tubularSegments;
  19556. var a = grid[ i ][ j ];
  19557. var b = grid[ ip ][ j ];
  19558. var c = grid[ ip ][ jp ];
  19559. var d = grid[ i ][ jp ];
  19560. var uva = new THREE.Vector2( i / radialSegments, j / tubularSegments );
  19561. var uvb = new THREE.Vector2( ( i + 1 ) / radialSegments, j / tubularSegments );
  19562. var uvc = new THREE.Vector2( ( i + 1 ) / radialSegments, ( j + 1 ) / tubularSegments );
  19563. var uvd = new THREE.Vector2( i / radialSegments, ( j + 1 ) / tubularSegments );
  19564. this.faces.push( new THREE.Face3( a, b, d ) );
  19565. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19566. this.faces.push( new THREE.Face3( b, c, d ) );
  19567. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19568. }
  19569. }
  19570. this.computeFaceNormals();
  19571. this.computeVertexNormals();
  19572. function getPos( u, in_q, in_p, radius, heightScale ) {
  19573. var cu = Math.cos( u );
  19574. var su = Math.sin( u );
  19575. var quOverP = in_q / in_p * u;
  19576. var cs = Math.cos( quOverP );
  19577. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19578. var ty = radius * ( 2 + cs ) * su * 0.5;
  19579. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19580. return new THREE.Vector3( tx, ty, tz );
  19581. }
  19582. };
  19583. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19584. THREE.TorusKnotGeometry.prototype.constructor = THREE.TorusKnotGeometry;
  19585. // File:src/extras/geometries/TubeGeometry.js
  19586. /**
  19587. * @author WestLangley / https://github.com/WestLangley
  19588. * @author zz85 / https://github.com/zz85
  19589. * @author miningold / https://github.com/miningold
  19590. * @author jonobr1 / https://github.com/jonobr1
  19591. *
  19592. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19593. *
  19594. * Creates a tube which extrudes along a 3d spline
  19595. *
  19596. * Uses parallel transport frames as described in
  19597. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19598. */
  19599. THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, taper ) {
  19600. THREE.Geometry.call( this );
  19601. this.type = 'TubeGeometry';
  19602. this.parameters = {
  19603. path: path,
  19604. segments: segments,
  19605. radius: radius,
  19606. radialSegments: radialSegments,
  19607. closed: closed
  19608. };
  19609. segments = segments || 64;
  19610. radius = radius || 1;
  19611. radialSegments = radialSegments || 8;
  19612. closed = closed || false;
  19613. taper = taper || THREE.TubeGeometry.NoTaper;
  19614. var grid = [];
  19615. var scope = this,
  19616. tangent,
  19617. normal,
  19618. binormal,
  19619. numpoints = segments + 1,
  19620. u, v, r,
  19621. cx, cy,
  19622. pos, pos2 = new THREE.Vector3(),
  19623. i, j,
  19624. ip, jp,
  19625. a, b, c, d,
  19626. uva, uvb, uvc, uvd;
  19627. var frames = new THREE.TubeGeometry.FrenetFrames( path, segments, closed ),
  19628. tangents = frames.tangents,
  19629. normals = frames.normals,
  19630. binormals = frames.binormals;
  19631. // proxy internals
  19632. this.tangents = tangents;
  19633. this.normals = normals;
  19634. this.binormals = binormals;
  19635. function vert( x, y, z ) {
  19636. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19637. }
  19638. // consruct the grid
  19639. for ( i = 0; i < numpoints; i ++ ) {
  19640. grid[ i ] = [];
  19641. u = i / ( numpoints - 1 );
  19642. pos = path.getPointAt( u );
  19643. tangent = tangents[ i ];
  19644. normal = normals[ i ];
  19645. binormal = binormals[ i ];
  19646. r = radius * taper( u );
  19647. for ( j = 0; j < radialSegments; j ++ ) {
  19648. v = j / radialSegments * 2 * Math.PI;
  19649. cx = - r * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19650. cy = r * Math.sin( v );
  19651. pos2.copy( pos );
  19652. pos2.x += cx * normal.x + cy * binormal.x;
  19653. pos2.y += cx * normal.y + cy * binormal.y;
  19654. pos2.z += cx * normal.z + cy * binormal.z;
  19655. grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19656. }
  19657. }
  19658. // construct the mesh
  19659. for ( i = 0; i < segments; i ++ ) {
  19660. for ( j = 0; j < radialSegments; j ++ ) {
  19661. ip = ( closed ) ? (i + 1) % segments : i + 1;
  19662. jp = (j + 1) % radialSegments;
  19663. a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19664. b = grid[ ip ][ j ];
  19665. c = grid[ ip ][ jp ];
  19666. d = grid[ i ][ jp ];
  19667. uva = new THREE.Vector2( i / segments, j / radialSegments );
  19668. uvb = new THREE.Vector2( ( i + 1 ) / segments, j / radialSegments );
  19669. uvc = new THREE.Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments );
  19670. uvd = new THREE.Vector2( i / segments, ( j + 1 ) / radialSegments );
  19671. this.faces.push( new THREE.Face3( a, b, d ) );
  19672. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19673. this.faces.push( new THREE.Face3( b, c, d ) );
  19674. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19675. }
  19676. }
  19677. this.computeFaceNormals();
  19678. this.computeVertexNormals();
  19679. };
  19680. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19681. THREE.TubeGeometry.prototype.constructor = THREE.TubeGeometry;
  19682. THREE.TubeGeometry.NoTaper = function ( u ) {
  19683. return 1;
  19684. };
  19685. THREE.TubeGeometry.SinusoidalTaper = function ( u ) {
  19686. return Math.sin( Math.PI * u );
  19687. };
  19688. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19689. THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) {
  19690. var normal = new THREE.Vector3(),
  19691. tangents = [],
  19692. normals = [],
  19693. binormals = [],
  19694. vec = new THREE.Vector3(),
  19695. mat = new THREE.Matrix4(),
  19696. numpoints = segments + 1,
  19697. theta,
  19698. epsilon = 0.0001,
  19699. smallest,
  19700. tx, ty, tz,
  19701. i, u;
  19702. // expose internals
  19703. this.tangents = tangents;
  19704. this.normals = normals;
  19705. this.binormals = binormals;
  19706. // compute the tangent vectors for each segment on the path
  19707. for ( i = 0; i < numpoints; i ++ ) {
  19708. u = i / ( numpoints - 1 );
  19709. tangents[ i ] = path.getTangentAt( u );
  19710. tangents[ i ].normalize();
  19711. }
  19712. initialNormal3();
  19713. /*
  19714. function initialNormal1(lastBinormal) {
  19715. // fixed start binormal. Has dangers of 0 vectors
  19716. normals[ 0 ] = new THREE.Vector3();
  19717. binormals[ 0 ] = new THREE.Vector3();
  19718. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19719. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19720. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19721. }
  19722. function initialNormal2() {
  19723. // This uses the Frenet-Serret formula for deriving binormal
  19724. var t2 = path.getTangentAt( epsilon );
  19725. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  19726. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  19727. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19728. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19729. }
  19730. */
  19731. function initialNormal3() {
  19732. // select an initial normal vector perpenicular to the first tangent vector,
  19733. // and in the direction of the smallest tangent xyz component
  19734. normals[ 0 ] = new THREE.Vector3();
  19735. binormals[ 0 ] = new THREE.Vector3();
  19736. smallest = Number.MAX_VALUE;
  19737. tx = Math.abs( tangents[ 0 ].x );
  19738. ty = Math.abs( tangents[ 0 ].y );
  19739. tz = Math.abs( tangents[ 0 ].z );
  19740. if ( tx <= smallest ) {
  19741. smallest = tx;
  19742. normal.set( 1, 0, 0 );
  19743. }
  19744. if ( ty <= smallest ) {
  19745. smallest = ty;
  19746. normal.set( 0, 1, 0 );
  19747. }
  19748. if ( tz <= smallest ) {
  19749. normal.set( 0, 0, 1 );
  19750. }
  19751. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19752. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19753. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19754. }
  19755. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19756. for ( i = 1; i < numpoints; i ++ ) {
  19757. normals[ i ] = normals[ i - 1 ].clone();
  19758. binormals[ i ] = binormals[ i - 1 ].clone();
  19759. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  19760. if ( vec.length() > epsilon ) {
  19761. vec.normalize();
  19762. theta = Math.acos( THREE.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  19763. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19764. }
  19765. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19766. }
  19767. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19768. if ( closed ) {
  19769. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) );
  19770. theta /= ( numpoints - 1 );
  19771. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) {
  19772. theta = - theta;
  19773. }
  19774. for ( i = 1; i < numpoints; i ++ ) {
  19775. // twist a little...
  19776. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19777. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19778. }
  19779. }
  19780. };
  19781. // File:src/extras/geometries/PolyhedronGeometry.js
  19782. /**
  19783. * @author clockworkgeek / https://github.com/clockworkgeek
  19784. * @author timothypratley / https://github.com/timothypratley
  19785. * @author WestLangley / http://github.com/WestLangley
  19786. */
  19787. THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) {
  19788. THREE.Geometry.call( this );
  19789. this.type = 'PolyhedronGeometry';
  19790. this.parameters = {
  19791. vertices: vertices,
  19792. indices: indices,
  19793. radius: radius,
  19794. detail: detail
  19795. };
  19796. radius = radius || 1;
  19797. detail = detail || 0;
  19798. var that = this;
  19799. for ( var i = 0, l = vertices.length; i < l; i += 3 ) {
  19800. prepare( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  19801. }
  19802. var p = this.vertices;
  19803. var faces = [];
  19804. for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) {
  19805. var v1 = p[ indices[ i ] ];
  19806. var v2 = p[ indices[ i + 1 ] ];
  19807. var v3 = p[ indices[ i + 2 ] ];
  19808. faces[ j ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19809. }
  19810. var centroid = new THREE.Vector3();
  19811. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19812. subdivide( faces[ i ], detail );
  19813. }
  19814. // Handle case when face straddles the seam
  19815. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  19816. var uvs = this.faceVertexUvs[ 0 ][ i ];
  19817. var x0 = uvs[ 0 ].x;
  19818. var x1 = uvs[ 1 ].x;
  19819. var x2 = uvs[ 2 ].x;
  19820. var max = Math.max( x0, Math.max( x1, x2 ) );
  19821. var min = Math.min( x0, Math.min( x1, x2 ) );
  19822. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  19823. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  19824. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  19825. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  19826. }
  19827. }
  19828. // Apply radius
  19829. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19830. this.vertices[ i ].multiplyScalar( radius );
  19831. }
  19832. // Merge vertices
  19833. this.mergeVertices();
  19834. this.computeFaceNormals();
  19835. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19836. // Project vector onto sphere's surface
  19837. function prepare( vector ) {
  19838. var vertex = vector.normalize().clone();
  19839. vertex.index = that.vertices.push( vertex ) - 1;
  19840. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19841. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19842. var v = inclination( vector ) / Math.PI + 0.5;
  19843. vertex.uv = new THREE.Vector2( u, 1 - v );
  19844. return vertex;
  19845. }
  19846. // Approximate a curved face with recursively sub-divided triangles.
  19847. function make( v1, v2, v3 ) {
  19848. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19849. that.faces.push( face );
  19850. centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  19851. var azi = azimuth( centroid );
  19852. that.faceVertexUvs[ 0 ].push( [
  19853. correctUV( v1.uv, v1, azi ),
  19854. correctUV( v2.uv, v2, azi ),
  19855. correctUV( v3.uv, v3, azi )
  19856. ] );
  19857. }
  19858. // Analytically subdivide a face to the required detail level.
  19859. function subdivide( face, detail ) {
  19860. var cols = Math.pow(2, detail);
  19861. var a = prepare( that.vertices[ face.a ] );
  19862. var b = prepare( that.vertices[ face.b ] );
  19863. var c = prepare( that.vertices[ face.c ] );
  19864. var v = [];
  19865. // Construct all of the vertices for this subdivision.
  19866. for ( var i = 0 ; i <= cols; i ++ ) {
  19867. v[ i ] = [];
  19868. var aj = prepare( a.clone().lerp( c, i / cols ) );
  19869. var bj = prepare( b.clone().lerp( c, i / cols ) );
  19870. var rows = cols - i;
  19871. for ( var j = 0; j <= rows; j ++) {
  19872. if ( j == 0 && i == cols ) {
  19873. v[ i ][ j ] = aj;
  19874. } else {
  19875. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  19876. }
  19877. }
  19878. }
  19879. // Construct all of the faces.
  19880. for ( var i = 0; i < cols ; i ++ ) {
  19881. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  19882. var k = Math.floor( j / 2 );
  19883. if ( j % 2 == 0 ) {
  19884. make(
  19885. v[ i ][ k + 1],
  19886. v[ i + 1 ][ k ],
  19887. v[ i ][ k ]
  19888. );
  19889. } else {
  19890. make(
  19891. v[ i ][ k + 1 ],
  19892. v[ i + 1][ k + 1],
  19893. v[ i + 1 ][ k ]
  19894. );
  19895. }
  19896. }
  19897. }
  19898. }
  19899. // Angle around the Y axis, counter-clockwise when looking from above.
  19900. function azimuth( vector ) {
  19901. return Math.atan2( vector.z, - vector.x );
  19902. }
  19903. // Angle above the XZ plane.
  19904. function inclination( vector ) {
  19905. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19906. }
  19907. // Texture fixing helper. Spheres have some odd behaviours.
  19908. function correctUV( uv, vector, azimuth ) {
  19909. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  19910. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  19911. return uv.clone();
  19912. }
  19913. };
  19914. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19915. THREE.PolyhedronGeometry.prototype.constructor = THREE.PolyhedronGeometry;
  19916. // File:src/extras/geometries/DodecahedronGeometry.js
  19917. /**
  19918. * @author Abe Pazos / https://hamoid.com
  19919. */
  19920. THREE.DodecahedronGeometry = function ( radius, detail ) {
  19921. this.parameters = {
  19922. radius: radius,
  19923. detail: detail
  19924. };
  19925. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19926. var r = 1 / t;
  19927. var vertices = [
  19928. // (±1, ±1, ±1)
  19929. -1, -1, -1, -1, -1, 1,
  19930. -1, 1, -1, -1, 1, 1,
  19931. 1, -1, -1, 1, -1, 1,
  19932. 1, 1, -1, 1, 1, 1,
  19933. // (0, ±1/φ, ±φ)
  19934. 0, -r, -t, 0, -r, t,
  19935. 0, r, -t, 0, r, t,
  19936. // (±1/φ, ±φ, 0)
  19937. -r, -t, 0, -r, t, 0,
  19938. r, -t, 0, r, t, 0,
  19939. // (±φ, 0, ±1/φ)
  19940. -t, 0, -r, t, 0, -r,
  19941. -t, 0, r, t, 0, r
  19942. ];
  19943. var indices = [
  19944. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  19945. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  19946. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  19947. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  19948. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  19949. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  19950. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  19951. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  19952. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  19953. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  19954. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  19955. 1, 12, 14, 1, 14, 5, 1, 5, 9
  19956. ];
  19957. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  19958. };
  19959. THREE.DodecahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19960. THREE.DodecahedronGeometry.prototype.constructor = THREE.DodecahedronGeometry;
  19961. // File:src/extras/geometries/IcosahedronGeometry.js
  19962. /**
  19963. * @author timothypratley / https://github.com/timothypratley
  19964. */
  19965. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19966. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19967. var vertices = [
  19968. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  19969. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  19970. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  19971. ];
  19972. var indices = [
  19973. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  19974. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  19975. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  19976. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  19977. ];
  19978. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  19979. this.type = 'IcosahedronGeometry';
  19980. this.parameters = {
  19981. radius: radius,
  19982. detail: detail
  19983. };
  19984. };
  19985. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19986. THREE.IcosahedronGeometry.prototype.constructor = THREE.IcosahedronGeometry;
  19987. // File:src/extras/geometries/OctahedronGeometry.js
  19988. /**
  19989. * @author timothypratley / https://github.com/timothypratley
  19990. */
  19991. THREE.OctahedronGeometry = function ( radius, detail ) {
  19992. this.parameters = {
  19993. radius: radius,
  19994. detail: detail
  19995. };
  19996. var vertices = [
  19997. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0,- 1, 0, 0, 0, 1, 0, 0,- 1
  19998. ];
  19999. var indices = [
  20000. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  20001. ];
  20002. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  20003. this.type = 'OctahedronGeometry';
  20004. this.parameters = {
  20005. radius: radius,
  20006. detail: detail
  20007. };
  20008. };
  20009. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20010. THREE.OctahedronGeometry.prototype.constructor = THREE.OctahedronGeometry;
  20011. // File:src/extras/geometries/TetrahedronGeometry.js
  20012. /**
  20013. * @author timothypratley / https://github.com/timothypratley
  20014. */
  20015. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20016. var vertices = [
  20017. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  20018. ];
  20019. var indices = [
  20020. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  20021. ];
  20022. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  20023. this.type = 'TetrahedronGeometry';
  20024. this.parameters = {
  20025. radius: radius,
  20026. detail: detail
  20027. };
  20028. };
  20029. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20030. THREE.TetrahedronGeometry.prototype.constructor = THREE.TetrahedronGeometry;
  20031. // File:src/extras/geometries/ParametricGeometry.js
  20032. /**
  20033. * @author zz85 / https://github.com/zz85
  20034. * Parametric Surfaces Geometry
  20035. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20036. *
  20037. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  20038. *
  20039. */
  20040. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  20041. THREE.Geometry.call( this );
  20042. this.type = 'ParametricGeometry';
  20043. this.parameters = {
  20044. func: func,
  20045. slices: slices,
  20046. stacks: stacks
  20047. };
  20048. var verts = this.vertices;
  20049. var faces = this.faces;
  20050. var uvs = this.faceVertexUvs[ 0 ];
  20051. var i, j, p;
  20052. var u, v;
  20053. var sliceCount = slices + 1;
  20054. for ( i = 0; i <= stacks; i ++ ) {
  20055. v = i / stacks;
  20056. for ( j = 0; j <= slices; j ++ ) {
  20057. u = j / slices;
  20058. p = func( u, v );
  20059. verts.push( p );
  20060. }
  20061. }
  20062. var a, b, c, d;
  20063. var uva, uvb, uvc, uvd;
  20064. for ( i = 0; i < stacks; i ++ ) {
  20065. for ( j = 0; j < slices; j ++ ) {
  20066. a = i * sliceCount + j;
  20067. b = i * sliceCount + j + 1;
  20068. c = (i + 1) * sliceCount + j + 1;
  20069. d = (i + 1) * sliceCount + j;
  20070. uva = new THREE.Vector2( j / slices, i / stacks );
  20071. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20072. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20073. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20074. faces.push( new THREE.Face3( a, b, d ) );
  20075. uvs.push( [ uva, uvb, uvd ] );
  20076. faces.push( new THREE.Face3( b, c, d ) );
  20077. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  20078. }
  20079. }
  20080. // THREE.log(this);
  20081. // magic bullet
  20082. // var diff = this.mergeVertices();
  20083. // THREE.log('removed ', diff, ' vertices by merging');
  20084. this.computeFaceNormals();
  20085. this.computeVertexNormals();
  20086. };
  20087. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20088. THREE.ParametricGeometry.prototype.constructor = THREE.ParametricGeometry;
  20089. // File:src/extras/helpers/AxisHelper.js
  20090. /**
  20091. * @author sroucheray / http://sroucheray.org/
  20092. * @author mrdoob / http://mrdoob.com/
  20093. */
  20094. THREE.AxisHelper = function ( size ) {
  20095. size = size || 1;
  20096. var vertices = new Float32Array( [
  20097. 0, 0, 0, size, 0, 0,
  20098. 0, 0, 0, 0, size, 0,
  20099. 0, 0, 0, 0, 0, size
  20100. ] );
  20101. var colors = new Float32Array( [
  20102. 1, 0, 0, 1, 0.6, 0,
  20103. 0, 1, 0, 0.6, 1, 0,
  20104. 0, 0, 1, 0, 0.6, 1
  20105. ] );
  20106. var geometry = new THREE.BufferGeometry();
  20107. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  20108. geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
  20109. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20110. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20111. };
  20112. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20113. THREE.AxisHelper.prototype.constructor = THREE.AxisHelper;
  20114. // File:src/extras/helpers/ArrowHelper.js
  20115. /**
  20116. * @author WestLangley / http://github.com/WestLangley
  20117. * @author zz85 / http://github.com/zz85
  20118. * @author bhouston / http://exocortex.com
  20119. *
  20120. * Creates an arrow for visualizing directions
  20121. *
  20122. * Parameters:
  20123. * dir - Vector3
  20124. * origin - Vector3
  20125. * length - Number
  20126. * color - color in hex value
  20127. * headLength - Number
  20128. * headWidth - Number
  20129. */
  20130. THREE.ArrowHelper = ( function () {
  20131. var lineGeometry = new THREE.Geometry();
  20132. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) );
  20133. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  20134. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  20135. return function ( dir, origin, length, color, headLength, headWidth ) {
  20136. // dir is assumed to be normalized
  20137. THREE.Object3D.call( this );
  20138. if ( color === undefined ) color = 0xffff00;
  20139. if ( length === undefined ) length = 1;
  20140. if ( headLength === undefined ) headLength = 0.2 * length;
  20141. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20142. this.position.copy( origin );
  20143. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: color } ) );
  20144. this.line.matrixAutoUpdate = false;
  20145. this.add( this.line );
  20146. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: color } ) );
  20147. this.cone.matrixAutoUpdate = false;
  20148. this.add( this.cone );
  20149. this.setDirection( dir );
  20150. this.setLength( length, headLength, headWidth );
  20151. }
  20152. }() );
  20153. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20154. THREE.ArrowHelper.prototype.constructor = THREE.ArrowHelper;
  20155. THREE.ArrowHelper.prototype.setDirection = ( function () {
  20156. var axis = new THREE.Vector3();
  20157. var radians;
  20158. return function ( dir ) {
  20159. // dir is assumed to be normalized
  20160. if ( dir.y > 0.99999 ) {
  20161. this.quaternion.set( 0, 0, 0, 1 );
  20162. } else if ( dir.y < - 0.99999 ) {
  20163. this.quaternion.set( 1, 0, 0, 0 );
  20164. } else {
  20165. axis.set( dir.z, 0, - dir.x ).normalize();
  20166. radians = Math.acos( dir.y );
  20167. this.quaternion.setFromAxisAngle( axis, radians );
  20168. }
  20169. };
  20170. }() );
  20171. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  20172. if ( headLength === undefined ) headLength = 0.2 * length;
  20173. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20174. this.line.scale.set( 1, length - headLength, 1 );
  20175. this.line.updateMatrix();
  20176. this.cone.scale.set( headWidth, headLength, headWidth );
  20177. this.cone.position.y = length;
  20178. this.cone.updateMatrix();
  20179. };
  20180. THREE.ArrowHelper.prototype.setColor = function ( color ) {
  20181. this.line.material.color.set( color );
  20182. this.cone.material.color.set( color );
  20183. };
  20184. // File:src/extras/helpers/BoxHelper.js
  20185. /**
  20186. * @author mrdoob / http://mrdoob.com/
  20187. */
  20188. THREE.BoxHelper = function ( object ) {
  20189. var geometry = new THREE.BufferGeometry();
  20190. geometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( 72 ), 3 ) );
  20191. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  20192. if ( object !== undefined ) {
  20193. this.update( object );
  20194. }
  20195. };
  20196. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20197. THREE.BoxHelper.prototype.constructor = THREE.BoxHelper;
  20198. THREE.BoxHelper.prototype.update = function ( object ) {
  20199. var geometry = object.geometry;
  20200. if ( geometry.boundingBox === null ) {
  20201. geometry.computeBoundingBox();
  20202. }
  20203. var min = geometry.boundingBox.min;
  20204. var max = geometry.boundingBox.max;
  20205. /*
  20206. 5____4
  20207. 1/___0/|
  20208. | 6__|_7
  20209. 2/___3/
  20210. 0: max.x, max.y, max.z
  20211. 1: min.x, max.y, max.z
  20212. 2: min.x, min.y, max.z
  20213. 3: max.x, min.y, max.z
  20214. 4: max.x, max.y, min.z
  20215. 5: min.x, max.y, min.z
  20216. 6: min.x, min.y, min.z
  20217. 7: max.x, min.y, min.z
  20218. */
  20219. var vertices = this.geometry.attributes.position.array;
  20220. vertices[ 0 ] = max.x; vertices[ 1 ] = max.y; vertices[ 2 ] = max.z;
  20221. vertices[ 3 ] = min.x; vertices[ 4 ] = max.y; vertices[ 5 ] = max.z;
  20222. vertices[ 6 ] = min.x; vertices[ 7 ] = max.y; vertices[ 8 ] = max.z;
  20223. vertices[ 9 ] = min.x; vertices[ 10 ] = min.y; vertices[ 11 ] = max.z;
  20224. vertices[ 12 ] = min.x; vertices[ 13 ] = min.y; vertices[ 14 ] = max.z;
  20225. vertices[ 15 ] = max.x; vertices[ 16 ] = min.y; vertices[ 17 ] = max.z;
  20226. vertices[ 18 ] = max.x; vertices[ 19 ] = min.y; vertices[ 20 ] = max.z;
  20227. vertices[ 21 ] = max.x; vertices[ 22 ] = max.y; vertices[ 23 ] = max.z;
  20228. //
  20229. vertices[ 24 ] = max.x; vertices[ 25 ] = max.y; vertices[ 26 ] = min.z;
  20230. vertices[ 27 ] = min.x; vertices[ 28 ] = max.y; vertices[ 29 ] = min.z;
  20231. vertices[ 30 ] = min.x; vertices[ 31 ] = max.y; vertices[ 32 ] = min.z;
  20232. vertices[ 33 ] = min.x; vertices[ 34 ] = min.y; vertices[ 35 ] = min.z;
  20233. vertices[ 36 ] = min.x; vertices[ 37 ] = min.y; vertices[ 38 ] = min.z;
  20234. vertices[ 39 ] = max.x; vertices[ 40 ] = min.y; vertices[ 41 ] = min.z;
  20235. vertices[ 42 ] = max.x; vertices[ 43 ] = min.y; vertices[ 44 ] = min.z;
  20236. vertices[ 45 ] = max.x; vertices[ 46 ] = max.y; vertices[ 47 ] = min.z;
  20237. //
  20238. vertices[ 48 ] = max.x; vertices[ 49 ] = max.y; vertices[ 50 ] = max.z;
  20239. vertices[ 51 ] = max.x; vertices[ 52 ] = max.y; vertices[ 53 ] = min.z;
  20240. vertices[ 54 ] = min.x; vertices[ 55 ] = max.y; vertices[ 56 ] = max.z;
  20241. vertices[ 57 ] = min.x; vertices[ 58 ] = max.y; vertices[ 59 ] = min.z;
  20242. vertices[ 60 ] = min.x; vertices[ 61 ] = min.y; vertices[ 62 ] = max.z;
  20243. vertices[ 63 ] = min.x; vertices[ 64 ] = min.y; vertices[ 65 ] = min.z;
  20244. vertices[ 66 ] = max.x; vertices[ 67 ] = min.y; vertices[ 68 ] = max.z;
  20245. vertices[ 69 ] = max.x; vertices[ 70 ] = min.y; vertices[ 71 ] = min.z;
  20246. this.geometry.attributes.position.needsUpdate = true;
  20247. this.geometry.computeBoundingSphere();
  20248. this.matrix = object.matrixWorld;
  20249. this.matrixAutoUpdate = false;
  20250. };
  20251. // File:src/extras/helpers/BoundingBoxHelper.js
  20252. /**
  20253. * @author WestLangley / http://github.com/WestLangley
  20254. */
  20255. // a helper to show the world-axis-aligned bounding box for an object
  20256. THREE.BoundingBoxHelper = function ( object, hex ) {
  20257. var color = ( hex !== undefined ) ? hex : 0x888888;
  20258. this.object = object;
  20259. this.box = new THREE.Box3();
  20260. THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20261. };
  20262. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20263. THREE.BoundingBoxHelper.prototype.constructor = THREE.BoundingBoxHelper;
  20264. THREE.BoundingBoxHelper.prototype.update = function () {
  20265. this.box.setFromObject( this.object );
  20266. this.box.size( this.scale );
  20267. this.box.center( this.position );
  20268. };
  20269. // File:src/extras/helpers/CameraHelper.js
  20270. /**
  20271. * @author alteredq / http://alteredqualia.com/
  20272. *
  20273. * - shows frustum, line of sight and up of the camera
  20274. * - suitable for fast updates
  20275. * - based on frustum visualization in lightgl.js shadowmap example
  20276. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20277. */
  20278. THREE.CameraHelper = function ( camera ) {
  20279. var geometry = new THREE.Geometry();
  20280. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20281. var pointMap = {};
  20282. // colors
  20283. var hexFrustum = 0xffaa00;
  20284. var hexCone = 0xff0000;
  20285. var hexUp = 0x00aaff;
  20286. var hexTarget = 0xffffff;
  20287. var hexCross = 0x333333;
  20288. // near
  20289. addLine( "n1", "n2", hexFrustum );
  20290. addLine( "n2", "n4", hexFrustum );
  20291. addLine( "n4", "n3", hexFrustum );
  20292. addLine( "n3", "n1", hexFrustum );
  20293. // far
  20294. addLine( "f1", "f2", hexFrustum );
  20295. addLine( "f2", "f4", hexFrustum );
  20296. addLine( "f4", "f3", hexFrustum );
  20297. addLine( "f3", "f1", hexFrustum );
  20298. // sides
  20299. addLine( "n1", "f1", hexFrustum );
  20300. addLine( "n2", "f2", hexFrustum );
  20301. addLine( "n3", "f3", hexFrustum );
  20302. addLine( "n4", "f4", hexFrustum );
  20303. // cone
  20304. addLine( "p", "n1", hexCone );
  20305. addLine( "p", "n2", hexCone );
  20306. addLine( "p", "n3", hexCone );
  20307. addLine( "p", "n4", hexCone );
  20308. // up
  20309. addLine( "u1", "u2", hexUp );
  20310. addLine( "u2", "u3", hexUp );
  20311. addLine( "u3", "u1", hexUp );
  20312. // target
  20313. addLine( "c", "t", hexTarget );
  20314. addLine( "p", "c", hexCross );
  20315. // cross
  20316. addLine( "cn1", "cn2", hexCross );
  20317. addLine( "cn3", "cn4", hexCross );
  20318. addLine( "cf1", "cf2", hexCross );
  20319. addLine( "cf3", "cf4", hexCross );
  20320. function addLine( a, b, hex ) {
  20321. addPoint( a, hex );
  20322. addPoint( b, hex );
  20323. }
  20324. function addPoint( id, hex ) {
  20325. geometry.vertices.push( new THREE.Vector3() );
  20326. geometry.colors.push( new THREE.Color( hex ) );
  20327. if ( pointMap[ id ] === undefined ) {
  20328. pointMap[ id ] = [];
  20329. }
  20330. pointMap[ id ].push( geometry.vertices.length - 1 );
  20331. }
  20332. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20333. this.camera = camera;
  20334. this.matrix = camera.matrixWorld;
  20335. this.matrixAutoUpdate = false;
  20336. this.pointMap = pointMap;
  20337. this.update();
  20338. };
  20339. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20340. THREE.CameraHelper.prototype.constructor = THREE.CameraHelper;
  20341. THREE.CameraHelper.prototype.update = function () {
  20342. var geometry, pointMap;
  20343. var vector = new THREE.Vector3();
  20344. var camera = new THREE.Camera();
  20345. var setPoint = function ( point, x, y, z ) {
  20346. vector.set( x, y, z ).unproject( camera );
  20347. var points = pointMap[ point ];
  20348. if ( points !== undefined ) {
  20349. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20350. geometry.vertices[ points[ i ] ].copy( vector );
  20351. }
  20352. }
  20353. };
  20354. return function () {
  20355. geometry = this.geometry;
  20356. pointMap = this.pointMap;
  20357. var w = 1, h = 1;
  20358. // we need just camera projection matrix
  20359. // world matrix must be identity
  20360. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20361. // center / target
  20362. setPoint( "c", 0, 0, - 1 );
  20363. setPoint( "t", 0, 0, 1 );
  20364. // near
  20365. setPoint( "n1", - w, - h, - 1 );
  20366. setPoint( "n2", w, - h, - 1 );
  20367. setPoint( "n3", - w, h, - 1 );
  20368. setPoint( "n4", w, h, - 1 );
  20369. // far
  20370. setPoint( "f1", - w, - h, 1 );
  20371. setPoint( "f2", w, - h, 1 );
  20372. setPoint( "f3", - w, h, 1 );
  20373. setPoint( "f4", w, h, 1 );
  20374. // up
  20375. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  20376. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  20377. setPoint( "u3", 0, h * 2, - 1 );
  20378. // cross
  20379. setPoint( "cf1", - w, 0, 1 );
  20380. setPoint( "cf2", w, 0, 1 );
  20381. setPoint( "cf3", 0, - h, 1 );
  20382. setPoint( "cf4", 0, h, 1 );
  20383. setPoint( "cn1", - w, 0, - 1 );
  20384. setPoint( "cn2", w, 0, - 1 );
  20385. setPoint( "cn3", 0, - h, - 1 );
  20386. setPoint( "cn4", 0, h, - 1 );
  20387. geometry.verticesNeedUpdate = true;
  20388. };
  20389. }();
  20390. // File:src/extras/helpers/DirectionalLightHelper.js
  20391. /**
  20392. * @author alteredq / http://alteredqualia.com/
  20393. * @author mrdoob / http://mrdoob.com/
  20394. * @author WestLangley / http://github.com/WestLangley
  20395. */
  20396. THREE.DirectionalLightHelper = function ( light, size ) {
  20397. THREE.Object3D.call( this );
  20398. this.light = light;
  20399. this.light.updateMatrixWorld();
  20400. this.matrix = light.matrixWorld;
  20401. this.matrixAutoUpdate = false;
  20402. size = size || 1;
  20403. var geometry = new THREE.Geometry();
  20404. geometry.vertices.push(
  20405. new THREE.Vector3( - size, size, 0 ),
  20406. new THREE.Vector3( size, size, 0 ),
  20407. new THREE.Vector3( size, - size, 0 ),
  20408. new THREE.Vector3( - size, - size, 0 ),
  20409. new THREE.Vector3( - size, size, 0 )
  20410. );
  20411. var material = new THREE.LineBasicMaterial( { fog: false } );
  20412. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20413. this.lightPlane = new THREE.Line( geometry, material );
  20414. this.add( this.lightPlane );
  20415. geometry = new THREE.Geometry();
  20416. geometry.vertices.push(
  20417. new THREE.Vector3(),
  20418. new THREE.Vector3()
  20419. );
  20420. material = new THREE.LineBasicMaterial( { fog: false } );
  20421. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20422. this.targetLine = new THREE.Line( geometry, material );
  20423. this.add( this.targetLine );
  20424. this.update();
  20425. };
  20426. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20427. THREE.DirectionalLightHelper.prototype.constructor = THREE.DirectionalLightHelper;
  20428. THREE.DirectionalLightHelper.prototype.dispose = function () {
  20429. this.lightPlane.geometry.dispose();
  20430. this.lightPlane.material.dispose();
  20431. this.targetLine.geometry.dispose();
  20432. this.targetLine.material.dispose();
  20433. };
  20434. THREE.DirectionalLightHelper.prototype.update = function () {
  20435. var v1 = new THREE.Vector3();
  20436. var v2 = new THREE.Vector3();
  20437. var v3 = new THREE.Vector3();
  20438. return function () {
  20439. v1.setFromMatrixPosition( this.light.matrixWorld );
  20440. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20441. v3.subVectors( v2, v1 );
  20442. this.lightPlane.lookAt( v3 );
  20443. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20444. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  20445. this.targetLine.geometry.verticesNeedUpdate = true;
  20446. this.targetLine.material.color.copy( this.lightPlane.material.color );
  20447. };
  20448. }();
  20449. // File:src/extras/helpers/EdgesHelper.js
  20450. /**
  20451. * @author WestLangley / http://github.com/WestLangley
  20452. * @param object THREE.Mesh whose geometry will be used
  20453. * @param hex line color
  20454. * @param thresholdAngle the minimim angle (in degrees),
  20455. * between the face normals of adjacent faces,
  20456. * that is required to render an edge. A value of 10 means
  20457. * an edge is only rendered if the angle is at least 10 degrees.
  20458. */
  20459. THREE.EdgesHelper = function ( object, hex, thresholdAngle ) {
  20460. var color = ( hex !== undefined ) ? hex : 0xffffff;
  20461. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  20462. var thresholdDot = Math.cos( THREE.Math.degToRad( thresholdAngle ) );
  20463. var edge = [ 0, 0 ], hash = {};
  20464. var sortFunction = function ( a, b ) { return a - b };
  20465. var keys = [ 'a', 'b', 'c' ];
  20466. var geometry = new THREE.BufferGeometry();
  20467. var geometry2;
  20468. if ( object.geometry instanceof THREE.BufferGeometry ) {
  20469. geometry2 = new THREE.Geometry();
  20470. geometry2.fromBufferGeometry( object.geometry );
  20471. } else {
  20472. geometry2 = object.geometry.clone();
  20473. }
  20474. geometry2.mergeVertices();
  20475. geometry2.computeFaceNormals();
  20476. var vertices = geometry2.vertices;
  20477. var faces = geometry2.faces;
  20478. var numEdges = 0;
  20479. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20480. var face = faces[ i ];
  20481. for ( var j = 0; j < 3; j ++ ) {
  20482. edge[ 0 ] = face[ keys[ j ] ];
  20483. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20484. edge.sort( sortFunction );
  20485. var key = edge.toString();
  20486. if ( hash[ key ] === undefined ) {
  20487. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  20488. numEdges ++;
  20489. } else {
  20490. hash[ key ].face2 = i;
  20491. }
  20492. }
  20493. }
  20494. var coords = new Float32Array( numEdges * 2 * 3 );
  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 ) <= thresholdDot ) {
  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. geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20510. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  20511. this.matrix = object.matrixWorld;
  20512. this.matrixAutoUpdate = false;
  20513. };
  20514. THREE.EdgesHelper.prototype = Object.create( THREE.Line.prototype );
  20515. THREE.EdgesHelper.prototype.constructor = THREE.EdgesHelper;
  20516. // File:src/extras/helpers/FaceNormalsHelper.js
  20517. /**
  20518. * @author mrdoob / http://mrdoob.com/
  20519. * @author WestLangley / http://github.com/WestLangley
  20520. */
  20521. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  20522. this.object = object;
  20523. this.size = ( size !== undefined ) ? size : 1;
  20524. var color = ( hex !== undefined ) ? hex : 0xffff00;
  20525. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20526. var geometry = new THREE.Geometry();
  20527. var faces = this.object.geometry.faces;
  20528. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20529. geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() );
  20530. }
  20531. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20532. this.matrixAutoUpdate = false;
  20533. this.normalMatrix = new THREE.Matrix3();
  20534. this.update();
  20535. };
  20536. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20537. THREE.FaceNormalsHelper.prototype.constructor = THREE.FaceNormalsHelper;
  20538. THREE.FaceNormalsHelper.prototype.update = function () {
  20539. var vertices = this.geometry.vertices;
  20540. var object = this.object;
  20541. var objectVertices = object.geometry.vertices;
  20542. var objectFaces = object.geometry.faces;
  20543. var objectWorldMatrix = object.matrixWorld;
  20544. object.updateMatrixWorld( true );
  20545. this.normalMatrix.getNormalMatrix( objectWorldMatrix );
  20546. for ( var i = 0, i2 = 0, l = objectFaces.length; i < l; i ++, i2 += 2 ) {
  20547. var face = objectFaces[ i ];
  20548. vertices[ i2 ].copy( objectVertices[ face.a ] )
  20549. .add( objectVertices[ face.b ] )
  20550. .add( objectVertices[ face.c ] )
  20551. .divideScalar( 3 )
  20552. .applyMatrix4( objectWorldMatrix );
  20553. vertices[ i2 + 1 ].copy( face.normal )
  20554. .applyMatrix3( this.normalMatrix )
  20555. .normalize()
  20556. .multiplyScalar( this.size )
  20557. .add( vertices[ i2 ] );
  20558. }
  20559. this.geometry.verticesNeedUpdate = true;
  20560. return this;
  20561. };
  20562. // File:src/extras/helpers/GridHelper.js
  20563. /**
  20564. * @author mrdoob / http://mrdoob.com/
  20565. */
  20566. THREE.GridHelper = function ( size, step ) {
  20567. var geometry = new THREE.Geometry();
  20568. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20569. this.color1 = new THREE.Color( 0x444444 );
  20570. this.color2 = new THREE.Color( 0x888888 );
  20571. for ( var i = - size; i <= size; i += step ) {
  20572. geometry.vertices.push(
  20573. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  20574. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  20575. );
  20576. var color = i === 0 ? this.color1 : this.color2;
  20577. geometry.colors.push( color, color, color, color );
  20578. }
  20579. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20580. };
  20581. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  20582. THREE.GridHelper.prototype.constructor = THREE.GridHelper;
  20583. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  20584. this.color1.set( colorCenterLine );
  20585. this.color2.set( colorGrid );
  20586. this.geometry.colorsNeedUpdate = true;
  20587. }
  20588. // File:src/extras/helpers/HemisphereLightHelper.js
  20589. /**
  20590. * @author alteredq / http://alteredqualia.com/
  20591. * @author mrdoob / http://mrdoob.com/
  20592. */
  20593. THREE.HemisphereLightHelper = function ( light, sphereSize ) {
  20594. THREE.Object3D.call( this );
  20595. this.light = light;
  20596. this.light.updateMatrixWorld();
  20597. this.matrix = light.matrixWorld;
  20598. this.matrixAutoUpdate = false;
  20599. this.colors = [ new THREE.Color(), new THREE.Color() ];
  20600. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20601. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20602. for ( var i = 0, il = 8; i < il; i ++ ) {
  20603. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  20604. }
  20605. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  20606. this.lightSphere = new THREE.Mesh( geometry, material );
  20607. this.add( this.lightSphere );
  20608. this.update();
  20609. };
  20610. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20611. THREE.HemisphereLightHelper.prototype.constructor = THREE.HemisphereLightHelper;
  20612. THREE.HemisphereLightHelper.prototype.dispose = function () {
  20613. this.lightSphere.geometry.dispose();
  20614. this.lightSphere.material.dispose();
  20615. };
  20616. THREE.HemisphereLightHelper.prototype.update = function () {
  20617. var vector = new THREE.Vector3();
  20618. return function () {
  20619. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  20620. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  20621. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20622. this.lightSphere.geometry.colorsNeedUpdate = true;
  20623. }
  20624. }();
  20625. // File:src/extras/helpers/PointLightHelper.js
  20626. /**
  20627. * @author alteredq / http://alteredqualia.com/
  20628. * @author mrdoob / http://mrdoob.com/
  20629. */
  20630. THREE.PointLightHelper = function ( light, sphereSize ) {
  20631. this.light = light;
  20632. this.light.updateMatrixWorld();
  20633. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20634. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20635. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20636. THREE.Mesh.call( this, geometry, material );
  20637. this.matrix = this.light.matrixWorld;
  20638. this.matrixAutoUpdate = false;
  20639. /*
  20640. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20641. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20642. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20643. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20644. var d = light.distance;
  20645. if ( d === 0.0 ) {
  20646. this.lightDistance.visible = false;
  20647. } else {
  20648. this.lightDistance.scale.set( d, d, d );
  20649. }
  20650. this.add( this.lightDistance );
  20651. */
  20652. };
  20653. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  20654. THREE.PointLightHelper.prototype.constructor = THREE.PointLightHelper;
  20655. THREE.PointLightHelper.prototype.dispose = function () {
  20656. this.geometry.dispose();
  20657. this.material.dispose();
  20658. };
  20659. THREE.PointLightHelper.prototype.update = function () {
  20660. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20661. /*
  20662. var d = this.light.distance;
  20663. if ( d === 0.0 ) {
  20664. this.lightDistance.visible = false;
  20665. } else {
  20666. this.lightDistance.visible = true;
  20667. this.lightDistance.scale.set( d, d, d );
  20668. }
  20669. */
  20670. };
  20671. // File:src/extras/helpers/SkeletonHelper.js
  20672. /**
  20673. * @author Sean Griffin / http://twitter.com/sgrif
  20674. * @author Michael Guerrero / http://realitymeltdown.com
  20675. * @author mrdoob / http://mrdoob.com/
  20676. * @author ikerr / http://verold.com
  20677. */
  20678. THREE.SkeletonHelper = function ( object ) {
  20679. this.bones = this.getBoneList( object );
  20680. var geometry = new THREE.Geometry();
  20681. for ( var i = 0; i < this.bones.length; i ++ ) {
  20682. var bone = this.bones[ i ];
  20683. if ( bone.parent instanceof THREE.Bone ) {
  20684. geometry.vertices.push( new THREE.Vector3() );
  20685. geometry.vertices.push( new THREE.Vector3() );
  20686. geometry.colors.push( new THREE.Color( 0, 0, 1 ) );
  20687. geometry.colors.push( new THREE.Color( 0, 1, 0 ) );
  20688. }
  20689. }
  20690. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  20691. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20692. this.root = object;
  20693. this.matrix = object.matrixWorld;
  20694. this.matrixAutoUpdate = false;
  20695. this.update();
  20696. };
  20697. THREE.SkeletonHelper.prototype = Object.create( THREE.Line.prototype );
  20698. THREE.SkeletonHelper.prototype.constructor = THREE.SkeletonHelper;
  20699. THREE.SkeletonHelper.prototype.getBoneList = function( object ) {
  20700. var boneList = [];
  20701. if ( object instanceof THREE.Bone ) {
  20702. boneList.push( object );
  20703. }
  20704. for ( var i = 0; i < object.children.length; i ++ ) {
  20705. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  20706. }
  20707. return boneList;
  20708. };
  20709. THREE.SkeletonHelper.prototype.update = function () {
  20710. var geometry = this.geometry;
  20711. var matrixWorldInv = new THREE.Matrix4().getInverse( this.root.matrixWorld );
  20712. var boneMatrix = new THREE.Matrix4();
  20713. var j = 0;
  20714. for ( var i = 0; i < this.bones.length; i ++ ) {
  20715. var bone = this.bones[ i ];
  20716. if ( bone.parent instanceof THREE.Bone ) {
  20717. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  20718. geometry.vertices[ j ].setFromMatrixPosition( boneMatrix );
  20719. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  20720. geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix );
  20721. j += 2;
  20722. }
  20723. }
  20724. geometry.verticesNeedUpdate = true;
  20725. geometry.computeBoundingSphere();
  20726. };
  20727. // File:src/extras/helpers/SpotLightHelper.js
  20728. /**
  20729. * @author alteredq / http://alteredqualia.com/
  20730. * @author mrdoob / http://mrdoob.com/
  20731. * @author WestLangley / http://github.com/WestLangley
  20732. */
  20733. THREE.SpotLightHelper = function ( light ) {
  20734. THREE.Object3D.call( this );
  20735. this.light = light;
  20736. this.light.updateMatrixWorld();
  20737. this.matrix = light.matrixWorld;
  20738. this.matrixAutoUpdate = false;
  20739. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  20740. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  20741. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20742. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20743. this.cone = new THREE.Mesh( geometry, material );
  20744. this.add( this.cone );
  20745. this.update();
  20746. };
  20747. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20748. THREE.SpotLightHelper.prototype.constructor = THREE.SpotLightHelper;
  20749. THREE.SpotLightHelper.prototype.dispose = function () {
  20750. this.cone.geometry.dispose();
  20751. this.cone.material.dispose();
  20752. };
  20753. THREE.SpotLightHelper.prototype.update = function () {
  20754. var vector = new THREE.Vector3();
  20755. var vector2 = new THREE.Vector3();
  20756. return function () {
  20757. var coneLength = this.light.distance ? this.light.distance : 10000;
  20758. var coneWidth = coneLength * Math.tan( this.light.angle );
  20759. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20760. vector.setFromMatrixPosition( this.light.matrixWorld );
  20761. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  20762. this.cone.lookAt( vector2.sub( vector ) );
  20763. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20764. };
  20765. }();
  20766. // File:src/extras/helpers/VertexNormalsHelper.js
  20767. /**
  20768. * @author mrdoob / http://mrdoob.com/
  20769. * @author WestLangley / http://github.com/WestLangley
  20770. */
  20771. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  20772. this.object = object;
  20773. this.size = ( size !== undefined ) ? size : 1;
  20774. var color = ( hex !== undefined ) ? hex : 0xff0000;
  20775. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20776. var geometry = new THREE.Geometry();
  20777. var faces = object.geometry.faces;
  20778. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20779. var face = faces[ i ];
  20780. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20781. geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() );
  20782. }
  20783. }
  20784. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20785. this.matrixAutoUpdate = false;
  20786. this.normalMatrix = new THREE.Matrix3();
  20787. this.update();
  20788. };
  20789. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20790. THREE.VertexNormalsHelper.prototype.constructor = THREE.VertexNormalsHelper;
  20791. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  20792. var v1 = new THREE.Vector3();
  20793. return function( object ) {
  20794. var keys = [ 'a', 'b', 'c', 'd' ];
  20795. this.object.updateMatrixWorld( true );
  20796. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20797. var vertices = this.geometry.vertices;
  20798. var verts = this.object.geometry.vertices;
  20799. var faces = this.object.geometry.faces;
  20800. var worldMatrix = this.object.matrixWorld;
  20801. var idx = 0;
  20802. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20803. var face = faces[ i ];
  20804. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20805. var vertexId = face[ keys[ j ] ];
  20806. var vertex = verts[ vertexId ];
  20807. var normal = face.vertexNormals[ j ];
  20808. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20809. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20810. v1.add( vertices[ idx ] );
  20811. idx = idx + 1;
  20812. vertices[ idx ].copy( v1 );
  20813. idx = idx + 1;
  20814. }
  20815. }
  20816. this.geometry.verticesNeedUpdate = true;
  20817. return this;
  20818. }
  20819. }());
  20820. // File:src/extras/helpers/VertexTangentsHelper.js
  20821. /**
  20822. * @author mrdoob / http://mrdoob.com/
  20823. * @author WestLangley / http://github.com/WestLangley
  20824. */
  20825. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  20826. this.object = object;
  20827. this.size = ( size !== undefined ) ? size : 1;
  20828. var color = ( hex !== undefined ) ? hex : 0x0000ff;
  20829. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20830. var geometry = new THREE.Geometry();
  20831. var faces = object.geometry.faces;
  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. geometry.vertices.push( new THREE.Vector3() );
  20836. geometry.vertices.push( new THREE.Vector3() );
  20837. }
  20838. }
  20839. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20840. this.matrixAutoUpdate = false;
  20841. this.update();
  20842. };
  20843. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  20844. THREE.VertexTangentsHelper.prototype.constructor = THREE.VertexTangentsHelper;
  20845. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  20846. var v1 = new THREE.Vector3();
  20847. return function( object ) {
  20848. var keys = [ 'a', 'b', 'c', 'd' ];
  20849. this.object.updateMatrixWorld( true );
  20850. var vertices = this.geometry.vertices;
  20851. var verts = this.object.geometry.vertices;
  20852. var faces = this.object.geometry.faces;
  20853. var worldMatrix = this.object.matrixWorld;
  20854. var idx = 0;
  20855. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20856. var face = faces[ i ];
  20857. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20858. var vertexId = face[ keys[ j ] ];
  20859. var vertex = verts[ vertexId ];
  20860. var tangent = face.vertexTangents[ j ];
  20861. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20862. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  20863. v1.add( vertices[ idx ] );
  20864. idx = idx + 1;
  20865. vertices[ idx ].copy( v1 );
  20866. idx = idx + 1;
  20867. }
  20868. }
  20869. this.geometry.verticesNeedUpdate = true;
  20870. return this;
  20871. }
  20872. }());
  20873. // File:src/extras/helpers/WireframeHelper.js
  20874. /**
  20875. * @author mrdoob / http://mrdoob.com/
  20876. */
  20877. THREE.WireframeHelper = function ( object, hex ) {
  20878. var color = ( hex !== undefined ) ? hex : 0xffffff;
  20879. var edge = [ 0, 0 ], hash = {};
  20880. var sortFunction = function ( a, b ) { return a - b };
  20881. var keys = [ 'a', 'b', 'c' ];
  20882. var geometry = new THREE.BufferGeometry();
  20883. if ( object.geometry instanceof THREE.Geometry ) {
  20884. var vertices = object.geometry.vertices;
  20885. var faces = object.geometry.faces;
  20886. var numEdges = 0;
  20887. // allocate maximal size
  20888. var edges = new Uint32Array( 6 * faces.length );
  20889. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20890. var face = faces[ i ];
  20891. for ( var j = 0; j < 3; j ++ ) {
  20892. edge[ 0 ] = face[ keys[ j ] ];
  20893. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20894. edge.sort( sortFunction );
  20895. var key = edge.toString();
  20896. if ( hash[ key ] === undefined ) {
  20897. edges[ 2 * numEdges ] = edge[ 0 ];
  20898. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  20899. hash[ key ] = true;
  20900. numEdges ++;
  20901. }
  20902. }
  20903. }
  20904. var coords = new Float32Array( numEdges * 2 * 3 );
  20905. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  20906. for ( var j = 0; j < 2; j ++ ) {
  20907. var vertex = vertices[ edges [ 2 * i + j] ];
  20908. var index = 6 * i + 3 * j;
  20909. coords[ index + 0 ] = vertex.x;
  20910. coords[ index + 1 ] = vertex.y;
  20911. coords[ index + 2 ] = vertex.z;
  20912. }
  20913. }
  20914. geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20915. } else if ( object.geometry instanceof THREE.BufferGeometry ) {
  20916. if ( object.geometry.attributes.index !== undefined ) { // Indexed BufferGeometry
  20917. var vertices = object.geometry.attributes.position.array;
  20918. var indices = object.geometry.attributes.index.array;
  20919. var drawcalls = object.geometry.drawcalls;
  20920. var numEdges = 0;
  20921. if ( drawcalls.length === 0 ) {
  20922. drawcalls = [ { count : indices.length, index : 0, start : 0 } ];
  20923. }
  20924. // allocate maximal size
  20925. var edges = new Uint32Array( 2 * indices.length );
  20926. for ( var o = 0, ol = drawcalls.length; o < ol; ++ o ) {
  20927. var start = drawcalls[ o ].start;
  20928. var count = drawcalls[ o ].count;
  20929. var index = drawcalls[ o ].index;
  20930. for ( var i = start, il = start + count; i < il; i += 3 ) {
  20931. for ( var j = 0; j < 3; j ++ ) {
  20932. edge[ 0 ] = index + indices[ i + j ];
  20933. edge[ 1 ] = index + indices[ i + ( j + 1 ) % 3 ];
  20934. edge.sort( sortFunction );
  20935. var key = edge.toString();
  20936. if ( hash[ key ] === undefined ) {
  20937. edges[ 2 * numEdges ] = edge[ 0 ];
  20938. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  20939. hash[ key ] = true;
  20940. numEdges ++;
  20941. }
  20942. }
  20943. }
  20944. }
  20945. var coords = new Float32Array( numEdges * 2 * 3 );
  20946. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  20947. for ( var j = 0; j < 2; j ++ ) {
  20948. var index = 6 * i + 3 * j;
  20949. var index2 = 3 * edges[ 2 * i + j];
  20950. coords[ index + 0 ] = vertices[ index2 ];
  20951. coords[ index + 1 ] = vertices[ index2 + 1 ];
  20952. coords[ index + 2 ] = vertices[ index2 + 2 ];
  20953. }
  20954. }
  20955. geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20956. } else { // non-indexed BufferGeometry
  20957. var vertices = object.geometry.attributes.position.array;
  20958. var numEdges = vertices.length / 3;
  20959. var numTris = numEdges / 3;
  20960. var coords = new Float32Array( numEdges * 2 * 3 );
  20961. for ( var i = 0, l = numTris; i < l; i ++ ) {
  20962. for ( var j = 0; j < 3; j ++ ) {
  20963. var index = 18 * i + 6 * j;
  20964. var index1 = 9 * i + 3 * j;
  20965. coords[ index + 0 ] = vertices[ index1 ];
  20966. coords[ index + 1 ] = vertices[ index1 + 1 ];
  20967. coords[ index + 2 ] = vertices[ index1 + 2 ];
  20968. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  20969. coords[ index + 3 ] = vertices[ index2 ];
  20970. coords[ index + 4 ] = vertices[ index2 + 1 ];
  20971. coords[ index + 5 ] = vertices[ index2 + 2 ];
  20972. }
  20973. }
  20974. geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20975. }
  20976. }
  20977. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  20978. this.matrix = object.matrixWorld;
  20979. this.matrixAutoUpdate = false;
  20980. };
  20981. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  20982. THREE.WireframeHelper.prototype.constructor = THREE.WireframeHelper;
  20983. // File:src/extras/objects/ImmediateRenderObject.js
  20984. /**
  20985. * @author alteredq / http://alteredqualia.com/
  20986. */
  20987. THREE.ImmediateRenderObject = function () {
  20988. THREE.Object3D.call( this );
  20989. this.render = function ( renderCallback ) {};
  20990. };
  20991. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20992. THREE.ImmediateRenderObject.prototype.constructor = THREE.ImmediateRenderObject;
  20993. // File:src/extras/objects/MorphBlendMesh.js
  20994. /**
  20995. * @author alteredq / http://alteredqualia.com/
  20996. */
  20997. THREE.MorphBlendMesh = function( geometry, material ) {
  20998. THREE.Mesh.call( this, geometry, material );
  20999. this.animationsMap = {};
  21000. this.animationsList = [];
  21001. // prepare default animation
  21002. // (all frames played together in 1 second)
  21003. var numFrames = this.geometry.morphTargets.length;
  21004. var name = "__default";
  21005. var startFrame = 0;
  21006. var endFrame = numFrames - 1;
  21007. var fps = numFrames / 1;
  21008. this.createAnimation( name, startFrame, endFrame, fps );
  21009. this.setAnimationWeight( name, 1 );
  21010. };
  21011. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  21012. THREE.MorphBlendMesh.prototype.constructor = THREE.MorphBlendMesh;
  21013. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  21014. var animation = {
  21015. startFrame: start,
  21016. endFrame: end,
  21017. length: end - start + 1,
  21018. fps: fps,
  21019. duration: ( end - start ) / fps,
  21020. lastFrame: 0,
  21021. currentFrame: 0,
  21022. active: false,
  21023. time: 0,
  21024. direction: 1,
  21025. weight: 1,
  21026. directionBackwards: false,
  21027. mirroredLoop: false
  21028. };
  21029. this.animationsMap[ name ] = animation;
  21030. this.animationsList.push( animation );
  21031. };
  21032. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21033. var pattern = /([a-z]+)_?(\d+)/;
  21034. var firstAnimation, frameRanges = {};
  21035. var geometry = this.geometry;
  21036. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21037. var morph = geometry.morphTargets[ i ];
  21038. var chunks = morph.name.match( pattern );
  21039. if ( chunks && chunks.length > 1 ) {
  21040. var name = chunks[ 1 ];
  21041. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  21042. var range = frameRanges[ name ];
  21043. if ( i < range.start ) range.start = i;
  21044. if ( i > range.end ) range.end = i;
  21045. if ( ! firstAnimation ) firstAnimation = name;
  21046. }
  21047. }
  21048. for ( var name in frameRanges ) {
  21049. var range = frameRanges[ name ];
  21050. this.createAnimation( name, range.start, range.end, fps );
  21051. }
  21052. this.firstAnimation = firstAnimation;
  21053. };
  21054. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  21055. var animation = this.animationsMap[ name ];
  21056. if ( animation ) {
  21057. animation.direction = 1;
  21058. animation.directionBackwards = false;
  21059. }
  21060. };
  21061. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  21062. var animation = this.animationsMap[ name ];
  21063. if ( animation ) {
  21064. animation.direction = - 1;
  21065. animation.directionBackwards = true;
  21066. }
  21067. };
  21068. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  21069. var animation = this.animationsMap[ name ];
  21070. if ( animation ) {
  21071. animation.fps = fps;
  21072. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21073. }
  21074. };
  21075. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21076. var animation = this.animationsMap[ name ];
  21077. if ( animation ) {
  21078. animation.duration = duration;
  21079. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21080. }
  21081. };
  21082. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21083. var animation = this.animationsMap[ name ];
  21084. if ( animation ) {
  21085. animation.weight = weight;
  21086. }
  21087. };
  21088. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21089. var animation = this.animationsMap[ name ];
  21090. if ( animation ) {
  21091. animation.time = time;
  21092. }
  21093. };
  21094. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21095. var time = 0;
  21096. var animation = this.animationsMap[ name ];
  21097. if ( animation ) {
  21098. time = animation.time;
  21099. }
  21100. return time;
  21101. };
  21102. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21103. var duration = - 1;
  21104. var animation = this.animationsMap[ name ];
  21105. if ( animation ) {
  21106. duration = animation.duration;
  21107. }
  21108. return duration;
  21109. };
  21110. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21111. var animation = this.animationsMap[ name ];
  21112. if ( animation ) {
  21113. animation.time = 0;
  21114. animation.active = true;
  21115. } else {
  21116. THREE.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  21117. }
  21118. };
  21119. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21120. var animation = this.animationsMap[ name ];
  21121. if ( animation ) {
  21122. animation.active = false;
  21123. }
  21124. };
  21125. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  21126. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21127. var animation = this.animationsList[ i ];
  21128. if ( ! animation.active ) continue;
  21129. var frameTime = animation.duration / animation.length;
  21130. animation.time += animation.direction * delta;
  21131. if ( animation.mirroredLoop ) {
  21132. if ( animation.time > animation.duration || animation.time < 0 ) {
  21133. animation.direction *= - 1;
  21134. if ( animation.time > animation.duration ) {
  21135. animation.time = animation.duration;
  21136. animation.directionBackwards = true;
  21137. }
  21138. if ( animation.time < 0 ) {
  21139. animation.time = 0;
  21140. animation.directionBackwards = false;
  21141. }
  21142. }
  21143. } else {
  21144. animation.time = animation.time % animation.duration;
  21145. if ( animation.time < 0 ) animation.time += animation.duration;
  21146. }
  21147. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21148. var weight = animation.weight;
  21149. if ( keyframe !== animation.currentFrame ) {
  21150. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21151. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21152. this.morphTargetInfluences[ keyframe ] = 0;
  21153. animation.lastFrame = animation.currentFrame;
  21154. animation.currentFrame = keyframe;
  21155. }
  21156. var mix = ( animation.time % frameTime ) / frameTime;
  21157. if ( animation.directionBackwards ) mix = 1 - mix;
  21158. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21159. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21160. }
  21161. };