three.js 796 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435
  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. renderer.setRenderTarget( null );
  6260. };
  6261. };
  6262. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  6263. THREE.CubeCamera.prototype.constructor = THREE.CubeCamera;
  6264. // File:src/cameras/OrthographicCamera.js
  6265. /**
  6266. * @author alteredq / http://alteredqualia.com/
  6267. */
  6268. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  6269. THREE.Camera.call( this );
  6270. this.type = 'OrthographicCamera';
  6271. this.zoom = 1;
  6272. this.left = left;
  6273. this.right = right;
  6274. this.top = top;
  6275. this.bottom = bottom;
  6276. this.near = ( near !== undefined ) ? near : 0.1;
  6277. this.far = ( far !== undefined ) ? far : 2000;
  6278. this.updateProjectionMatrix();
  6279. };
  6280. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  6281. THREE.OrthographicCamera.prototype.constructor = THREE.OrthographicCamera;
  6282. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  6283. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  6284. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  6285. var cx = ( this.right + this.left ) / 2;
  6286. var cy = ( this.top + this.bottom ) / 2;
  6287. this.projectionMatrix.makeOrthographic( cx - dx, cx + dx, cy + dy, cy - dy, this.near, this.far );
  6288. };
  6289. THREE.OrthographicCamera.prototype.clone = function () {
  6290. var camera = new THREE.OrthographicCamera();
  6291. THREE.Camera.prototype.clone.call( this, camera );
  6292. camera.zoom = this.zoom;
  6293. camera.left = this.left;
  6294. camera.right = this.right;
  6295. camera.top = this.top;
  6296. camera.bottom = this.bottom;
  6297. camera.near = this.near;
  6298. camera.far = this.far;
  6299. camera.projectionMatrix.copy( this.projectionMatrix );
  6300. return camera;
  6301. };
  6302. THREE.OrthographicCamera.prototype.toJSON = function ( meta ) {
  6303. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  6304. data.object.left = this.left;
  6305. data.object.right = this.right;
  6306. data.object.top = this.top;
  6307. data.object.bottom = this.bottom;
  6308. data.object.near = this.near;
  6309. data.object.far = this.far;
  6310. return data;
  6311. };
  6312. // File:src/cameras/PerspectiveCamera.js
  6313. /**
  6314. * @author mrdoob / http://mrdoob.com/
  6315. * @author greggman / http://games.greggman.com/
  6316. * @author zz85 / http://www.lab4games.net/zz85/blog
  6317. */
  6318. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  6319. THREE.Camera.call( this );
  6320. this.type = 'PerspectiveCamera';
  6321. this.zoom = 1;
  6322. this.fov = fov !== undefined ? fov : 50;
  6323. this.aspect = aspect !== undefined ? aspect : 1;
  6324. this.near = near !== undefined ? near : 0.1;
  6325. this.far = far !== undefined ? far : 2000;
  6326. this.updateProjectionMatrix();
  6327. };
  6328. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  6329. THREE.PerspectiveCamera.prototype.constructor = THREE.PerspectiveCamera;
  6330. /**
  6331. * Uses Focal Length (in mm) to estimate and set FOV
  6332. * 35mm (fullframe) camera is used if frame size is not specified;
  6333. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  6334. */
  6335. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  6336. if ( frameHeight === undefined ) frameHeight = 24;
  6337. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  6338. this.updateProjectionMatrix();
  6339. }
  6340. /**
  6341. * Sets an offset in a larger frustum. This is useful for multi-window or
  6342. * multi-monitor/multi-machine setups.
  6343. *
  6344. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6345. * the monitors are in grid like this
  6346. *
  6347. * +---+---+---+
  6348. * | A | B | C |
  6349. * +---+---+---+
  6350. * | D | E | F |
  6351. * +---+---+---+
  6352. *
  6353. * then for each monitor you would call it like this
  6354. *
  6355. * var w = 1920;
  6356. * var h = 1080;
  6357. * var fullWidth = w * 3;
  6358. * var fullHeight = h * 2;
  6359. *
  6360. * --A--
  6361. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6362. * --B--
  6363. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6364. * --C--
  6365. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6366. * --D--
  6367. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6368. * --E--
  6369. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  6370. * --F--
  6371. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  6372. *
  6373. * Note there is no reason monitors have to be the same size or in a grid.
  6374. */
  6375. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  6376. this.fullWidth = fullWidth;
  6377. this.fullHeight = fullHeight;
  6378. this.x = x;
  6379. this.y = y;
  6380. this.width = width;
  6381. this.height = height;
  6382. this.updateProjectionMatrix();
  6383. };
  6384. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  6385. var fov = THREE.Math.radToDeg( 2 * Math.atan( Math.tan( THREE.Math.degToRad( this.fov ) * 0.5 ) / this.zoom ) );
  6386. if ( this.fullWidth ) {
  6387. var aspect = this.fullWidth / this.fullHeight;
  6388. var top = Math.tan( THREE.Math.degToRad( fov * 0.5 ) ) * this.near;
  6389. var bottom = - top;
  6390. var left = aspect * bottom;
  6391. var right = aspect * top;
  6392. var width = Math.abs( right - left );
  6393. var height = Math.abs( top - bottom );
  6394. this.projectionMatrix.makeFrustum(
  6395. left + this.x * width / this.fullWidth,
  6396. left + ( this.x + this.width ) * width / this.fullWidth,
  6397. top - ( this.y + this.height ) * height / this.fullHeight,
  6398. top - this.y * height / this.fullHeight,
  6399. this.near,
  6400. this.far
  6401. );
  6402. } else {
  6403. this.projectionMatrix.makePerspective( fov, this.aspect, this.near, this.far );
  6404. }
  6405. };
  6406. THREE.PerspectiveCamera.prototype.clone = function () {
  6407. var camera = new THREE.PerspectiveCamera();
  6408. THREE.Camera.prototype.clone.call( this, camera );
  6409. camera.zoom = this.zoom;
  6410. camera.fov = this.fov;
  6411. camera.aspect = this.aspect;
  6412. camera.near = this.near;
  6413. camera.far = this.far;
  6414. camera.projectionMatrix.copy( this.projectionMatrix );
  6415. return camera;
  6416. };
  6417. THREE.PerspectiveCamera.prototype.toJSON = function ( meta ) {
  6418. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  6419. data.object.fov = this.fov;
  6420. data.object.aspect = this.aspect;
  6421. data.object.near = this.near;
  6422. data.object.far = this.far;
  6423. return data;
  6424. };
  6425. // File:src/lights/Light.js
  6426. /**
  6427. * @author mrdoob / http://mrdoob.com/
  6428. * @author alteredq / http://alteredqualia.com/
  6429. */
  6430. THREE.Light = function ( color ) {
  6431. THREE.Object3D.call( this );
  6432. this.type = 'Light';
  6433. this.color = new THREE.Color( color );
  6434. };
  6435. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  6436. THREE.Light.prototype.constructor = THREE.Light;
  6437. THREE.Light.prototype.clone = function ( light ) {
  6438. if ( light === undefined ) light = new THREE.Light();
  6439. THREE.Object3D.prototype.clone.call( this, light );
  6440. light.color.copy( this.color );
  6441. return light;
  6442. };
  6443. // File:src/lights/AmbientLight.js
  6444. /**
  6445. * @author mrdoob / http://mrdoob.com/
  6446. */
  6447. THREE.AmbientLight = function ( color ) {
  6448. THREE.Light.call( this, color );
  6449. this.type = 'AmbientLight';
  6450. };
  6451. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  6452. THREE.AmbientLight.prototype.constructor = THREE.AmbientLight;
  6453. THREE.AmbientLight.prototype.clone = function () {
  6454. var light = new THREE.AmbientLight();
  6455. THREE.Light.prototype.clone.call( this, light );
  6456. return light;
  6457. };
  6458. THREE.AmbientLight.prototype.toJSON = function ( meta ) {
  6459. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  6460. data.object.color = this.color.getHex();
  6461. return data;
  6462. };
  6463. // File:src/lights/AreaLight.js
  6464. /**
  6465. * @author MPanknin / http://www.redplant.de/
  6466. * @author alteredq / http://alteredqualia.com/
  6467. */
  6468. THREE.AreaLight = function ( color, intensity ) {
  6469. THREE.Light.call( this, color );
  6470. this.type = 'AreaLight';
  6471. this.normal = new THREE.Vector3( 0, - 1, 0 );
  6472. this.right = new THREE.Vector3( 1, 0, 0 );
  6473. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6474. this.width = 1.0;
  6475. this.height = 1.0;
  6476. this.constantAttenuation = 1.5;
  6477. this.linearAttenuation = 0.5;
  6478. this.quadraticAttenuation = 0.1;
  6479. };
  6480. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  6481. THREE.AreaLight.prototype.constructor = THREE.AreaLight;
  6482. // File:src/lights/DirectionalLight.js
  6483. /**
  6484. * @author mrdoob / http://mrdoob.com/
  6485. * @author alteredq / http://alteredqualia.com/
  6486. */
  6487. THREE.DirectionalLight = function ( color, intensity ) {
  6488. THREE.Light.call( this, color );
  6489. this.type = 'DirectionalLight';
  6490. this.position.set( 0, 1, 0 );
  6491. this.target = new THREE.Object3D();
  6492. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6493. this.castShadow = false;
  6494. this.onlyShadow = false;
  6495. //
  6496. this.shadowCameraNear = 50;
  6497. this.shadowCameraFar = 5000;
  6498. this.shadowCameraLeft = - 500;
  6499. this.shadowCameraRight = 500;
  6500. this.shadowCameraTop = 500;
  6501. this.shadowCameraBottom = - 500;
  6502. this.shadowCameraVisible = false;
  6503. this.shadowBias = 0;
  6504. this.shadowDarkness = 0.5;
  6505. this.shadowMapWidth = 512;
  6506. this.shadowMapHeight = 512;
  6507. //
  6508. this.shadowCascade = false;
  6509. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, - 1000 );
  6510. this.shadowCascadeCount = 2;
  6511. this.shadowCascadeBias = [ 0, 0, 0 ];
  6512. this.shadowCascadeWidth = [ 512, 512, 512 ];
  6513. this.shadowCascadeHeight = [ 512, 512, 512 ];
  6514. this.shadowCascadeNearZ = [ - 1.000, 0.990, 0.998 ];
  6515. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  6516. this.shadowCascadeArray = [];
  6517. //
  6518. this.shadowMap = null;
  6519. this.shadowMapSize = null;
  6520. this.shadowCamera = null;
  6521. this.shadowMatrix = null;
  6522. };
  6523. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  6524. THREE.DirectionalLight.prototype.constructor = THREE.DirectionalLight;
  6525. THREE.DirectionalLight.prototype.clone = function () {
  6526. var light = new THREE.DirectionalLight();
  6527. THREE.Light.prototype.clone.call( this, light );
  6528. light.target = this.target.clone();
  6529. light.intensity = this.intensity;
  6530. light.castShadow = this.castShadow;
  6531. light.onlyShadow = this.onlyShadow;
  6532. //
  6533. light.shadowCameraNear = this.shadowCameraNear;
  6534. light.shadowCameraFar = this.shadowCameraFar;
  6535. light.shadowCameraLeft = this.shadowCameraLeft;
  6536. light.shadowCameraRight = this.shadowCameraRight;
  6537. light.shadowCameraTop = this.shadowCameraTop;
  6538. light.shadowCameraBottom = this.shadowCameraBottom;
  6539. light.shadowCameraVisible = this.shadowCameraVisible;
  6540. light.shadowBias = this.shadowBias;
  6541. light.shadowDarkness = this.shadowDarkness;
  6542. light.shadowMapWidth = this.shadowMapWidth;
  6543. light.shadowMapHeight = this.shadowMapHeight;
  6544. //
  6545. light.shadowCascade = this.shadowCascade;
  6546. light.shadowCascadeOffset.copy( this.shadowCascadeOffset );
  6547. light.shadowCascadeCount = this.shadowCascadeCount;
  6548. light.shadowCascadeBias = this.shadowCascadeBias.slice( 0 );
  6549. light.shadowCascadeWidth = this.shadowCascadeWidth.slice( 0 );
  6550. light.shadowCascadeHeight = this.shadowCascadeHeight.slice( 0 );
  6551. light.shadowCascadeNearZ = this.shadowCascadeNearZ.slice( 0 );
  6552. light.shadowCascadeFarZ = this.shadowCascadeFarZ.slice( 0 );
  6553. return light;
  6554. };
  6555. THREE.DirectionalLight.prototype.toJSON = function ( meta ) {
  6556. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  6557. data.object.color = this.color.getHex();
  6558. data.object.intensity = this.intensity;
  6559. return data;
  6560. };
  6561. // File:src/lights/HemisphereLight.js
  6562. /**
  6563. * @author alteredq / http://alteredqualia.com/
  6564. */
  6565. THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
  6566. THREE.Light.call( this, skyColor );
  6567. this.type = 'HemisphereLight';
  6568. this.position.set( 0, 100, 0 );
  6569. this.groundColor = new THREE.Color( groundColor );
  6570. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6571. };
  6572. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  6573. THREE.HemisphereLight.prototype.constructor = THREE.HemisphereLight;
  6574. THREE.HemisphereLight.prototype.clone = function () {
  6575. var light = new THREE.HemisphereLight();
  6576. THREE.Light.prototype.clone.call( this, light );
  6577. light.groundColor.copy( this.groundColor );
  6578. light.intensity = this.intensity;
  6579. return light;
  6580. };
  6581. THREE.HemisphereLight.prototype.toJSON = function ( meta ) {
  6582. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  6583. data.object.color = this.color.getHex();
  6584. data.object.groundColor = this.groundColor.getHex();
  6585. return data;
  6586. };
  6587. // File:src/lights/PointLight.js
  6588. /**
  6589. * @author mrdoob / http://mrdoob.com/
  6590. */
  6591. THREE.PointLight = function ( color, intensity, distance, decay ) {
  6592. THREE.Light.call( this, color );
  6593. this.type = 'PointLight';
  6594. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6595. this.distance = ( distance !== undefined ) ? distance : 0;
  6596. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  6597. };
  6598. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  6599. THREE.PointLight.prototype.constructor = THREE.PointLight;
  6600. THREE.PointLight.prototype.clone = function () {
  6601. var light = new THREE.PointLight();
  6602. THREE.Light.prototype.clone.call( this, light );
  6603. light.intensity = this.intensity;
  6604. light.distance = this.distance;
  6605. light.decay = this.decay;
  6606. return light;
  6607. };
  6608. THREE.PointLight.prototype.toJSON = function ( meta ) {
  6609. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  6610. data.object.color = this.color.getHex();
  6611. data.object.intensity = this.intensity;
  6612. data.object.distance = this.distance;
  6613. data.object.decay = this.decay;
  6614. return data;
  6615. };
  6616. // File:src/lights/SpotLight.js
  6617. /**
  6618. * @author alteredq / http://alteredqualia.com/
  6619. */
  6620. THREE.SpotLight = function ( color, intensity, distance, angle, exponent, decay ) {
  6621. THREE.Light.call( this, color );
  6622. this.type = 'SpotLight';
  6623. this.position.set( 0, 1, 0 );
  6624. this.target = new THREE.Object3D();
  6625. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6626. this.distance = ( distance !== undefined ) ? distance : 0;
  6627. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  6628. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  6629. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  6630. this.castShadow = false;
  6631. this.onlyShadow = false;
  6632. //
  6633. this.shadowCameraNear = 50;
  6634. this.shadowCameraFar = 5000;
  6635. this.shadowCameraFov = 50;
  6636. this.shadowCameraVisible = false;
  6637. this.shadowBias = 0;
  6638. this.shadowDarkness = 0.5;
  6639. this.shadowMapWidth = 512;
  6640. this.shadowMapHeight = 512;
  6641. //
  6642. this.shadowMap = null;
  6643. this.shadowMapSize = null;
  6644. this.shadowCamera = null;
  6645. this.shadowMatrix = null;
  6646. };
  6647. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  6648. THREE.SpotLight.prototype.constructor = THREE.SpotLight;
  6649. THREE.SpotLight.prototype.clone = function () {
  6650. var light = new THREE.SpotLight();
  6651. THREE.Light.prototype.clone.call( this, light );
  6652. light.target = this.target.clone();
  6653. light.intensity = this.intensity;
  6654. light.distance = this.distance;
  6655. light.angle = this.angle;
  6656. light.exponent = this.exponent;
  6657. light.decay = this.decay;
  6658. light.castShadow = this.castShadow;
  6659. light.onlyShadow = this.onlyShadow;
  6660. //
  6661. light.shadowCameraNear = this.shadowCameraNear;
  6662. light.shadowCameraFar = this.shadowCameraFar;
  6663. light.shadowCameraFov = this.shadowCameraFov;
  6664. light.shadowCameraVisible = this.shadowCameraVisible;
  6665. light.shadowBias = this.shadowBias;
  6666. light.shadowDarkness = this.shadowDarkness;
  6667. light.shadowMapWidth = this.shadowMapWidth;
  6668. light.shadowMapHeight = this.shadowMapHeight;
  6669. return light;
  6670. };
  6671. THREE.SpotLight.prototype.toJSON = function ( meta ) {
  6672. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  6673. data.object.color = this.color.getHex();
  6674. data.object.intensity = this.intensity;
  6675. data.object.distance = this.distance;
  6676. data.object.angle = this.angle;
  6677. data.object.exponent = this.exponent;
  6678. data.object.decay = this.decay;
  6679. return data;
  6680. };
  6681. // File:src/loaders/Cache.js
  6682. /**
  6683. * @author mrdoob / http://mrdoob.com/
  6684. */
  6685. THREE.Cache = {
  6686. files: {},
  6687. add: function ( key, file ) {
  6688. // THREE.log( 'THREE.Cache', 'Adding key:', key );
  6689. this.files[ key ] = file;
  6690. },
  6691. get: function ( key ) {
  6692. // THREE.log( 'THREE.Cache', 'Checking key:', key );
  6693. return this.files[ key ];
  6694. },
  6695. remove: function ( key ) {
  6696. delete this.files[ key ];
  6697. },
  6698. clear: function () {
  6699. this.files = {}
  6700. }
  6701. };
  6702. // File:src/loaders/Loader.js
  6703. /**
  6704. * @author alteredq / http://alteredqualia.com/
  6705. */
  6706. THREE.Loader = function ( showStatus ) {
  6707. this.showStatus = showStatus;
  6708. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  6709. this.imageLoader = new THREE.ImageLoader();
  6710. this.onLoadStart = function () {};
  6711. this.onLoadProgress = function () {};
  6712. this.onLoadComplete = function () {};
  6713. };
  6714. THREE.Loader.prototype = {
  6715. constructor: THREE.Loader,
  6716. crossOrigin: undefined,
  6717. addStatusElement: function () {
  6718. var e = document.createElement( 'div' );
  6719. e.style.position = 'absolute';
  6720. e.style.right = '0px';
  6721. e.style.top = '0px';
  6722. e.style.fontSize = '0.8em';
  6723. e.style.textAlign = 'left';
  6724. e.style.background = 'rgba(0,0,0,0.25)';
  6725. e.style.color = '#fff';
  6726. e.style.width = '120px';
  6727. e.style.padding = '0.5em 0.5em 0.5em 0.5em';
  6728. e.style.zIndex = 1000;
  6729. e.innerHTML = 'Loading ...';
  6730. return e;
  6731. },
  6732. updateProgress: function ( progress ) {
  6733. var message = 'Loaded ';
  6734. if ( progress.total ) {
  6735. message += ( 100 * progress.loaded / progress.total ).toFixed( 0 ) + '%';
  6736. } else {
  6737. message += ( progress.loaded / 1024 ).toFixed( 2 ) + ' KB';
  6738. }
  6739. this.statusDomElement.innerHTML = message;
  6740. },
  6741. extractUrlBase: function ( url ) {
  6742. var parts = url.split( '/' );
  6743. if ( parts.length === 1 ) return './';
  6744. parts.pop();
  6745. return parts.join( '/' ) + '/';
  6746. },
  6747. initMaterials: function ( materials, texturePath ) {
  6748. var array = [];
  6749. for ( var i = 0; i < materials.length; ++ i ) {
  6750. array[ i ] = this.createMaterial( materials[ i ], texturePath );
  6751. }
  6752. return array;
  6753. },
  6754. needsTangents: function ( materials ) {
  6755. for ( var i = 0, il = materials.length; i < il; i ++ ) {
  6756. var m = materials[ i ];
  6757. if ( m instanceof THREE.ShaderMaterial ) return true;
  6758. }
  6759. return false;
  6760. },
  6761. createMaterial: function ( m, texturePath ) {
  6762. var scope = this;
  6763. function nearest_pow2( n ) {
  6764. var l = Math.log( n ) / Math.LN2;
  6765. return Math.pow( 2, Math.round( l ) );
  6766. }
  6767. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  6768. var fullPath = texturePath + sourceFile;
  6769. var texture;
  6770. var loader = THREE.Loader.Handlers.get( fullPath );
  6771. if ( loader !== null ) {
  6772. texture = loader.load( fullPath );
  6773. } else {
  6774. texture = new THREE.Texture();
  6775. loader = scope.imageLoader;
  6776. loader.crossOrigin = scope.crossOrigin;
  6777. loader.load( fullPath, function ( image ) {
  6778. if ( THREE.Math.isPowerOfTwo( image.width ) === false ||
  6779. THREE.Math.isPowerOfTwo( image.height ) === false ) {
  6780. var width = nearest_pow2( image.width );
  6781. var height = nearest_pow2( image.height );
  6782. var canvas = document.createElement( 'canvas' );
  6783. canvas.width = width;
  6784. canvas.height = height;
  6785. var context = canvas.getContext( '2d' );
  6786. context.drawImage( image, 0, 0, width, height );
  6787. texture.image = canvas;
  6788. } else {
  6789. texture.image = image;
  6790. }
  6791. texture.needsUpdate = true;
  6792. } );
  6793. }
  6794. texture.sourceFile = sourceFile;
  6795. if ( repeat ) {
  6796. texture.repeat.set( repeat[ 0 ], repeat[ 1 ] );
  6797. if ( repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  6798. if ( repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  6799. }
  6800. if ( offset ) {
  6801. texture.offset.set( offset[ 0 ], offset[ 1 ] );
  6802. }
  6803. if ( wrap ) {
  6804. var wrapMap = {
  6805. 'repeat': THREE.RepeatWrapping,
  6806. 'mirror': THREE.MirroredRepeatWrapping
  6807. }
  6808. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ wrap[ 0 ] ];
  6809. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ wrap[ 1 ] ];
  6810. }
  6811. if ( anisotropy ) {
  6812. texture.anisotropy = anisotropy;
  6813. }
  6814. where[ name ] = texture;
  6815. }
  6816. function rgb2hex( rgb ) {
  6817. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  6818. }
  6819. // defaults
  6820. var mtype = 'MeshLambertMaterial';
  6821. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  6822. // parameters from model file
  6823. if ( m.shading ) {
  6824. var shading = m.shading.toLowerCase();
  6825. if ( shading === 'phong' ) mtype = 'MeshPhongMaterial';
  6826. else if ( shading === 'basic' ) mtype = 'MeshBasicMaterial';
  6827. }
  6828. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  6829. mpars.blending = THREE[ m.blending ];
  6830. }
  6831. if ( m.transparent !== undefined ) {
  6832. mpars.transparent = m.transparent;
  6833. }
  6834. if ( m.opacity !== undefined && m.opacity < 1.0 ) {
  6835. mpars.transparent = true;
  6836. }
  6837. if ( m.depthTest !== undefined ) {
  6838. mpars.depthTest = m.depthTest;
  6839. }
  6840. if ( m.depthWrite !== undefined ) {
  6841. mpars.depthWrite = m.depthWrite;
  6842. }
  6843. if ( m.visible !== undefined ) {
  6844. mpars.visible = m.visible;
  6845. }
  6846. if ( m.flipSided !== undefined ) {
  6847. mpars.side = THREE.BackSide;
  6848. }
  6849. if ( m.doubleSided !== undefined ) {
  6850. mpars.side = THREE.DoubleSide;
  6851. }
  6852. if ( m.wireframe !== undefined ) {
  6853. mpars.wireframe = m.wireframe;
  6854. }
  6855. if ( m.vertexColors !== undefined ) {
  6856. if ( m.vertexColors === 'face' ) {
  6857. mpars.vertexColors = THREE.FaceColors;
  6858. } else if ( m.vertexColors ) {
  6859. mpars.vertexColors = THREE.VertexColors;
  6860. }
  6861. }
  6862. // colors
  6863. if ( m.colorDiffuse ) {
  6864. mpars.color = rgb2hex( m.colorDiffuse );
  6865. } else if ( m.DbgColor ) {
  6866. mpars.color = m.DbgColor;
  6867. }
  6868. if ( m.colorSpecular ) {
  6869. mpars.specular = rgb2hex( m.colorSpecular );
  6870. }
  6871. if ( m.colorEmissive ) {
  6872. mpars.emissive = rgb2hex( m.colorEmissive );
  6873. }
  6874. // modifiers
  6875. if ( m.transparency !== undefined ) {
  6876. THREE.warn( 'THREE.Loader: transparency has been renamed to opacity' );
  6877. m.opacity = m.transparency;
  6878. }
  6879. if ( m.opacity !== undefined ) {
  6880. mpars.opacity = m.opacity;
  6881. }
  6882. if ( m.specularCoef ) {
  6883. mpars.shininess = m.specularCoef;
  6884. }
  6885. // textures
  6886. if ( m.mapDiffuse && texturePath ) {
  6887. create_texture( mpars, 'map', m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  6888. }
  6889. if ( m.mapLight && texturePath ) {
  6890. create_texture( mpars, 'lightMap', m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  6891. }
  6892. if ( m.mapAO && texturePath ) {
  6893. create_texture( mpars, 'aoMap', m.mapAO, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  6894. }
  6895. if ( m.mapBump && texturePath ) {
  6896. create_texture( mpars, 'bumpMap', m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  6897. }
  6898. if ( m.mapNormal && texturePath ) {
  6899. create_texture( mpars, 'normalMap', m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  6900. }
  6901. if ( m.mapSpecular && texturePath ) {
  6902. create_texture( mpars, 'specularMap', m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  6903. }
  6904. if ( m.mapAlpha && texturePath ) {
  6905. create_texture( mpars, 'alphaMap', m.mapAlpha, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  6906. }
  6907. //
  6908. if ( m.mapBumpScale ) {
  6909. mpars.bumpScale = m.mapBumpScale;
  6910. }
  6911. if ( m.mapNormalFactor ) {
  6912. mpars.normalScale = new THREE.Vector2( m.mapNormalFactor, m.mapNormalFactor );
  6913. }
  6914. var material = new THREE[ mtype ]( mpars );
  6915. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6916. return material;
  6917. }
  6918. };
  6919. THREE.Loader.Handlers = {
  6920. handlers: [],
  6921. add: function ( regex, loader ) {
  6922. this.handlers.push( regex, loader );
  6923. },
  6924. get: function ( file ) {
  6925. for ( var i = 0, l = this.handlers.length; i < l; i += 2 ) {
  6926. var regex = this.handlers[ i ];
  6927. var loader = this.handlers[ i + 1 ];
  6928. if ( regex.test( file ) ) {
  6929. return loader;
  6930. }
  6931. }
  6932. return null;
  6933. }
  6934. };
  6935. // File:src/loaders/XHRLoader.js
  6936. /**
  6937. * @author mrdoob / http://mrdoob.com/
  6938. */
  6939. THREE.XHRLoader = function ( manager ) {
  6940. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6941. };
  6942. THREE.XHRLoader.prototype = {
  6943. constructor: THREE.XHRLoader,
  6944. load: function ( url, onLoad, onProgress, onError ) {
  6945. var scope = this;
  6946. var cached = THREE.Cache.get( url );
  6947. if ( cached !== undefined ) {
  6948. if ( onLoad ) onLoad( cached );
  6949. return;
  6950. }
  6951. var request = new XMLHttpRequest();
  6952. request.open( 'GET', url, true );
  6953. request.addEventListener( 'load', function ( event ) {
  6954. THREE.Cache.add( url, this.response );
  6955. if ( onLoad ) onLoad( this.response );
  6956. scope.manager.itemEnd( url );
  6957. }, false );
  6958. if ( onProgress !== undefined ) {
  6959. request.addEventListener( 'progress', function ( event ) {
  6960. onProgress( event );
  6961. }, false );
  6962. }
  6963. if ( onError !== undefined ) {
  6964. request.addEventListener( 'error', function ( event ) {
  6965. onError( event );
  6966. }, false );
  6967. }
  6968. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  6969. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  6970. request.send( null );
  6971. scope.manager.itemStart( url );
  6972. },
  6973. setResponseType: function ( value ) {
  6974. this.responseType = value;
  6975. },
  6976. setCrossOrigin: function ( value ) {
  6977. this.crossOrigin = value;
  6978. }
  6979. };
  6980. // File:src/loaders/ImageLoader.js
  6981. /**
  6982. * @author mrdoob / http://mrdoob.com/
  6983. */
  6984. THREE.ImageLoader = function ( manager ) {
  6985. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6986. };
  6987. THREE.ImageLoader.prototype = {
  6988. constructor: THREE.ImageLoader,
  6989. load: function ( url, onLoad, onProgress, onError ) {
  6990. var scope = this;
  6991. var cached = THREE.Cache.get( url );
  6992. if ( cached !== undefined ) {
  6993. onLoad( cached );
  6994. return;
  6995. }
  6996. var image = document.createElement( 'img' );
  6997. image.addEventListener( 'load', function ( event ) {
  6998. THREE.Cache.add( url, this );
  6999. if ( onLoad ) onLoad( this );
  7000. scope.manager.itemEnd( url );
  7001. }, false );
  7002. if ( onProgress !== undefined ) {
  7003. image.addEventListener( 'progress', function ( event ) {
  7004. onProgress( event );
  7005. }, false );
  7006. }
  7007. if ( onError !== undefined ) {
  7008. image.addEventListener( 'error', function ( event ) {
  7009. onError( event );
  7010. }, false );
  7011. }
  7012. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  7013. image.src = url;
  7014. scope.manager.itemStart( url );
  7015. return image;
  7016. },
  7017. setCrossOrigin: function ( value ) {
  7018. this.crossOrigin = value;
  7019. }
  7020. }
  7021. // File:src/loaders/JSONLoader.js
  7022. /**
  7023. * @author mrdoob / http://mrdoob.com/
  7024. * @author alteredq / http://alteredqualia.com/
  7025. */
  7026. THREE.JSONLoader = function ( showStatus ) {
  7027. THREE.Loader.call( this, showStatus );
  7028. this.withCredentials = false;
  7029. };
  7030. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  7031. THREE.JSONLoader.prototype.constructor = THREE.JSONLoader;
  7032. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  7033. // todo: unify load API to for easier SceneLoader use
  7034. texturePath = texturePath && ( typeof texturePath === 'string' ) ? texturePath : this.extractUrlBase( url );
  7035. this.onLoadStart();
  7036. this.loadAjaxJSON( this, url, callback, texturePath );
  7037. };
  7038. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  7039. var xhr = new XMLHttpRequest();
  7040. var length = 0;
  7041. xhr.onreadystatechange = function () {
  7042. if ( xhr.readyState === xhr.DONE ) {
  7043. if ( xhr.status === 200 || xhr.status === 0 ) {
  7044. if ( xhr.responseText ) {
  7045. var json = JSON.parse( xhr.responseText );
  7046. var metadata = json.metadata;
  7047. if ( metadata !== undefined ) {
  7048. if ( metadata.type === 'object' ) {
  7049. THREE.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  7050. return;
  7051. }
  7052. if ( metadata.type === 'scene' ) {
  7053. THREE.error( 'THREE.JSONLoader: ' + url + ' seems to be a Scene. Use THREE.SceneLoader instead.' );
  7054. return;
  7055. }
  7056. }
  7057. var result = context.parse( json, texturePath );
  7058. callback( result.geometry, result.materials );
  7059. } else {
  7060. THREE.error( 'THREE.JSONLoader: ' + url + ' seems to be unreachable or the file is empty.' );
  7061. }
  7062. // in context of more complex asset initialization
  7063. // do not block on single failed file
  7064. // maybe should go even one more level up
  7065. context.onLoadComplete();
  7066. } else {
  7067. THREE.error( 'THREE.JSONLoader: Couldn\'t load ' + url + ' (' + xhr.status + ')' );
  7068. }
  7069. } else if ( xhr.readyState === xhr.LOADING ) {
  7070. if ( callbackProgress ) {
  7071. if ( length === 0 ) {
  7072. length = xhr.getResponseHeader( 'Content-Length' );
  7073. }
  7074. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  7075. }
  7076. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  7077. if ( callbackProgress !== undefined ) {
  7078. length = xhr.getResponseHeader( 'Content-Length' );
  7079. }
  7080. }
  7081. };
  7082. xhr.open( 'GET', url, true );
  7083. xhr.withCredentials = this.withCredentials;
  7084. xhr.send( null );
  7085. };
  7086. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  7087. var geometry = new THREE.Geometry(),
  7088. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  7089. parseModel( scale );
  7090. parseSkin();
  7091. parseMorphing( scale );
  7092. geometry.computeFaceNormals();
  7093. geometry.computeBoundingSphere();
  7094. function parseModel( scale ) {
  7095. function isBitSet( value, position ) {
  7096. return value & ( 1 << position );
  7097. }
  7098. var i, j, fi,
  7099. offset, zLength,
  7100. colorIndex, normalIndex, uvIndex, materialIndex,
  7101. type,
  7102. isQuad,
  7103. hasMaterial,
  7104. hasFaceVertexUv,
  7105. hasFaceNormal, hasFaceVertexNormal,
  7106. hasFaceColor, hasFaceVertexColor,
  7107. vertex, face, faceA, faceB, hex, normal,
  7108. uvLayer, uv, u, v,
  7109. faces = json.faces,
  7110. vertices = json.vertices,
  7111. normals = json.normals,
  7112. colors = json.colors,
  7113. nUvLayers = 0;
  7114. if ( json.uvs !== undefined ) {
  7115. // disregard empty arrays
  7116. for ( i = 0; i < json.uvs.length; i ++ ) {
  7117. if ( json.uvs[ i ].length ) nUvLayers ++;
  7118. }
  7119. for ( i = 0; i < nUvLayers; i ++ ) {
  7120. geometry.faceVertexUvs[ i ] = [];
  7121. }
  7122. }
  7123. offset = 0;
  7124. zLength = vertices.length;
  7125. while ( offset < zLength ) {
  7126. vertex = new THREE.Vector3();
  7127. vertex.x = vertices[ offset ++ ] * scale;
  7128. vertex.y = vertices[ offset ++ ] * scale;
  7129. vertex.z = vertices[ offset ++ ] * scale;
  7130. geometry.vertices.push( vertex );
  7131. }
  7132. offset = 0;
  7133. zLength = faces.length;
  7134. while ( offset < zLength ) {
  7135. type = faces[ offset ++ ];
  7136. isQuad = isBitSet( type, 0 );
  7137. hasMaterial = isBitSet( type, 1 );
  7138. hasFaceVertexUv = isBitSet( type, 3 );
  7139. hasFaceNormal = isBitSet( type, 4 );
  7140. hasFaceVertexNormal = isBitSet( type, 5 );
  7141. hasFaceColor = isBitSet( type, 6 );
  7142. hasFaceVertexColor = isBitSet( type, 7 );
  7143. // THREE.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  7144. if ( isQuad ) {
  7145. faceA = new THREE.Face3();
  7146. faceA.a = faces[ offset ];
  7147. faceA.b = faces[ offset + 1 ];
  7148. faceA.c = faces[ offset + 3 ];
  7149. faceB = new THREE.Face3();
  7150. faceB.a = faces[ offset + 1 ];
  7151. faceB.b = faces[ offset + 2 ];
  7152. faceB.c = faces[ offset + 3 ];
  7153. offset += 4;
  7154. if ( hasMaterial ) {
  7155. materialIndex = faces[ offset ++ ];
  7156. faceA.materialIndex = materialIndex;
  7157. faceB.materialIndex = materialIndex;
  7158. }
  7159. // to get face <=> uv index correspondence
  7160. fi = geometry.faces.length;
  7161. if ( hasFaceVertexUv ) {
  7162. for ( i = 0; i < nUvLayers; i ++ ) {
  7163. uvLayer = json.uvs[ i ];
  7164. geometry.faceVertexUvs[ i ][ fi ] = [];
  7165. geometry.faceVertexUvs[ i ][ fi + 1 ] = []
  7166. for ( j = 0; j < 4; j ++ ) {
  7167. uvIndex = faces[ offset ++ ];
  7168. u = uvLayer[ uvIndex * 2 ];
  7169. v = uvLayer[ uvIndex * 2 + 1 ];
  7170. uv = new THREE.Vector2( u, v );
  7171. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7172. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  7173. }
  7174. }
  7175. }
  7176. if ( hasFaceNormal ) {
  7177. normalIndex = faces[ offset ++ ] * 3;
  7178. faceA.normal.set(
  7179. normals[ normalIndex ++ ],
  7180. normals[ normalIndex ++ ],
  7181. normals[ normalIndex ]
  7182. );
  7183. faceB.normal.copy( faceA.normal );
  7184. }
  7185. if ( hasFaceVertexNormal ) {
  7186. for ( i = 0; i < 4; i ++ ) {
  7187. normalIndex = faces[ offset ++ ] * 3;
  7188. normal = new THREE.Vector3(
  7189. normals[ normalIndex ++ ],
  7190. normals[ normalIndex ++ ],
  7191. normals[ normalIndex ]
  7192. );
  7193. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  7194. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  7195. }
  7196. }
  7197. if ( hasFaceColor ) {
  7198. colorIndex = faces[ offset ++ ];
  7199. hex = colors[ colorIndex ];
  7200. faceA.color.setHex( hex );
  7201. faceB.color.setHex( hex );
  7202. }
  7203. if ( hasFaceVertexColor ) {
  7204. for ( i = 0; i < 4; i ++ ) {
  7205. colorIndex = faces[ offset ++ ];
  7206. hex = colors[ colorIndex ];
  7207. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  7208. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  7209. }
  7210. }
  7211. geometry.faces.push( faceA );
  7212. geometry.faces.push( faceB );
  7213. } else {
  7214. face = new THREE.Face3();
  7215. face.a = faces[ offset ++ ];
  7216. face.b = faces[ offset ++ ];
  7217. face.c = faces[ offset ++ ];
  7218. if ( hasMaterial ) {
  7219. materialIndex = faces[ offset ++ ];
  7220. face.materialIndex = materialIndex;
  7221. }
  7222. // to get face <=> uv index correspondence
  7223. fi = geometry.faces.length;
  7224. if ( hasFaceVertexUv ) {
  7225. for ( i = 0; i < nUvLayers; i ++ ) {
  7226. uvLayer = json.uvs[ i ];
  7227. geometry.faceVertexUvs[ i ][ fi ] = [];
  7228. for ( j = 0; j < 3; j ++ ) {
  7229. uvIndex = faces[ offset ++ ];
  7230. u = uvLayer[ uvIndex * 2 ];
  7231. v = uvLayer[ uvIndex * 2 + 1 ];
  7232. uv = new THREE.Vector2( u, v );
  7233. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7234. }
  7235. }
  7236. }
  7237. if ( hasFaceNormal ) {
  7238. normalIndex = faces[ offset ++ ] * 3;
  7239. face.normal.set(
  7240. normals[ normalIndex ++ ],
  7241. normals[ normalIndex ++ ],
  7242. normals[ normalIndex ]
  7243. );
  7244. }
  7245. if ( hasFaceVertexNormal ) {
  7246. for ( i = 0; i < 3; i ++ ) {
  7247. normalIndex = faces[ offset ++ ] * 3;
  7248. normal = new THREE.Vector3(
  7249. normals[ normalIndex ++ ],
  7250. normals[ normalIndex ++ ],
  7251. normals[ normalIndex ]
  7252. );
  7253. face.vertexNormals.push( normal );
  7254. }
  7255. }
  7256. if ( hasFaceColor ) {
  7257. colorIndex = faces[ offset ++ ];
  7258. face.color.setHex( colors[ colorIndex ] );
  7259. }
  7260. if ( hasFaceVertexColor ) {
  7261. for ( i = 0; i < 3; i ++ ) {
  7262. colorIndex = faces[ offset ++ ];
  7263. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  7264. }
  7265. }
  7266. geometry.faces.push( face );
  7267. }
  7268. }
  7269. };
  7270. function parseSkin() {
  7271. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  7272. if ( json.skinWeights ) {
  7273. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  7274. var x = json.skinWeights[ i ];
  7275. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  7276. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  7277. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  7278. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  7279. }
  7280. }
  7281. if ( json.skinIndices ) {
  7282. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  7283. var a = json.skinIndices[ i ];
  7284. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  7285. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  7286. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  7287. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  7288. }
  7289. }
  7290. geometry.bones = json.bones;
  7291. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  7292. THREE.warn( 'THREE.JSONLoader: When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  7293. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  7294. }
  7295. // could change this to json.animations[0] or remove completely
  7296. geometry.animation = json.animation;
  7297. geometry.animations = json.animations;
  7298. };
  7299. function parseMorphing( scale ) {
  7300. if ( json.morphTargets !== undefined ) {
  7301. var i, l, v, vl, dstVertices, srcVertices;
  7302. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  7303. geometry.morphTargets[ i ] = {};
  7304. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  7305. geometry.morphTargets[ i ].vertices = [];
  7306. dstVertices = geometry.morphTargets[ i ].vertices;
  7307. srcVertices = json.morphTargets [ i ].vertices;
  7308. for ( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  7309. var vertex = new THREE.Vector3();
  7310. vertex.x = srcVertices[ v ] * scale;
  7311. vertex.y = srcVertices[ v + 1 ] * scale;
  7312. vertex.z = srcVertices[ v + 2 ] * scale;
  7313. dstVertices.push( vertex );
  7314. }
  7315. }
  7316. }
  7317. if ( json.morphColors !== undefined ) {
  7318. var i, l, c, cl, dstColors, srcColors, color;
  7319. for ( i = 0, l = json.morphColors.length; i < l; i ++ ) {
  7320. geometry.morphColors[ i ] = {};
  7321. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  7322. geometry.morphColors[ i ].colors = [];
  7323. dstColors = geometry.morphColors[ i ].colors;
  7324. srcColors = json.morphColors [ i ].colors;
  7325. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  7326. color = new THREE.Color( 0xffaa00 );
  7327. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  7328. dstColors.push( color );
  7329. }
  7330. }
  7331. }
  7332. };
  7333. if ( json.materials === undefined || json.materials.length === 0 ) {
  7334. return { geometry: geometry };
  7335. } else {
  7336. var materials = this.initMaterials( json.materials, texturePath );
  7337. if ( this.needsTangents( materials ) ) {
  7338. geometry.computeTangents();
  7339. }
  7340. return { geometry: geometry, materials: materials };
  7341. }
  7342. };
  7343. // File:src/loaders/LoadingManager.js
  7344. /**
  7345. * @author mrdoob / http://mrdoob.com/
  7346. */
  7347. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  7348. var scope = this;
  7349. var loaded = 0, total = 0;
  7350. this.onLoad = onLoad;
  7351. this.onProgress = onProgress;
  7352. this.onError = onError;
  7353. this.itemStart = function ( url ) {
  7354. total ++;
  7355. };
  7356. this.itemEnd = function ( url ) {
  7357. loaded ++;
  7358. if ( scope.onProgress !== undefined ) {
  7359. scope.onProgress( url, loaded, total );
  7360. }
  7361. if ( loaded === total && scope.onLoad !== undefined ) {
  7362. scope.onLoad();
  7363. }
  7364. };
  7365. };
  7366. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  7367. // File:src/loaders/BufferGeometryLoader.js
  7368. /**
  7369. * @author mrdoob / http://mrdoob.com/
  7370. */
  7371. THREE.BufferGeometryLoader = function ( manager ) {
  7372. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7373. };
  7374. THREE.BufferGeometryLoader.prototype = {
  7375. constructor: THREE.BufferGeometryLoader,
  7376. load: function ( url, onLoad, onProgress, onError ) {
  7377. var scope = this;
  7378. var loader = new THREE.XHRLoader( scope.manager );
  7379. loader.setCrossOrigin( this.crossOrigin );
  7380. loader.load( url, function ( text ) {
  7381. onLoad( scope.parse( JSON.parse( text ) ) );
  7382. }, onProgress, onError );
  7383. },
  7384. setCrossOrigin: function ( value ) {
  7385. this.crossOrigin = value;
  7386. },
  7387. parse: function ( json ) {
  7388. var geometry = new THREE.BufferGeometry();
  7389. var attributes = json.data.attributes;
  7390. for ( var key in attributes ) {
  7391. var attribute = attributes[ key ];
  7392. var typedArray = new self[ attribute.type ]( attribute.array );
  7393. geometry.addAttribute( key, new THREE.BufferAttribute( typedArray, attribute.itemSize ) );
  7394. }
  7395. var offsets = json.data.offsets;
  7396. if ( offsets !== undefined ) {
  7397. geometry.offsets = JSON.parse( JSON.stringify( offsets ) );
  7398. }
  7399. var boundingSphere = json.data.boundingSphere;
  7400. if ( boundingSphere !== undefined ) {
  7401. var center = new THREE.Vector3();
  7402. if ( boundingSphere.center !== undefined ) {
  7403. center.fromArray( boundingSphere.center );
  7404. }
  7405. geometry.boundingSphere = new THREE.Sphere( center, boundingSphere.radius );
  7406. }
  7407. return geometry;
  7408. }
  7409. };
  7410. // File:src/loaders/MaterialLoader.js
  7411. /**
  7412. * @author mrdoob / http://mrdoob.com/
  7413. */
  7414. THREE.MaterialLoader = function ( manager ) {
  7415. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7416. };
  7417. THREE.MaterialLoader.prototype = {
  7418. constructor: THREE.MaterialLoader,
  7419. load: function ( url, onLoad, onProgress, onError ) {
  7420. var scope = this;
  7421. var loader = new THREE.XHRLoader( scope.manager );
  7422. loader.setCrossOrigin( this.crossOrigin );
  7423. loader.load( url, function ( text ) {
  7424. onLoad( scope.parse( JSON.parse( text ) ) );
  7425. }, onProgress, onError );
  7426. },
  7427. setCrossOrigin: function ( value ) {
  7428. this.crossOrigin = value;
  7429. },
  7430. parse: function ( json ) {
  7431. var material = new THREE[ json.type ];
  7432. if ( json.color !== undefined ) material.color.setHex( json.color );
  7433. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  7434. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  7435. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  7436. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  7437. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  7438. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  7439. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  7440. if ( json.shading !== undefined ) material.shading = json.shading;
  7441. if ( json.blending !== undefined ) material.blending = json.blending;
  7442. if ( json.side !== undefined ) material.side = json.side;
  7443. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  7444. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  7445. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  7446. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  7447. // for PointCloudMaterial
  7448. if ( json.size !== undefined ) material.size = json.size;
  7449. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  7450. if ( json.materials !== undefined ) {
  7451. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  7452. material.materials.push( this.parse( json.materials[ i ] ) );
  7453. }
  7454. }
  7455. return material;
  7456. }
  7457. };
  7458. // File:src/loaders/ObjectLoader.js
  7459. /**
  7460. * @author mrdoob / http://mrdoob.com/
  7461. */
  7462. THREE.ObjectLoader = function ( manager ) {
  7463. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7464. this.texturePath = '';
  7465. };
  7466. THREE.ObjectLoader.prototype = {
  7467. constructor: THREE.ObjectLoader,
  7468. load: function ( url, onLoad, onProgress, onError ) {
  7469. if ( this.texturePath === '' ) {
  7470. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  7471. }
  7472. var scope = this;
  7473. var loader = new THREE.XHRLoader( scope.manager );
  7474. loader.setCrossOrigin( this.crossOrigin );
  7475. loader.load( url, function ( text ) {
  7476. scope.parse( JSON.parse( text ), onLoad );
  7477. }, onProgress, onError );
  7478. },
  7479. setTexturePath: function ( value ) {
  7480. this.texturePath = value;
  7481. },
  7482. setCrossOrigin: function ( value ) {
  7483. this.crossOrigin = value;
  7484. },
  7485. parse: function ( json, onLoad ) {
  7486. var geometries = this.parseGeometries( json.geometries );
  7487. var images = this.parseImages( json.images, function () {
  7488. if ( onLoad !== undefined ) onLoad( object );
  7489. } );
  7490. var textures = this.parseTextures( json.textures, images );
  7491. var materials = this.parseMaterials( json.materials, textures );
  7492. var object = this.parseObject( json.object, geometries, materials );
  7493. if ( json.images === undefined || json.images.length === 0 ) {
  7494. if ( onLoad !== undefined ) onLoad( object );
  7495. }
  7496. return object;
  7497. },
  7498. parseGeometries: function ( json ) {
  7499. var geometries = {};
  7500. if ( json !== undefined ) {
  7501. var geometryLoader = new THREE.JSONLoader();
  7502. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  7503. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7504. var geometry;
  7505. var data = json[ i ];
  7506. switch ( data.type ) {
  7507. case 'PlaneGeometry':
  7508. case 'PlaneBufferGeometry':
  7509. geometry = new THREE[ data.type ](
  7510. data.width,
  7511. data.height,
  7512. data.widthSegments,
  7513. data.heightSegments
  7514. );
  7515. break;
  7516. case 'BoxGeometry':
  7517. case 'CubeGeometry': // backwards compatible
  7518. geometry = new THREE.BoxGeometry(
  7519. data.width,
  7520. data.height,
  7521. data.depth,
  7522. data.widthSegments,
  7523. data.heightSegments,
  7524. data.depthSegments
  7525. );
  7526. break;
  7527. case 'CircleGeometry':
  7528. geometry = new THREE.CircleGeometry(
  7529. data.radius,
  7530. data.segments
  7531. );
  7532. break;
  7533. case 'CylinderGeometry':
  7534. geometry = new THREE.CylinderGeometry(
  7535. data.radiusTop,
  7536. data.radiusBottom,
  7537. data.height,
  7538. data.radialSegments,
  7539. data.heightSegments,
  7540. data.openEnded
  7541. );
  7542. break;
  7543. case 'SphereGeometry':
  7544. geometry = new THREE.SphereGeometry(
  7545. data.radius,
  7546. data.widthSegments,
  7547. data.heightSegments,
  7548. data.phiStart,
  7549. data.phiLength,
  7550. data.thetaStart,
  7551. data.thetaLength
  7552. );
  7553. break;
  7554. case 'IcosahedronGeometry':
  7555. geometry = new THREE.IcosahedronGeometry(
  7556. data.radius,
  7557. data.detail
  7558. );
  7559. break;
  7560. case 'TorusGeometry':
  7561. geometry = new THREE.TorusGeometry(
  7562. data.radius,
  7563. data.tube,
  7564. data.radialSegments,
  7565. data.tubularSegments,
  7566. data.arc
  7567. );
  7568. break;
  7569. case 'TorusKnotGeometry':
  7570. geometry = new THREE.TorusKnotGeometry(
  7571. data.radius,
  7572. data.tube,
  7573. data.radialSegments,
  7574. data.tubularSegments,
  7575. data.p,
  7576. data.q,
  7577. data.heightScale
  7578. );
  7579. break;
  7580. case 'BufferGeometry':
  7581. geometry = bufferGeometryLoader.parse( data );
  7582. break;
  7583. case 'Geometry':
  7584. geometry = geometryLoader.parse( data.data ).geometry;
  7585. break;
  7586. case 'TextGeometry':
  7587. geometry = new THREE.TextGeometry(
  7588. data.text,
  7589. data.data
  7590. );
  7591. break;
  7592. }
  7593. geometry.uuid = data.uuid;
  7594. if ( data.name !== undefined ) geometry.name = data.name;
  7595. geometries[ data.uuid ] = geometry;
  7596. }
  7597. }
  7598. return geometries;
  7599. },
  7600. parseMaterials: function ( json, textures ) {
  7601. var materials = {};
  7602. if ( json !== undefined ) {
  7603. var getTexture = function ( name ) {
  7604. if ( textures[ name ] === undefined ) {
  7605. THREE.warn( 'THREE.ObjectLoader: Undefined texture', name );
  7606. }
  7607. return textures[ name ];
  7608. };
  7609. var loader = new THREE.MaterialLoader();
  7610. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7611. var data = json[ i ];
  7612. var material = loader.parse( data );
  7613. material.uuid = data.uuid;
  7614. if ( data.name !== undefined ) material.name = data.name;
  7615. if ( data.map !== undefined ) {
  7616. material.map = getTexture( data.map );
  7617. }
  7618. if ( data.bumpMap !== undefined ) {
  7619. material.bumpMap = getTexture( data.bumpMap );
  7620. if ( data.bumpScale !== undefined ) {
  7621. material.bumpScale = data.bumpScale;
  7622. }
  7623. }
  7624. if ( data.alphaMap !== undefined ) {
  7625. material.alphaMap = getTexture( data.alphaMap );
  7626. }
  7627. if ( data.envMap !== undefined ) {
  7628. material.envMap = getTexture( data.envMap );
  7629. }
  7630. if ( data.normalMap !== undefined ) {
  7631. material.normalMap = getTexture( data.normalMap );
  7632. if ( data.normalScale !== undefined ) {
  7633. material.normalScale = new THREE.Vector2( data.normalScale, data.normalScale );
  7634. }
  7635. }
  7636. if ( data.lightMap !== undefined ) {
  7637. material.lightMap = getTexture( data.lightMap );
  7638. if ( data.lightMapIntensity !== undefined ) {
  7639. material.lightMapIntensity = data.lightMapIntensity;
  7640. }
  7641. }
  7642. if ( data.aoMap !== undefined ) {
  7643. material.aoMap = getTexture( data.aoMap );
  7644. if ( data.aoMapIntensity !== undefined ) {
  7645. material.aoMapIntensity = data.aoMapIntensity;
  7646. }
  7647. }
  7648. if ( data.specularMap !== undefined ) {
  7649. material.specularMap = getTexture( data.specularMap );
  7650. }
  7651. materials[ data.uuid ] = material;
  7652. }
  7653. }
  7654. return materials;
  7655. },
  7656. parseImages: function ( json, onLoad ) {
  7657. var scope = this;
  7658. var images = {};
  7659. if ( json !== undefined && json.length > 0 ) {
  7660. var manager = new THREE.LoadingManager( onLoad );
  7661. var loader = new THREE.ImageLoader( manager );
  7662. loader.setCrossOrigin( this.crossOrigin );
  7663. var loadImage = function ( url ) {
  7664. scope.manager.itemStart( url );
  7665. return loader.load( url, function () {
  7666. scope.manager.itemEnd( url );
  7667. } );
  7668. };
  7669. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7670. var image = json[ i ];
  7671. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  7672. images[ image.uuid ] = loadImage( path );
  7673. }
  7674. }
  7675. return images;
  7676. },
  7677. parseTextures: function ( json, images ) {
  7678. var textures = {};
  7679. if ( json !== undefined ) {
  7680. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7681. var data = json[ i ];
  7682. if ( data.image === undefined ) {
  7683. THREE.warn( 'THREE.ObjectLoader: No "image" speficied for', data.uuid );
  7684. }
  7685. if ( images[ data.image ] === undefined ) {
  7686. THREE.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  7687. }
  7688. var texture = new THREE.Texture( images[ data.image ] );
  7689. texture.needsUpdate = true;
  7690. texture.uuid = data.uuid;
  7691. if ( data.name !== undefined ) texture.name = data.name;
  7692. if ( data.repeat !== undefined ) texture.repeat = new THREE.Vector2( data.repeat[ 0 ], data.repeat[ 1 ] );
  7693. if ( data.minFilter !== undefined ) texture.minFilter = THREE[ data.minFilter ];
  7694. if ( data.magFilter !== undefined ) texture.magFilter = THREE[ data.magFilter ];
  7695. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  7696. if ( data.wrap instanceof Array ) {
  7697. texture.wrapS = THREE[ data.wrap[ 0 ] ];
  7698. texture.wrapT = THREE[ data.wrap[ 1 ] ];
  7699. }
  7700. textures[ data.uuid ] = texture;
  7701. }
  7702. }
  7703. return textures;
  7704. },
  7705. parseObject: function () {
  7706. var matrix = new THREE.Matrix4();
  7707. return function ( data, geometries, materials ) {
  7708. var object;
  7709. var getGeometry = function ( name ) {
  7710. if ( geometries[ name ] === undefined ) {
  7711. THREE.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  7712. }
  7713. return geometries[ name ];
  7714. };
  7715. var getMaterial = function ( name ) {
  7716. if ( materials[ name ] === undefined ) {
  7717. THREE.warn( 'THREE.ObjectLoader: Undefined material', name );
  7718. }
  7719. return materials[ name ];
  7720. };
  7721. switch ( data.type ) {
  7722. case 'Scene':
  7723. object = new THREE.Scene();
  7724. break;
  7725. case 'PerspectiveCamera':
  7726. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  7727. break;
  7728. case 'OrthographicCamera':
  7729. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  7730. break;
  7731. case 'AmbientLight':
  7732. object = new THREE.AmbientLight( data.color );
  7733. break;
  7734. case 'DirectionalLight':
  7735. object = new THREE.DirectionalLight( data.color, data.intensity );
  7736. break;
  7737. case 'PointLight':
  7738. object = new THREE.PointLight( data.color, data.intensity, data.distance, data.decay );
  7739. break;
  7740. case 'SpotLight':
  7741. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent, data.decay );
  7742. break;
  7743. case 'HemisphereLight':
  7744. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  7745. break;
  7746. case 'Mesh':
  7747. object = new THREE.Mesh( getGeometry( data.geometry ), getMaterial( data.material ) );
  7748. break;
  7749. case 'Line':
  7750. object = new THREE.Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  7751. break;
  7752. case 'PointCloud':
  7753. object = new THREE.PointCloud( getGeometry( data.geometry ), getMaterial( data.material ) );
  7754. break;
  7755. case 'Sprite':
  7756. object = new THREE.Sprite( getMaterial( data.material ) );
  7757. break;
  7758. case 'Group':
  7759. object = new THREE.Group();
  7760. break;
  7761. default:
  7762. object = new THREE.Object3D();
  7763. }
  7764. object.uuid = data.uuid;
  7765. if ( data.name !== undefined ) object.name = data.name;
  7766. if ( data.matrix !== undefined ) {
  7767. matrix.fromArray( data.matrix );
  7768. matrix.decompose( object.position, object.quaternion, object.scale );
  7769. } else {
  7770. if ( data.position !== undefined ) object.position.fromArray( data.position );
  7771. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  7772. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  7773. }
  7774. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  7775. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  7776. if ( data.visible !== undefined ) object.visible = data.visible;
  7777. if ( data.userData !== undefined ) object.userData = data.userData;
  7778. if ( data.children !== undefined ) {
  7779. for ( var child in data.children ) {
  7780. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  7781. }
  7782. }
  7783. return object;
  7784. }
  7785. }()
  7786. };
  7787. // File:src/loaders/TextureLoader.js
  7788. /**
  7789. * @author mrdoob / http://mrdoob.com/
  7790. */
  7791. THREE.TextureLoader = function ( manager ) {
  7792. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7793. };
  7794. THREE.TextureLoader.prototype = {
  7795. constructor: THREE.TextureLoader,
  7796. load: function ( url, onLoad, onProgress, onError ) {
  7797. var scope = this;
  7798. var loader = new THREE.ImageLoader( scope.manager );
  7799. loader.setCrossOrigin( this.crossOrigin );
  7800. loader.load( url, function ( image ) {
  7801. var texture = new THREE.Texture( image );
  7802. texture.needsUpdate = true;
  7803. if ( onLoad !== undefined ) {
  7804. onLoad( texture );
  7805. }
  7806. }, onProgress, onError );
  7807. },
  7808. setCrossOrigin: function ( value ) {
  7809. this.crossOrigin = value;
  7810. }
  7811. };
  7812. // File:src/loaders/BinaryTextureLoader.js
  7813. /**
  7814. * @author Nikos M. / https://github.com/foo123/
  7815. *
  7816. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  7817. */
  7818. THREE.DataTextureLoader = THREE.BinaryTextureLoader = function () {
  7819. // override in sub classes
  7820. this._parser = null;
  7821. };
  7822. THREE.BinaryTextureLoader.prototype = {
  7823. constructor: THREE.BinaryTextureLoader,
  7824. load: function ( url, onLoad, onProgress, onError ) {
  7825. var scope = this;
  7826. var texture = new THREE.DataTexture( );
  7827. var loader = new THREE.XHRLoader();
  7828. loader.setResponseType( 'arraybuffer' );
  7829. loader.load( url, function ( buffer ) {
  7830. var texData = scope._parser( buffer );
  7831. if ( !texData ) return;
  7832. if ( undefined !== texData.image ) {
  7833. texture.image = texData.image;
  7834. } else if ( undefined !== texData.data ) {
  7835. texture.image.width = texData.width;
  7836. texture.image.height = texData.height;
  7837. texture.image.data = texData.data;
  7838. }
  7839. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : THREE.ClampToEdgeWrapping;
  7840. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : THREE.ClampToEdgeWrapping;
  7841. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : THREE.LinearFilter;
  7842. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : THREE.LinearMipMapLinearFilter;
  7843. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  7844. if ( undefined !== texData.format ) {
  7845. texture.format = texData.format;
  7846. }
  7847. if ( undefined !== texData.type ) {
  7848. texture.type = texData.type;
  7849. }
  7850. if ( undefined !== texData.mipmaps ) {
  7851. texture.mipmaps = texData.mipmaps;
  7852. }
  7853. if ( 1 === texData.mipmapCount ) {
  7854. texture.minFilter = THREE.LinearFilter;
  7855. }
  7856. texture.needsUpdate = true;
  7857. if ( onLoad ) onLoad( texture, texData );
  7858. }, onProgress, onError );
  7859. return texture;
  7860. }
  7861. };
  7862. // File:src/loaders/CompressedTextureLoader.js
  7863. /**
  7864. * @author mrdoob / http://mrdoob.com/
  7865. *
  7866. * Abstract Base class to block based textures loader (dds, pvr, ...)
  7867. */
  7868. THREE.CompressedTextureLoader = function () {
  7869. // override in sub classes
  7870. this._parser = null;
  7871. };
  7872. THREE.CompressedTextureLoader.prototype = {
  7873. constructor: THREE.CompressedTextureLoader,
  7874. load: function ( url, onLoad, onError ) {
  7875. var scope = this;
  7876. var images = [];
  7877. var texture = new THREE.CompressedTexture();
  7878. texture.image = images;
  7879. var loader = new THREE.XHRLoader();
  7880. loader.setResponseType( 'arraybuffer' );
  7881. if ( url instanceof Array ) {
  7882. var loaded = 0;
  7883. var loadTexture = function ( i ) {
  7884. loader.load( url[ i ], function ( buffer ) {
  7885. var texDatas = scope._parser( buffer, true );
  7886. images[ i ] = {
  7887. width: texDatas.width,
  7888. height: texDatas.height,
  7889. format: texDatas.format,
  7890. mipmaps: texDatas.mipmaps
  7891. };
  7892. loaded += 1;
  7893. if ( loaded === 6 ) {
  7894. if (texDatas.mipmapCount == 1)
  7895. texture.minFilter = THREE.LinearFilter;
  7896. texture.format = texDatas.format;
  7897. texture.needsUpdate = true;
  7898. if ( onLoad ) onLoad( texture );
  7899. }
  7900. } );
  7901. };
  7902. for ( var i = 0, il = url.length; i < il; ++ i ) {
  7903. loadTexture( i );
  7904. }
  7905. } else {
  7906. // compressed cubemap texture stored in a single DDS file
  7907. loader.load( url, function ( buffer ) {
  7908. var texDatas = scope._parser( buffer, true );
  7909. if ( texDatas.isCubemap ) {
  7910. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  7911. for ( var f = 0; f < faces; f ++ ) {
  7912. images[ f ] = { mipmaps : [] };
  7913. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  7914. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  7915. images[ f ].format = texDatas.format;
  7916. images[ f ].width = texDatas.width;
  7917. images[ f ].height = texDatas.height;
  7918. }
  7919. }
  7920. } else {
  7921. texture.image.width = texDatas.width;
  7922. texture.image.height = texDatas.height;
  7923. texture.mipmaps = texDatas.mipmaps;
  7924. }
  7925. if ( texDatas.mipmapCount === 1 ) {
  7926. texture.minFilter = THREE.LinearFilter;
  7927. }
  7928. texture.format = texDatas.format;
  7929. texture.needsUpdate = true;
  7930. if ( onLoad ) onLoad( texture );
  7931. } );
  7932. }
  7933. return texture;
  7934. }
  7935. };
  7936. // File:src/materials/Material.js
  7937. /**
  7938. * @author mrdoob / http://mrdoob.com/
  7939. * @author alteredq / http://alteredqualia.com/
  7940. */
  7941. THREE.Material = function () {
  7942. Object.defineProperty( this, 'id', { value: THREE.MaterialIdCount ++ } );
  7943. this.uuid = THREE.Math.generateUUID();
  7944. this.name = '';
  7945. this.type = 'Material';
  7946. this.side = THREE.FrontSide;
  7947. this.opacity = 1;
  7948. this.transparent = false;
  7949. this.blending = THREE.NormalBlending;
  7950. this.blendSrc = THREE.SrcAlphaFactor;
  7951. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  7952. this.blendEquation = THREE.AddEquation;
  7953. this.blendSrcAlpha = null;
  7954. this.blendDstAlpha = null;
  7955. this.blendEquationAlpha = null;
  7956. this.depthTest = true;
  7957. this.depthWrite = true;
  7958. this.colorWrite = true;
  7959. this.polygonOffset = false;
  7960. this.polygonOffsetFactor = 0;
  7961. this.polygonOffsetUnits = 0;
  7962. this.alphaTest = 0;
  7963. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  7964. this.visible = true;
  7965. this._needsUpdate = true;
  7966. };
  7967. THREE.Material.prototype = {
  7968. constructor: THREE.Material,
  7969. get needsUpdate () {
  7970. return this._needsUpdate;
  7971. },
  7972. set needsUpdate ( value ) {
  7973. if ( value === true ) this.update();
  7974. this._needsUpdate = value;
  7975. },
  7976. setValues: function ( values ) {
  7977. if ( values === undefined ) return;
  7978. for ( var key in values ) {
  7979. var newValue = values[ key ];
  7980. if ( newValue === undefined ) {
  7981. THREE.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  7982. continue;
  7983. }
  7984. if ( key in this ) {
  7985. var currentValue = this[ key ];
  7986. if ( currentValue instanceof THREE.Color ) {
  7987. currentValue.set( newValue );
  7988. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  7989. currentValue.copy( newValue );
  7990. } else if ( key == 'overdraw' ) {
  7991. // ensure overdraw is backwards-compatable with legacy boolean type
  7992. this[ key ] = Number( newValue );
  7993. } else {
  7994. this[ key ] = newValue;
  7995. }
  7996. }
  7997. }
  7998. },
  7999. toJSON: function() {
  8000. // we will store all serialization data on 'data'
  8001. var data = {};
  8002. // add metadata
  8003. data.metadata = {
  8004. version: 4.4,
  8005. type: 'Material',
  8006. generator: 'Material.toJSON'
  8007. }
  8008. // standard Material serialization
  8009. data.type = this.type;
  8010. data.uuid = this.uuid;
  8011. if ( this.name !== '' ) data.name = this.name;
  8012. if ( this.opacity < 1 ) data.opacity = this.opacity;
  8013. if ( this.transparent !== false ) data.transparent = this.transparent;
  8014. if ( this.wireframe !== false ) data.wireframe = this.wireframe;
  8015. return data;
  8016. },
  8017. clone: function ( material ) {
  8018. if ( material === undefined ) material = new THREE.Material();
  8019. material.name = this.name;
  8020. material.side = this.side;
  8021. material.opacity = this.opacity;
  8022. material.transparent = this.transparent;
  8023. material.blending = this.blending;
  8024. material.blendSrc = this.blendSrc;
  8025. material.blendDst = this.blendDst;
  8026. material.blendEquation = this.blendEquation;
  8027. material.blendSrcAlpha = this.blendSrcAlpha;
  8028. material.blendDstAlpha = this.blendDstAlpha;
  8029. material.blendEquationAlpha = this.blendEquationAlpha;
  8030. material.depthTest = this.depthTest;
  8031. material.depthWrite = this.depthWrite;
  8032. material.polygonOffset = this.polygonOffset;
  8033. material.polygonOffsetFactor = this.polygonOffsetFactor;
  8034. material.polygonOffsetUnits = this.polygonOffsetUnits;
  8035. material.alphaTest = this.alphaTest;
  8036. material.overdraw = this.overdraw;
  8037. material.visible = this.visible;
  8038. return material;
  8039. },
  8040. update: function () {
  8041. this.dispatchEvent( { type: 'update' } );
  8042. },
  8043. dispose: function () {
  8044. this.dispatchEvent( { type: 'dispose' } );
  8045. }
  8046. };
  8047. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  8048. THREE.MaterialIdCount = 0;
  8049. // File:src/materials/LineBasicMaterial.js
  8050. /**
  8051. * @author mrdoob / http://mrdoob.com/
  8052. * @author alteredq / http://alteredqualia.com/
  8053. *
  8054. * parameters = {
  8055. * color: <hex>,
  8056. * opacity: <float>,
  8057. *
  8058. * blending: THREE.NormalBlending,
  8059. * depthTest: <bool>,
  8060. * depthWrite: <bool>,
  8061. *
  8062. * linewidth: <float>,
  8063. * linecap: "round",
  8064. * linejoin: "round",
  8065. *
  8066. * vertexColors: <bool>
  8067. *
  8068. * fog: <bool>
  8069. * }
  8070. */
  8071. THREE.LineBasicMaterial = function ( parameters ) {
  8072. THREE.Material.call( this );
  8073. this.type = 'LineBasicMaterial';
  8074. this.color = new THREE.Color( 0xffffff );
  8075. this.linewidth = 1;
  8076. this.linecap = 'round';
  8077. this.linejoin = 'round';
  8078. this.vertexColors = THREE.NoColors;
  8079. this.fog = true;
  8080. this.setValues( parameters );
  8081. };
  8082. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8083. THREE.LineBasicMaterial.prototype.constructor = THREE.LineBasicMaterial;
  8084. THREE.LineBasicMaterial.prototype.clone = function () {
  8085. var material = new THREE.LineBasicMaterial();
  8086. THREE.Material.prototype.clone.call( this, material );
  8087. material.color.copy( this.color );
  8088. material.linewidth = this.linewidth;
  8089. material.linecap = this.linecap;
  8090. material.linejoin = this.linejoin;
  8091. material.vertexColors = this.vertexColors;
  8092. material.fog = this.fog;
  8093. return material;
  8094. };
  8095. // File:src/materials/LineDashedMaterial.js
  8096. /**
  8097. * @author alteredq / http://alteredqualia.com/
  8098. *
  8099. * parameters = {
  8100. * color: <hex>,
  8101. * opacity: <float>,
  8102. *
  8103. * blending: THREE.NormalBlending,
  8104. * depthTest: <bool>,
  8105. * depthWrite: <bool>,
  8106. *
  8107. * linewidth: <float>,
  8108. *
  8109. * scale: <float>,
  8110. * dashSize: <float>,
  8111. * gapSize: <float>,
  8112. *
  8113. * vertexColors: <bool>
  8114. *
  8115. * fog: <bool>
  8116. * }
  8117. */
  8118. THREE.LineDashedMaterial = function ( parameters ) {
  8119. THREE.Material.call( this );
  8120. this.type = 'LineDashedMaterial';
  8121. this.color = new THREE.Color( 0xffffff );
  8122. this.linewidth = 1;
  8123. this.scale = 1;
  8124. this.dashSize = 3;
  8125. this.gapSize = 1;
  8126. this.vertexColors = false;
  8127. this.fog = true;
  8128. this.setValues( parameters );
  8129. };
  8130. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  8131. THREE.LineDashedMaterial.prototype.constructor = THREE.LineDashedMaterial;
  8132. THREE.LineDashedMaterial.prototype.clone = function () {
  8133. var material = new THREE.LineDashedMaterial();
  8134. THREE.Material.prototype.clone.call( this, material );
  8135. material.color.copy( this.color );
  8136. material.linewidth = this.linewidth;
  8137. material.scale = this.scale;
  8138. material.dashSize = this.dashSize;
  8139. material.gapSize = this.gapSize;
  8140. material.vertexColors = this.vertexColors;
  8141. material.fog = this.fog;
  8142. return material;
  8143. };
  8144. // File:src/materials/MeshBasicMaterial.js
  8145. /**
  8146. * @author mrdoob / http://mrdoob.com/
  8147. * @author alteredq / http://alteredqualia.com/
  8148. *
  8149. * parameters = {
  8150. * color: <hex>,
  8151. * opacity: <float>,
  8152. * map: new THREE.Texture( <Image> ),
  8153. *
  8154. * lightMap: new THREE.Texture( <Image> ),
  8155. *
  8156. * specularMap: new THREE.Texture( <Image> ),
  8157. *
  8158. * alphaMap: new THREE.Texture( <Image> ),
  8159. *
  8160. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8161. * combine: THREE.Multiply,
  8162. * reflectivity: <float>,
  8163. * refractionRatio: <float>,
  8164. *
  8165. * shading: THREE.SmoothShading,
  8166. * blending: THREE.NormalBlending,
  8167. * depthTest: <bool>,
  8168. * depthWrite: <bool>,
  8169. *
  8170. * wireframe: <boolean>,
  8171. * wireframeLinewidth: <float>,
  8172. *
  8173. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8174. *
  8175. * skinning: <bool>,
  8176. * morphTargets: <bool>,
  8177. *
  8178. * fog: <bool>
  8179. * }
  8180. */
  8181. THREE.MeshBasicMaterial = function ( parameters ) {
  8182. THREE.Material.call( this );
  8183. this.type = 'MeshBasicMaterial';
  8184. this.color = new THREE.Color( 0xffffff ); // emissive
  8185. this.map = null;
  8186. this.lightMap = null;
  8187. this.specularMap = null;
  8188. this.alphaMap = null;
  8189. this.envMap = null;
  8190. this.combine = THREE.MultiplyOperation;
  8191. this.reflectivity = 1;
  8192. this.refractionRatio = 0.98;
  8193. this.fog = true;
  8194. this.shading = THREE.SmoothShading;
  8195. this.wireframe = false;
  8196. this.wireframeLinewidth = 1;
  8197. this.wireframeLinecap = 'round';
  8198. this.wireframeLinejoin = 'round';
  8199. this.vertexColors = THREE.NoColors;
  8200. this.skinning = false;
  8201. this.morphTargets = false;
  8202. this.setValues( parameters );
  8203. };
  8204. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8205. THREE.MeshBasicMaterial.prototype.constructor = THREE.MeshBasicMaterial;
  8206. THREE.MeshBasicMaterial.prototype.clone = function () {
  8207. var material = new THREE.MeshBasicMaterial();
  8208. THREE.Material.prototype.clone.call( this, material );
  8209. material.color.copy( this.color );
  8210. material.map = this.map;
  8211. material.lightMap = this.lightMap;
  8212. material.specularMap = this.specularMap;
  8213. material.alphaMap = this.alphaMap;
  8214. material.envMap = this.envMap;
  8215. material.combine = this.combine;
  8216. material.reflectivity = this.reflectivity;
  8217. material.refractionRatio = this.refractionRatio;
  8218. material.fog = this.fog;
  8219. material.shading = this.shading;
  8220. material.wireframe = this.wireframe;
  8221. material.wireframeLinewidth = this.wireframeLinewidth;
  8222. material.wireframeLinecap = this.wireframeLinecap;
  8223. material.wireframeLinejoin = this.wireframeLinejoin;
  8224. material.vertexColors = this.vertexColors;
  8225. material.skinning = this.skinning;
  8226. material.morphTargets = this.morphTargets;
  8227. return material;
  8228. };
  8229. THREE.MeshBasicMaterial.prototype.toJSON = function () {
  8230. var data = THREE.Material.prototype.toJSON.call( this );
  8231. data.color = this.color.getHex();
  8232. if ( this.vertexColors !== THREE.NoColors ) data.vertexColors = this.vertexColors;
  8233. if ( this.blending !== THREE.NormalBlending ) data.blending = this.blending;
  8234. if ( this.side !== THREE.FrontSide ) data.side = this.side;
  8235. return data;
  8236. };
  8237. // File:src/materials/MeshLambertMaterial.js
  8238. /**
  8239. * @author mrdoob / http://mrdoob.com/
  8240. * @author alteredq / http://alteredqualia.com/
  8241. *
  8242. * parameters = {
  8243. * color: <hex>,
  8244. * emissive: <hex>,
  8245. * opacity: <float>,
  8246. *
  8247. * map: new THREE.Texture( <Image> ),
  8248. *
  8249. * lightMap: new THREE.Texture( <Image> ),
  8250. *
  8251. * specularMap: new THREE.Texture( <Image> ),
  8252. *
  8253. * alphaMap: new THREE.Texture( <Image> ),
  8254. *
  8255. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8256. * combine: THREE.Multiply,
  8257. * reflectivity: <float>,
  8258. * refractionRatio: <float>,
  8259. *
  8260. * shading: THREE.SmoothShading,
  8261. * blending: THREE.NormalBlending,
  8262. * depthTest: <bool>,
  8263. * depthWrite: <bool>,
  8264. *
  8265. * wireframe: <boolean>,
  8266. * wireframeLinewidth: <float>,
  8267. *
  8268. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8269. *
  8270. * skinning: <bool>,
  8271. * morphTargets: <bool>,
  8272. * morphNormals: <bool>,
  8273. *
  8274. * fog: <bool>
  8275. * }
  8276. */
  8277. THREE.MeshLambertMaterial = function ( parameters ) {
  8278. THREE.Material.call( this );
  8279. this.type = 'MeshLambertMaterial';
  8280. this.color = new THREE.Color( 0xffffff ); // diffuse
  8281. this.emissive = new THREE.Color( 0x000000 );
  8282. this.wrapAround = false;
  8283. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8284. this.map = null;
  8285. this.lightMap = null;
  8286. this.specularMap = null;
  8287. this.alphaMap = null;
  8288. this.envMap = null;
  8289. this.combine = THREE.MultiplyOperation;
  8290. this.reflectivity = 1;
  8291. this.refractionRatio = 0.98;
  8292. this.fog = true;
  8293. this.shading = THREE.SmoothShading;
  8294. this.wireframe = false;
  8295. this.wireframeLinewidth = 1;
  8296. this.wireframeLinecap = 'round';
  8297. this.wireframeLinejoin = 'round';
  8298. this.vertexColors = THREE.NoColors;
  8299. this.skinning = false;
  8300. this.morphTargets = false;
  8301. this.morphNormals = false;
  8302. this.setValues( parameters );
  8303. };
  8304. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  8305. THREE.MeshLambertMaterial.prototype.constructor = THREE.MeshLambertMaterial;
  8306. THREE.MeshLambertMaterial.prototype.clone = function () {
  8307. var material = new THREE.MeshLambertMaterial();
  8308. THREE.Material.prototype.clone.call( this, material );
  8309. material.color.copy( this.color );
  8310. material.emissive.copy( this.emissive );
  8311. material.wrapAround = this.wrapAround;
  8312. material.wrapRGB.copy( this.wrapRGB );
  8313. material.map = this.map;
  8314. material.lightMap = this.lightMap;
  8315. material.specularMap = this.specularMap;
  8316. material.alphaMap = this.alphaMap;
  8317. material.envMap = this.envMap;
  8318. material.combine = this.combine;
  8319. material.reflectivity = this.reflectivity;
  8320. material.refractionRatio = this.refractionRatio;
  8321. material.fog = this.fog;
  8322. material.shading = this.shading;
  8323. material.wireframe = this.wireframe;
  8324. material.wireframeLinewidth = this.wireframeLinewidth;
  8325. material.wireframeLinecap = this.wireframeLinecap;
  8326. material.wireframeLinejoin = this.wireframeLinejoin;
  8327. material.vertexColors = this.vertexColors;
  8328. material.skinning = this.skinning;
  8329. material.morphTargets = this.morphTargets;
  8330. material.morphNormals = this.morphNormals;
  8331. return material;
  8332. };
  8333. THREE.MeshLambertMaterial.prototype.toJSON = function () {
  8334. var data = THREE.Material.prototype.toJSON.call( this );
  8335. data.color = this.color.getHex();
  8336. data.emissive = this.emissive.getHex();
  8337. if ( this.vertexColors !== THREE.NoColors ) data.vertexColors = this.vertexColors;
  8338. if ( this.shading !== THREE.SmoothShading ) data.shading = this.shading;
  8339. if ( this.blending !== THREE.NormalBlending ) data.blending = this.blending;
  8340. if ( this.side !== THREE.FrontSide ) data.side = this.side;
  8341. return data;
  8342. };
  8343. // File:src/materials/MeshPhongMaterial.js
  8344. /**
  8345. * @author mrdoob / http://mrdoob.com/
  8346. * @author alteredq / http://alteredqualia.com/
  8347. *
  8348. * parameters = {
  8349. * color: <hex>,
  8350. * emissive: <hex>,
  8351. * specular: <hex>,
  8352. * shininess: <float>,
  8353. * opacity: <float>,
  8354. *
  8355. * map: new THREE.Texture( <Image> ),
  8356. *
  8357. * lightMap: new THREE.Texture( <Image> ),
  8358. * lightMapIntensity: <float>
  8359. *
  8360. * aoMap: new THREE.Texture( <Image> ),
  8361. * aoMapIntensity: <float>
  8362. *
  8363. * bumpMap: new THREE.Texture( <Image> ),
  8364. * bumpScale: <float>,
  8365. *
  8366. * normalMap: new THREE.Texture( <Image> ),
  8367. * normalScale: <Vector2>,
  8368. *
  8369. * specularMap: new THREE.Texture( <Image> ),
  8370. *
  8371. * alphaMap: new THREE.Texture( <Image> ),
  8372. *
  8373. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8374. * combine: THREE.Multiply,
  8375. * reflectivity: <float>,
  8376. * refractionRatio: <float>,
  8377. *
  8378. * shading: THREE.SmoothShading,
  8379. * blending: THREE.NormalBlending,
  8380. * depthTest: <bool>,
  8381. * depthWrite: <bool>,
  8382. *
  8383. * wireframe: <boolean>,
  8384. * wireframeLinewidth: <float>,
  8385. *
  8386. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8387. *
  8388. * skinning: <bool>,
  8389. * morphTargets: <bool>,
  8390. * morphNormals: <bool>,
  8391. *
  8392. * fog: <bool>
  8393. * }
  8394. */
  8395. THREE.MeshPhongMaterial = function ( parameters ) {
  8396. THREE.Material.call( this );
  8397. this.type = 'MeshPhongMaterial';
  8398. this.color = new THREE.Color( 0xffffff ); // diffuse
  8399. this.emissive = new THREE.Color( 0x000000 );
  8400. this.specular = new THREE.Color( 0x111111 );
  8401. this.shininess = 30;
  8402. this.metal = false;
  8403. this.wrapAround = false;
  8404. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8405. this.map = null;
  8406. this.lightMap = null;
  8407. this.lightMapIntensity = 1.0;
  8408. this.aoMap = null;
  8409. this.aoMapIntensity = 1.0;
  8410. this.bumpMap = null;
  8411. this.bumpScale = 1;
  8412. this.normalMap = null;
  8413. this.normalScale = new THREE.Vector2( 1, 1 );
  8414. this.specularMap = null;
  8415. this.alphaMap = null;
  8416. this.envMap = null;
  8417. this.combine = THREE.MultiplyOperation;
  8418. this.reflectivity = 1;
  8419. this.refractionRatio = 0.98;
  8420. this.fog = true;
  8421. this.shading = THREE.SmoothShading;
  8422. this.wireframe = false;
  8423. this.wireframeLinewidth = 1;
  8424. this.wireframeLinecap = 'round';
  8425. this.wireframeLinejoin = 'round';
  8426. this.vertexColors = THREE.NoColors;
  8427. this.skinning = false;
  8428. this.morphTargets = false;
  8429. this.morphNormals = false;
  8430. this.setValues( parameters );
  8431. };
  8432. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  8433. THREE.MeshPhongMaterial.prototype.constructor = THREE.MeshPhongMaterial;
  8434. THREE.MeshPhongMaterial.prototype.clone = function () {
  8435. var material = new THREE.MeshPhongMaterial();
  8436. THREE.Material.prototype.clone.call( this, material );
  8437. material.color.copy( this.color );
  8438. material.emissive.copy( this.emissive );
  8439. material.specular.copy( this.specular );
  8440. material.shininess = this.shininess;
  8441. material.metal = this.metal;
  8442. material.wrapAround = this.wrapAround;
  8443. material.wrapRGB.copy( this.wrapRGB );
  8444. material.map = this.map;
  8445. material.lightMap = this.lightMap;
  8446. material.lightMapIntensity = this.lightMapIntensity;
  8447. material.aoMap = this.aoMap;
  8448. material.aoMapIntensity = this.aoMapIntensity;
  8449. material.bumpMap = this.bumpMap;
  8450. material.bumpScale = this.bumpScale;
  8451. material.normalMap = this.normalMap;
  8452. material.normalScale.copy( this.normalScale );
  8453. material.specularMap = this.specularMap;
  8454. material.alphaMap = this.alphaMap;
  8455. material.envMap = this.envMap;
  8456. material.combine = this.combine;
  8457. material.reflectivity = this.reflectivity;
  8458. material.refractionRatio = this.refractionRatio;
  8459. material.fog = this.fog;
  8460. material.shading = this.shading;
  8461. material.wireframe = this.wireframe;
  8462. material.wireframeLinewidth = this.wireframeLinewidth;
  8463. material.wireframeLinecap = this.wireframeLinecap;
  8464. material.wireframeLinejoin = this.wireframeLinejoin;
  8465. material.vertexColors = this.vertexColors;
  8466. material.skinning = this.skinning;
  8467. material.morphTargets = this.morphTargets;
  8468. material.morphNormals = this.morphNormals;
  8469. return material;
  8470. };
  8471. THREE.MeshPhongMaterial.prototype.toJSON = function () {
  8472. var data = THREE.Material.prototype.toJSON.call( this );
  8473. data.color = this.color.getHex();
  8474. data.emissive = this.emissive.getHex();
  8475. data.specular = this.specular.getHex();
  8476. data.shininess = this.shininess;
  8477. if ( this.vertexColors !== THREE.NoColors ) data.vertexColors = this.vertexColors;
  8478. if ( this.shading !== THREE.SmoothShading ) data.shading = this.shading;
  8479. if ( this.blending !== THREE.NormalBlending ) data.blending = this.blending;
  8480. if ( this.side !== THREE.FrontSide ) data.side = this.side;
  8481. return data;
  8482. };
  8483. // File:src/materials/MeshDepthMaterial.js
  8484. /**
  8485. * @author mrdoob / http://mrdoob.com/
  8486. * @author alteredq / http://alteredqualia.com/
  8487. *
  8488. * parameters = {
  8489. * opacity: <float>,
  8490. *
  8491. * blending: THREE.NormalBlending,
  8492. * depthTest: <bool>,
  8493. * depthWrite: <bool>,
  8494. *
  8495. * wireframe: <boolean>,
  8496. * wireframeLinewidth: <float>
  8497. * }
  8498. */
  8499. THREE.MeshDepthMaterial = function ( parameters ) {
  8500. THREE.Material.call( this );
  8501. this.type = 'MeshDepthMaterial';
  8502. this.morphTargets = false;
  8503. this.wireframe = false;
  8504. this.wireframeLinewidth = 1;
  8505. this.setValues( parameters );
  8506. };
  8507. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  8508. THREE.MeshDepthMaterial.prototype.constructor = THREE.MeshDepthMaterial;
  8509. THREE.MeshDepthMaterial.prototype.clone = function () {
  8510. var material = new THREE.MeshDepthMaterial();
  8511. THREE.Material.prototype.clone.call( this, material );
  8512. material.wireframe = this.wireframe;
  8513. material.wireframeLinewidth = this.wireframeLinewidth;
  8514. return material;
  8515. };
  8516. THREE.MeshDepthMaterial.prototype.toJSON = function () {
  8517. var data = THREE.Material.prototype.toJSON.call( this );
  8518. if ( this.blending !== THREE.NormalBlending ) data.blending = this.blending;
  8519. if ( this.side !== THREE.FrontSide ) data.side = this.side;
  8520. return data;
  8521. };
  8522. // File:src/materials/MeshNormalMaterial.js
  8523. /**
  8524. * @author mrdoob / http://mrdoob.com/
  8525. *
  8526. * parameters = {
  8527. * opacity: <float>,
  8528. *
  8529. * shading: THREE.FlatShading,
  8530. * blending: THREE.NormalBlending,
  8531. * depthTest: <bool>,
  8532. * depthWrite: <bool>,
  8533. *
  8534. * wireframe: <boolean>,
  8535. * wireframeLinewidth: <float>
  8536. * }
  8537. */
  8538. THREE.MeshNormalMaterial = function ( parameters ) {
  8539. THREE.Material.call( this, parameters );
  8540. this.type = 'MeshNormalMaterial';
  8541. this.wireframe = false;
  8542. this.wireframeLinewidth = 1;
  8543. this.morphTargets = false;
  8544. this.setValues( parameters );
  8545. };
  8546. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  8547. THREE.MeshNormalMaterial.prototype.constructor = THREE.MeshNormalMaterial;
  8548. THREE.MeshNormalMaterial.prototype.clone = function () {
  8549. var material = new THREE.MeshNormalMaterial();
  8550. THREE.Material.prototype.clone.call( this, material );
  8551. material.wireframe = this.wireframe;
  8552. material.wireframeLinewidth = this.wireframeLinewidth;
  8553. return material;
  8554. };
  8555. THREE.MeshNormalMaterial.prototype.toJSON = function () {
  8556. var data = THREE.Material.prototype.toJSON.call( this );
  8557. if ( this.blending !== THREE.NormalBlending ) data.blending = this.blending;
  8558. if ( this.side !== THREE.FrontSide ) data.side = this.side;
  8559. return data;
  8560. };
  8561. // File:src/materials/MeshFaceMaterial.js
  8562. /**
  8563. * @author mrdoob / http://mrdoob.com/
  8564. */
  8565. THREE.MeshFaceMaterial = function ( materials ) {
  8566. this.uuid = THREE.Math.generateUUID();
  8567. this.type = 'MeshFaceMaterial';
  8568. this.materials = materials instanceof Array ? materials : [];
  8569. };
  8570. THREE.MeshFaceMaterial.prototype = {
  8571. constructor: THREE.MeshFaceMaterial,
  8572. toJSON: function () {
  8573. var data = THREE.Material.prototype.toJSON.call( this );
  8574. data.materials = [];
  8575. for ( var i = 0, l = this.materials.length; i < l; i ++ ) {
  8576. data.materials.push( this.materials[ i ].toJSON() );
  8577. }
  8578. return data;
  8579. },
  8580. clone: function () {
  8581. var material = new THREE.MeshFaceMaterial();
  8582. for ( var i = 0; i < this.materials.length; i ++ ) {
  8583. material.materials.push( this.materials[ i ].clone() );
  8584. }
  8585. return material;
  8586. }
  8587. };
  8588. // File:src/materials/PointCloudMaterial.js
  8589. /**
  8590. * @author mrdoob / http://mrdoob.com/
  8591. * @author alteredq / http://alteredqualia.com/
  8592. *
  8593. * parameters = {
  8594. * color: <hex>,
  8595. * opacity: <float>,
  8596. * map: new THREE.Texture( <Image> ),
  8597. *
  8598. * size: <float>,
  8599. * sizeAttenuation: <bool>,
  8600. *
  8601. * blending: THREE.NormalBlending,
  8602. * depthTest: <bool>,
  8603. * depthWrite: <bool>,
  8604. *
  8605. * vertexColors: <bool>,
  8606. *
  8607. * fog: <bool>
  8608. * }
  8609. */
  8610. THREE.PointCloudMaterial = function ( parameters ) {
  8611. THREE.Material.call( this );
  8612. this.type = 'PointCloudMaterial';
  8613. this.color = new THREE.Color( 0xffffff );
  8614. this.map = null;
  8615. this.size = 1;
  8616. this.sizeAttenuation = true;
  8617. this.vertexColors = THREE.NoColors;
  8618. this.fog = true;
  8619. this.setValues( parameters );
  8620. };
  8621. THREE.PointCloudMaterial.prototype = Object.create( THREE.Material.prototype );
  8622. THREE.PointCloudMaterial.prototype.constructor = THREE.PointCloudMaterial;
  8623. THREE.PointCloudMaterial.prototype.clone = function () {
  8624. var material = new THREE.PointCloudMaterial();
  8625. THREE.Material.prototype.clone.call( this, material );
  8626. material.color.copy( this.color );
  8627. material.map = this.map;
  8628. material.size = this.size;
  8629. material.sizeAttenuation = this.sizeAttenuation;
  8630. material.vertexColors = this.vertexColors;
  8631. material.fog = this.fog;
  8632. return material;
  8633. };
  8634. THREE.PointCloudMaterial.prototype.toJSON = function () {
  8635. var data = THREE.Material.prototype.toJSON.call( this );
  8636. data.size = this.size;
  8637. data.sizeAttenuation = this.sizeAttenuation;
  8638. data.color = this.color.getHex();
  8639. if ( this.vertexColors !== THREE.NoColors ) data.vertexColors = this.vertexColors;
  8640. if ( this.blending !== THREE.NormalBlending ) data.blending = this.blending;
  8641. return data;
  8642. };
  8643. // backwards compatibility
  8644. THREE.ParticleBasicMaterial = function ( parameters ) {
  8645. THREE.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointCloudMaterial.' );
  8646. return new THREE.PointCloudMaterial( parameters );
  8647. };
  8648. THREE.ParticleSystemMaterial = function ( parameters ) {
  8649. THREE.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointCloudMaterial.' );
  8650. return new THREE.PointCloudMaterial( parameters );
  8651. };
  8652. // File:src/materials/ShaderMaterial.js
  8653. /**
  8654. * @author alteredq / http://alteredqualia.com/
  8655. *
  8656. * parameters = {
  8657. * defines: { "label" : "value" },
  8658. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  8659. *
  8660. * fragmentShader: <string>,
  8661. * vertexShader: <string>,
  8662. *
  8663. * shading: THREE.SmoothShading,
  8664. * blending: THREE.NormalBlending,
  8665. * depthTest: <bool>,
  8666. * depthWrite: <bool>,
  8667. *
  8668. * wireframe: <boolean>,
  8669. * wireframeLinewidth: <float>,
  8670. *
  8671. * lights: <bool>,
  8672. *
  8673. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8674. *
  8675. * skinning: <bool>,
  8676. * morphTargets: <bool>,
  8677. * morphNormals: <bool>,
  8678. *
  8679. * fog: <bool>
  8680. * }
  8681. */
  8682. THREE.ShaderMaterial = function ( parameters ) {
  8683. THREE.Material.call( this );
  8684. this.type = 'ShaderMaterial';
  8685. this.defines = {};
  8686. this.uniforms = {};
  8687. this.attributes = null;
  8688. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  8689. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  8690. this.shading = THREE.SmoothShading;
  8691. this.linewidth = 1;
  8692. this.wireframe = false;
  8693. this.wireframeLinewidth = 1;
  8694. this.fog = false; // set to use scene fog
  8695. this.lights = false; // set to use scene lights
  8696. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  8697. this.skinning = false; // set to use skinning attribute streams
  8698. this.morphTargets = false; // set to use morph targets
  8699. this.morphNormals = false; // set to use morph normals
  8700. // When rendered geometry doesn't include these attributes but the material does,
  8701. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8702. this.defaultAttributeValues = {
  8703. 'color': [ 1, 1, 1 ],
  8704. 'uv': [ 0, 0 ],
  8705. 'uv2': [ 0, 0 ]
  8706. };
  8707. this.index0AttributeName = undefined;
  8708. this.setValues( parameters );
  8709. };
  8710. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  8711. THREE.ShaderMaterial.prototype.constructor = THREE.ShaderMaterial;
  8712. THREE.ShaderMaterial.prototype.clone = function ( material ) {
  8713. if ( material === undefined ) material = new THREE.ShaderMaterial();
  8714. THREE.Material.prototype.clone.call( this, material );
  8715. material.fragmentShader = this.fragmentShader;
  8716. material.vertexShader = this.vertexShader;
  8717. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  8718. material.attributes = this.attributes;
  8719. material.defines = this.defines;
  8720. material.shading = this.shading;
  8721. material.wireframe = this.wireframe;
  8722. material.wireframeLinewidth = this.wireframeLinewidth;
  8723. material.fog = this.fog;
  8724. material.lights = this.lights;
  8725. material.vertexColors = this.vertexColors;
  8726. material.skinning = this.skinning;
  8727. material.morphTargets = this.morphTargets;
  8728. material.morphNormals = this.morphNormals;
  8729. return material;
  8730. };
  8731. THREE.ShaderMaterial.prototype.toJSON = function () {
  8732. var data = THREE.Material.prototype.toJSON.call( this );
  8733. data.uniforms = this.uniforms;
  8734. data.vertexShader = this.vertexShader;
  8735. data.fragmentShader = this.fragmentShader;
  8736. return data;
  8737. };
  8738. // File:src/materials/RawShaderMaterial.js
  8739. /**
  8740. * @author mrdoob / http://mrdoob.com/
  8741. */
  8742. THREE.RawShaderMaterial = function ( parameters ) {
  8743. THREE.ShaderMaterial.call( this, parameters );
  8744. this.type = 'RawShaderMaterial';
  8745. };
  8746. THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype );
  8747. THREE.RawShaderMaterial.prototype.constructor = THREE.RawShaderMaterial;
  8748. THREE.RawShaderMaterial.prototype.clone = function () {
  8749. var material = new THREE.RawShaderMaterial();
  8750. THREE.ShaderMaterial.prototype.clone.call( this, material );
  8751. return material;
  8752. };
  8753. // File:src/materials/SpriteMaterial.js
  8754. /**
  8755. * @author alteredq / http://alteredqualia.com/
  8756. *
  8757. * parameters = {
  8758. * color: <hex>,
  8759. * opacity: <float>,
  8760. * map: new THREE.Texture( <Image> ),
  8761. *
  8762. * blending: THREE.NormalBlending,
  8763. * depthTest: <bool>,
  8764. * depthWrite: <bool>,
  8765. *
  8766. * uvOffset: new THREE.Vector2(),
  8767. * uvScale: new THREE.Vector2(),
  8768. *
  8769. * fog: <bool>
  8770. * }
  8771. */
  8772. THREE.SpriteMaterial = function ( parameters ) {
  8773. THREE.Material.call( this );
  8774. this.type = 'SpriteMaterial';
  8775. this.color = new THREE.Color( 0xffffff );
  8776. this.map = null;
  8777. this.rotation = 0;
  8778. this.fog = false;
  8779. // set parameters
  8780. this.setValues( parameters );
  8781. };
  8782. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  8783. THREE.SpriteMaterial.prototype.constructor = THREE.SpriteMaterial;
  8784. THREE.SpriteMaterial.prototype.clone = function () {
  8785. var material = new THREE.SpriteMaterial();
  8786. THREE.Material.prototype.clone.call( this, material );
  8787. material.color.copy( this.color );
  8788. material.map = this.map;
  8789. material.rotation = this.rotation;
  8790. material.fog = this.fog;
  8791. return material;
  8792. };
  8793. THREE.SpriteMaterial.prototype.toJSON = function () {
  8794. var data = THREE.Material.prototype.toJSON.call( this );
  8795. data.color = this.color.getHex();
  8796. return data;
  8797. };
  8798. // File:src/textures/Texture.js
  8799. /**
  8800. * @author mrdoob / http://mrdoob.com/
  8801. * @author alteredq / http://alteredqualia.com/
  8802. * @author szimek / https://github.com/szimek/
  8803. */
  8804. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8805. Object.defineProperty( this, 'id', { value: THREE.TextureIdCount ++ } );
  8806. this.uuid = THREE.Math.generateUUID();
  8807. this.name = '';
  8808. this.sourceFile = '';
  8809. this.image = image !== undefined ? image : THREE.Texture.DEFAULT_IMAGE;
  8810. this.mipmaps = [];
  8811. this.mapping = mapping !== undefined ? mapping : THREE.Texture.DEFAULT_MAPPING;
  8812. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  8813. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  8814. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  8815. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  8816. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  8817. this.format = format !== undefined ? format : THREE.RGBAFormat;
  8818. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  8819. this.offset = new THREE.Vector2( 0, 0 );
  8820. this.repeat = new THREE.Vector2( 1, 1 );
  8821. this.generateMipmaps = true;
  8822. this.premultiplyAlpha = false;
  8823. this.flipY = true;
  8824. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  8825. this._needsUpdate = false;
  8826. this.onUpdate = null;
  8827. };
  8828. THREE.Texture.DEFAULT_IMAGE = undefined;
  8829. THREE.Texture.DEFAULT_MAPPING = THREE.UVMapping;
  8830. THREE.Texture.prototype = {
  8831. constructor: THREE.Texture,
  8832. get needsUpdate () {
  8833. return this._needsUpdate;
  8834. },
  8835. set needsUpdate ( value ) {
  8836. if ( value === true ) this.update();
  8837. this._needsUpdate = value;
  8838. },
  8839. clone: function ( texture ) {
  8840. if ( texture === undefined ) texture = new THREE.Texture();
  8841. texture.image = this.image;
  8842. texture.mipmaps = this.mipmaps.slice( 0 );
  8843. texture.mapping = this.mapping;
  8844. texture.wrapS = this.wrapS;
  8845. texture.wrapT = this.wrapT;
  8846. texture.magFilter = this.magFilter;
  8847. texture.minFilter = this.minFilter;
  8848. texture.anisotropy = this.anisotropy;
  8849. texture.format = this.format;
  8850. texture.type = this.type;
  8851. texture.offset.copy( this.offset );
  8852. texture.repeat.copy( this.repeat );
  8853. texture.generateMipmaps = this.generateMipmaps;
  8854. texture.premultiplyAlpha = this.premultiplyAlpha;
  8855. texture.flipY = this.flipY;
  8856. texture.unpackAlignment = this.unpackAlignment;
  8857. return texture;
  8858. },
  8859. update: function () {
  8860. this.dispatchEvent( { type: 'update' } );
  8861. },
  8862. dispose: function () {
  8863. this.dispatchEvent( { type: 'dispose' } );
  8864. }
  8865. };
  8866. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  8867. THREE.TextureIdCount = 0;
  8868. // File:src/textures/CubeTexture.js
  8869. /**
  8870. * @author mrdoob / http://mrdoob.com/
  8871. */
  8872. THREE.CubeTexture = function ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8873. mapping = mapping !== undefined ? mapping : THREE.CubeReflectionMapping;
  8874. THREE.Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8875. this.images = images;
  8876. };
  8877. THREE.CubeTexture.prototype = Object.create( THREE.Texture.prototype );
  8878. THREE.CubeTexture.prototype.constructor = THREE.CubeTexture;
  8879. THREE.CubeTexture.clone = function ( texture ) {
  8880. if ( texture === undefined ) texture = new THREE.CubeTexture();
  8881. THREE.Texture.prototype.clone.call( this, texture );
  8882. texture.images = this.images;
  8883. return texture;
  8884. };
  8885. // File:src/textures/CompressedTexture.js
  8886. /**
  8887. * @author alteredq / http://alteredqualia.com/
  8888. */
  8889. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8890. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8891. this.image = { width: width, height: height };
  8892. this.mipmaps = mipmaps;
  8893. // no flipping for cube textures
  8894. // (also flipping doesn't work for compressed textures )
  8895. this.flipY = false;
  8896. // can't generate mipmaps for compressed textures
  8897. // mips must be embedded in DDS files
  8898. this.generateMipmaps = false;
  8899. };
  8900. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  8901. THREE.CompressedTexture.prototype.constructor = THREE.CompressedTexture;
  8902. THREE.CompressedTexture.prototype.clone = function () {
  8903. var texture = new THREE.CompressedTexture();
  8904. THREE.Texture.prototype.clone.call( this, texture );
  8905. return texture;
  8906. };
  8907. // File:src/textures/DataTexture.js
  8908. /**
  8909. * @author alteredq / http://alteredqualia.com/
  8910. */
  8911. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8912. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8913. this.image = { data: data, width: width, height: height };
  8914. };
  8915. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  8916. THREE.DataTexture.prototype.constructor = THREE.DataTexture;
  8917. THREE.DataTexture.prototype.clone = function () {
  8918. var texture = new THREE.DataTexture();
  8919. THREE.Texture.prototype.clone.call( this, texture );
  8920. return texture;
  8921. };
  8922. // File:src/textures/VideoTexture.js
  8923. /**
  8924. * @author mrdoob / http://mrdoob.com/
  8925. */
  8926. THREE.VideoTexture = function ( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8927. THREE.Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8928. this.generateMipmaps = false;
  8929. var scope = this;
  8930. var update = function () {
  8931. requestAnimationFrame( update );
  8932. if ( video.readyState === video.HAVE_ENOUGH_DATA ) {
  8933. scope.needsUpdate = true;
  8934. }
  8935. };
  8936. update();
  8937. };
  8938. THREE.VideoTexture.prototype = Object.create( THREE.Texture.prototype );
  8939. THREE.VideoTexture.prototype.constructor = THREE.VideoTexture;
  8940. // File:src/objects/Group.js
  8941. /**
  8942. * @author mrdoob / http://mrdoob.com/
  8943. */
  8944. THREE.Group = function () {
  8945. THREE.Object3D.call( this );
  8946. this.type = 'Group';
  8947. };
  8948. THREE.Group.prototype = Object.create( THREE.Object3D.prototype );
  8949. THREE.Group.prototype.constructor = THREE.Group;
  8950. // File:src/objects/PointCloud.js
  8951. /**
  8952. * @author alteredq / http://alteredqualia.com/
  8953. */
  8954. THREE.PointCloud = function ( geometry, material ) {
  8955. THREE.Object3D.call( this );
  8956. this.type = 'PointCloud';
  8957. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8958. this.material = material !== undefined ? material : new THREE.PointCloudMaterial( { color: Math.random() * 0xffffff } );
  8959. };
  8960. THREE.PointCloud.prototype = Object.create( THREE.Object3D.prototype );
  8961. THREE.PointCloud.prototype.constructor = THREE.PointCloud;
  8962. THREE.PointCloud.prototype.raycast = ( function () {
  8963. var inverseMatrix = new THREE.Matrix4();
  8964. var ray = new THREE.Ray();
  8965. return function ( raycaster, intersects ) {
  8966. var object = this;
  8967. var geometry = object.geometry;
  8968. var threshold = raycaster.params.PointCloud.threshold;
  8969. inverseMatrix.getInverse( this.matrixWorld );
  8970. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  8971. if ( geometry.boundingBox !== null ) {
  8972. if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) {
  8973. return;
  8974. }
  8975. }
  8976. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  8977. var position = new THREE.Vector3();
  8978. var testPoint = function ( point, index ) {
  8979. var rayPointDistance = ray.distanceToPoint( point );
  8980. if ( rayPointDistance < localThreshold ) {
  8981. var intersectPoint = ray.closestPointToPoint( point );
  8982. intersectPoint.applyMatrix4( object.matrixWorld );
  8983. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  8984. intersects.push( {
  8985. distance: distance,
  8986. distanceToRay: rayPointDistance,
  8987. point: intersectPoint.clone(),
  8988. index: index,
  8989. face: null,
  8990. object: object
  8991. } );
  8992. }
  8993. };
  8994. if ( geometry instanceof THREE.BufferGeometry ) {
  8995. var attributes = geometry.attributes;
  8996. var positions = attributes.position.array;
  8997. if ( attributes.index !== undefined ) {
  8998. var indices = attributes.index.array;
  8999. var offsets = geometry.offsets;
  9000. if ( offsets.length === 0 ) {
  9001. var offset = {
  9002. start: 0,
  9003. count: indices.length,
  9004. index: 0
  9005. };
  9006. offsets = [ offset ];
  9007. }
  9008. for ( var oi = 0, ol = offsets.length; oi < ol; ++ oi ) {
  9009. var start = offsets[ oi ].start;
  9010. var count = offsets[ oi ].count;
  9011. var index = offsets[ oi ].index;
  9012. for ( var i = start, il = start + count; i < il; i ++ ) {
  9013. var a = index + indices[ i ];
  9014. position.fromArray( positions, a * 3 );
  9015. testPoint( position, a );
  9016. }
  9017. }
  9018. } else {
  9019. var pointCount = positions.length / 3;
  9020. for ( var i = 0; i < pointCount; i ++ ) {
  9021. position.set(
  9022. positions[ 3 * i ],
  9023. positions[ 3 * i + 1 ],
  9024. positions[ 3 * i + 2 ]
  9025. );
  9026. testPoint( position, i );
  9027. }
  9028. }
  9029. } else {
  9030. var vertices = this.geometry.vertices;
  9031. for ( var i = 0; i < vertices.length; i ++ ) {
  9032. testPoint( vertices[ i ], i );
  9033. }
  9034. }
  9035. };
  9036. }() );
  9037. THREE.PointCloud.prototype.clone = function ( object ) {
  9038. if ( object === undefined ) object = new THREE.PointCloud( this.geometry, this.material );
  9039. THREE.Object3D.prototype.clone.call( this, object );
  9040. return object;
  9041. };
  9042. THREE.PointCloud.prototype.toJSON = function ( meta ) {
  9043. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  9044. // only serialize if not in meta geometries cache
  9045. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  9046. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON();
  9047. }
  9048. // only serialize if not in meta materials cache
  9049. if ( meta.materials[ this.material.uuid ] === undefined ) {
  9050. meta.materials[ this.material.uuid ] = this.material.toJSON();
  9051. }
  9052. data.object.geometry = this.geometry.uuid;
  9053. data.object.material = this.material.uuid;
  9054. return data;
  9055. };
  9056. // Backwards compatibility
  9057. THREE.ParticleSystem = function ( geometry, material ) {
  9058. THREE.warn( 'THREE.ParticleSystem has been renamed to THREE.PointCloud.' );
  9059. return new THREE.PointCloud( geometry, material );
  9060. };
  9061. // File:src/objects/Line.js
  9062. /**
  9063. * @author mrdoob / http://mrdoob.com/
  9064. */
  9065. THREE.Line = function ( geometry, material, mode ) {
  9066. THREE.Object3D.call( this );
  9067. this.type = 'Line';
  9068. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9069. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  9070. this.mode = mode !== undefined ? mode : THREE.LineStrip;
  9071. };
  9072. THREE.LineStrip = 0;
  9073. THREE.LinePieces = 1;
  9074. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  9075. THREE.Line.prototype.constructor = THREE.Line;
  9076. THREE.Line.prototype.raycast = ( function () {
  9077. var inverseMatrix = new THREE.Matrix4();
  9078. var ray = new THREE.Ray();
  9079. var sphere = new THREE.Sphere();
  9080. return function ( raycaster, intersects ) {
  9081. var precision = raycaster.linePrecision;
  9082. var precisionSq = precision * precision;
  9083. var geometry = this.geometry;
  9084. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9085. // Checking boundingSphere distance to ray
  9086. sphere.copy( geometry.boundingSphere );
  9087. sphere.applyMatrix4( this.matrixWorld );
  9088. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  9089. return;
  9090. }
  9091. inverseMatrix.getInverse( this.matrixWorld );
  9092. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  9093. var vStart = new THREE.Vector3();
  9094. var vEnd = new THREE.Vector3();
  9095. var interSegment = new THREE.Vector3();
  9096. var interRay = new THREE.Vector3();
  9097. var step = this.mode === THREE.LineStrip ? 1 : 2;
  9098. if ( geometry instanceof THREE.BufferGeometry ) {
  9099. var attributes = geometry.attributes;
  9100. if ( attributes.index !== undefined ) {
  9101. var indices = attributes.index.array;
  9102. var positions = attributes.position.array;
  9103. var offsets = geometry.offsets;
  9104. if ( offsets.length === 0 ) {
  9105. offsets = [ { start: 0, count: indices.length, index: 0 } ];
  9106. }
  9107. for ( var oi = 0; oi < offsets.length; oi ++) {
  9108. var start = offsets[ oi ].start;
  9109. var count = offsets[ oi ].count;
  9110. var index = offsets[ oi ].index;
  9111. for ( var i = start; i < start + count - 1; i += step ) {
  9112. var a = index + indices[ i ];
  9113. var b = index + indices[ i + 1 ];
  9114. vStart.fromArray( positions, a * 3 );
  9115. vEnd.fromArray( positions, b * 3 );
  9116. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  9117. if ( distSq > precisionSq ) continue;
  9118. var distance = ray.origin.distanceTo( interRay );
  9119. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  9120. intersects.push( {
  9121. distance: distance,
  9122. // What do we want? intersection point on the ray or on the segment??
  9123. // point: raycaster.ray.at( distance ),
  9124. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  9125. index: i,
  9126. offsetIndex: oi,
  9127. face: null,
  9128. faceIndex: null,
  9129. object: this
  9130. } );
  9131. }
  9132. }
  9133. } else {
  9134. var positions = attributes.position.array;
  9135. for ( var i = 0; i < positions.length / 3 - 1; i += step ) {
  9136. vStart.fromArray( positions, 3 * i );
  9137. vEnd.fromArray( positions, 3 * i + 3 );
  9138. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  9139. if ( distSq > precisionSq ) continue;
  9140. var distance = ray.origin.distanceTo( interRay );
  9141. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  9142. intersects.push( {
  9143. distance: distance,
  9144. // What do we want? intersection point on the ray or on the segment??
  9145. // point: raycaster.ray.at( distance ),
  9146. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  9147. index: i,
  9148. face: null,
  9149. faceIndex: null,
  9150. object: this
  9151. } );
  9152. }
  9153. }
  9154. } else if ( geometry instanceof THREE.Geometry ) {
  9155. var vertices = geometry.vertices;
  9156. var nbVertices = vertices.length;
  9157. for ( var i = 0; i < nbVertices - 1; i += step ) {
  9158. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  9159. if ( distSq > precisionSq ) continue;
  9160. var distance = ray.origin.distanceTo( interRay );
  9161. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  9162. intersects.push( {
  9163. distance: distance,
  9164. // What do we want? intersection point on the ray or on the segment??
  9165. // point: raycaster.ray.at( distance ),
  9166. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  9167. index: i,
  9168. face: null,
  9169. faceIndex: null,
  9170. object: this
  9171. } );
  9172. }
  9173. }
  9174. };
  9175. }() );
  9176. THREE.Line.prototype.clone = function ( object ) {
  9177. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.mode );
  9178. THREE.Object3D.prototype.clone.call( this, object );
  9179. return object;
  9180. };
  9181. THREE.Line.prototype.toJSON = function ( meta ) {
  9182. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  9183. data.object.mode = this.mode;
  9184. // only serialize if not in meta geometries cache
  9185. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  9186. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON();
  9187. }
  9188. // only serialize if not in meta materials cache
  9189. if ( meta.materials[ this.material.uuid ] === undefined ) {
  9190. meta.materials[ this.material.uuid ] = this.material.toJSON();
  9191. }
  9192. data.object.geometry = this.geometry.uuid;
  9193. data.object.material = this.material.uuid;
  9194. return data;
  9195. };
  9196. // File:src/objects/Mesh.js
  9197. /**
  9198. * @author mrdoob / http://mrdoob.com/
  9199. * @author alteredq / http://alteredqualia.com/
  9200. * @author mikael emtinger / http://gomo.se/
  9201. * @author jonobr1 / http://jonobr1.com/
  9202. */
  9203. THREE.Mesh = function ( geometry, material ) {
  9204. THREE.Object3D.call( this );
  9205. this.type = 'Mesh';
  9206. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9207. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  9208. this.updateMorphTargets();
  9209. };
  9210. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  9211. THREE.Mesh.prototype.constructor = THREE.Mesh;
  9212. THREE.Mesh.prototype.updateMorphTargets = function () {
  9213. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  9214. this.morphTargetBase = - 1;
  9215. this.morphTargetForcedOrder = [];
  9216. this.morphTargetInfluences = [];
  9217. this.morphTargetDictionary = {};
  9218. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  9219. this.morphTargetInfluences.push( 0 );
  9220. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  9221. }
  9222. }
  9223. };
  9224. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  9225. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  9226. return this.morphTargetDictionary[ name ];
  9227. }
  9228. THREE.warn( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' );
  9229. return 0;
  9230. };
  9231. THREE.Mesh.prototype.raycast = ( function () {
  9232. var inverseMatrix = new THREE.Matrix4();
  9233. var ray = new THREE.Ray();
  9234. var sphere = new THREE.Sphere();
  9235. var vA = new THREE.Vector3();
  9236. var vB = new THREE.Vector3();
  9237. var vC = new THREE.Vector3();
  9238. return function ( raycaster, intersects ) {
  9239. var geometry = this.geometry;
  9240. // Checking boundingSphere distance to ray
  9241. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9242. sphere.copy( geometry.boundingSphere );
  9243. sphere.applyMatrix4( this.matrixWorld );
  9244. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  9245. return;
  9246. }
  9247. // Check boundingBox before continuing
  9248. inverseMatrix.getInverse( this.matrixWorld );
  9249. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  9250. if ( geometry.boundingBox !== null ) {
  9251. if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) {
  9252. return;
  9253. }
  9254. }
  9255. if ( geometry instanceof THREE.BufferGeometry ) {
  9256. var material = this.material;
  9257. if ( material === undefined ) return;
  9258. var attributes = geometry.attributes;
  9259. var a, b, c;
  9260. var precision = raycaster.precision;
  9261. if ( attributes.index !== undefined ) {
  9262. var indices = attributes.index.array;
  9263. var positions = attributes.position.array;
  9264. var offsets = geometry.offsets;
  9265. if ( offsets.length === 0 ) {
  9266. offsets = [ { start: 0, count: indices.length, index: 0 } ];
  9267. }
  9268. for ( var oi = 0, ol = offsets.length; oi < ol; ++ oi ) {
  9269. var start = offsets[ oi ].start;
  9270. var count = offsets[ oi ].count;
  9271. var index = offsets[ oi ].index;
  9272. for ( var i = start, il = start + count; i < il; i += 3 ) {
  9273. a = index + indices[ i ];
  9274. b = index + indices[ i + 1 ];
  9275. c = index + indices[ i + 2 ];
  9276. vA.fromArray( positions, a * 3 );
  9277. vB.fromArray( positions, b * 3 );
  9278. vC.fromArray( positions, c * 3 );
  9279. if ( material.side === THREE.BackSide ) {
  9280. var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true );
  9281. } else {
  9282. var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  9283. }
  9284. if ( intersectionPoint === null ) continue;
  9285. intersectionPoint.applyMatrix4( this.matrixWorld );
  9286. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  9287. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  9288. intersects.push( {
  9289. distance: distance,
  9290. point: intersectionPoint,
  9291. face: new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) ),
  9292. faceIndex: null,
  9293. object: this
  9294. } );
  9295. }
  9296. }
  9297. } else {
  9298. var positions = attributes.position.array;
  9299. for ( var i = 0, j = 0, il = positions.length; i < il; i += 3, j += 9 ) {
  9300. a = i;
  9301. b = i + 1;
  9302. c = i + 2;
  9303. vA.fromArray( positions, j );
  9304. vB.fromArray( positions, j + 3 );
  9305. vC.fromArray( positions, j + 6 );
  9306. if ( material.side === THREE.BackSide ) {
  9307. var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true );
  9308. } else {
  9309. var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  9310. }
  9311. if ( intersectionPoint === null ) continue;
  9312. intersectionPoint.applyMatrix4( this.matrixWorld );
  9313. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  9314. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  9315. intersects.push( {
  9316. distance: distance,
  9317. point: intersectionPoint,
  9318. face: new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) ),
  9319. faceIndex: null,
  9320. object: this
  9321. } );
  9322. }
  9323. }
  9324. } else if ( geometry instanceof THREE.Geometry ) {
  9325. var isFaceMaterial = this.material instanceof THREE.MeshFaceMaterial;
  9326. var objectMaterials = isFaceMaterial === true ? this.material.materials : null;
  9327. var a, b, c;
  9328. var precision = raycaster.precision;
  9329. var vertices = geometry.vertices;
  9330. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  9331. var face = geometry.faces[ f ];
  9332. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : this.material;
  9333. if ( material === undefined ) continue;
  9334. a = vertices[ face.a ];
  9335. b = vertices[ face.b ];
  9336. c = vertices[ face.c ];
  9337. if ( material.morphTargets === true ) {
  9338. var morphTargets = geometry.morphTargets;
  9339. var morphInfluences = this.morphTargetInfluences;
  9340. vA.set( 0, 0, 0 );
  9341. vB.set( 0, 0, 0 );
  9342. vC.set( 0, 0, 0 );
  9343. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  9344. var influence = morphInfluences[ t ];
  9345. if ( influence === 0 ) continue;
  9346. var targets = morphTargets[ t ].vertices;
  9347. vA.x += ( targets[ face.a ].x - a.x ) * influence;
  9348. vA.y += ( targets[ face.a ].y - a.y ) * influence;
  9349. vA.z += ( targets[ face.a ].z - a.z ) * influence;
  9350. vB.x += ( targets[ face.b ].x - b.x ) * influence;
  9351. vB.y += ( targets[ face.b ].y - b.y ) * influence;
  9352. vB.z += ( targets[ face.b ].z - b.z ) * influence;
  9353. vC.x += ( targets[ face.c ].x - c.x ) * influence;
  9354. vC.y += ( targets[ face.c ].y - c.y ) * influence;
  9355. vC.z += ( targets[ face.c ].z - c.z ) * influence;
  9356. }
  9357. vA.add( a );
  9358. vB.add( b );
  9359. vC.add( c );
  9360. a = vA;
  9361. b = vB;
  9362. c = vC;
  9363. }
  9364. if ( material.side === THREE.BackSide ) {
  9365. var intersectionPoint = ray.intersectTriangle( c, b, a, true );
  9366. } else {
  9367. var intersectionPoint = ray.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide );
  9368. }
  9369. if ( intersectionPoint === null ) continue;
  9370. intersectionPoint.applyMatrix4( this.matrixWorld );
  9371. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  9372. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  9373. intersects.push( {
  9374. distance: distance,
  9375. point: intersectionPoint,
  9376. face: face,
  9377. faceIndex: f,
  9378. object: this
  9379. } );
  9380. }
  9381. }
  9382. };
  9383. }() );
  9384. THREE.Mesh.prototype.clone = function ( object, recursive ) {
  9385. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  9386. THREE.Object3D.prototype.clone.call( this, object, recursive );
  9387. return object;
  9388. };
  9389. THREE.Mesh.prototype.toJSON = function ( meta ) {
  9390. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  9391. // only serialize if not in meta geometries cache
  9392. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  9393. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON();
  9394. }
  9395. // only serialize if not in meta materials cache
  9396. if ( meta.materials[ this.material.uuid ] === undefined ) {
  9397. meta.materials[ this.material.uuid ] = this.material.toJSON();
  9398. }
  9399. data.object.geometry = this.geometry.uuid;
  9400. data.object.material = this.material.uuid;
  9401. return data;
  9402. };
  9403. // File:src/objects/Bone.js
  9404. /**
  9405. * @author mikael emtinger / http://gomo.se/
  9406. * @author alteredq / http://alteredqualia.com/
  9407. * @author ikerr / http://verold.com
  9408. */
  9409. THREE.Bone = function ( skin ) {
  9410. THREE.Object3D.call( this );
  9411. this.type = 'Bone';
  9412. this.skin = skin;
  9413. };
  9414. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  9415. THREE.Bone.prototype.constructor = THREE.Bone;
  9416. // File:src/objects/Skeleton.js
  9417. /**
  9418. * @author mikael emtinger / http://gomo.se/
  9419. * @author alteredq / http://alteredqualia.com/
  9420. * @author michael guerrero / http://realitymeltdown.com
  9421. * @author ikerr / http://verold.com
  9422. */
  9423. THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) {
  9424. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  9425. this.identityMatrix = new THREE.Matrix4();
  9426. // copy the bone array
  9427. bones = bones || [];
  9428. this.bones = bones.slice( 0 );
  9429. // create a bone texture or an array of floats
  9430. if ( this.useVertexTexture ) {
  9431. // layout (1 matrix = 4 pixels)
  9432. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  9433. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  9434. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  9435. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  9436. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  9437. var size;
  9438. if ( this.bones.length > 256 )
  9439. size = 64;
  9440. else if ( this.bones.length > 64 )
  9441. size = 32;
  9442. else if ( this.bones.length > 16 )
  9443. size = 16;
  9444. else
  9445. size = 8;
  9446. this.boneTextureWidth = size;
  9447. this.boneTextureHeight = size;
  9448. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  9449. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  9450. this.boneTexture.minFilter = THREE.NearestFilter;
  9451. this.boneTexture.magFilter = THREE.NearestFilter;
  9452. this.boneTexture.generateMipmaps = false;
  9453. this.boneTexture.flipY = false;
  9454. } else {
  9455. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  9456. }
  9457. // use the supplied bone inverses or calculate the inverses
  9458. if ( boneInverses === undefined ) {
  9459. this.calculateInverses();
  9460. } else {
  9461. if ( this.bones.length === boneInverses.length ) {
  9462. this.boneInverses = boneInverses.slice( 0 );
  9463. } else {
  9464. THREE.warn( 'THREE.Skeleton bonInverses is the wrong length.' );
  9465. this.boneInverses = [];
  9466. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9467. this.boneInverses.push( new THREE.Matrix4() );
  9468. }
  9469. }
  9470. }
  9471. };
  9472. THREE.Skeleton.prototype.calculateInverses = function () {
  9473. this.boneInverses = [];
  9474. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9475. var inverse = new THREE.Matrix4();
  9476. if ( this.bones[ b ] ) {
  9477. inverse.getInverse( this.bones[ b ].matrixWorld );
  9478. }
  9479. this.boneInverses.push( inverse );
  9480. }
  9481. };
  9482. THREE.Skeleton.prototype.pose = function () {
  9483. var bone;
  9484. // recover the bind-time world matrices
  9485. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9486. bone = this.bones[ b ];
  9487. if ( bone ) {
  9488. bone.matrixWorld.getInverse( this.boneInverses[ b ] );
  9489. }
  9490. }
  9491. // compute the local matrices, positions, rotations and scales
  9492. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9493. bone = this.bones[ b ];
  9494. if ( bone ) {
  9495. if ( bone.parent ) {
  9496. bone.matrix.getInverse( bone.parent.matrixWorld );
  9497. bone.matrix.multiply( bone.matrixWorld );
  9498. } else {
  9499. bone.matrix.copy( bone.matrixWorld );
  9500. }
  9501. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  9502. }
  9503. }
  9504. };
  9505. THREE.Skeleton.prototype.update = ( function () {
  9506. var offsetMatrix = new THREE.Matrix4();
  9507. return function () {
  9508. // flatten bone matrices to array
  9509. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9510. // compute the offset between the current and the original transform
  9511. var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix;
  9512. offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] );
  9513. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  9514. }
  9515. if ( this.useVertexTexture ) {
  9516. this.boneTexture.needsUpdate = true;
  9517. }
  9518. };
  9519. } )();
  9520. // File:src/objects/SkinnedMesh.js
  9521. /**
  9522. * @author mikael emtinger / http://gomo.se/
  9523. * @author alteredq / http://alteredqualia.com/
  9524. * @author ikerr / http://verold.com
  9525. */
  9526. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  9527. THREE.Mesh.call( this, geometry, material );
  9528. this.type = 'SkinnedMesh';
  9529. this.bindMode = "attached";
  9530. this.bindMatrix = new THREE.Matrix4();
  9531. this.bindMatrixInverse = new THREE.Matrix4();
  9532. // init bones
  9533. // TODO: remove bone creation as there is no reason (other than
  9534. // convenience) for THREE.SkinnedMesh to do this.
  9535. var bones = [];
  9536. if ( this.geometry && this.geometry.bones !== undefined ) {
  9537. var bone, gbone, p, q, s;
  9538. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  9539. gbone = this.geometry.bones[ b ];
  9540. p = gbone.pos;
  9541. q = gbone.rotq;
  9542. s = gbone.scl;
  9543. bone = new THREE.Bone( this );
  9544. bones.push( bone );
  9545. bone.name = gbone.name;
  9546. bone.position.set( p[ 0 ], p[ 1 ], p[ 2 ] );
  9547. bone.quaternion.set( q[ 0 ], q[ 1 ], q[ 2 ], q[ 3 ] );
  9548. if ( s !== undefined ) {
  9549. bone.scale.set( s[ 0 ], s[ 1 ], s[ 2 ] );
  9550. } else {
  9551. bone.scale.set( 1, 1, 1 );
  9552. }
  9553. }
  9554. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  9555. gbone = this.geometry.bones[ b ];
  9556. if ( gbone.parent !== - 1 ) {
  9557. bones[ gbone.parent ].add( bones[ b ] );
  9558. } else {
  9559. this.add( bones[ b ] );
  9560. }
  9561. }
  9562. }
  9563. this.normalizeSkinWeights();
  9564. this.updateMatrixWorld( true );
  9565. this.bind( new THREE.Skeleton( bones, undefined, useVertexTexture ) );
  9566. };
  9567. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  9568. THREE.SkinnedMesh.prototype.constructor = THREE.SkinnedMesh;
  9569. THREE.SkinnedMesh.prototype.bind = function( skeleton, bindMatrix ) {
  9570. this.skeleton = skeleton;
  9571. if ( bindMatrix === undefined ) {
  9572. this.updateMatrixWorld( true );
  9573. bindMatrix = this.matrixWorld;
  9574. }
  9575. this.bindMatrix.copy( bindMatrix );
  9576. this.bindMatrixInverse.getInverse( bindMatrix );
  9577. };
  9578. THREE.SkinnedMesh.prototype.pose = function () {
  9579. this.skeleton.pose();
  9580. };
  9581. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  9582. if ( this.geometry instanceof THREE.Geometry ) {
  9583. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  9584. var sw = this.geometry.skinWeights[ i ];
  9585. var scale = 1.0 / sw.lengthManhattan();
  9586. if ( scale !== Infinity ) {
  9587. sw.multiplyScalar( scale );
  9588. } else {
  9589. sw.set( 1 ); // this will be normalized by the shader anyway
  9590. }
  9591. }
  9592. } else {
  9593. // skinning weights assumed to be normalized for THREE.BufferGeometry
  9594. }
  9595. };
  9596. THREE.SkinnedMesh.prototype.updateMatrixWorld = function( force ) {
  9597. THREE.Mesh.prototype.updateMatrixWorld.call( this, true );
  9598. if ( this.bindMode === "attached" ) {
  9599. this.bindMatrixInverse.getInverse( this.matrixWorld );
  9600. } else if ( this.bindMode === "detached" ) {
  9601. this.bindMatrixInverse.getInverse( this.bindMatrix );
  9602. } else {
  9603. THREE.warn( 'THREE.SkinnedMesh unreckognized bindMode: ' + this.bindMode );
  9604. }
  9605. };
  9606. THREE.SkinnedMesh.prototype.clone = function( object ) {
  9607. if ( object === undefined ) {
  9608. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  9609. }
  9610. THREE.Mesh.prototype.clone.call( this, object );
  9611. return object;
  9612. };
  9613. // File:src/objects/MorphAnimMesh.js
  9614. /**
  9615. * @author alteredq / http://alteredqualia.com/
  9616. */
  9617. THREE.MorphAnimMesh = function ( geometry, material ) {
  9618. THREE.Mesh.call( this, geometry, material );
  9619. this.type = 'MorphAnimMesh';
  9620. // API
  9621. this.duration = 1000; // milliseconds
  9622. this.mirroredLoop = false;
  9623. this.time = 0;
  9624. // internals
  9625. this.lastKeyframe = 0;
  9626. this.currentKeyframe = 0;
  9627. this.direction = 1;
  9628. this.directionBackwards = false;
  9629. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  9630. };
  9631. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  9632. THREE.MorphAnimMesh.prototype.constructor = THREE.MorphAnimMesh;
  9633. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  9634. this.startKeyframe = start;
  9635. this.endKeyframe = end;
  9636. this.length = this.endKeyframe - this.startKeyframe + 1;
  9637. };
  9638. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  9639. this.direction = 1;
  9640. this.directionBackwards = false;
  9641. };
  9642. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  9643. this.direction = - 1;
  9644. this.directionBackwards = true;
  9645. };
  9646. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  9647. var geometry = this.geometry;
  9648. if ( ! geometry.animations ) geometry.animations = {};
  9649. var firstAnimation, animations = geometry.animations;
  9650. var pattern = /([a-z]+)_?(\d+)/;
  9651. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  9652. var morph = geometry.morphTargets[ i ];
  9653. var parts = morph.name.match( pattern );
  9654. if ( parts && parts.length > 1 ) {
  9655. var label = parts[ 1 ];
  9656. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: - Infinity };
  9657. var animation = animations[ label ];
  9658. if ( i < animation.start ) animation.start = i;
  9659. if ( i > animation.end ) animation.end = i;
  9660. if ( ! firstAnimation ) firstAnimation = label;
  9661. }
  9662. }
  9663. geometry.firstAnimation = firstAnimation;
  9664. };
  9665. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  9666. if ( ! this.geometry.animations ) this.geometry.animations = {};
  9667. this.geometry.animations[ label ] = { start: start, end: end };
  9668. };
  9669. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  9670. var animation = this.geometry.animations[ label ];
  9671. if ( animation ) {
  9672. this.setFrameRange( animation.start, animation.end );
  9673. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  9674. this.time = 0;
  9675. } else {
  9676. THREE.warn( 'THREE.MorphAnimMesh: animation[' + label + '] undefined in .playAnimation()' );
  9677. }
  9678. };
  9679. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  9680. var frameTime = this.duration / this.length;
  9681. this.time += this.direction * delta;
  9682. if ( this.mirroredLoop ) {
  9683. if ( this.time > this.duration || this.time < 0 ) {
  9684. this.direction *= - 1;
  9685. if ( this.time > this.duration ) {
  9686. this.time = this.duration;
  9687. this.directionBackwards = true;
  9688. }
  9689. if ( this.time < 0 ) {
  9690. this.time = 0;
  9691. this.directionBackwards = false;
  9692. }
  9693. }
  9694. } else {
  9695. this.time = this.time % this.duration;
  9696. if ( this.time < 0 ) this.time += this.duration;
  9697. }
  9698. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  9699. if ( keyframe !== this.currentKeyframe ) {
  9700. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  9701. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  9702. this.morphTargetInfluences[ keyframe ] = 0;
  9703. this.lastKeyframe = this.currentKeyframe;
  9704. this.currentKeyframe = keyframe;
  9705. }
  9706. var mix = ( this.time % frameTime ) / frameTime;
  9707. if ( this.directionBackwards ) {
  9708. mix = 1 - mix;
  9709. }
  9710. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  9711. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  9712. };
  9713. THREE.MorphAnimMesh.prototype.interpolateTargets = function ( a, b, t ) {
  9714. var influences = this.morphTargetInfluences;
  9715. for ( var i = 0, l = influences.length; i < l; i ++ ) {
  9716. influences[ i ] = 0;
  9717. }
  9718. if ( a > -1 ) influences[ a ] = 1 - t;
  9719. if ( b > -1 ) influences[ b ] = t;
  9720. };
  9721. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  9722. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  9723. object.duration = this.duration;
  9724. object.mirroredLoop = this.mirroredLoop;
  9725. object.time = this.time;
  9726. object.lastKeyframe = this.lastKeyframe;
  9727. object.currentKeyframe = this.currentKeyframe;
  9728. object.direction = this.direction;
  9729. object.directionBackwards = this.directionBackwards;
  9730. THREE.Mesh.prototype.clone.call( this, object );
  9731. return object;
  9732. };
  9733. // File:src/objects/LOD.js
  9734. /**
  9735. * @author mikael emtinger / http://gomo.se/
  9736. * @author alteredq / http://alteredqualia.com/
  9737. * @author mrdoob / http://mrdoob.com/
  9738. */
  9739. THREE.LOD = function () {
  9740. THREE.Object3D.call( this );
  9741. this.objects = [];
  9742. };
  9743. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  9744. THREE.LOD.prototype.constructor = THREE.LOD;
  9745. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  9746. if ( distance === undefined ) distance = 0;
  9747. distance = Math.abs( distance );
  9748. for ( var l = 0; l < this.objects.length; l ++ ) {
  9749. if ( distance < this.objects[ l ].distance ) {
  9750. break;
  9751. }
  9752. }
  9753. this.objects.splice( l, 0, { distance: distance, object: object } );
  9754. this.add( object );
  9755. };
  9756. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  9757. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9758. if ( distance < this.objects[ i ].distance ) {
  9759. break;
  9760. }
  9761. }
  9762. return this.objects[ i - 1 ].object;
  9763. };
  9764. THREE.LOD.prototype.raycast = ( function () {
  9765. var matrixPosition = new THREE.Vector3();
  9766. return function ( raycaster, intersects ) {
  9767. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  9768. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  9769. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  9770. };
  9771. }() );
  9772. THREE.LOD.prototype.update = function () {
  9773. var v1 = new THREE.Vector3();
  9774. var v2 = new THREE.Vector3();
  9775. return function ( camera ) {
  9776. if ( this.objects.length > 1 ) {
  9777. v1.setFromMatrixPosition( camera.matrixWorld );
  9778. v2.setFromMatrixPosition( this.matrixWorld );
  9779. var distance = v1.distanceTo( v2 );
  9780. this.objects[ 0 ].object.visible = true;
  9781. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9782. if ( distance >= this.objects[ i ].distance ) {
  9783. this.objects[ i - 1 ].object.visible = false;
  9784. this.objects[ i ].object.visible = true;
  9785. } else {
  9786. break;
  9787. }
  9788. }
  9789. for ( ; i < l; i ++ ) {
  9790. this.objects[ i ].object.visible = false;
  9791. }
  9792. }
  9793. };
  9794. }();
  9795. THREE.LOD.prototype.clone = function ( object ) {
  9796. if ( object === undefined ) object = new THREE.LOD();
  9797. THREE.Object3D.prototype.clone.call( this, object );
  9798. for ( var i = 0, l = this.objects.length; i < l; i ++ ) {
  9799. var x = this.objects[ i ].object.clone();
  9800. x.visible = i === 0;
  9801. object.addLevel( x, this.objects[ i ].distance );
  9802. }
  9803. return object;
  9804. };
  9805. // File:src/objects/Sprite.js
  9806. /**
  9807. * @author mikael emtinger / http://gomo.se/
  9808. * @author alteredq / http://alteredqualia.com/
  9809. */
  9810. THREE.Sprite = ( function () {
  9811. var indices = new Uint16Array( [ 0, 1, 2, 0, 2, 3 ] );
  9812. var vertices = new Float32Array( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0, - 0.5, 0.5, 0 ] );
  9813. var uvs = new Float32Array( [ 0, 0, 1, 0, 1, 1, 0, 1 ] );
  9814. var geometry = new THREE.BufferGeometry();
  9815. geometry.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) );
  9816. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  9817. geometry.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  9818. return function ( material ) {
  9819. THREE.Object3D.call( this );
  9820. this.type = 'Sprite';
  9821. this.geometry = geometry;
  9822. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  9823. };
  9824. } )();
  9825. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  9826. THREE.Sprite.prototype.constructor = THREE.Sprite;
  9827. THREE.Sprite.prototype.raycast = ( function () {
  9828. var matrixPosition = new THREE.Vector3();
  9829. return function ( raycaster, intersects ) {
  9830. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  9831. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  9832. if ( distance > this.scale.x ) {
  9833. return;
  9834. }
  9835. intersects.push( {
  9836. distance: distance,
  9837. point: this.position,
  9838. face: null,
  9839. object: this
  9840. } );
  9841. };
  9842. }() );
  9843. THREE.Sprite.prototype.clone = function ( object ) {
  9844. if ( object === undefined ) object = new THREE.Sprite( this.material );
  9845. THREE.Object3D.prototype.clone.call( this, object );
  9846. return object;
  9847. };
  9848. THREE.Sprite.prototype.toJSON = function ( meta ) {
  9849. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  9850. // only serialize if not in meta materials cache
  9851. if ( meta.materials[ this.material.uuid ] === undefined ) {
  9852. meta.materials[ this.material.uuid ] = this.material.toJSON();
  9853. }
  9854. data.object.material = this.material.uuid;
  9855. return data;
  9856. };
  9857. // Backwards compatibility
  9858. THREE.Particle = THREE.Sprite;
  9859. // File:src/objects/LensFlare.js
  9860. /**
  9861. * @author mikael emtinger / http://gomo.se/
  9862. * @author alteredq / http://alteredqualia.com/
  9863. */
  9864. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  9865. THREE.Object3D.call( this );
  9866. this.lensFlares = [];
  9867. this.positionScreen = new THREE.Vector3();
  9868. this.customUpdateCallback = undefined;
  9869. if ( texture !== undefined ) {
  9870. this.add( texture, size, distance, blending, color );
  9871. }
  9872. };
  9873. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  9874. THREE.LensFlare.prototype.constructor = THREE.LensFlare;
  9875. /*
  9876. * Add: adds another flare
  9877. */
  9878. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  9879. if ( size === undefined ) size = - 1;
  9880. if ( distance === undefined ) distance = 0;
  9881. if ( opacity === undefined ) opacity = 1;
  9882. if ( color === undefined ) color = new THREE.Color( 0xffffff );
  9883. if ( blending === undefined ) blending = THREE.NormalBlending;
  9884. distance = Math.min( distance, Math.max( 0, distance ) );
  9885. this.lensFlares.push( {
  9886. texture: texture, // THREE.Texture
  9887. size: size, // size in pixels (-1 = use texture.width)
  9888. distance: distance, // distance (0-1) from light source (0=at light source)
  9889. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  9890. scale: 1, // scale
  9891. rotation: 1, // rotation
  9892. opacity: opacity, // opacity
  9893. color: color, // color
  9894. blending: blending // blending
  9895. } );
  9896. };
  9897. /*
  9898. * Update lens flares update positions on all flares based on the screen position
  9899. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  9900. */
  9901. THREE.LensFlare.prototype.updateLensFlares = function () {
  9902. var f, fl = this.lensFlares.length;
  9903. var flare;
  9904. var vecX = - this.positionScreen.x * 2;
  9905. var vecY = - this.positionScreen.y * 2;
  9906. for ( f = 0; f < fl; f ++ ) {
  9907. flare = this.lensFlares[ f ];
  9908. flare.x = this.positionScreen.x + vecX * flare.distance;
  9909. flare.y = this.positionScreen.y + vecY * flare.distance;
  9910. flare.wantedRotation = flare.x * Math.PI * 0.25;
  9911. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  9912. }
  9913. };
  9914. // File:src/scenes/Scene.js
  9915. /**
  9916. * @author mrdoob / http://mrdoob.com/
  9917. */
  9918. THREE.Scene = function () {
  9919. THREE.Object3D.call( this );
  9920. this.type = 'Scene';
  9921. this.fog = null;
  9922. this.overrideMaterial = null;
  9923. this.autoUpdate = true; // checked by the renderer
  9924. };
  9925. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  9926. THREE.Scene.prototype.constructor = THREE.Scene;
  9927. THREE.Scene.prototype.clone = function ( object ) {
  9928. if ( object === undefined ) object = new THREE.Scene();
  9929. THREE.Object3D.prototype.clone.call( this, object );
  9930. if ( this.fog !== null ) object.fog = this.fog.clone();
  9931. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  9932. object.autoUpdate = this.autoUpdate;
  9933. object.matrixAutoUpdate = this.matrixAutoUpdate;
  9934. return object;
  9935. };
  9936. // File:src/scenes/Fog.js
  9937. /**
  9938. * @author mrdoob / http://mrdoob.com/
  9939. * @author alteredq / http://alteredqualia.com/
  9940. */
  9941. THREE.Fog = function ( color, near, far ) {
  9942. this.name = '';
  9943. this.color = new THREE.Color( color );
  9944. this.near = ( near !== undefined ) ? near : 1;
  9945. this.far = ( far !== undefined ) ? far : 1000;
  9946. };
  9947. THREE.Fog.prototype.clone = function () {
  9948. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  9949. };
  9950. // File:src/scenes/FogExp2.js
  9951. /**
  9952. * @author mrdoob / http://mrdoob.com/
  9953. * @author alteredq / http://alteredqualia.com/
  9954. */
  9955. THREE.FogExp2 = function ( color, density ) {
  9956. this.name = '';
  9957. this.color = new THREE.Color( color );
  9958. this.density = ( density !== undefined ) ? density : 0.00025;
  9959. };
  9960. THREE.FogExp2.prototype.clone = function () {
  9961. return new THREE.FogExp2( this.color.getHex(), this.density );
  9962. };
  9963. // File:src/renderers/shaders/ShaderChunk.js
  9964. THREE.ShaderChunk = {};
  9965. // File:src/renderers/shaders/ShaderChunk/alphamap_fragment.glsl
  9966. THREE.ShaderChunk[ 'alphamap_fragment'] = "#ifdef USE_ALPHAMAP\n\n diffuseColor.a *= texture2D( alphaMap, vUv ).g;\n\n#endif\n";
  9967. // File:src/renderers/shaders/ShaderChunk/alphamap_pars_fragment.glsl
  9968. THREE.ShaderChunk[ 'alphamap_pars_fragment'] = "#ifdef USE_ALPHAMAP\n\n uniform sampler2D alphaMap;\n\n#endif\n";
  9969. // File:src/renderers/shaders/ShaderChunk/alphatest_fragment.glsl
  9970. THREE.ShaderChunk[ 'alphatest_fragment'] = "#ifdef ALPHATEST\n\n if ( diffuseColor.a < ALPHATEST ) discard;\n\n#endif\n";
  9971. // File:src/renderers/shaders/ShaderChunk/aomap_fragment.glsl
  9972. THREE.ShaderChunk[ 'aomap_fragment'] = "#ifdef USE_AOMAP\n\n outgoingLight *= ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\n#endif";
  9973. // File:src/renderers/shaders/ShaderChunk/aomap_pars_fragment.glsl
  9974. THREE.ShaderChunk[ 'aomap_pars_fragment'] = "#ifdef USE_AOMAP\n\n uniform sampler2D aoMap;\n uniform float aoMapIntensity;\n\n#endif";
  9975. // File:src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl
  9976. 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";
  9977. // File:src/renderers/shaders/ShaderChunk/color_fragment.glsl
  9978. THREE.ShaderChunk[ 'color_fragment'] = "#ifdef USE_COLOR\n\n diffuseColor.rgb *= vColor;\n\n#endif";
  9979. // File:src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl
  9980. THREE.ShaderChunk[ 'color_pars_fragment'] = "#ifdef USE_COLOR\n\n varying vec3 vColor;\n\n#endif\n";
  9981. // File:src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl
  9982. THREE.ShaderChunk[ 'color_pars_vertex'] = "#ifdef USE_COLOR\n\n varying vec3 vColor;\n\n#endif";
  9983. // File:src/renderers/shaders/ShaderChunk/color_vertex.glsl
  9984. THREE.ShaderChunk[ 'color_vertex'] = "#ifdef USE_COLOR\n\n vColor.xyz = inputToLinear( color.xyz );\n\n#endif";
  9985. // File:src/renderers/shaders/ShaderChunk/common.glsl
  9986. 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";
  9987. // File:src/renderers/shaders/ShaderChunk/default_vertex.glsl
  9988. 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";
  9989. // File:src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl
  9990. 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";
  9991. // File:src/renderers/shaders/ShaderChunk/envmap_fragment.glsl
  9992. 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";
  9993. // File:src/renderers/shaders/ShaderChunk/envmap_pars_fragment.glsl
  9994. 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";
  9995. // File:src/renderers/shaders/ShaderChunk/envmap_pars_vertex.glsl
  9996. 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";
  9997. // File:src/renderers/shaders/ShaderChunk/envmap_vertex.glsl
  9998. 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";
  9999. // File:src/renderers/shaders/ShaderChunk/fog_fragment.glsl
  10000. 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";
  10001. // File:src/renderers/shaders/ShaderChunk/fog_pars_fragment.glsl
  10002. 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";
  10003. // File:src/renderers/shaders/ShaderChunk/lightmap_fragment.glsl
  10004. THREE.ShaderChunk[ 'lightmap_fragment'] = "#ifdef USE_LIGHTMAP\n\n outgoingLight += diffuseColor.xyz * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\n#endif";
  10005. // File:src/renderers/shaders/ShaderChunk/lightmap_pars_fragment.glsl
  10006. THREE.ShaderChunk[ 'lightmap_pars_fragment'] = "#ifdef USE_LIGHTMAP\n\n uniform sampler2D lightMap;\n uniform float lightMapIntensity;\n\n#endif";
  10007. // File:src/renderers/shaders/ShaderChunk/lights_lambert_pars_vertex.glsl
  10008. 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";
  10009. // File:src/renderers/shaders/ShaderChunk/lights_lambert_vertex.glsl
  10010. 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";
  10011. // File:src/renderers/shaders/ShaderChunk/lights_phong_fragment.glsl
  10012. 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";
  10013. // File:src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl
  10014. 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";
  10015. // File:src/renderers/shaders/ShaderChunk/lights_phong_pars_vertex.glsl
  10016. 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";
  10017. // File:src/renderers/shaders/ShaderChunk/lights_phong_vertex.glsl
  10018. THREE.ShaderChunk[ 'lights_phong_vertex'] = "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )\n\n vWorldPosition = worldPosition.xyz;\n\n#endif";
  10019. // File:src/renderers/shaders/ShaderChunk/linear_to_gamma_fragment.glsl
  10020. THREE.ShaderChunk[ 'linear_to_gamma_fragment'] = "\n outgoingLight = linearToOutput( outgoingLight );\n";
  10021. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl
  10022. THREE.ShaderChunk[ 'logdepthbuf_fragment'] = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\n gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n\n#endif";
  10023. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl
  10024. 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";
  10025. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl
  10026. 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";
  10027. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl
  10028. 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";
  10029. // File:src/renderers/shaders/ShaderChunk/map_fragment.glsl
  10030. 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";
  10031. // File:src/renderers/shaders/ShaderChunk/map_pars_fragment.glsl
  10032. THREE.ShaderChunk[ 'map_pars_fragment'] = "#ifdef USE_MAP\n\n uniform sampler2D map;\n\n#endif";
  10033. // File:src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl
  10034. 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";
  10035. // File:src/renderers/shaders/ShaderChunk/map_particle_pars_fragment.glsl
  10036. THREE.ShaderChunk[ 'map_particle_pars_fragment'] = "#ifdef USE_MAP\n\n uniform vec4 offsetRepeat;\n uniform sampler2D map;\n\n#endif\n";
  10037. // File:src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl
  10038. 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";
  10039. // File:src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl
  10040. 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";
  10041. // File:src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl
  10042. 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";
  10043. // File:src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl
  10044. 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";
  10045. // File:src/renderers/shaders/ShaderChunk/shadowmap_fragment.glsl
  10046. 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";
  10047. // File:src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl
  10048. 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";
  10049. // File:src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl
  10050. THREE.ShaderChunk[ 'shadowmap_pars_vertex'] = "#ifdef USE_SHADOWMAP\n\n varying vec4 vShadowCoord[ MAX_SHADOWS ];\n uniform mat4 shadowMatrix[ MAX_SHADOWS ];\n\n#endif";
  10051. // File:src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl
  10052. 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";
  10053. // File:src/renderers/shaders/ShaderChunk/skinbase_vertex.glsl
  10054. 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";
  10055. // File:src/renderers/shaders/ShaderChunk/skinning_pars_vertex.glsl
  10056. 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";
  10057. // File:src/renderers/shaders/ShaderChunk/skinning_vertex.glsl
  10058. 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";
  10059. // File:src/renderers/shaders/ShaderChunk/skinnormal_vertex.glsl
  10060. 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";
  10061. // File:src/renderers/shaders/ShaderChunk/specularmap_fragment.glsl
  10062. 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";
  10063. // File:src/renderers/shaders/ShaderChunk/specularmap_pars_fragment.glsl
  10064. THREE.ShaderChunk[ 'specularmap_pars_fragment'] = "#ifdef USE_SPECULARMAP\n\n uniform sampler2D specularMap;\n\n#endif";
  10065. // File:src/renderers/shaders/ShaderChunk/uv2_pars_fragment.glsl
  10066. THREE.ShaderChunk[ 'uv2_pars_fragment'] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n varying vec2 vUv2;\n\n#endif";
  10067. // File:src/renderers/shaders/ShaderChunk/uv2_pars_vertex.glsl
  10068. THREE.ShaderChunk[ 'uv2_pars_vertex'] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n attribute vec2 uv2;\n varying vec2 vUv2;\n\n#endif";
  10069. // File:src/renderers/shaders/ShaderChunk/uv2_vertex.glsl
  10070. THREE.ShaderChunk[ 'uv2_vertex'] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n vUv2 = uv2;\n\n#endif";
  10071. // File:src/renderers/shaders/ShaderChunk/uv_pars_fragment.glsl
  10072. 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";
  10073. // File:src/renderers/shaders/ShaderChunk/uv_pars_vertex.glsl
  10074. 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";
  10075. // File:src/renderers/shaders/ShaderChunk/uv_vertex.glsl
  10076. 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";
  10077. // File:src/renderers/shaders/ShaderChunk/worldpos_vertex.glsl
  10078. 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";
  10079. // File:src/renderers/shaders/UniformsUtils.js
  10080. /**
  10081. * Uniform Utilities
  10082. */
  10083. THREE.UniformsUtils = {
  10084. merge: function ( uniforms ) {
  10085. var merged = {};
  10086. for ( var u = 0; u < uniforms.length; u ++ ) {
  10087. var tmp = this.clone( uniforms[ u ] );
  10088. for ( var p in tmp ) {
  10089. merged[ p ] = tmp[ p ];
  10090. }
  10091. }
  10092. return merged;
  10093. },
  10094. clone: function ( uniforms_src ) {
  10095. var uniforms_dst = {};
  10096. for ( var u in uniforms_src ) {
  10097. uniforms_dst[ u ] = {};
  10098. for ( var p in uniforms_src[ u ] ) {
  10099. var parameter_src = uniforms_src[ u ][ p ];
  10100. if ( parameter_src instanceof THREE.Color ||
  10101. parameter_src instanceof THREE.Vector2 ||
  10102. parameter_src instanceof THREE.Vector3 ||
  10103. parameter_src instanceof THREE.Vector4 ||
  10104. parameter_src instanceof THREE.Matrix3 ||
  10105. parameter_src instanceof THREE.Matrix4 ||
  10106. parameter_src instanceof THREE.Texture ) {
  10107. uniforms_dst[ u ][ p ] = parameter_src.clone();
  10108. } else if ( parameter_src instanceof Array ) {
  10109. uniforms_dst[ u ][ p ] = parameter_src.slice();
  10110. } else {
  10111. uniforms_dst[ u ][ p ] = parameter_src;
  10112. }
  10113. }
  10114. }
  10115. return uniforms_dst;
  10116. }
  10117. };
  10118. // File:src/renderers/shaders/UniformsLib.js
  10119. /**
  10120. * Uniforms library for shared webgl shaders
  10121. */
  10122. THREE.UniformsLib = {
  10123. common: {
  10124. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10125. "opacity" : { type: "f", value: 1.0 },
  10126. "map" : { type: "t", value: null },
  10127. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10128. "lightMap" : { type: "t", value: null },
  10129. "lightMapIntensity" : { type: "f", value: 1 },
  10130. "aoMap" : { type: "t", value: null },
  10131. "aoMapIntensity" : { type: "f", value: 1 },
  10132. "specularMap" : { type: "t", value: null },
  10133. "alphaMap" : { type: "t", value: null },
  10134. "envMap" : { type: "t", value: null },
  10135. "flipEnvMap" : { type: "f", value: - 1 },
  10136. "reflectivity" : { type: "f", value: 1.0 },
  10137. "refractionRatio" : { type: "f", value: 0.98 },
  10138. "morphTargetInfluences" : { type: "f", value: 0 }
  10139. },
  10140. bump: {
  10141. "bumpMap" : { type: "t", value: null },
  10142. "bumpScale" : { type: "f", value: 1 }
  10143. },
  10144. normalmap: {
  10145. "normalMap" : { type: "t", value: null },
  10146. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  10147. },
  10148. fog : {
  10149. "fogDensity" : { type: "f", value: 0.00025 },
  10150. "fogNear" : { type: "f", value: 1 },
  10151. "fogFar" : { type: "f", value: 2000 },
  10152. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10153. },
  10154. lights: {
  10155. "ambientLightColor" : { type: "fv", value: [] },
  10156. "directionalLightDirection" : { type: "fv", value: [] },
  10157. "directionalLightColor" : { type: "fv", value: [] },
  10158. "hemisphereLightDirection" : { type: "fv", value: [] },
  10159. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  10160. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  10161. "pointLightColor" : { type: "fv", value: [] },
  10162. "pointLightPosition" : { type: "fv", value: [] },
  10163. "pointLightDistance" : { type: "fv1", value: [] },
  10164. "pointLightDecay" : { type: "fv1", value: [] },
  10165. "spotLightColor" : { type: "fv", value: [] },
  10166. "spotLightPosition" : { type: "fv", value: [] },
  10167. "spotLightDirection" : { type: "fv", value: [] },
  10168. "spotLightDistance" : { type: "fv1", value: [] },
  10169. "spotLightAngleCos" : { type: "fv1", value: [] },
  10170. "spotLightExponent" : { type: "fv1", value: [] },
  10171. "spotLightDecay" : { type: "fv1", value: [] }
  10172. },
  10173. particle: {
  10174. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10175. "opacity" : { type: "f", value: 1.0 },
  10176. "size" : { type: "f", value: 1.0 },
  10177. "scale" : { type: "f", value: 1.0 },
  10178. "map" : { type: "t", value: null },
  10179. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10180. "fogDensity" : { type: "f", value: 0.00025 },
  10181. "fogNear" : { type: "f", value: 1 },
  10182. "fogFar" : { type: "f", value: 2000 },
  10183. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10184. },
  10185. shadowmap: {
  10186. "shadowMap": { type: "tv", value: [] },
  10187. "shadowMapSize": { type: "v2v", value: [] },
  10188. "shadowBias" : { type: "fv1", value: [] },
  10189. "shadowDarkness": { type: "fv1", value: [] },
  10190. "shadowMatrix" : { type: "m4v", value: [] }
  10191. }
  10192. };
  10193. // File:src/renderers/shaders/ShaderLib.js
  10194. /**
  10195. * Webgl Shader Library for three.js
  10196. *
  10197. * @author alteredq / http://alteredqualia.com/
  10198. * @author mrdoob / http://mrdoob.com/
  10199. * @author mikael emtinger / http://gomo.se/
  10200. */
  10201. THREE.ShaderLib = {
  10202. 'basic': {
  10203. uniforms: THREE.UniformsUtils.merge( [
  10204. THREE.UniformsLib[ "common" ],
  10205. THREE.UniformsLib[ "fog" ],
  10206. THREE.UniformsLib[ "shadowmap" ]
  10207. ] ),
  10208. vertexShader: [
  10209. THREE.ShaderChunk[ "common" ],
  10210. THREE.ShaderChunk[ "uv_pars_vertex" ],
  10211. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  10212. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10213. THREE.ShaderChunk[ "color_pars_vertex" ],
  10214. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10215. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10216. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10217. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10218. "void main() {",
  10219. THREE.ShaderChunk[ "uv_vertex" ],
  10220. THREE.ShaderChunk[ "uv2_vertex" ],
  10221. THREE.ShaderChunk[ "color_vertex" ],
  10222. THREE.ShaderChunk[ "skinbase_vertex" ],
  10223. " #ifdef USE_ENVMAP",
  10224. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10225. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10226. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10227. " #endif",
  10228. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10229. THREE.ShaderChunk[ "skinning_vertex" ],
  10230. THREE.ShaderChunk[ "default_vertex" ],
  10231. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10232. THREE.ShaderChunk[ "worldpos_vertex" ],
  10233. THREE.ShaderChunk[ "envmap_vertex" ],
  10234. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10235. "}"
  10236. ].join("\n"),
  10237. fragmentShader: [
  10238. "uniform vec3 diffuse;",
  10239. "uniform float opacity;",
  10240. THREE.ShaderChunk[ "common" ],
  10241. THREE.ShaderChunk[ "color_pars_fragment" ],
  10242. THREE.ShaderChunk[ "uv_pars_fragment" ],
  10243. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  10244. THREE.ShaderChunk[ "map_pars_fragment" ],
  10245. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  10246. THREE.ShaderChunk[ "aomap_pars_fragment" ],
  10247. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10248. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10249. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10250. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10251. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10252. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10253. "void main() {",
  10254. " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does
  10255. " vec4 diffuseColor = vec4( diffuse, opacity );",
  10256. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10257. THREE.ShaderChunk[ "map_fragment" ],
  10258. THREE.ShaderChunk[ "color_fragment" ],
  10259. THREE.ShaderChunk[ "alphamap_fragment" ],
  10260. THREE.ShaderChunk[ "alphatest_fragment" ],
  10261. THREE.ShaderChunk[ "specularmap_fragment" ],
  10262. " outgoingLight = diffuseColor.rgb;", // simple shader
  10263. THREE.ShaderChunk[ "aomap_fragment" ],
  10264. THREE.ShaderChunk[ "lightmap_fragment" ],
  10265. THREE.ShaderChunk[ "envmap_fragment" ],
  10266. THREE.ShaderChunk[ "shadowmap_fragment" ], // TODO: Shadows on an otherwise unlit surface doesn't make sense.
  10267. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10268. THREE.ShaderChunk[ "fog_fragment" ],
  10269. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects
  10270. "}"
  10271. ].join("\n")
  10272. },
  10273. 'lambert': {
  10274. uniforms: THREE.UniformsUtils.merge( [
  10275. THREE.UniformsLib[ "common" ],
  10276. THREE.UniformsLib[ "fog" ],
  10277. THREE.UniformsLib[ "lights" ],
  10278. THREE.UniformsLib[ "shadowmap" ],
  10279. {
  10280. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10281. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10282. }
  10283. ] ),
  10284. vertexShader: [
  10285. "#define LAMBERT",
  10286. "varying vec3 vLightFront;",
  10287. "#ifdef DOUBLE_SIDED",
  10288. " varying vec3 vLightBack;",
  10289. "#endif",
  10290. THREE.ShaderChunk[ "common" ],
  10291. THREE.ShaderChunk[ "uv_pars_vertex" ],
  10292. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  10293. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10294. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  10295. THREE.ShaderChunk[ "color_pars_vertex" ],
  10296. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10297. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10298. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10299. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10300. "void main() {",
  10301. THREE.ShaderChunk[ "uv_vertex" ],
  10302. THREE.ShaderChunk[ "uv2_vertex" ],
  10303. THREE.ShaderChunk[ "color_vertex" ],
  10304. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10305. THREE.ShaderChunk[ "skinbase_vertex" ],
  10306. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10307. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10308. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10309. THREE.ShaderChunk[ "skinning_vertex" ],
  10310. THREE.ShaderChunk[ "default_vertex" ],
  10311. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10312. THREE.ShaderChunk[ "worldpos_vertex" ],
  10313. THREE.ShaderChunk[ "envmap_vertex" ],
  10314. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  10315. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10316. "}"
  10317. ].join("\n"),
  10318. fragmentShader: [
  10319. "uniform vec3 diffuse;",
  10320. "uniform vec3 emissive;",
  10321. "uniform float opacity;",
  10322. "varying vec3 vLightFront;",
  10323. "#ifdef DOUBLE_SIDED",
  10324. " varying vec3 vLightBack;",
  10325. "#endif",
  10326. THREE.ShaderChunk[ "common" ],
  10327. THREE.ShaderChunk[ "color_pars_fragment" ],
  10328. THREE.ShaderChunk[ "uv_pars_fragment" ],
  10329. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  10330. THREE.ShaderChunk[ "map_pars_fragment" ],
  10331. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  10332. THREE.ShaderChunk[ "aomap_pars_fragment" ],
  10333. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10334. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10335. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10336. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10337. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10338. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10339. "void main() {",
  10340. " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does
  10341. " vec4 diffuseColor = vec4( diffuse, opacity );",
  10342. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10343. THREE.ShaderChunk[ "map_fragment" ],
  10344. THREE.ShaderChunk[ "color_fragment" ],
  10345. THREE.ShaderChunk[ "alphamap_fragment" ],
  10346. THREE.ShaderChunk[ "alphatest_fragment" ],
  10347. THREE.ShaderChunk[ "specularmap_fragment" ],
  10348. " #ifdef DOUBLE_SIDED",
  10349. //"float isFront = float( gl_FrontFacing );",
  10350. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  10351. " if ( gl_FrontFacing )",
  10352. " outgoingLight += diffuseColor.rgb * vLightFront + emissive;",
  10353. " else",
  10354. " outgoingLight += diffuseColor.rgb * vLightBack + emissive;",
  10355. " #else",
  10356. " outgoingLight += diffuseColor.rgb * vLightFront + emissive;",
  10357. " #endif",
  10358. THREE.ShaderChunk[ "aomap_fragment" ],
  10359. THREE.ShaderChunk[ "lightmap_fragment" ],
  10360. THREE.ShaderChunk[ "envmap_fragment" ],
  10361. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10362. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10363. THREE.ShaderChunk[ "fog_fragment" ],
  10364. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects
  10365. "}"
  10366. ].join("\n")
  10367. },
  10368. 'phong': {
  10369. uniforms: THREE.UniformsUtils.merge( [
  10370. THREE.UniformsLib[ "common" ],
  10371. THREE.UniformsLib[ "bump" ],
  10372. THREE.UniformsLib[ "normalmap" ],
  10373. THREE.UniformsLib[ "fog" ],
  10374. THREE.UniformsLib[ "lights" ],
  10375. THREE.UniformsLib[ "shadowmap" ],
  10376. {
  10377. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10378. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10379. "shininess": { type: "f", value: 30 },
  10380. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10381. }
  10382. ] ),
  10383. vertexShader: [
  10384. "#define PHONG",
  10385. "varying vec3 vViewPosition;",
  10386. "#ifndef FLAT_SHADED",
  10387. " varying vec3 vNormal;",
  10388. "#endif",
  10389. THREE.ShaderChunk[ "common" ],
  10390. THREE.ShaderChunk[ "uv_pars_vertex" ],
  10391. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  10392. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10393. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10394. THREE.ShaderChunk[ "color_pars_vertex" ],
  10395. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10396. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10397. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10398. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10399. "void main() {",
  10400. THREE.ShaderChunk[ "uv_vertex" ],
  10401. THREE.ShaderChunk[ "uv2_vertex" ],
  10402. THREE.ShaderChunk[ "color_vertex" ],
  10403. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10404. THREE.ShaderChunk[ "skinbase_vertex" ],
  10405. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10406. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10407. "#ifndef FLAT_SHADED", // Normal computed with derivatives when FLAT_SHADED
  10408. " vNormal = normalize( transformedNormal );",
  10409. "#endif",
  10410. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10411. THREE.ShaderChunk[ "skinning_vertex" ],
  10412. THREE.ShaderChunk[ "default_vertex" ],
  10413. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10414. " vViewPosition = -mvPosition.xyz;",
  10415. THREE.ShaderChunk[ "worldpos_vertex" ],
  10416. THREE.ShaderChunk[ "envmap_vertex" ],
  10417. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10418. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10419. "}"
  10420. ].join("\n"),
  10421. fragmentShader: [
  10422. "#define PHONG",
  10423. "uniform vec3 diffuse;",
  10424. "uniform vec3 emissive;",
  10425. "uniform vec3 specular;",
  10426. "uniform float shininess;",
  10427. "uniform float opacity;",
  10428. THREE.ShaderChunk[ "common" ],
  10429. THREE.ShaderChunk[ "color_pars_fragment" ],
  10430. THREE.ShaderChunk[ "uv_pars_fragment" ],
  10431. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  10432. THREE.ShaderChunk[ "map_pars_fragment" ],
  10433. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  10434. THREE.ShaderChunk[ "aomap_pars_fragment" ],
  10435. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10436. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10437. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10438. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10439. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10440. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10441. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10442. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10443. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10444. "void main() {",
  10445. " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does
  10446. " vec4 diffuseColor = vec4( diffuse, opacity );",
  10447. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10448. THREE.ShaderChunk[ "map_fragment" ],
  10449. THREE.ShaderChunk[ "color_fragment" ],
  10450. THREE.ShaderChunk[ "alphamap_fragment" ],
  10451. THREE.ShaderChunk[ "alphatest_fragment" ],
  10452. THREE.ShaderChunk[ "specularmap_fragment" ],
  10453. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10454. THREE.ShaderChunk[ "aomap_fragment" ],
  10455. THREE.ShaderChunk[ "lightmap_fragment" ],
  10456. THREE.ShaderChunk[ "envmap_fragment" ],
  10457. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10458. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10459. THREE.ShaderChunk[ "fog_fragment" ],
  10460. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects
  10461. "}"
  10462. ].join("\n")
  10463. },
  10464. 'particle_basic': {
  10465. uniforms: THREE.UniformsUtils.merge( [
  10466. THREE.UniformsLib[ "particle" ],
  10467. THREE.UniformsLib[ "shadowmap" ]
  10468. ] ),
  10469. vertexShader: [
  10470. "uniform float size;",
  10471. "uniform float scale;",
  10472. THREE.ShaderChunk[ "common" ],
  10473. THREE.ShaderChunk[ "color_pars_vertex" ],
  10474. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10475. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10476. "void main() {",
  10477. THREE.ShaderChunk[ "color_vertex" ],
  10478. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10479. " #ifdef USE_SIZEATTENUATION",
  10480. " gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  10481. " #else",
  10482. " gl_PointSize = size;",
  10483. " #endif",
  10484. " gl_Position = projectionMatrix * mvPosition;",
  10485. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10486. THREE.ShaderChunk[ "worldpos_vertex" ],
  10487. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10488. "}"
  10489. ].join("\n"),
  10490. fragmentShader: [
  10491. "uniform vec3 psColor;",
  10492. "uniform float opacity;",
  10493. THREE.ShaderChunk[ "common" ],
  10494. THREE.ShaderChunk[ "color_pars_fragment" ],
  10495. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  10496. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10497. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10498. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10499. "void main() {",
  10500. " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does
  10501. " vec4 diffuseColor = vec4( psColor, opacity );",
  10502. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10503. THREE.ShaderChunk[ "map_particle_fragment" ],
  10504. THREE.ShaderChunk[ "color_fragment" ],
  10505. THREE.ShaderChunk[ "alphatest_fragment" ],
  10506. " outgoingLight = diffuseColor.rgb;", // simple shader
  10507. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10508. THREE.ShaderChunk[ "fog_fragment" ],
  10509. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects
  10510. "}"
  10511. ].join("\n")
  10512. },
  10513. 'dashed': {
  10514. uniforms: THREE.UniformsUtils.merge( [
  10515. THREE.UniformsLib[ "common" ],
  10516. THREE.UniformsLib[ "fog" ],
  10517. {
  10518. "scale" : { type: "f", value: 1 },
  10519. "dashSize" : { type: "f", value: 1 },
  10520. "totalSize": { type: "f", value: 2 }
  10521. }
  10522. ] ),
  10523. vertexShader: [
  10524. "uniform float scale;",
  10525. "attribute float lineDistance;",
  10526. "varying float vLineDistance;",
  10527. THREE.ShaderChunk[ "common" ],
  10528. THREE.ShaderChunk[ "color_pars_vertex" ],
  10529. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10530. "void main() {",
  10531. THREE.ShaderChunk[ "color_vertex" ],
  10532. " vLineDistance = scale * lineDistance;",
  10533. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10534. " gl_Position = projectionMatrix * mvPosition;",
  10535. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10536. "}"
  10537. ].join("\n"),
  10538. fragmentShader: [
  10539. "uniform vec3 diffuse;",
  10540. "uniform float opacity;",
  10541. "uniform float dashSize;",
  10542. "uniform float totalSize;",
  10543. "varying float vLineDistance;",
  10544. THREE.ShaderChunk[ "common" ],
  10545. THREE.ShaderChunk[ "color_pars_fragment" ],
  10546. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10547. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10548. "void main() {",
  10549. " if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  10550. " discard;",
  10551. " }",
  10552. " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does
  10553. " vec4 diffuseColor = vec4( diffuse, opacity );",
  10554. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10555. THREE.ShaderChunk[ "color_fragment" ],
  10556. " outgoingLight = diffuseColor.rgb;", // simple shader
  10557. THREE.ShaderChunk[ "fog_fragment" ],
  10558. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects
  10559. "}"
  10560. ].join("\n")
  10561. },
  10562. 'depth': {
  10563. uniforms: {
  10564. "mNear": { type: "f", value: 1.0 },
  10565. "mFar" : { type: "f", value: 2000.0 },
  10566. "opacity" : { type: "f", value: 1.0 }
  10567. },
  10568. vertexShader: [
  10569. THREE.ShaderChunk[ "common" ],
  10570. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10571. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10572. "void main() {",
  10573. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10574. THREE.ShaderChunk[ "default_vertex" ],
  10575. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10576. "}"
  10577. ].join("\n"),
  10578. fragmentShader: [
  10579. "uniform float mNear;",
  10580. "uniform float mFar;",
  10581. "uniform float opacity;",
  10582. THREE.ShaderChunk[ "common" ],
  10583. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10584. "void main() {",
  10585. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10586. " #ifdef USE_LOGDEPTHBUF_EXT",
  10587. " float depth = gl_FragDepthEXT / gl_FragCoord.w;",
  10588. " #else",
  10589. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10590. " #endif",
  10591. " float color = 1.0 - smoothstep( mNear, mFar, depth );",
  10592. " gl_FragColor = vec4( vec3( color ), opacity );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects
  10593. "}"
  10594. ].join("\n")
  10595. },
  10596. 'normal': {
  10597. uniforms: {
  10598. "opacity" : { type: "f", value: 1.0 }
  10599. },
  10600. vertexShader: [
  10601. "varying vec3 vNormal;",
  10602. THREE.ShaderChunk[ "common" ],
  10603. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10604. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10605. "void main() {",
  10606. " vNormal = normalize( normalMatrix * normal );",
  10607. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10608. THREE.ShaderChunk[ "default_vertex" ],
  10609. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10610. "}"
  10611. ].join("\n"),
  10612. fragmentShader: [
  10613. "uniform float opacity;",
  10614. "varying vec3 vNormal;",
  10615. THREE.ShaderChunk[ "common" ],
  10616. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10617. "void main() {",
  10618. " gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  10619. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10620. "}"
  10621. ].join("\n")
  10622. },
  10623. /* -------------------------------------------------------------------------
  10624. // Cube map shader
  10625. ------------------------------------------------------------------------- */
  10626. 'cube': {
  10627. uniforms: { "tCube": { type: "t", value: null },
  10628. "tFlip": { type: "f", value: - 1 } },
  10629. vertexShader: [
  10630. "varying vec3 vWorldPosition;",
  10631. THREE.ShaderChunk[ "common" ],
  10632. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10633. "void main() {",
  10634. " vWorldPosition = transformDirection( position, modelMatrix );",
  10635. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10636. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10637. "}"
  10638. ].join("\n"),
  10639. fragmentShader: [
  10640. "uniform samplerCube tCube;",
  10641. "uniform float tFlip;",
  10642. "varying vec3 vWorldPosition;",
  10643. THREE.ShaderChunk[ "common" ],
  10644. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10645. "void main() {",
  10646. " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  10647. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10648. "}"
  10649. ].join("\n")
  10650. },
  10651. /* -------------------------------------------------------------------------
  10652. // Cube map shader
  10653. ------------------------------------------------------------------------- */
  10654. 'equirect': {
  10655. uniforms: { "tEquirect": { type: "t", value: null },
  10656. "tFlip": { type: "f", value: - 1 } },
  10657. vertexShader: [
  10658. "varying vec3 vWorldPosition;",
  10659. THREE.ShaderChunk[ "common" ],
  10660. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10661. "void main() {",
  10662. " vWorldPosition = transformDirection( position, modelMatrix );",
  10663. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10664. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10665. "}"
  10666. ].join("\n"),
  10667. fragmentShader: [
  10668. "uniform sampler2D tEquirect;",
  10669. "uniform float tFlip;",
  10670. "varying vec3 vWorldPosition;",
  10671. THREE.ShaderChunk[ "common" ],
  10672. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10673. "void main() {",
  10674. // " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  10675. "vec3 direction = normalize( vWorldPosition );",
  10676. "vec2 sampleUV;",
  10677. "sampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );",
  10678. "sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;",
  10679. "gl_FragColor = texture2D( tEquirect, sampleUV );",
  10680. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10681. "}"
  10682. ].join("\n")
  10683. },
  10684. /* Depth encoding into RGBA texture
  10685. *
  10686. * based on SpiderGL shadow map example
  10687. * http://spidergl.org/example.php?id=6
  10688. *
  10689. * originally from
  10690. * http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  10691. *
  10692. * see also
  10693. * http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  10694. */
  10695. 'depthRGBA': {
  10696. uniforms: {},
  10697. vertexShader: [
  10698. THREE.ShaderChunk[ "common" ],
  10699. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10700. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10701. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10702. "void main() {",
  10703. THREE.ShaderChunk[ "skinbase_vertex" ],
  10704. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10705. THREE.ShaderChunk[ "skinning_vertex" ],
  10706. THREE.ShaderChunk[ "default_vertex" ],
  10707. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10708. "}"
  10709. ].join("\n"),
  10710. fragmentShader: [
  10711. THREE.ShaderChunk[ "common" ],
  10712. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10713. "vec4 pack_depth( const in float depth ) {",
  10714. " const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  10715. " const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  10716. " vec4 res = mod( depth * bit_shift * vec4( 255 ), vec4( 256 ) ) / vec4( 255 );", // " vec4 res = fract( depth * bit_shift );",
  10717. " res -= res.xxyz * bit_mask;",
  10718. " return res;",
  10719. "}",
  10720. "void main() {",
  10721. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10722. " #ifdef USE_LOGDEPTHBUF_EXT",
  10723. " gl_FragData[ 0 ] = pack_depth( gl_FragDepthEXT );",
  10724. " #else",
  10725. " gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  10726. " #endif",
  10727. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  10728. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  10729. //"gl_FragData[ 0 ] = pack_depth( z );",
  10730. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  10731. "}"
  10732. ].join("\n")
  10733. }
  10734. };
  10735. // File:src/renderers/WebGLRenderer.js
  10736. /**
  10737. * @author supereggbert / http://www.paulbrunt.co.uk/
  10738. * @author mrdoob / http://mrdoob.com/
  10739. * @author alteredq / http://alteredqualia.com/
  10740. * @author szimek / https://github.com/szimek/
  10741. */
  10742. THREE.WebGLRenderer = function ( parameters ) {
  10743. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  10744. parameters = parameters || {};
  10745. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  10746. _context = parameters.context !== undefined ? parameters.context : null,
  10747. _width = _canvas.width,
  10748. _height = _canvas.height,
  10749. pixelRatio = 1,
  10750. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  10751. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  10752. _depth = parameters.depth !== undefined ? parameters.depth : true,
  10753. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  10754. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  10755. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  10756. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  10757. _logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false,
  10758. _clearColor = new THREE.Color( 0x000000 ),
  10759. _clearAlpha = 0;
  10760. var lights = [];
  10761. var _webglObjects = {};
  10762. var _webglObjectsImmediate = [];
  10763. var opaqueObjects = [];
  10764. var transparentObjects = [];
  10765. var sprites = [];
  10766. var lensFlares = [];
  10767. // public properties
  10768. this.domElement = _canvas;
  10769. this.context = null;
  10770. // clearing
  10771. this.autoClear = true;
  10772. this.autoClearColor = true;
  10773. this.autoClearDepth = true;
  10774. this.autoClearStencil = true;
  10775. // scene graph
  10776. this.sortObjects = true;
  10777. // physically based shading
  10778. this.gammaFactor = 2.0; // for backwards compatibility
  10779. this.gammaInput = false;
  10780. this.gammaOutput = false;
  10781. // morphs
  10782. this.maxMorphTargets = 8;
  10783. this.maxMorphNormals = 4;
  10784. // flags
  10785. this.autoScaleCubemaps = true;
  10786. // info
  10787. this.info = {
  10788. memory: {
  10789. programs: 0,
  10790. geometries: 0,
  10791. textures: 0
  10792. },
  10793. render: {
  10794. calls: 0,
  10795. vertices: 0,
  10796. faces: 0,
  10797. points: 0
  10798. }
  10799. };
  10800. // internal properties
  10801. var _this = this,
  10802. _programs = [],
  10803. // internal state cache
  10804. _currentProgram = null,
  10805. _currentFramebuffer = null,
  10806. _currentMaterialId = - 1,
  10807. _currentGeometryProgram = '',
  10808. _currentCamera = null,
  10809. _usedTextureUnits = 0,
  10810. _viewportX = 0,
  10811. _viewportY = 0,
  10812. _viewportWidth = _canvas.width,
  10813. _viewportHeight = _canvas.height,
  10814. _currentWidth = 0,
  10815. _currentHeight = 0,
  10816. // frustum
  10817. _frustum = new THREE.Frustum(),
  10818. // camera matrices cache
  10819. _projScreenMatrix = new THREE.Matrix4(),
  10820. _vector3 = new THREE.Vector3(),
  10821. // light arrays cache
  10822. _direction = new THREE.Vector3(),
  10823. _lightsNeedUpdate = true,
  10824. _lights = {
  10825. ambient: [ 0, 0, 0 ],
  10826. directional: { length: 0, colors:[], positions: [] },
  10827. point: { length: 0, colors: [], positions: [], distances: [], decays: [] },
  10828. spot: { length: 0, colors: [], positions: [], distances: [], directions: [], anglesCos: [], exponents: [], decays: [] },
  10829. hemi: { length: 0, skyColors: [], groundColors: [], positions: [] }
  10830. };
  10831. // initialize
  10832. var _gl;
  10833. try {
  10834. var attributes = {
  10835. alpha: _alpha,
  10836. depth: _depth,
  10837. stencil: _stencil,
  10838. antialias: _antialias,
  10839. premultipliedAlpha: _premultipliedAlpha,
  10840. preserveDrawingBuffer: _preserveDrawingBuffer
  10841. };
  10842. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  10843. if ( _gl === null ) {
  10844. if ( _canvas.getContext( 'webgl') !== null ) {
  10845. throw 'Error creating WebGL context with your selected attributes.';
  10846. } else {
  10847. throw 'Error creating WebGL context.';
  10848. }
  10849. }
  10850. _canvas.addEventListener( 'webglcontextlost', function ( event ) {
  10851. event.preventDefault();
  10852. resetGLState();
  10853. setDefaultGLState();
  10854. _webglObjects = {};
  10855. }, false);
  10856. } catch ( error ) {
  10857. THREE.error( 'THREE.WebGLRenderer: ' + error );
  10858. }
  10859. var state = new THREE.WebGLState( _gl, paramThreeToGL );
  10860. if ( _gl.getShaderPrecisionFormat === undefined ) {
  10861. _gl.getShaderPrecisionFormat = function () {
  10862. return {
  10863. 'rangeMin': 1,
  10864. 'rangeMax': 1,
  10865. 'precision': 1
  10866. };
  10867. }
  10868. }
  10869. var extensions = new THREE.WebGLExtensions( _gl );
  10870. var buffers = new THREE.WebGLBuffers( _gl, this.info, extensions, getBufferMaterial );
  10871. extensions.get( 'OES_texture_float' );
  10872. extensions.get( 'OES_texture_float_linear' );
  10873. extensions.get( 'OES_texture_half_float' );
  10874. extensions.get( 'OES_texture_half_float_linear' );
  10875. extensions.get( 'OES_standard_derivatives' );
  10876. if ( _logarithmicDepthBuffer ) {
  10877. extensions.get( 'EXT_frag_depth' );
  10878. }
  10879. //
  10880. var glClearColor = function ( r, g, b, a ) {
  10881. if ( _premultipliedAlpha === true ) {
  10882. r *= a; g *= a; b *= a;
  10883. }
  10884. _gl.clearColor( r, g, b, a );
  10885. };
  10886. var setDefaultGLState = function () {
  10887. _gl.clearColor( 0, 0, 0, 1 );
  10888. _gl.clearDepth( 1 );
  10889. _gl.clearStencil( 0 );
  10890. _gl.enable( _gl.DEPTH_TEST );
  10891. _gl.depthFunc( _gl.LEQUAL );
  10892. _gl.frontFace( _gl.CCW );
  10893. _gl.cullFace( _gl.BACK );
  10894. _gl.enable( _gl.CULL_FACE );
  10895. _gl.enable( _gl.BLEND );
  10896. _gl.blendEquation( _gl.FUNC_ADD );
  10897. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  10898. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  10899. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10900. };
  10901. var resetGLState = function () {
  10902. _currentProgram = null;
  10903. _currentCamera = null;
  10904. _currentGeometryProgram = '';
  10905. _currentMaterialId = - 1;
  10906. _lightsNeedUpdate = true;
  10907. state.reset();
  10908. };
  10909. setDefaultGLState();
  10910. this.context = _gl;
  10911. this.extensions = extensions;
  10912. this.state = state;
  10913. // shadow map
  10914. var shadowMap = new THREE.WebGLShadowMap( this, lights, _webglObjects, _webglObjectsImmediate );
  10915. this.shadowMap = shadowMap;
  10916. // GPU capabilities
  10917. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  10918. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  10919. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  10920. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  10921. var _supportsVertexTextures = _maxVertexTextures > 0;
  10922. var _supportsBoneTextures = _supportsVertexTextures && extensions.get( 'OES_texture_float' );
  10923. //
  10924. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  10925. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  10926. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  10927. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  10928. var getCompressedTextureFormats = ( function () {
  10929. var array;
  10930. return function () {
  10931. if ( array !== undefined ) {
  10932. return array;
  10933. }
  10934. array = [];
  10935. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) || extensions.get( 'WEBGL_compressed_texture_s3tc' ) ) {
  10936. var formats = _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS );
  10937. for ( var i = 0; i < formats.length; i ++ ) {
  10938. array.push( formats[ i ] );
  10939. }
  10940. }
  10941. return array;
  10942. };
  10943. } )();
  10944. // clamp precision to maximum available
  10945. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  10946. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  10947. if ( _precision === 'highp' && ! highpAvailable ) {
  10948. if ( mediumpAvailable ) {
  10949. _precision = 'mediump';
  10950. THREE.warn( 'THREE.WebGLRenderer: highp not supported, using mediump.' );
  10951. } else {
  10952. _precision = 'lowp';
  10953. THREE.warn( 'THREE.WebGLRenderer: highp and mediump not supported, using lowp.' );
  10954. }
  10955. }
  10956. if ( _precision === 'mediump' && ! mediumpAvailable ) {
  10957. _precision = 'lowp';
  10958. THREE.warn( 'THREE.WebGLRenderer: mediump not supported, using lowp.' );
  10959. }
  10960. // Plugins
  10961. var spritePlugin = new THREE.SpritePlugin( this, sprites );
  10962. var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares );
  10963. // API
  10964. this.getContext = function () {
  10965. return _gl;
  10966. };
  10967. this.forceContextLoss = function () {
  10968. extensions.get( 'WEBGL_lose_context' ).loseContext();
  10969. };
  10970. this.supportsVertexTextures = function () {
  10971. return _supportsVertexTextures;
  10972. };
  10973. this.supportsFloatTextures = function () {
  10974. return extensions.get( 'OES_texture_float' );
  10975. };
  10976. this.supportsHalfFloatTextures = function () {
  10977. return extensions.get( 'OES_texture_half_float' );
  10978. };
  10979. this.supportsStandardDerivatives = function () {
  10980. return extensions.get( 'OES_standard_derivatives' );
  10981. };
  10982. this.supportsCompressedTextureS3TC = function () {
  10983. return extensions.get( 'WEBGL_compressed_texture_s3tc' );
  10984. };
  10985. this.supportsCompressedTexturePVRTC = function () {
  10986. return extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  10987. };
  10988. this.supportsBlendMinMax = function () {
  10989. return extensions.get( 'EXT_blend_minmax' );
  10990. };
  10991. this.getMaxAnisotropy = ( function () {
  10992. var value;
  10993. return function () {
  10994. if ( value !== undefined ) {
  10995. return value;
  10996. }
  10997. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  10998. value = extension !== null ? _gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  10999. return value;
  11000. }
  11001. } )();
  11002. this.getPrecision = function () {
  11003. return _precision;
  11004. };
  11005. this.getPixelRatio = function () {
  11006. return pixelRatio;
  11007. };
  11008. this.setPixelRatio = function ( value ) {
  11009. pixelRatio = value;
  11010. };
  11011. this.getSize = function () {
  11012. return {
  11013. width: _width,
  11014. height: _height
  11015. };
  11016. };
  11017. this.setSize = function ( width, height, updateStyle ) {
  11018. _width = width;
  11019. _height = height;
  11020. _canvas.width = width * pixelRatio;
  11021. _canvas.height = height * pixelRatio;
  11022. if ( updateStyle !== false ) {
  11023. _canvas.style.width = width + 'px';
  11024. _canvas.style.height = height + 'px';
  11025. }
  11026. this.setViewport( 0, 0, width, height );
  11027. };
  11028. this.setViewport = function ( x, y, width, height ) {
  11029. _viewportX = x * pixelRatio;
  11030. _viewportY = y * pixelRatio;
  11031. _viewportWidth = width * pixelRatio;
  11032. _viewportHeight = height * pixelRatio;
  11033. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  11034. };
  11035. this.setScissor = function ( x, y, width, height ) {
  11036. _gl.scissor(
  11037. x * pixelRatio,
  11038. y * pixelRatio,
  11039. width * pixelRatio,
  11040. height * pixelRatio
  11041. );
  11042. };
  11043. this.enableScissorTest = function ( enable ) {
  11044. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  11045. };
  11046. // Clearing
  11047. this.getClearColor = function () {
  11048. return _clearColor;
  11049. };
  11050. this.setClearColor = function ( color, alpha ) {
  11051. _clearColor.set( color );
  11052. _clearAlpha = alpha !== undefined ? alpha : 1;
  11053. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11054. };
  11055. this.getClearAlpha = function () {
  11056. return _clearAlpha;
  11057. };
  11058. this.setClearAlpha = function ( alpha ) {
  11059. _clearAlpha = alpha;
  11060. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11061. };
  11062. this.clear = function ( color, depth, stencil ) {
  11063. var bits = 0;
  11064. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11065. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11066. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11067. _gl.clear( bits );
  11068. };
  11069. this.clearColor = function () {
  11070. _gl.clear( _gl.COLOR_BUFFER_BIT );
  11071. };
  11072. this.clearDepth = function () {
  11073. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  11074. };
  11075. this.clearStencil = function () {
  11076. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  11077. };
  11078. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11079. this.setRenderTarget( renderTarget );
  11080. this.clear( color, depth, stencil );
  11081. };
  11082. // Reset
  11083. this.resetGLState = resetGLState;
  11084. // Events
  11085. var onObjectRemoved = function ( event ) {
  11086. var object = event.target;
  11087. object.traverse( function ( child ) {
  11088. child.removeEventListener( 'remove', onObjectRemoved );
  11089. removeObject( child );
  11090. } );
  11091. };
  11092. var onGeometryDispose = function ( event ) {
  11093. var geometry = event.target;
  11094. geometry.removeEventListener( 'dispose', onGeometryDispose );
  11095. deallocateGeometry( geometry );
  11096. };
  11097. var onTextureDispose = function ( event ) {
  11098. var texture = event.target;
  11099. texture.removeEventListener( 'dispose', onTextureDispose );
  11100. deallocateTexture( texture );
  11101. _this.info.memory.textures --;
  11102. };
  11103. var onRenderTargetDispose = function ( event ) {
  11104. var renderTarget = event.target;
  11105. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  11106. deallocateRenderTarget( renderTarget );
  11107. _this.info.memory.textures --;
  11108. };
  11109. var onMaterialDispose = function ( event ) {
  11110. var material = event.target;
  11111. material.removeEventListener( 'dispose', onMaterialDispose );
  11112. deallocateMaterial( material );
  11113. };
  11114. // Buffer deallocation
  11115. var deallocateGeometry = function ( geometry ) {
  11116. delete geometry.__webglInit;
  11117. if ( geometry instanceof THREE.BufferGeometry ) {
  11118. for ( var name in geometry.attributes ) {
  11119. var attribute = geometry.attributes[ name ];
  11120. if ( attribute.buffer !== undefined ) {
  11121. _gl.deleteBuffer( attribute.buffer );
  11122. delete attribute.buffer;
  11123. }
  11124. }
  11125. _this.info.memory.geometries --;
  11126. } else {
  11127. var geometryGroupsList = geometryGroups[ geometry.id ];
  11128. if ( geometryGroupsList !== undefined ) {
  11129. for ( var i = 0, l = geometryGroupsList.length; i < l; i ++ ) {
  11130. var geometryGroup = geometryGroupsList[ i ];
  11131. if ( geometryGroup.numMorphTargets !== undefined ) {
  11132. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11133. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  11134. }
  11135. delete geometryGroup.__webglMorphTargetsBuffers;
  11136. }
  11137. if ( geometryGroup.numMorphNormals !== undefined ) {
  11138. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11139. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  11140. }
  11141. delete geometryGroup.__webglMorphNormalsBuffers;
  11142. }
  11143. buffers.delete( geometryGroup );
  11144. }
  11145. delete geometryGroups[ geometry.id ];
  11146. } else {
  11147. buffers.delete( geometry );
  11148. }
  11149. }
  11150. // TOFIX: Workaround for deleted geometry being currently bound
  11151. _currentGeometryProgram = '';
  11152. };
  11153. var deallocateTexture = function ( texture ) {
  11154. if ( texture.image && texture.image.__webglTextureCube ) {
  11155. // cube texture
  11156. _gl.deleteTexture( texture.image.__webglTextureCube );
  11157. delete texture.image.__webglTextureCube;
  11158. } else {
  11159. // 2D texture
  11160. if ( texture.__webglInit === undefined ) return;
  11161. _gl.deleteTexture( texture.__webglTexture );
  11162. delete texture.__webglTexture;
  11163. delete texture.__webglInit;
  11164. }
  11165. };
  11166. var deallocateRenderTarget = function ( renderTarget ) {
  11167. if ( ! renderTarget || renderTarget.__webglTexture === undefined ) return;
  11168. _gl.deleteTexture( renderTarget.__webglTexture );
  11169. delete renderTarget.__webglTexture;
  11170. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  11171. for ( var i = 0; i < 6; i ++ ) {
  11172. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  11173. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  11174. }
  11175. } else {
  11176. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  11177. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  11178. }
  11179. delete renderTarget.__webglFramebuffer;
  11180. delete renderTarget.__webglRenderbuffer;
  11181. };
  11182. var deallocateMaterial = function ( material ) {
  11183. var program = material.program.program;
  11184. if ( program === undefined ) return;
  11185. material.program = undefined;
  11186. // only deallocate GL program if this was the last use of shared program
  11187. // assumed there is only single copy of any program in the _programs list
  11188. // (that's how it's constructed)
  11189. var i, il, programInfo;
  11190. var deleteProgram = false;
  11191. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11192. programInfo = _programs[ i ];
  11193. if ( programInfo.program === program ) {
  11194. programInfo.usedTimes --;
  11195. if ( programInfo.usedTimes === 0 ) {
  11196. deleteProgram = true;
  11197. }
  11198. break;
  11199. }
  11200. }
  11201. if ( deleteProgram === true ) {
  11202. // avoid using array.splice, this is costlier than creating new array from scratch
  11203. var newPrograms = [];
  11204. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11205. programInfo = _programs[ i ];
  11206. if ( programInfo.program !== program ) {
  11207. newPrograms.push( programInfo );
  11208. }
  11209. }
  11210. _programs = newPrograms;
  11211. _gl.deleteProgram( program );
  11212. _this.info.memory.programs --;
  11213. }
  11214. };
  11215. // Buffer initialization
  11216. function getBufferMaterial( object, geometryGroup ) {
  11217. return object.material instanceof THREE.MeshFaceMaterial
  11218. ? object.material.materials[ geometryGroup.materialIndex ]
  11219. : object.material;
  11220. }
  11221. // Buffer rendering
  11222. this.renderBufferImmediate = function ( object, program, material ) {
  11223. state.initAttributes();
  11224. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  11225. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  11226. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  11227. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  11228. if ( object.hasPositions ) {
  11229. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  11230. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  11231. state.enableAttribute( program.attributes.position );
  11232. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11233. }
  11234. if ( object.hasNormals ) {
  11235. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  11236. if ( material instanceof THREE.MeshPhongMaterial === false &&
  11237. material.shading === THREE.FlatShading ) {
  11238. var nx, ny, nz,
  11239. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  11240. normalArray,
  11241. i, il = object.count * 3;
  11242. for ( i = 0; i < il; i += 9 ) {
  11243. normalArray = object.normalArray;
  11244. nax = normalArray[ i ];
  11245. nay = normalArray[ i + 1 ];
  11246. naz = normalArray[ i + 2 ];
  11247. nbx = normalArray[ i + 3 ];
  11248. nby = normalArray[ i + 4 ];
  11249. nbz = normalArray[ i + 5 ];
  11250. ncx = normalArray[ i + 6 ];
  11251. ncy = normalArray[ i + 7 ];
  11252. ncz = normalArray[ i + 8 ];
  11253. nx = ( nax + nbx + ncx ) / 3;
  11254. ny = ( nay + nby + ncy ) / 3;
  11255. nz = ( naz + nbz + ncz ) / 3;
  11256. normalArray[ i ] = nx;
  11257. normalArray[ i + 1 ] = ny;
  11258. normalArray[ i + 2 ] = nz;
  11259. normalArray[ i + 3 ] = nx;
  11260. normalArray[ i + 4 ] = ny;
  11261. normalArray[ i + 5 ] = nz;
  11262. normalArray[ i + 6 ] = nx;
  11263. normalArray[ i + 7 ] = ny;
  11264. normalArray[ i + 8 ] = nz;
  11265. }
  11266. }
  11267. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  11268. state.enableAttribute( program.attributes.normal );
  11269. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11270. }
  11271. if ( object.hasUvs && material.map ) {
  11272. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  11273. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  11274. state.enableAttribute( program.attributes.uv );
  11275. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11276. }
  11277. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  11278. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  11279. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  11280. state.enableAttribute( program.attributes.color );
  11281. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11282. }
  11283. state.disableUnusedAttributes();
  11284. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  11285. object.count = 0;
  11286. };
  11287. function setupVertexAttributes( material, program, geometry, startIndex ) {
  11288. var geometryAttributes = geometry.attributes;
  11289. var programAttributes = program.attributes;
  11290. var programAttributesKeys = program.attributesKeys;
  11291. for ( var i = 0, l = programAttributesKeys.length; i < l; i ++ ) {
  11292. var key = programAttributesKeys[ i ];
  11293. var programAttribute = programAttributes[ key ];
  11294. if ( programAttribute >= 0 ) {
  11295. var geometryAttribute = geometryAttributes[ key ];
  11296. if ( geometryAttribute !== undefined ) {
  11297. var size = geometryAttribute.itemSize;
  11298. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryAttribute.buffer );
  11299. state.enableAttribute( programAttribute );
  11300. _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, 0, startIndex * size * 4 ); // 4 bytes per Float32
  11301. } else if ( material.defaultAttributeValues !== undefined ) {
  11302. if ( material.defaultAttributeValues[ key ].length === 2 ) {
  11303. _gl.vertexAttrib2fv( programAttribute, material.defaultAttributeValues[ key ] );
  11304. } else if ( material.defaultAttributeValues[ key ].length === 3 ) {
  11305. _gl.vertexAttrib3fv( programAttribute, material.defaultAttributeValues[ key ] );
  11306. }
  11307. }
  11308. }
  11309. }
  11310. state.disableUnusedAttributes();
  11311. }
  11312. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  11313. if ( material.visible === false ) return;
  11314. updateObject( object );
  11315. var program = setProgram( camera, lights, fog, material, object );
  11316. var updateBuffers = false,
  11317. wireframeBit = material.wireframe ? 1 : 0,
  11318. geometryProgram = 'direct_' + geometry.id + '_' + program.id + '_' + wireframeBit;
  11319. if ( geometryProgram !== _currentGeometryProgram ) {
  11320. _currentGeometryProgram = geometryProgram;
  11321. updateBuffers = true;
  11322. }
  11323. if ( updateBuffers ) {
  11324. state.initAttributes();
  11325. }
  11326. // render mesh
  11327. if ( object instanceof THREE.Mesh ) {
  11328. var mode = material.wireframe === true ? _gl.LINES : _gl.TRIANGLES;
  11329. var index = geometry.attributes.index;
  11330. if ( index ) {
  11331. // indexed triangles
  11332. var type, size;
  11333. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  11334. type = _gl.UNSIGNED_INT;
  11335. size = 4;
  11336. } else {
  11337. type = _gl.UNSIGNED_SHORT;
  11338. size = 2;
  11339. }
  11340. var offsets = geometry.offsets;
  11341. if ( offsets.length === 0 ) {
  11342. if ( updateBuffers ) {
  11343. setupVertexAttributes( material, program, geometry, 0 );
  11344. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11345. }
  11346. _gl.drawElements( mode, index.array.length, type, 0 );
  11347. _this.info.render.calls ++;
  11348. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  11349. _this.info.render.faces += index.array.length / 3;
  11350. } else {
  11351. // if there is more than 1 chunk
  11352. // must set attribute pointers to use new offsets for each chunk
  11353. // even if geometry and materials didn't change
  11354. updateBuffers = true;
  11355. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  11356. var startIndex = offsets[ i ].index;
  11357. if ( updateBuffers ) {
  11358. setupVertexAttributes( material, program, geometry, startIndex );
  11359. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11360. }
  11361. // render indexed triangles
  11362. _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size );
  11363. _this.info.render.calls ++;
  11364. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  11365. _this.info.render.faces += offsets[ i ].count / 3;
  11366. }
  11367. }
  11368. } else {
  11369. // non-indexed triangles
  11370. if ( updateBuffers ) {
  11371. setupVertexAttributes( material, program, geometry, 0 );
  11372. }
  11373. var position = geometry.attributes[ 'position' ];
  11374. // render non-indexed triangles
  11375. _gl.drawArrays( mode, 0, position.array.length / position.itemSize );
  11376. _this.info.render.calls ++;
  11377. _this.info.render.vertices += position.array.length / position.itemSize;
  11378. _this.info.render.faces += position.array.length / ( 3 * position.itemSize );
  11379. }
  11380. } else if ( object instanceof THREE.PointCloud ) {
  11381. // render particles
  11382. var mode = _gl.POINTS;
  11383. var index = geometry.attributes.index;
  11384. if ( index ) {
  11385. // indexed points
  11386. var type, size;
  11387. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  11388. type = _gl.UNSIGNED_INT;
  11389. size = 4;
  11390. } else {
  11391. type = _gl.UNSIGNED_SHORT;
  11392. size = 2;
  11393. }
  11394. var offsets = geometry.offsets;
  11395. if ( offsets.length === 0 ) {
  11396. if ( updateBuffers ) {
  11397. setupVertexAttributes( material, program, geometry, 0 );
  11398. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11399. }
  11400. _gl.drawElements( mode, index.array.length, type, 0);
  11401. _this.info.render.calls ++;
  11402. _this.info.render.points += index.array.length;
  11403. } else {
  11404. // if there is more than 1 chunk
  11405. // must set attribute pointers to use new offsets for each chunk
  11406. // even if geometry and materials didn't change
  11407. if ( offsets.length > 1 ) updateBuffers = true;
  11408. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  11409. var startIndex = offsets[ i ].index;
  11410. if ( updateBuffers ) {
  11411. setupVertexAttributes( material, program, geometry, startIndex );
  11412. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11413. }
  11414. // render indexed points
  11415. _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size );
  11416. _this.info.render.calls ++;
  11417. _this.info.render.points += offsets[ i ].count;
  11418. }
  11419. }
  11420. } else {
  11421. // non-indexed points
  11422. if ( updateBuffers ) {
  11423. setupVertexAttributes( material, program, geometry, 0 );
  11424. }
  11425. var position = geometry.attributes.position;
  11426. var offsets = geometry.offsets;
  11427. if ( offsets.length === 0 ) {
  11428. _gl.drawArrays( mode, 0, position.array.length / 3 );
  11429. _this.info.render.calls ++;
  11430. _this.info.render.points += position.array.length / 3;
  11431. } else {
  11432. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  11433. _gl.drawArrays( mode, offsets[ i ].index, offsets[ i ].count );
  11434. _this.info.render.calls ++;
  11435. _this.info.render.points += offsets[ i ].count;
  11436. }
  11437. }
  11438. }
  11439. } else if ( object instanceof THREE.Line ) {
  11440. var mode = ( object.mode === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  11441. state.setLineWidth( material.linewidth * pixelRatio );
  11442. var index = geometry.attributes.index;
  11443. if ( index ) {
  11444. // indexed lines
  11445. var type, size;
  11446. if ( index.array instanceof Uint32Array ) {
  11447. type = _gl.UNSIGNED_INT;
  11448. size = 4;
  11449. } else {
  11450. type = _gl.UNSIGNED_SHORT;
  11451. size = 2;
  11452. }
  11453. var offsets = geometry.offsets;
  11454. if ( offsets.length === 0 ) {
  11455. if ( updateBuffers ) {
  11456. setupVertexAttributes( material, program, geometry, 0 );
  11457. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11458. }
  11459. _gl.drawElements( mode, index.array.length, type, 0 ); // 2 bytes per Uint16Array
  11460. _this.info.render.calls ++;
  11461. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  11462. } else {
  11463. // if there is more than 1 chunk
  11464. // must set attribute pointers to use new offsets for each chunk
  11465. // even if geometry and materials didn't change
  11466. if ( offsets.length > 1 ) updateBuffers = true;
  11467. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  11468. var startIndex = offsets[ i ].index;
  11469. if ( updateBuffers ) {
  11470. setupVertexAttributes( material, program, geometry, startIndex );
  11471. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11472. }
  11473. // render indexed lines
  11474. _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size ); // 2 bytes per Uint16Array
  11475. _this.info.render.calls ++;
  11476. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  11477. }
  11478. }
  11479. } else {
  11480. // non-indexed lines
  11481. if ( updateBuffers ) {
  11482. setupVertexAttributes( material, program, geometry, 0 );
  11483. }
  11484. var position = geometry.attributes.position;
  11485. var offsets = geometry.offsets;
  11486. if ( offsets.length === 0 ) {
  11487. _gl.drawArrays( mode, 0, position.array.length / 3 );
  11488. _this.info.render.calls ++;
  11489. _this.info.render.vertices += position.array.length / 3;
  11490. } else {
  11491. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  11492. _gl.drawArrays( mode, offsets[ i ].index, offsets[ i ].count );
  11493. _this.info.render.calls ++;
  11494. _this.info.render.vertices += offsets[ i ].count;
  11495. }
  11496. }
  11497. }
  11498. }
  11499. };
  11500. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  11501. if ( material.visible === false ) return;
  11502. updateObject( object );
  11503. var program = setProgram( camera, lights, fog, material, object );
  11504. var attributes = program.attributes;
  11505. var updateBuffers = false,
  11506. wireframeBit = material.wireframe ? 1 : 0,
  11507. geometryProgram = geometryGroup.id + '_' + program.id + '_' + wireframeBit;
  11508. if ( geometryProgram !== _currentGeometryProgram ) {
  11509. _currentGeometryProgram = geometryProgram;
  11510. updateBuffers = true;
  11511. }
  11512. if ( updateBuffers ) {
  11513. state.initAttributes();
  11514. }
  11515. // vertices
  11516. if ( ! material.morphTargets && attributes.position >= 0 ) {
  11517. if ( updateBuffers ) {
  11518. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11519. state.enableAttribute( attributes.position );
  11520. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11521. }
  11522. } else {
  11523. if ( object.morphTargetBase ) {
  11524. setupMorphTargets( material, geometryGroup, object );
  11525. }
  11526. }
  11527. if ( updateBuffers ) {
  11528. // custom attributes
  11529. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  11530. if ( geometryGroup.__webglCustomAttributesList ) {
  11531. for ( var i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  11532. var attribute = geometryGroup.__webglCustomAttributesList[ i ];
  11533. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  11534. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  11535. state.enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  11536. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  11537. }
  11538. }
  11539. }
  11540. // colors
  11541. if ( attributes.color >= 0 ) {
  11542. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  11543. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  11544. state.enableAttribute( attributes.color );
  11545. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11546. } else if ( material.defaultAttributeValues !== undefined ) {
  11547. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  11548. }
  11549. }
  11550. // normals
  11551. if ( attributes.normal >= 0 ) {
  11552. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  11553. state.enableAttribute( attributes.normal );
  11554. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11555. }
  11556. // tangents
  11557. if ( attributes.tangent >= 0 ) {
  11558. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  11559. state.enableAttribute( attributes.tangent );
  11560. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  11561. }
  11562. // uvs
  11563. if ( attributes.uv >= 0 ) {
  11564. if ( object.geometry.faceVertexUvs[ 0 ] ) {
  11565. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  11566. state.enableAttribute( attributes.uv );
  11567. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11568. } else if ( material.defaultAttributeValues !== undefined ) {
  11569. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  11570. }
  11571. }
  11572. if ( attributes.uv2 >= 0 ) {
  11573. if ( object.geometry.faceVertexUvs[ 1 ] ) {
  11574. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  11575. state.enableAttribute( attributes.uv2 );
  11576. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  11577. } else if ( material.defaultAttributeValues !== undefined ) {
  11578. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  11579. }
  11580. }
  11581. if ( material.skinning &&
  11582. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  11583. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  11584. state.enableAttribute( attributes.skinIndex );
  11585. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  11586. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  11587. state.enableAttribute( attributes.skinWeight );
  11588. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  11589. }
  11590. // line distances
  11591. if ( attributes.lineDistance >= 0 ) {
  11592. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  11593. state.enableAttribute( attributes.lineDistance );
  11594. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  11595. }
  11596. }
  11597. state.disableUnusedAttributes();
  11598. // render mesh
  11599. if ( object instanceof THREE.Mesh ) {
  11600. var type = geometryGroup.__typeArray === Uint32Array ? _gl.UNSIGNED_INT : _gl.UNSIGNED_SHORT;
  11601. // wireframe
  11602. if ( material.wireframe ) {
  11603. state.setLineWidth( material.wireframeLinewidth * pixelRatio );
  11604. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  11605. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, type, 0 );
  11606. // triangles
  11607. } else {
  11608. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  11609. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, type, 0 );
  11610. }
  11611. _this.info.render.calls ++;
  11612. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  11613. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  11614. // render lines
  11615. } else if ( object instanceof THREE.Line ) {
  11616. var mode = ( object.mode === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  11617. state.setLineWidth( material.linewidth * pixelRatio );
  11618. _gl.drawArrays( mode, 0, geometryGroup.__webglLineCount );
  11619. _this.info.render.calls ++;
  11620. // render particles
  11621. } else if ( object instanceof THREE.PointCloud ) {
  11622. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  11623. _this.info.render.calls ++;
  11624. _this.info.render.points += geometryGroup.__webglParticleCount;
  11625. }
  11626. };
  11627. function setupMorphTargets ( material, geometryGroup, object ) {
  11628. // set base
  11629. var attributes = material.program.attributes;
  11630. if ( object.morphTargetBase !== - 1 && attributes.position >= 0 ) {
  11631. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  11632. state.enableAttribute( attributes.position );
  11633. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11634. } else if ( attributes.position >= 0 ) {
  11635. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11636. state.enableAttribute( attributes.position );
  11637. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11638. }
  11639. if ( object.morphTargetForcedOrder.length ) {
  11640. // set forced order
  11641. var m = 0;
  11642. var order = object.morphTargetForcedOrder;
  11643. var influences = object.morphTargetInfluences;
  11644. var attribute;
  11645. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  11646. attribute = attributes[ 'morphTarget' + m ];
  11647. if ( attribute >= 0 ) {
  11648. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  11649. state.enableAttribute( attribute );
  11650. _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 );
  11651. }
  11652. attribute = attributes[ 'morphNormal' + m ];
  11653. if ( attribute >= 0 && material.morphNormals ) {
  11654. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  11655. state.enableAttribute( attribute );
  11656. _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 );
  11657. }
  11658. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  11659. m ++;
  11660. }
  11661. } else {
  11662. // find the most influencing
  11663. var activeInfluenceIndices = [];
  11664. var influences = object.morphTargetInfluences;
  11665. var morphTargets = object.geometry.morphTargets;
  11666. if ( influences.length > morphTargets.length ) {
  11667. THREE.warn( 'THREE.WebGLRenderer: Influences array is bigger than morphTargets array.' );
  11668. influences.length = morphTargets.length;
  11669. }
  11670. for ( var i = 0, il = influences.length; i < il; i ++ ) {
  11671. var influence = influences[ i ];
  11672. activeInfluenceIndices.push( [ influence, i ] );
  11673. }
  11674. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  11675. activeInfluenceIndices.sort( numericalSort );
  11676. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  11677. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  11678. activeInfluenceIndices.sort( numericalSort );
  11679. } else if ( activeInfluenceIndices.length === 0 ) {
  11680. activeInfluenceIndices.push( [ 0, 0 ] );
  11681. }
  11682. var attribute;
  11683. for ( var m = 0, ml = material.numSupportedMorphTargets; m < ml; m ++ ) {
  11684. if ( activeInfluenceIndices[ m ] ) {
  11685. var influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  11686. attribute = attributes[ 'morphTarget' + m ];
  11687. if ( attribute >= 0 ) {
  11688. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  11689. state.enableAttribute( attribute );
  11690. _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 );
  11691. }
  11692. attribute = attributes[ 'morphNormal' + m ];
  11693. if ( attribute >= 0 && material.morphNormals ) {
  11694. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  11695. state.enableAttribute( attribute );
  11696. _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 );
  11697. }
  11698. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  11699. } else {
  11700. /*
  11701. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11702. if ( material.morphNormals ) {
  11703. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11704. }
  11705. */
  11706. object.__webglMorphTargetInfluences[ m ] = 0;
  11707. }
  11708. }
  11709. }
  11710. // load updated influences uniform
  11711. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  11712. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  11713. }
  11714. }
  11715. // Sorting
  11716. function painterSortStable ( a, b ) {
  11717. if ( a.object.renderOrder !== b.object.renderOrder ) {
  11718. return a.object.renderOrder - b.object.renderOrder;
  11719. } else if ( a.material.id !== b.material.id ) {
  11720. return a.material.id - b.material.id;
  11721. } else if ( a.z !== b.z ) {
  11722. return a.z - b.z;
  11723. } else {
  11724. return a.id - b.id;
  11725. }
  11726. }
  11727. function reversePainterSortStable ( a, b ) {
  11728. if ( a.object.renderOrder !== b.object.renderOrder ) {
  11729. return a.object.renderOrder - b.object.renderOrder;
  11730. } if ( a.z !== b.z ) {
  11731. return b.z - a.z;
  11732. } else {
  11733. return a.id - b.id;
  11734. }
  11735. }
  11736. function numericalSort ( a, b ) {
  11737. return b[ 0 ] - a[ 0 ];
  11738. }
  11739. // Rendering
  11740. this.render = function ( scene, camera, renderTarget, forceClear ) {
  11741. if ( camera instanceof THREE.Camera === false ) {
  11742. THREE.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  11743. return;
  11744. }
  11745. var fog = scene.fog;
  11746. // reset caching for this frame
  11747. _currentGeometryProgram = '';
  11748. _currentMaterialId = - 1;
  11749. _currentCamera = null;
  11750. _lightsNeedUpdate = true;
  11751. // update scene graph
  11752. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  11753. // update camera matrices and frustum
  11754. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  11755. // update Skeleton objects
  11756. scene.traverse( function ( object ) {
  11757. if ( object instanceof THREE.SkinnedMesh ) {
  11758. object.skeleton.update();
  11759. }
  11760. } );
  11761. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  11762. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  11763. _frustum.setFromMatrix( _projScreenMatrix );
  11764. lights.length = 0;
  11765. opaqueObjects.length = 0;
  11766. transparentObjects.length = 0;
  11767. sprites.length = 0;
  11768. lensFlares.length = 0;
  11769. projectObject( scene );
  11770. if ( _this.sortObjects === true ) {
  11771. opaqueObjects.sort( painterSortStable );
  11772. transparentObjects.sort( reversePainterSortStable );
  11773. }
  11774. //
  11775. shadowMap.render( scene, camera );
  11776. //
  11777. _this.info.render.calls = 0;
  11778. _this.info.render.vertices = 0;
  11779. _this.info.render.faces = 0;
  11780. _this.info.render.points = 0;
  11781. this.setRenderTarget( renderTarget );
  11782. if ( this.autoClear || forceClear ) {
  11783. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  11784. }
  11785. // set matrices for immediate objects
  11786. for ( var i = 0, il = _webglObjectsImmediate.length; i < il; i ++ ) {
  11787. var webglObject = _webglObjectsImmediate[ i ];
  11788. var object = webglObject.object;
  11789. if ( object.visible ) {
  11790. setupMatrices( object, camera );
  11791. unrollImmediateBufferMaterial( webglObject );
  11792. }
  11793. }
  11794. if ( scene.overrideMaterial ) {
  11795. var overrideMaterial = scene.overrideMaterial;
  11796. setMaterial( overrideMaterial );
  11797. renderObjects( opaqueObjects, camera, lights, fog, overrideMaterial );
  11798. renderObjects( transparentObjects, camera, lights, fog, overrideMaterial );
  11799. renderObjectsImmediate( _webglObjectsImmediate, '', camera, lights, fog, overrideMaterial );
  11800. } else {
  11801. // opaque pass (front-to-back order)
  11802. state.setBlending( THREE.NoBlending );
  11803. renderObjects( opaqueObjects, camera, lights, fog, null );
  11804. renderObjectsImmediate( _webglObjectsImmediate, 'opaque', camera, lights, fog, null );
  11805. // transparent pass (back-to-front order)
  11806. renderObjects( transparentObjects, camera, lights, fog, null );
  11807. renderObjectsImmediate( _webglObjectsImmediate, 'transparent', camera, lights, fog, null );
  11808. }
  11809. // custom render plugins (post pass)
  11810. spritePlugin.render( scene, camera );
  11811. lensFlarePlugin.render( scene, camera, _currentWidth, _currentHeight );
  11812. // Generate mipmap if we're using any kind of mipmap filtering
  11813. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  11814. updateRenderTargetMipmap( renderTarget );
  11815. }
  11816. // Ensure depth buffer writing is enabled so it can be cleared on next render
  11817. state.setDepthTest( true );
  11818. state.setDepthWrite( true );
  11819. state.setColorWrite( true );
  11820. // _gl.finish();
  11821. };
  11822. function projectObject( object ) {
  11823. if ( object.visible === false ) return;
  11824. if ( object instanceof THREE.Scene || object instanceof THREE.Group ) {
  11825. // skip
  11826. } else {
  11827. initObject( object );
  11828. if ( object instanceof THREE.Light ) {
  11829. lights.push( object );
  11830. } else if ( object instanceof THREE.Sprite ) {
  11831. sprites.push( object );
  11832. } else if ( object instanceof THREE.LensFlare ) {
  11833. lensFlares.push( object );
  11834. } else {
  11835. var webglObjects = _webglObjects[ object.id ];
  11836. if ( webglObjects && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  11837. for ( var i = 0, l = webglObjects.length; i < l; i ++ ) {
  11838. var webglObject = webglObjects[ i ];
  11839. unrollBufferMaterial( webglObject );
  11840. webglObject.render = true;
  11841. if ( _this.sortObjects === true ) {
  11842. _vector3.setFromMatrixPosition( object.matrixWorld );
  11843. _vector3.applyProjection( _projScreenMatrix );
  11844. webglObject.z = _vector3.z;
  11845. }
  11846. }
  11847. }
  11848. }
  11849. }
  11850. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  11851. projectObject( object.children[ i ] );
  11852. }
  11853. }
  11854. function renderObjects( renderList, camera, lights, fog, overrideMaterial ) {
  11855. var material;
  11856. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  11857. var webglObject = renderList[ i ];
  11858. var object = webglObject.object;
  11859. var buffer = webglObject.buffer;
  11860. setupMatrices( object, camera );
  11861. if ( overrideMaterial ) {
  11862. material = overrideMaterial;
  11863. } else {
  11864. material = webglObject.material;
  11865. if ( ! material ) continue;
  11866. setMaterial( material );
  11867. }
  11868. _this.setMaterialFaces( material );
  11869. if ( buffer instanceof THREE.BufferGeometry ) {
  11870. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  11871. } else {
  11872. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  11873. }
  11874. }
  11875. }
  11876. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, overrideMaterial ) {
  11877. var material;
  11878. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  11879. var webglObject = renderList[ i ];
  11880. var object = webglObject.object;
  11881. if ( object.visible ) {
  11882. if ( overrideMaterial ) {
  11883. material = overrideMaterial;
  11884. } else {
  11885. material = webglObject[ materialType ];
  11886. if ( ! material ) continue;
  11887. setMaterial( material );
  11888. }
  11889. _this.renderImmediateObject( camera, lights, fog, material, object );
  11890. }
  11891. }
  11892. }
  11893. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  11894. var program = setProgram( camera, lights, fog, material, object );
  11895. _currentGeometryProgram = '';
  11896. _this.setMaterialFaces( material );
  11897. if ( object.immediateRenderCallback ) {
  11898. object.immediateRenderCallback( program, _gl, _frustum );
  11899. } else {
  11900. object.render( function ( object ) { _this.renderBufferImmediate( object, program, material ); } );
  11901. }
  11902. };
  11903. function unrollImmediateBufferMaterial ( globject ) {
  11904. var object = globject.object,
  11905. material = object.material;
  11906. if ( material.transparent ) {
  11907. globject.transparent = material;
  11908. globject.opaque = null;
  11909. } else {
  11910. globject.opaque = material;
  11911. globject.transparent = null;
  11912. }
  11913. }
  11914. function unrollBufferMaterial ( globject ) {
  11915. var object = globject.object;
  11916. var buffer = globject.buffer;
  11917. var geometry = object.geometry;
  11918. var material = object.material;
  11919. if ( material instanceof THREE.MeshFaceMaterial ) {
  11920. var materialIndex = geometry instanceof THREE.BufferGeometry ? 0 : buffer.materialIndex;
  11921. material = material.materials[ materialIndex ];
  11922. globject.material = material;
  11923. if ( material.transparent ) {
  11924. transparentObjects.push( globject );
  11925. } else {
  11926. opaqueObjects.push( globject );
  11927. }
  11928. } else if ( material ) {
  11929. globject.material = material;
  11930. if ( material.transparent ) {
  11931. transparentObjects.push( globject );
  11932. } else {
  11933. opaqueObjects.push( globject );
  11934. }
  11935. }
  11936. }
  11937. function initObject( object ) {
  11938. if ( object.__webglInit === undefined ) {
  11939. object.__webglInit = true;
  11940. object._modelViewMatrix = new THREE.Matrix4();
  11941. object._normalMatrix = new THREE.Matrix3();
  11942. object.addEventListener( 'removed', onObjectRemoved );
  11943. }
  11944. var geometry = object.geometry;
  11945. if ( geometry === undefined ) {
  11946. // ImmediateRenderObject
  11947. } else if ( geometry.__webglInit === undefined ) {
  11948. geometry.__webglInit = true;
  11949. geometry.addEventListener( 'dispose', onGeometryDispose );
  11950. if ( geometry instanceof THREE.BufferGeometry ) {
  11951. _this.info.memory.geometries ++;
  11952. } else if ( object instanceof THREE.Mesh ) {
  11953. initGeometryGroups( object, geometry );
  11954. } else if ( object instanceof THREE.Line ) {
  11955. buffers.initLineBuffers( geometry, object );
  11956. } else if ( object instanceof THREE.PointCloud ) {
  11957. buffers.initPointCloudBuffers( geometry, object );
  11958. }
  11959. }
  11960. if ( object.__webglActive === undefined) {
  11961. object.__webglActive = true;
  11962. if ( object instanceof THREE.Mesh ) {
  11963. if ( geometry instanceof THREE.BufferGeometry ) {
  11964. addBuffer( _webglObjects, geometry, object );
  11965. } else if ( geometry instanceof THREE.Geometry ) {
  11966. var geometryGroupsList = geometryGroups[ geometry.id ];
  11967. for ( var i = 0,l = geometryGroupsList.length; i < l; i ++ ) {
  11968. addBuffer( _webglObjects, geometryGroupsList[ i ], object );
  11969. }
  11970. }
  11971. } else if ( object instanceof THREE.Line || object instanceof THREE.PointCloud ) {
  11972. addBuffer( _webglObjects, geometry, object );
  11973. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  11974. addBufferImmediate( _webglObjectsImmediate, object );
  11975. }
  11976. }
  11977. }
  11978. // Geometry splitting
  11979. var geometryGroups = {};
  11980. var geometryGroupCounter = 0;
  11981. function makeGroups( geometry, usesFaceMaterial ) {
  11982. var maxVerticesInGroup = extensions.get( 'OES_element_index_uint' ) ? 4294967296 : 65535;
  11983. var groupHash, hash_map = {};
  11984. var numMorphTargets = geometry.morphTargets.length;
  11985. var numMorphNormals = geometry.morphNormals.length;
  11986. var group;
  11987. var groups = {};
  11988. var groupsList = [];
  11989. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  11990. var face = geometry.faces[ f ];
  11991. var materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  11992. if ( ! ( materialIndex in hash_map ) ) {
  11993. hash_map[ materialIndex ] = { hash: materialIndex, counter: 0 };
  11994. }
  11995. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  11996. if ( ! ( groupHash in groups ) ) {
  11997. group = {
  11998. id: geometryGroupCounter ++,
  11999. faces3: [],
  12000. materialIndex: materialIndex,
  12001. vertices: 0,
  12002. numMorphTargets: numMorphTargets,
  12003. numMorphNormals: numMorphNormals
  12004. };
  12005. groups[ groupHash ] = group;
  12006. groupsList.push( group );
  12007. }
  12008. if ( groups[ groupHash ].vertices + 3 > maxVerticesInGroup ) {
  12009. hash_map[ materialIndex ].counter += 1;
  12010. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  12011. if ( ! ( groupHash in groups ) ) {
  12012. group = {
  12013. id: geometryGroupCounter ++,
  12014. faces3: [],
  12015. materialIndex: materialIndex,
  12016. vertices: 0,
  12017. numMorphTargets: numMorphTargets,
  12018. numMorphNormals: numMorphNormals
  12019. };
  12020. groups[ groupHash ] = group;
  12021. groupsList.push( group );
  12022. }
  12023. }
  12024. groups[ groupHash ].faces3.push( f );
  12025. groups[ groupHash ].vertices += 3;
  12026. }
  12027. return groupsList;
  12028. }
  12029. function initGeometryGroups( object, geometry ) {
  12030. var material = object.material, addBuffers = false;
  12031. if ( geometryGroups[ geometry.id ] === undefined || geometry.groupsNeedUpdate === true ) {
  12032. delete _webglObjects[ object.id ];
  12033. geometryGroups[ geometry.id ] = makeGroups( geometry, material instanceof THREE.MeshFaceMaterial );
  12034. geometry.groupsNeedUpdate = false;
  12035. }
  12036. var geometryGroupsList = geometryGroups[ geometry.id ];
  12037. // create separate VBOs per geometry chunk
  12038. for ( var i = 0, il = geometryGroupsList.length; i < il; i ++ ) {
  12039. var geometryGroup = geometryGroupsList[ i ];
  12040. // initialise VBO on the first access
  12041. if ( geometryGroup.__webglVertexBuffer === undefined ) {
  12042. buffers.initMeshBuffers( geometryGroup, object );
  12043. geometry.verticesNeedUpdate = true;
  12044. geometry.morphTargetsNeedUpdate = true;
  12045. geometry.elementsNeedUpdate = true;
  12046. geometry.uvsNeedUpdate = true;
  12047. geometry.normalsNeedUpdate = true;
  12048. geometry.tangentsNeedUpdate = true;
  12049. geometry.colorsNeedUpdate = true;
  12050. addBuffers = true;
  12051. } else {
  12052. addBuffers = false;
  12053. }
  12054. if ( addBuffers || object.__webglActive === undefined ) {
  12055. addBuffer( _webglObjects, geometryGroup, object );
  12056. }
  12057. }
  12058. object.__webglActive = true;
  12059. }
  12060. function addBuffer( objlist, buffer, object ) {
  12061. var id = object.id;
  12062. objlist[id] = objlist[id] || [];
  12063. objlist[id].push(
  12064. {
  12065. id: id,
  12066. buffer: buffer,
  12067. object: object,
  12068. material: null,
  12069. z: 0
  12070. }
  12071. );
  12072. };
  12073. function addBufferImmediate( objlist, object ) {
  12074. objlist.push(
  12075. {
  12076. id: null,
  12077. object: object,
  12078. opaque: null,
  12079. transparent: null,
  12080. z: 0
  12081. }
  12082. );
  12083. };
  12084. // Objects updates
  12085. function updateObject( object ) {
  12086. var geometry = object.geometry;
  12087. if ( geometry instanceof THREE.BufferGeometry ) {
  12088. var attributes = geometry.attributes;
  12089. var attributesKeys = geometry.attributesKeys;
  12090. for ( var i = 0, l = attributesKeys.length; i < l; i ++ ) {
  12091. var key = attributesKeys[ i ];
  12092. var attribute = attributes[ key ];
  12093. var bufferType = ( key === 'index' ) ? _gl.ELEMENT_ARRAY_BUFFER : _gl.ARRAY_BUFFER;
  12094. if ( attribute.buffer === undefined ) {
  12095. attribute.buffer = _gl.createBuffer();
  12096. _gl.bindBuffer( bufferType, attribute.buffer );
  12097. _gl.bufferData( bufferType, attribute.array, ( attribute instanceof THREE.DynamicBufferAttribute ) ? _gl.DYNAMIC_DRAW : _gl.STATIC_DRAW );
  12098. attribute.needsUpdate = false;
  12099. } else if ( attribute.needsUpdate === true ) {
  12100. _gl.bindBuffer( bufferType, attribute.buffer );
  12101. if ( attribute.updateRange === undefined || attribute.updateRange.count === -1 ) { // Not using update ranges
  12102. _gl.bufferSubData( bufferType, 0, attribute.array );
  12103. } else if ( attribute.updateRange.count === 0 ) {
  12104. 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.' );
  12105. } else {
  12106. _gl.bufferSubData( bufferType, attribute.updateRange.offset * attribute.array.BYTES_PER_ELEMENT,
  12107. attribute.array.subarray( attribute.updateRange.offset, attribute.updateRange.offset + attribute.updateRange.count ) );
  12108. attribute.updateRange.count = 0; // reset range
  12109. }
  12110. attribute.needsUpdate = false;
  12111. }
  12112. }
  12113. } else if ( object instanceof THREE.Mesh ) {
  12114. // check all geometry groups
  12115. if ( geometry.groupsNeedUpdate === true ) {
  12116. initGeometryGroups( object, geometry );
  12117. }
  12118. var geometryGroupsList = geometryGroups[ geometry.id ];
  12119. for ( var i = 0, il = geometryGroupsList.length; i < il; i ++ ) {
  12120. var geometryGroup = geometryGroupsList[ i ];
  12121. var material = getBufferMaterial( object, geometryGroup );
  12122. var customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12123. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  12124. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  12125. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  12126. buffers.setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, ! geometry.dynamic, material );
  12127. }
  12128. }
  12129. geometry.verticesNeedUpdate = false;
  12130. geometry.morphTargetsNeedUpdate = false;
  12131. geometry.elementsNeedUpdate = false;
  12132. geometry.uvsNeedUpdate = false;
  12133. geometry.normalsNeedUpdate = false;
  12134. geometry.colorsNeedUpdate = false;
  12135. geometry.tangentsNeedUpdate = false;
  12136. material.attributes && clearCustomAttributes( material );
  12137. } else if ( object instanceof THREE.Line ) {
  12138. var material = getBufferMaterial( object, geometry );
  12139. var customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12140. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  12141. buffers.setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  12142. }
  12143. geometry.verticesNeedUpdate = false;
  12144. geometry.colorsNeedUpdate = false;
  12145. geometry.lineDistancesNeedUpdate = false;
  12146. material.attributes && clearCustomAttributes( material );
  12147. } else if ( object instanceof THREE.PointCloud ) {
  12148. var material = getBufferMaterial( object, geometry );
  12149. var customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12150. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || customAttributesDirty ) {
  12151. buffers.setPointCloudBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  12152. }
  12153. geometry.verticesNeedUpdate = false;
  12154. geometry.colorsNeedUpdate = false;
  12155. material.attributes && clearCustomAttributes( material );
  12156. }
  12157. }
  12158. // Objects updates - custom attributes check
  12159. function areCustomAttributesDirty( material ) {
  12160. for ( var name in material.attributes ) {
  12161. if ( material.attributes[ name ].needsUpdate ) return true;
  12162. }
  12163. return false;
  12164. }
  12165. function clearCustomAttributes( material ) {
  12166. for ( var name in material.attributes ) {
  12167. material.attributes[ name ].needsUpdate = false;
  12168. }
  12169. }
  12170. // Objects removal
  12171. function removeObject( object ) {
  12172. if ( object instanceof THREE.Mesh ||
  12173. object instanceof THREE.PointCloud ||
  12174. object instanceof THREE.Line ) {
  12175. delete _webglObjects[ object.id ];
  12176. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12177. removeInstances( _webglObjectsImmediate, object );
  12178. }
  12179. delete object.__webglInit;
  12180. delete object._modelViewMatrix;
  12181. delete object._normalMatrix;
  12182. delete object.__webglActive;
  12183. }
  12184. function removeInstances( objlist, object ) {
  12185. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  12186. if ( objlist[ o ].object === object ) {
  12187. objlist.splice( o, 1 );
  12188. }
  12189. }
  12190. }
  12191. // Materials
  12192. var shaderIDs = {
  12193. MeshDepthMaterial: 'depth',
  12194. MeshNormalMaterial: 'normal',
  12195. MeshBasicMaterial: 'basic',
  12196. MeshLambertMaterial: 'lambert',
  12197. MeshPhongMaterial: 'phong',
  12198. LineBasicMaterial: 'basic',
  12199. LineDashedMaterial: 'dashed',
  12200. PointCloudMaterial: 'particle_basic'
  12201. };
  12202. function initMaterial( material, lights, fog, object ) {
  12203. material.addEventListener( 'dispose', onMaterialDispose );
  12204. var shaderID = shaderIDs[ material.type ];
  12205. if ( shaderID ) {
  12206. var shader = THREE.ShaderLib[ shaderID ];
  12207. material.__webglShader = {
  12208. uniforms: THREE.UniformsUtils.clone( shader.uniforms ),
  12209. vertexShader: shader.vertexShader,
  12210. fragmentShader: shader.fragmentShader
  12211. }
  12212. } else {
  12213. material.__webglShader = {
  12214. uniforms: material.uniforms,
  12215. vertexShader: material.vertexShader,
  12216. fragmentShader: material.fragmentShader
  12217. }
  12218. }
  12219. // heuristics to create shader parameters according to lights in the scene
  12220. // (not to blow over maxLights budget)
  12221. var maxLightCount = allocateLights( lights );
  12222. var maxShadows = allocateShadows( lights );
  12223. var maxBones = allocateBones( object );
  12224. var parameters = {
  12225. precision: _precision,
  12226. supportsVertexTextures: _supportsVertexTextures,
  12227. map: !! material.map,
  12228. envMap: !! material.envMap,
  12229. envMapMode: material.envMap && material.envMap.mapping,
  12230. lightMap: !! material.lightMap,
  12231. aoMap: !! material.aoMap,
  12232. bumpMap: !! material.bumpMap,
  12233. normalMap: !! material.normalMap,
  12234. specularMap: !! material.specularMap,
  12235. alphaMap: !! material.alphaMap,
  12236. combine: material.combine,
  12237. vertexColors: material.vertexColors,
  12238. fog: fog,
  12239. useFog: material.fog,
  12240. fogExp: fog instanceof THREE.FogExp2,
  12241. flatShading: material.shading === THREE.FlatShading,
  12242. sizeAttenuation: material.sizeAttenuation,
  12243. logarithmicDepthBuffer: _logarithmicDepthBuffer,
  12244. skinning: material.skinning,
  12245. maxBones: maxBones,
  12246. useVertexTexture: _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  12247. morphTargets: material.morphTargets,
  12248. morphNormals: material.morphNormals,
  12249. maxMorphTargets: _this.maxMorphTargets,
  12250. maxMorphNormals: _this.maxMorphNormals,
  12251. maxDirLights: maxLightCount.directional,
  12252. maxPointLights: maxLightCount.point,
  12253. maxSpotLights: maxLightCount.spot,
  12254. maxHemiLights: maxLightCount.hemi,
  12255. maxShadows: maxShadows,
  12256. shadowMapEnabled: shadowMap.enabled && object.receiveShadow && maxShadows > 0,
  12257. shadowMapType: shadowMap.type,
  12258. shadowMapDebug: shadowMap.debug,
  12259. shadowMapCascade: shadowMap.cascade,
  12260. alphaTest: material.alphaTest,
  12261. metal: material.metal,
  12262. wrapAround: material.wrapAround,
  12263. doubleSided: material.side === THREE.DoubleSide,
  12264. flipSided: material.side === THREE.BackSide
  12265. };
  12266. // Generate code
  12267. var chunks = [];
  12268. if ( shaderID ) {
  12269. chunks.push( shaderID );
  12270. } else {
  12271. chunks.push( material.fragmentShader );
  12272. chunks.push( material.vertexShader );
  12273. }
  12274. if ( material.defines !== undefined ) {
  12275. for ( var name in material.defines ) {
  12276. chunks.push( name );
  12277. chunks.push( material.defines[ name ] );
  12278. }
  12279. }
  12280. for ( var name in parameters ) {
  12281. chunks.push( name );
  12282. chunks.push( parameters[ name ] );
  12283. }
  12284. var code = chunks.join();
  12285. var program;
  12286. // Check if code has been already compiled
  12287. for ( var p = 0, pl = _programs.length; p < pl; p ++ ) {
  12288. var programInfo = _programs[ p ];
  12289. if ( programInfo.code === code ) {
  12290. program = programInfo;
  12291. program.usedTimes ++;
  12292. break;
  12293. }
  12294. }
  12295. if ( program === undefined ) {
  12296. program = new THREE.WebGLProgram( _this, code, material, parameters );
  12297. _programs.push( program );
  12298. _this.info.memory.programs = _programs.length;
  12299. }
  12300. material.program = program;
  12301. var attributes = program.attributes;
  12302. if ( material.morphTargets ) {
  12303. material.numSupportedMorphTargets = 0;
  12304. var id, base = 'morphTarget';
  12305. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  12306. id = base + i;
  12307. if ( attributes[ id ] >= 0 ) {
  12308. material.numSupportedMorphTargets ++;
  12309. }
  12310. }
  12311. }
  12312. if ( material.morphNormals ) {
  12313. material.numSupportedMorphNormals = 0;
  12314. var id, base = 'morphNormal';
  12315. for ( i = 0; i < _this.maxMorphNormals; i ++ ) {
  12316. id = base + i;
  12317. if ( attributes[ id ] >= 0 ) {
  12318. material.numSupportedMorphNormals ++;
  12319. }
  12320. }
  12321. }
  12322. material.uniformsList = [];
  12323. for ( var u in material.__webglShader.uniforms ) {
  12324. var location = material.program.uniforms[ u ];
  12325. if ( location ) {
  12326. material.uniformsList.push( [ material.__webglShader.uniforms[ u ], location ] );
  12327. }
  12328. }
  12329. }
  12330. function setMaterial( material ) {
  12331. if ( material.transparent === true ) {
  12332. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha );
  12333. } else {
  12334. state.setBlending( THREE.NoBlending );
  12335. }
  12336. state.setDepthTest( material.depthTest );
  12337. state.setDepthWrite( material.depthWrite );
  12338. state.setColorWrite( material.colorWrite );
  12339. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12340. }
  12341. function setProgram( camera, lights, fog, material, object ) {
  12342. _usedTextureUnits = 0;
  12343. if ( material.needsUpdate ) {
  12344. if ( material.program ) deallocateMaterial( material );
  12345. initMaterial( material, lights, fog, object );
  12346. material.needsUpdate = false;
  12347. }
  12348. if ( material.morphTargets ) {
  12349. if ( ! object.__webglMorphTargetInfluences ) {
  12350. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  12351. }
  12352. }
  12353. var refreshProgram = false;
  12354. var refreshMaterial = false;
  12355. var refreshLights = false;
  12356. var program = material.program,
  12357. p_uniforms = program.uniforms,
  12358. m_uniforms = material.__webglShader.uniforms;
  12359. if ( program.id !== _currentProgram ) {
  12360. _gl.useProgram( program.program );
  12361. _currentProgram = program.id;
  12362. refreshProgram = true;
  12363. refreshMaterial = true;
  12364. refreshLights = true;
  12365. }
  12366. if ( material.id !== _currentMaterialId ) {
  12367. if ( _currentMaterialId === -1 ) refreshLights = true;
  12368. _currentMaterialId = material.id;
  12369. refreshMaterial = true;
  12370. }
  12371. if ( refreshProgram || camera !== _currentCamera ) {
  12372. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  12373. if ( _logarithmicDepthBuffer ) {
  12374. _gl.uniform1f( p_uniforms.logDepthBufFC, 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  12375. }
  12376. if ( camera !== _currentCamera ) _currentCamera = camera;
  12377. // load material specific uniforms
  12378. // (shader material also gets them for the sake of genericity)
  12379. if ( material instanceof THREE.ShaderMaterial ||
  12380. material instanceof THREE.MeshPhongMaterial ||
  12381. material.envMap ) {
  12382. if ( p_uniforms.cameraPosition !== null ) {
  12383. _vector3.setFromMatrixPosition( camera.matrixWorld );
  12384. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  12385. }
  12386. }
  12387. if ( material instanceof THREE.MeshPhongMaterial ||
  12388. material instanceof THREE.MeshLambertMaterial ||
  12389. material instanceof THREE.MeshBasicMaterial ||
  12390. material instanceof THREE.ShaderMaterial ||
  12391. material.skinning ) {
  12392. if ( p_uniforms.viewMatrix !== null ) {
  12393. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  12394. }
  12395. }
  12396. }
  12397. // skinning uniforms must be set even if material didn't change
  12398. // auto-setting of texture unit for bone texture must go before other textures
  12399. // not sure why, but otherwise weird things happen
  12400. if ( material.skinning ) {
  12401. if ( object.bindMatrix && p_uniforms.bindMatrix !== null ) {
  12402. _gl.uniformMatrix4fv( p_uniforms.bindMatrix, false, object.bindMatrix.elements );
  12403. }
  12404. if ( object.bindMatrixInverse && p_uniforms.bindMatrixInverse !== null ) {
  12405. _gl.uniformMatrix4fv( p_uniforms.bindMatrixInverse, false, object.bindMatrixInverse.elements );
  12406. }
  12407. if ( _supportsBoneTextures && object.skeleton && object.skeleton.useVertexTexture ) {
  12408. if ( p_uniforms.boneTexture !== null ) {
  12409. var textureUnit = getTextureUnit();
  12410. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  12411. _this.setTexture( object.skeleton.boneTexture, textureUnit );
  12412. }
  12413. if ( p_uniforms.boneTextureWidth !== null ) {
  12414. _gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth );
  12415. }
  12416. if ( p_uniforms.boneTextureHeight !== null ) {
  12417. _gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight );
  12418. }
  12419. } else if ( object.skeleton && object.skeleton.boneMatrices ) {
  12420. if ( p_uniforms.boneGlobalMatrices !== null ) {
  12421. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices );
  12422. }
  12423. }
  12424. }
  12425. if ( refreshMaterial ) {
  12426. // refresh uniforms common to several materials
  12427. if ( fog && material.fog ) {
  12428. refreshUniformsFog( m_uniforms, fog );
  12429. }
  12430. if ( material instanceof THREE.MeshPhongMaterial ||
  12431. material instanceof THREE.MeshLambertMaterial ||
  12432. material.lights ) {
  12433. if ( _lightsNeedUpdate ) {
  12434. refreshLights = true;
  12435. setupLights( lights );
  12436. _lightsNeedUpdate = false;
  12437. }
  12438. if ( refreshLights ) {
  12439. refreshUniformsLights( m_uniforms, _lights );
  12440. markUniformsLightsNeedsUpdate( m_uniforms, true );
  12441. } else {
  12442. markUniformsLightsNeedsUpdate( m_uniforms, false );
  12443. }
  12444. }
  12445. if ( material instanceof THREE.MeshBasicMaterial ||
  12446. material instanceof THREE.MeshLambertMaterial ||
  12447. material instanceof THREE.MeshPhongMaterial ) {
  12448. refreshUniformsCommon( m_uniforms, material );
  12449. }
  12450. // refresh single material specific uniforms
  12451. if ( material instanceof THREE.LineBasicMaterial ) {
  12452. refreshUniformsLine( m_uniforms, material );
  12453. } else if ( material instanceof THREE.LineDashedMaterial ) {
  12454. refreshUniformsLine( m_uniforms, material );
  12455. refreshUniformsDash( m_uniforms, material );
  12456. } else if ( material instanceof THREE.PointCloudMaterial ) {
  12457. refreshUniformsParticle( m_uniforms, material );
  12458. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  12459. refreshUniformsPhong( m_uniforms, material );
  12460. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  12461. refreshUniformsLambert( m_uniforms, material );
  12462. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  12463. m_uniforms.mNear.value = camera.near;
  12464. m_uniforms.mFar.value = camera.far;
  12465. m_uniforms.opacity.value = material.opacity;
  12466. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  12467. m_uniforms.opacity.value = material.opacity;
  12468. }
  12469. if ( object.receiveShadow && ! material._shadowPass ) {
  12470. refreshUniformsShadow( m_uniforms, lights );
  12471. }
  12472. // load common uniforms
  12473. loadUniformsGeneric( material.uniformsList );
  12474. }
  12475. loadUniformsMatrices( p_uniforms, object );
  12476. if ( p_uniforms.modelMatrix !== null ) {
  12477. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  12478. }
  12479. return program;
  12480. }
  12481. // Uniforms (refresh uniforms objects)
  12482. function refreshUniformsCommon ( uniforms, material ) {
  12483. uniforms.opacity.value = material.opacity;
  12484. uniforms.diffuse.value = material.color;
  12485. uniforms.map.value = material.map;
  12486. uniforms.lightMap.value = material.lightMap;
  12487. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  12488. uniforms.aoMap.value = material.aoMap;
  12489. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  12490. uniforms.specularMap.value = material.specularMap;
  12491. uniforms.alphaMap.value = material.alphaMap;
  12492. if ( material.bumpMap ) {
  12493. uniforms.bumpMap.value = material.bumpMap;
  12494. uniforms.bumpScale.value = material.bumpScale;
  12495. }
  12496. if ( material.normalMap ) {
  12497. uniforms.normalMap.value = material.normalMap;
  12498. uniforms.normalScale.value.copy( material.normalScale );
  12499. }
  12500. // uv repeat and offset setting priorities
  12501. // 1. color map
  12502. // 2. specular map
  12503. // 3. normal map
  12504. // 4. bump map
  12505. // 5. alpha map
  12506. var uvScaleMap;
  12507. if ( material.map ) {
  12508. uvScaleMap = material.map;
  12509. } else if ( material.specularMap ) {
  12510. uvScaleMap = material.specularMap;
  12511. } else if ( material.normalMap ) {
  12512. uvScaleMap = material.normalMap;
  12513. } else if ( material.bumpMap ) {
  12514. uvScaleMap = material.bumpMap;
  12515. } else if ( material.alphaMap ) {
  12516. uvScaleMap = material.alphaMap;
  12517. }
  12518. if ( uvScaleMap !== undefined ) {
  12519. var offset = uvScaleMap.offset;
  12520. var repeat = uvScaleMap.repeat;
  12521. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12522. }
  12523. uniforms.envMap.value = material.envMap;
  12524. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1;
  12525. uniforms.reflectivity.value = material.reflectivity;
  12526. uniforms.refractionRatio.value = material.refractionRatio;
  12527. }
  12528. function refreshUniformsLine ( uniforms, material ) {
  12529. uniforms.diffuse.value = material.color;
  12530. uniforms.opacity.value = material.opacity;
  12531. }
  12532. function refreshUniformsDash ( uniforms, material ) {
  12533. uniforms.dashSize.value = material.dashSize;
  12534. uniforms.totalSize.value = material.dashSize + material.gapSize;
  12535. uniforms.scale.value = material.scale;
  12536. }
  12537. function refreshUniformsParticle ( uniforms, material ) {
  12538. uniforms.psColor.value = material.color;
  12539. uniforms.opacity.value = material.opacity;
  12540. uniforms.size.value = material.size;
  12541. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  12542. uniforms.map.value = material.map;
  12543. if ( material.map !== null ) {
  12544. var offset = material.map.offset;
  12545. var repeat = material.map.repeat;
  12546. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12547. }
  12548. }
  12549. function refreshUniformsFog ( uniforms, fog ) {
  12550. uniforms.fogColor.value = fog.color;
  12551. if ( fog instanceof THREE.Fog ) {
  12552. uniforms.fogNear.value = fog.near;
  12553. uniforms.fogFar.value = fog.far;
  12554. } else if ( fog instanceof THREE.FogExp2 ) {
  12555. uniforms.fogDensity.value = fog.density;
  12556. }
  12557. }
  12558. function refreshUniformsPhong ( uniforms, material ) {
  12559. uniforms.shininess.value = material.shininess;
  12560. uniforms.emissive.value = material.emissive;
  12561. uniforms.specular.value = material.specular;
  12562. if ( material.wrapAround ) {
  12563. uniforms.wrapRGB.value.copy( material.wrapRGB );
  12564. }
  12565. }
  12566. function refreshUniformsLambert ( uniforms, material ) {
  12567. uniforms.emissive.value = material.emissive;
  12568. if ( material.wrapAround ) {
  12569. uniforms.wrapRGB.value.copy( material.wrapRGB );
  12570. }
  12571. }
  12572. function refreshUniformsLights ( uniforms, lights ) {
  12573. uniforms.ambientLightColor.value = lights.ambient;
  12574. uniforms.directionalLightColor.value = lights.directional.colors;
  12575. uniforms.directionalLightDirection.value = lights.directional.positions;
  12576. uniforms.pointLightColor.value = lights.point.colors;
  12577. uniforms.pointLightPosition.value = lights.point.positions;
  12578. uniforms.pointLightDistance.value = lights.point.distances;
  12579. uniforms.pointLightDecay.value = lights.point.decays;
  12580. uniforms.spotLightColor.value = lights.spot.colors;
  12581. uniforms.spotLightPosition.value = lights.spot.positions;
  12582. uniforms.spotLightDistance.value = lights.spot.distances;
  12583. uniforms.spotLightDirection.value = lights.spot.directions;
  12584. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  12585. uniforms.spotLightExponent.value = lights.spot.exponents;
  12586. uniforms.spotLightDecay.value = lights.spot.decays;
  12587. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  12588. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  12589. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  12590. }
  12591. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  12592. function markUniformsLightsNeedsUpdate ( uniforms, value ) {
  12593. uniforms.ambientLightColor.needsUpdate = value;
  12594. uniforms.directionalLightColor.needsUpdate = value;
  12595. uniforms.directionalLightDirection.needsUpdate = value;
  12596. uniforms.pointLightColor.needsUpdate = value;
  12597. uniforms.pointLightPosition.needsUpdate = value;
  12598. uniforms.pointLightDistance.needsUpdate = value;
  12599. uniforms.pointLightDecay.needsUpdate = value;
  12600. uniforms.spotLightColor.needsUpdate = value;
  12601. uniforms.spotLightPosition.needsUpdate = value;
  12602. uniforms.spotLightDistance.needsUpdate = value;
  12603. uniforms.spotLightDirection.needsUpdate = value;
  12604. uniforms.spotLightAngleCos.needsUpdate = value;
  12605. uniforms.spotLightExponent.needsUpdate = value;
  12606. uniforms.spotLightDecay.needsUpdate = value;
  12607. uniforms.hemisphereLightSkyColor.needsUpdate = value;
  12608. uniforms.hemisphereLightGroundColor.needsUpdate = value;
  12609. uniforms.hemisphereLightDirection.needsUpdate = value;
  12610. }
  12611. function refreshUniformsShadow ( uniforms, lights ) {
  12612. if ( uniforms.shadowMatrix ) {
  12613. var j = 0;
  12614. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  12615. var light = lights[ i ];
  12616. if ( ! light.castShadow ) continue;
  12617. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  12618. uniforms.shadowMap.value[ j ] = light.shadowMap;
  12619. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  12620. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  12621. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  12622. uniforms.shadowBias.value[ j ] = light.shadowBias;
  12623. j ++;
  12624. }
  12625. }
  12626. }
  12627. }
  12628. // Uniforms (load to GPU)
  12629. function loadUniformsMatrices ( uniforms, object ) {
  12630. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  12631. if ( uniforms.normalMatrix ) {
  12632. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  12633. }
  12634. }
  12635. function getTextureUnit() {
  12636. var textureUnit = _usedTextureUnits;
  12637. if ( textureUnit >= _maxTextures ) {
  12638. THREE.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + _maxTextures );
  12639. }
  12640. _usedTextureUnits += 1;
  12641. return textureUnit;
  12642. }
  12643. function loadUniformsGeneric ( uniforms ) {
  12644. var texture, textureUnit, offset;
  12645. for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) {
  12646. var uniform = uniforms[ j ][ 0 ];
  12647. // needsUpdate property is not added to all uniforms.
  12648. if ( uniform.needsUpdate === false ) continue;
  12649. var type = uniform.type;
  12650. var value = uniform.value;
  12651. var location = uniforms[ j ][ 1 ];
  12652. switch ( type ) {
  12653. case '1i':
  12654. _gl.uniform1i( location, value );
  12655. break;
  12656. case '1f':
  12657. _gl.uniform1f( location, value );
  12658. break;
  12659. case '2f':
  12660. _gl.uniform2f( location, value[ 0 ], value[ 1 ] );
  12661. break;
  12662. case '3f':
  12663. _gl.uniform3f( location, value[ 0 ], value[ 1 ], value[ 2 ] );
  12664. break;
  12665. case '4f':
  12666. _gl.uniform4f( location, value[ 0 ], value[ 1 ], value[ 2 ], value[ 3 ] );
  12667. break;
  12668. case '1iv':
  12669. _gl.uniform1iv( location, value );
  12670. break;
  12671. case '3iv':
  12672. _gl.uniform3iv( location, value );
  12673. break;
  12674. case '1fv':
  12675. _gl.uniform1fv( location, value );
  12676. break;
  12677. case '2fv':
  12678. _gl.uniform2fv( location, value );
  12679. break;
  12680. case '3fv':
  12681. _gl.uniform3fv( location, value );
  12682. break;
  12683. case '4fv':
  12684. _gl.uniform4fv( location, value );
  12685. break;
  12686. case 'Matrix3fv':
  12687. _gl.uniformMatrix3fv( location, false, value );
  12688. break;
  12689. case 'Matrix4fv':
  12690. _gl.uniformMatrix4fv( location, false, value );
  12691. break;
  12692. //
  12693. case 'i':
  12694. // single integer
  12695. _gl.uniform1i( location, value );
  12696. break;
  12697. case 'f':
  12698. // single float
  12699. _gl.uniform1f( location, value );
  12700. break;
  12701. case 'v2':
  12702. // single THREE.Vector2
  12703. _gl.uniform2f( location, value.x, value.y );
  12704. break;
  12705. case 'v3':
  12706. // single THREE.Vector3
  12707. _gl.uniform3f( location, value.x, value.y, value.z );
  12708. break;
  12709. case 'v4':
  12710. // single THREE.Vector4
  12711. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  12712. break;
  12713. case 'c':
  12714. // single THREE.Color
  12715. _gl.uniform3f( location, value.r, value.g, value.b );
  12716. break;
  12717. case 'iv1':
  12718. // flat array of integers (JS or typed array)
  12719. _gl.uniform1iv( location, value );
  12720. break;
  12721. case 'iv':
  12722. // flat array of integers with 3 x N size (JS or typed array)
  12723. _gl.uniform3iv( location, value );
  12724. break;
  12725. case 'fv1':
  12726. // flat array of floats (JS or typed array)
  12727. _gl.uniform1fv( location, value );
  12728. break;
  12729. case 'fv':
  12730. // flat array of floats with 3 x N size (JS or typed array)
  12731. _gl.uniform3fv( location, value );
  12732. break;
  12733. case 'v2v':
  12734. // array of THREE.Vector2
  12735. if ( uniform._array === undefined ) {
  12736. uniform._array = new Float32Array( 2 * value.length );
  12737. }
  12738. for ( var i = 0, il = value.length; i < il; i ++ ) {
  12739. offset = i * 2;
  12740. uniform._array[ offset ] = value[ i ].x;
  12741. uniform._array[ offset + 1 ] = value[ i ].y;
  12742. }
  12743. _gl.uniform2fv( location, uniform._array );
  12744. break;
  12745. case 'v3v':
  12746. // array of THREE.Vector3
  12747. if ( uniform._array === undefined ) {
  12748. uniform._array = new Float32Array( 3 * value.length );
  12749. }
  12750. for ( var i = 0, il = value.length; i < il; i ++ ) {
  12751. offset = i * 3;
  12752. uniform._array[ offset ] = value[ i ].x;
  12753. uniform._array[ offset + 1 ] = value[ i ].y;
  12754. uniform._array[ offset + 2 ] = value[ i ].z;
  12755. }
  12756. _gl.uniform3fv( location, uniform._array );
  12757. break;
  12758. case 'v4v':
  12759. // array of THREE.Vector4
  12760. if ( uniform._array === undefined ) {
  12761. uniform._array = new Float32Array( 4 * value.length );
  12762. }
  12763. for ( var i = 0, il = value.length; i < il; i ++ ) {
  12764. offset = i * 4;
  12765. uniform._array[ offset ] = value[ i ].x;
  12766. uniform._array[ offset + 1 ] = value[ i ].y;
  12767. uniform._array[ offset + 2 ] = value[ i ].z;
  12768. uniform._array[ offset + 3 ] = value[ i ].w;
  12769. }
  12770. _gl.uniform4fv( location, uniform._array );
  12771. break;
  12772. case 'm3':
  12773. // single THREE.Matrix3
  12774. _gl.uniformMatrix3fv( location, false, value.elements );
  12775. break;
  12776. case 'm3v':
  12777. // array of THREE.Matrix3
  12778. if ( uniform._array === undefined ) {
  12779. uniform._array = new Float32Array( 9 * value.length );
  12780. }
  12781. for ( var i = 0, il = value.length; i < il; i ++ ) {
  12782. value[ i ].flattenToArrayOffset( uniform._array, i * 9 );
  12783. }
  12784. _gl.uniformMatrix3fv( location, false, uniform._array );
  12785. break;
  12786. case 'm4':
  12787. // single THREE.Matrix4
  12788. _gl.uniformMatrix4fv( location, false, value.elements );
  12789. break;
  12790. case 'm4v':
  12791. // array of THREE.Matrix4
  12792. if ( uniform._array === undefined ) {
  12793. uniform._array = new Float32Array( 16 * value.length );
  12794. }
  12795. for ( var i = 0, il = value.length; i < il; i ++ ) {
  12796. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  12797. }
  12798. _gl.uniformMatrix4fv( location, false, uniform._array );
  12799. break;
  12800. case 't':
  12801. // single THREE.Texture (2d or cube)
  12802. texture = value;
  12803. textureUnit = getTextureUnit();
  12804. _gl.uniform1i( location, textureUnit );
  12805. if ( ! texture ) continue;
  12806. if ( texture instanceof THREE.CubeTexture ||
  12807. ( texture.image instanceof Array && texture.image.length === 6 ) ) { // CompressedTexture can have Array in image :/
  12808. setCubeTexture( texture, textureUnit );
  12809. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  12810. setCubeTextureDynamic( texture, textureUnit );
  12811. } else {
  12812. _this.setTexture( texture, textureUnit );
  12813. }
  12814. break;
  12815. case 'tv':
  12816. // array of THREE.Texture (2d)
  12817. if ( uniform._array === undefined ) {
  12818. uniform._array = [];
  12819. }
  12820. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  12821. uniform._array[ i ] = getTextureUnit();
  12822. }
  12823. _gl.uniform1iv( location, uniform._array );
  12824. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  12825. texture = uniform.value[ i ];
  12826. textureUnit = uniform._array[ i ];
  12827. if ( ! texture ) continue;
  12828. _this.setTexture( texture, textureUnit );
  12829. }
  12830. break;
  12831. default:
  12832. THREE.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  12833. }
  12834. }
  12835. }
  12836. function setupMatrices ( object, camera ) {
  12837. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  12838. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  12839. }
  12840. function setColorLinear( array, offset, color, intensity ) {
  12841. array[ offset ] = color.r * intensity;
  12842. array[ offset + 1 ] = color.g * intensity;
  12843. array[ offset + 2 ] = color.b * intensity;
  12844. }
  12845. function setupLights ( lights ) {
  12846. var l, ll, light,
  12847. r = 0, g = 0, b = 0,
  12848. color, skyColor, groundColor,
  12849. intensity,
  12850. distance,
  12851. zlights = _lights,
  12852. dirColors = zlights.directional.colors,
  12853. dirPositions = zlights.directional.positions,
  12854. pointColors = zlights.point.colors,
  12855. pointPositions = zlights.point.positions,
  12856. pointDistances = zlights.point.distances,
  12857. pointDecays = zlights.point.decays,
  12858. spotColors = zlights.spot.colors,
  12859. spotPositions = zlights.spot.positions,
  12860. spotDistances = zlights.spot.distances,
  12861. spotDirections = zlights.spot.directions,
  12862. spotAnglesCos = zlights.spot.anglesCos,
  12863. spotExponents = zlights.spot.exponents,
  12864. spotDecays = zlights.spot.decays,
  12865. hemiSkyColors = zlights.hemi.skyColors,
  12866. hemiGroundColors = zlights.hemi.groundColors,
  12867. hemiPositions = zlights.hemi.positions,
  12868. dirLength = 0,
  12869. pointLength = 0,
  12870. spotLength = 0,
  12871. hemiLength = 0,
  12872. dirCount = 0,
  12873. pointCount = 0,
  12874. spotCount = 0,
  12875. hemiCount = 0,
  12876. dirOffset = 0,
  12877. pointOffset = 0,
  12878. spotOffset = 0,
  12879. hemiOffset = 0;
  12880. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12881. light = lights[ l ];
  12882. if ( light.onlyShadow ) continue;
  12883. color = light.color;
  12884. intensity = light.intensity;
  12885. distance = light.distance;
  12886. if ( light instanceof THREE.AmbientLight ) {
  12887. if ( ! light.visible ) continue;
  12888. r += color.r;
  12889. g += color.g;
  12890. b += color.b;
  12891. } else if ( light instanceof THREE.DirectionalLight ) {
  12892. dirCount += 1;
  12893. if ( ! light.visible ) continue;
  12894. _direction.setFromMatrixPosition( light.matrixWorld );
  12895. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  12896. _direction.sub( _vector3 );
  12897. _direction.normalize();
  12898. dirOffset = dirLength * 3;
  12899. dirPositions[ dirOffset ] = _direction.x;
  12900. dirPositions[ dirOffset + 1 ] = _direction.y;
  12901. dirPositions[ dirOffset + 2 ] = _direction.z;
  12902. setColorLinear( dirColors, dirOffset, color, intensity );
  12903. dirLength += 1;
  12904. } else if ( light instanceof THREE.PointLight ) {
  12905. pointCount += 1;
  12906. if ( ! light.visible ) continue;
  12907. pointOffset = pointLength * 3;
  12908. setColorLinear( pointColors, pointOffset, color, intensity );
  12909. _vector3.setFromMatrixPosition( light.matrixWorld );
  12910. pointPositions[ pointOffset ] = _vector3.x;
  12911. pointPositions[ pointOffset + 1 ] = _vector3.y;
  12912. pointPositions[ pointOffset + 2 ] = _vector3.z;
  12913. // distance is 0 if decay is 0, because there is no attenuation at all.
  12914. pointDistances[ pointLength ] = distance;
  12915. pointDecays[ pointLength ] = ( light.distance === 0 ) ? 0.0 : light.decay;
  12916. pointLength += 1;
  12917. } else if ( light instanceof THREE.SpotLight ) {
  12918. spotCount += 1;
  12919. if ( ! light.visible ) continue;
  12920. spotOffset = spotLength * 3;
  12921. setColorLinear( spotColors, spotOffset, color, intensity );
  12922. _direction.setFromMatrixPosition( light.matrixWorld );
  12923. spotPositions[ spotOffset ] = _direction.x;
  12924. spotPositions[ spotOffset + 1 ] = _direction.y;
  12925. spotPositions[ spotOffset + 2 ] = _direction.z;
  12926. spotDistances[ spotLength ] = distance;
  12927. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  12928. _direction.sub( _vector3 );
  12929. _direction.normalize();
  12930. spotDirections[ spotOffset ] = _direction.x;
  12931. spotDirections[ spotOffset + 1 ] = _direction.y;
  12932. spotDirections[ spotOffset + 2 ] = _direction.z;
  12933. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  12934. spotExponents[ spotLength ] = light.exponent;
  12935. spotDecays[ spotLength ] = ( light.distance === 0 ) ? 0.0 : light.decay;
  12936. spotLength += 1;
  12937. } else if ( light instanceof THREE.HemisphereLight ) {
  12938. hemiCount += 1;
  12939. if ( ! light.visible ) continue;
  12940. _direction.setFromMatrixPosition( light.matrixWorld );
  12941. _direction.normalize();
  12942. hemiOffset = hemiLength * 3;
  12943. hemiPositions[ hemiOffset ] = _direction.x;
  12944. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  12945. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  12946. skyColor = light.color;
  12947. groundColor = light.groundColor;
  12948. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  12949. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  12950. hemiLength += 1;
  12951. }
  12952. }
  12953. // null eventual remains from removed lights
  12954. // (this is to avoid if in shader)
  12955. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  12956. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  12957. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  12958. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  12959. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  12960. zlights.directional.length = dirLength;
  12961. zlights.point.length = pointLength;
  12962. zlights.spot.length = spotLength;
  12963. zlights.hemi.length = hemiLength;
  12964. zlights.ambient[ 0 ] = r;
  12965. zlights.ambient[ 1 ] = g;
  12966. zlights.ambient[ 2 ] = b;
  12967. }
  12968. // GL state setting
  12969. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  12970. if ( cullFace === THREE.CullFaceNone ) {
  12971. _gl.disable( _gl.CULL_FACE );
  12972. } else {
  12973. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  12974. _gl.frontFace( _gl.CW );
  12975. } else {
  12976. _gl.frontFace( _gl.CCW );
  12977. }
  12978. if ( cullFace === THREE.CullFaceBack ) {
  12979. _gl.cullFace( _gl.BACK );
  12980. } else if ( cullFace === THREE.CullFaceFront ) {
  12981. _gl.cullFace( _gl.FRONT );
  12982. } else {
  12983. _gl.cullFace( _gl.FRONT_AND_BACK );
  12984. }
  12985. _gl.enable( _gl.CULL_FACE );
  12986. }
  12987. };
  12988. this.setMaterialFaces = function ( material ) {
  12989. state.setDoubleSided( material.side === THREE.DoubleSide );
  12990. state.setFlipSided( material.side === THREE.BackSide );
  12991. };
  12992. // Textures
  12993. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  12994. var extension;
  12995. if ( isImagePowerOfTwo ) {
  12996. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  12997. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  12998. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  12999. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  13000. } else {
  13001. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  13002. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  13003. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) {
  13004. THREE.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping. ( ' + texture.sourceFile + ' )' );
  13005. }
  13006. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  13007. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  13008. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) {
  13009. THREE.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter. ( ' + texture.sourceFile + ' )' );
  13010. }
  13011. }
  13012. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  13013. if ( extension && texture.type !== THREE.FloatType && texture.type !== THREE.HalfFloatType ) {
  13014. if ( texture.anisotropy > 1 || texture.__currentAnisotropy ) {
  13015. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _this.getMaxAnisotropy() ) );
  13016. texture.__currentAnisotropy = texture.anisotropy;
  13017. }
  13018. }
  13019. }
  13020. this.uploadTexture = function ( texture, slot ) {
  13021. if ( texture.__webglInit === undefined ) {
  13022. texture.__webglInit = true;
  13023. texture.addEventListener( 'dispose', onTextureDispose );
  13024. texture.__webglTexture = _gl.createTexture();
  13025. _this.info.memory.textures ++;
  13026. }
  13027. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13028. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13029. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13030. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  13031. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  13032. texture.image = clampToMaxSize( texture.image, _maxTextureSize );
  13033. var image = texture.image,
  13034. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  13035. glFormat = paramThreeToGL( texture.format ),
  13036. glType = paramThreeToGL( texture.type );
  13037. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  13038. var mipmap, mipmaps = texture.mipmaps;
  13039. if ( texture instanceof THREE.DataTexture ) {
  13040. // use manually created mipmaps if available
  13041. // if there are no manual mipmaps
  13042. // set 0 level mipmap and then use GL to generate other mipmap levels
  13043. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  13044. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13045. mipmap = mipmaps[ i ];
  13046. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13047. }
  13048. texture.generateMipmaps = false;
  13049. } else {
  13050. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13051. }
  13052. } else if ( texture instanceof THREE.CompressedTexture ) {
  13053. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13054. mipmap = mipmaps[ i ];
  13055. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  13056. if ( getCompressedTextureFormats().indexOf( glFormat ) > -1 ) {
  13057. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13058. } else {
  13059. THREE.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  13060. }
  13061. } else {
  13062. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13063. }
  13064. }
  13065. } else { // regular Texture (image, video, canvas)
  13066. // use manually created mipmaps if available
  13067. // if there are no manual mipmaps
  13068. // set 0 level mipmap and then use GL to generate other mipmap levels
  13069. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  13070. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13071. mipmap = mipmaps[ i ];
  13072. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  13073. }
  13074. texture.generateMipmaps = false;
  13075. } else {
  13076. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  13077. }
  13078. }
  13079. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13080. texture.needsUpdate = false;
  13081. if ( texture.onUpdate ) texture.onUpdate( texture );
  13082. };
  13083. this.setTexture = function ( texture, slot ) {
  13084. if ( texture.needsUpdate === true ) {
  13085. var image = texture.image;
  13086. if ( image.complete === false ) {
  13087. THREE.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  13088. return;
  13089. }
  13090. _this.uploadTexture( texture, slot );
  13091. return;
  13092. }
  13093. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13094. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13095. };
  13096. function clampToMaxSize ( image, maxSize ) {
  13097. if ( image.width > maxSize || image.height > maxSize ) {
  13098. // Warning: Scaling through the canvas will only work with images that use
  13099. // premultiplied alpha.
  13100. var scale = maxSize / Math.max( image.width, image.height );
  13101. var canvas = document.createElement( 'canvas' );
  13102. canvas.width = Math.floor( image.width * scale );
  13103. canvas.height = Math.floor( image.height * scale );
  13104. var context = canvas.getContext( '2d' );
  13105. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  13106. THREE.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  13107. return canvas;
  13108. }
  13109. return image;
  13110. }
  13111. function setCubeTexture ( texture, slot ) {
  13112. if ( texture.image.length === 6 ) {
  13113. if ( texture.needsUpdate ) {
  13114. if ( ! texture.image.__webglTextureCube ) {
  13115. texture.addEventListener( 'dispose', onTextureDispose );
  13116. texture.image.__webglTextureCube = _gl.createTexture();
  13117. _this.info.memory.textures ++;
  13118. }
  13119. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13120. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13121. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13122. var isCompressed = texture instanceof THREE.CompressedTexture;
  13123. var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture;
  13124. var cubeImage = [];
  13125. for ( var i = 0; i < 6; i ++ ) {
  13126. if ( _this.autoScaleCubemaps && ! isCompressed && ! isDataTexture ) {
  13127. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  13128. } else {
  13129. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  13130. }
  13131. }
  13132. var image = cubeImage[ 0 ],
  13133. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  13134. glFormat = paramThreeToGL( texture.format ),
  13135. glType = paramThreeToGL( texture.type );
  13136. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  13137. for ( var i = 0; i < 6; i ++ ) {
  13138. if ( ! isCompressed ) {
  13139. if ( isDataTexture ) {
  13140. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  13141. } else {
  13142. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  13143. }
  13144. } else {
  13145. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  13146. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  13147. mipmap = mipmaps[ j ];
  13148. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  13149. if ( getCompressedTextureFormats().indexOf( glFormat ) > -1 ) {
  13150. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13151. } else {
  13152. THREE.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setCubeTexture()" );
  13153. }
  13154. } else {
  13155. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13156. }
  13157. }
  13158. }
  13159. }
  13160. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  13161. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13162. }
  13163. texture.needsUpdate = false;
  13164. if ( texture.onUpdate ) texture.onUpdate( texture );
  13165. } else {
  13166. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13167. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13168. }
  13169. }
  13170. }
  13171. function setCubeTextureDynamic ( texture, slot ) {
  13172. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13173. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  13174. }
  13175. // Render targets
  13176. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  13177. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13178. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  13179. }
  13180. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  13181. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  13182. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13183. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  13184. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13185. /* For some reason this is not working. Defaulting to RGBA4.
  13186. } else if ( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13187. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  13188. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13189. */
  13190. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13191. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  13192. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13193. } else {
  13194. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  13195. }
  13196. }
  13197. this.setRenderTarget = function ( renderTarget ) {
  13198. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  13199. if ( renderTarget && renderTarget.__webglFramebuffer === undefined ) {
  13200. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  13201. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  13202. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  13203. renderTarget.__webglTexture = _gl.createTexture();
  13204. _this.info.memory.textures ++;
  13205. // Setup texture, create render and frame buffers
  13206. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ),
  13207. glFormat = paramThreeToGL( renderTarget.format ),
  13208. glType = paramThreeToGL( renderTarget.type );
  13209. if ( isCube ) {
  13210. renderTarget.__webglFramebuffer = [];
  13211. renderTarget.__webglRenderbuffer = [];
  13212. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13213. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  13214. for ( var i = 0; i < 6; i ++ ) {
  13215. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  13216. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  13217. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13218. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  13219. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  13220. }
  13221. if ( renderTarget.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13222. } else {
  13223. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  13224. if ( renderTarget.shareDepthFrom ) {
  13225. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  13226. } else {
  13227. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  13228. }
  13229. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13230. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  13231. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13232. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  13233. if ( renderTarget.shareDepthFrom ) {
  13234. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13235. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  13236. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13237. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  13238. }
  13239. } else {
  13240. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  13241. }
  13242. if ( renderTarget.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13243. }
  13244. // Release everything
  13245. if ( isCube ) {
  13246. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13247. } else {
  13248. _gl.bindTexture( _gl.TEXTURE_2D, null );
  13249. }
  13250. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  13251. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  13252. }
  13253. var framebuffer, width, height, vx, vy;
  13254. if ( renderTarget ) {
  13255. if ( isCube ) {
  13256. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  13257. } else {
  13258. framebuffer = renderTarget.__webglFramebuffer;
  13259. }
  13260. width = renderTarget.width;
  13261. height = renderTarget.height;
  13262. vx = 0;
  13263. vy = 0;
  13264. } else {
  13265. framebuffer = null;
  13266. width = _viewportWidth;
  13267. height = _viewportHeight;
  13268. vx = _viewportX;
  13269. vy = _viewportY;
  13270. }
  13271. if ( framebuffer !== _currentFramebuffer ) {
  13272. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13273. _gl.viewport( vx, vy, width, height );
  13274. _currentFramebuffer = framebuffer;
  13275. }
  13276. _currentWidth = width;
  13277. _currentHeight = height;
  13278. };
  13279. this.readRenderTargetPixels = function( renderTarget, x, y, width, height, buffer ) {
  13280. if ( ! ( renderTarget instanceof THREE.WebGLRenderTarget ) ) {
  13281. THREE.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  13282. return;
  13283. }
  13284. if ( renderTarget.__webglFramebuffer ) {
  13285. if ( renderTarget.format !== THREE.RGBAFormat ) {
  13286. THREE.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA format. readPixels can read only RGBA format.' );
  13287. return;
  13288. }
  13289. var restore = false;
  13290. if ( renderTarget.__webglFramebuffer !== _currentFramebuffer ) {
  13291. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTarget.__webglFramebuffer );
  13292. restore = true;
  13293. }
  13294. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  13295. _gl.readPixels( x, y, width, height, _gl.RGBA, _gl.UNSIGNED_BYTE, buffer );
  13296. } else {
  13297. THREE.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  13298. }
  13299. if ( restore ) {
  13300. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  13301. }
  13302. }
  13303. };
  13304. function updateRenderTargetMipmap ( renderTarget ) {
  13305. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  13306. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13307. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13308. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13309. } else {
  13310. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13311. _gl.generateMipmap( _gl.TEXTURE_2D );
  13312. _gl.bindTexture( _gl.TEXTURE_2D, null );
  13313. }
  13314. }
  13315. // Fallback filters for non-power-of-2 textures
  13316. function filterFallback ( f ) {
  13317. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  13318. return _gl.NEAREST;
  13319. }
  13320. return _gl.LINEAR;
  13321. }
  13322. // Map three.js constants to WebGL constants
  13323. function paramThreeToGL ( p ) {
  13324. var extension;
  13325. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  13326. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  13327. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  13328. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  13329. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  13330. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13331. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  13332. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13333. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13334. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13335. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13336. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13337. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13338. if ( p === THREE.ByteType ) return _gl.BYTE;
  13339. if ( p === THREE.ShortType ) return _gl.SHORT;
  13340. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13341. if ( p === THREE.IntType ) return _gl.INT;
  13342. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  13343. if ( p === THREE.FloatType ) return _gl.FLOAT;
  13344. extension = extensions.get( 'OES_texture_half_float' );
  13345. if ( extension !== null ) {
  13346. if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES;
  13347. }
  13348. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  13349. if ( p === THREE.RGBFormat ) return _gl.RGB;
  13350. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  13351. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  13352. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13353. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  13354. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13355. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13356. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  13357. if ( p === THREE.OneFactor ) return _gl.ONE;
  13358. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  13359. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13360. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13361. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13362. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  13363. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13364. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  13365. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13366. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13367. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  13368. if ( extension !== null ) {
  13369. if ( p === THREE.RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13370. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13371. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13372. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13373. }
  13374. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  13375. if ( extension !== null ) {
  13376. if ( p === THREE.RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13377. if ( p === THREE.RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13378. if ( p === THREE.RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13379. if ( p === THREE.RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13380. }
  13381. extension = extensions.get( 'EXT_blend_minmax' );
  13382. if ( extension !== null ) {
  13383. if ( p === THREE.MinEquation ) return extension.MIN_EXT;
  13384. if ( p === THREE.MaxEquation ) return extension.MAX_EXT;
  13385. }
  13386. return 0;
  13387. }
  13388. // Allocations
  13389. function allocateBones ( object ) {
  13390. if ( _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  13391. return 1024;
  13392. } else {
  13393. // default for when object is not specified
  13394. // ( for example when prebuilding shader
  13395. // to be used with multiple objects )
  13396. //
  13397. // - leave some extra space for other uniforms
  13398. // - limit here is ANGLE's 254 max uniform vectors
  13399. // (up to 54 should be safe)
  13400. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  13401. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  13402. var maxBones = nVertexMatrices;
  13403. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  13404. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  13405. if ( maxBones < object.skeleton.bones.length ) {
  13406. THREE.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  13407. }
  13408. }
  13409. return maxBones;
  13410. }
  13411. }
  13412. function allocateLights( lights ) {
  13413. var dirLights = 0;
  13414. var pointLights = 0;
  13415. var spotLights = 0;
  13416. var hemiLights = 0;
  13417. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  13418. var light = lights[ l ];
  13419. if ( light.onlyShadow || light.visible === false ) continue;
  13420. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  13421. if ( light instanceof THREE.PointLight ) pointLights ++;
  13422. if ( light instanceof THREE.SpotLight ) spotLights ++;
  13423. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  13424. }
  13425. return { 'directional': dirLights, 'point': pointLights, 'spot': spotLights, 'hemi': hemiLights };
  13426. }
  13427. function allocateShadows( lights ) {
  13428. var maxShadows = 0;
  13429. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  13430. var light = lights[ l ];
  13431. if ( ! light.castShadow ) continue;
  13432. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  13433. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  13434. }
  13435. return maxShadows;
  13436. }
  13437. // DEPRECATED
  13438. this.initMaterial = function () {
  13439. THREE.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  13440. };
  13441. this.addPrePlugin = function () {
  13442. THREE.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  13443. };
  13444. this.addPostPlugin = function () {
  13445. THREE.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  13446. };
  13447. this.updateShadowMap = function () {
  13448. THREE.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  13449. };
  13450. Object.defineProperties( this, {
  13451. shadowMapEnabled: {
  13452. get: function () {
  13453. return shadowMap.enabled;
  13454. },
  13455. set: function ( value ) {
  13456. THREE.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  13457. shadowMap.enabled = value;
  13458. }
  13459. },
  13460. shadowMapType: {
  13461. get: function () {
  13462. return shadowMap.type;
  13463. },
  13464. set: function ( value ) {
  13465. THREE.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  13466. shadowMap.type = value;
  13467. }
  13468. },
  13469. shadowMapCullFace: {
  13470. get: function () {
  13471. return shadowMap.cullFace;
  13472. },
  13473. set: function ( value ) {
  13474. THREE.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  13475. shadowMap.cullFace = value;
  13476. }
  13477. },
  13478. shadowMapDebug: {
  13479. get: function () {
  13480. return shadowMap.debug;
  13481. },
  13482. set: function ( value ) {
  13483. THREE.warn( 'THREE.WebGLRenderer: .shadowMapDebug is now .shadowMap.debug.' );
  13484. shadowMap.debug = value;
  13485. }
  13486. },
  13487. shadowMapCascade: {
  13488. get: function () {
  13489. return shadowMap.cascade;
  13490. },
  13491. set: function ( value ) {
  13492. THREE.warn( 'THREE.WebGLRenderer: .shadowMapCascade is now .shadowMap.cascade.' );
  13493. shadowMap.cascade = value;
  13494. }
  13495. }
  13496. } );
  13497. };
  13498. // File:src/renderers/WebGLRenderTarget.js
  13499. /**
  13500. * @author szimek / https://github.com/szimek/
  13501. * @author alteredq / http://alteredqualia.com/
  13502. */
  13503. THREE.WebGLRenderTarget = function ( width, height, options ) {
  13504. this.width = width;
  13505. this.height = height;
  13506. options = options || {};
  13507. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  13508. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  13509. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  13510. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  13511. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  13512. this.offset = new THREE.Vector2( 0, 0 );
  13513. this.repeat = new THREE.Vector2( 1, 1 );
  13514. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  13515. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  13516. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  13517. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  13518. this.generateMipmaps = true;
  13519. this.shareDepthFrom = options.shareDepthFrom !== undefined ? options.shareDepthFrom : null;
  13520. };
  13521. THREE.WebGLRenderTarget.prototype = {
  13522. constructor: THREE.WebGLRenderTarget,
  13523. setSize: function ( width, height ) {
  13524. this.width = width;
  13525. this.height = height;
  13526. },
  13527. clone: function () {
  13528. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  13529. tmp.wrapS = this.wrapS;
  13530. tmp.wrapT = this.wrapT;
  13531. tmp.magFilter = this.magFilter;
  13532. tmp.minFilter = this.minFilter;
  13533. tmp.anisotropy = this.anisotropy;
  13534. tmp.offset.copy( this.offset );
  13535. tmp.repeat.copy( this.repeat );
  13536. tmp.format = this.format;
  13537. tmp.type = this.type;
  13538. tmp.depthBuffer = this.depthBuffer;
  13539. tmp.stencilBuffer = this.stencilBuffer;
  13540. tmp.generateMipmaps = this.generateMipmaps;
  13541. tmp.shareDepthFrom = this.shareDepthFrom;
  13542. return tmp;
  13543. },
  13544. dispose: function () {
  13545. this.dispatchEvent( { type: 'dispose' } );
  13546. }
  13547. };
  13548. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  13549. // File:src/renderers/WebGLRenderTargetCube.js
  13550. /**
  13551. * @author alteredq / http://alteredqualia.com
  13552. */
  13553. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  13554. THREE.WebGLRenderTarget.call( this, width, height, options );
  13555. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  13556. };
  13557. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  13558. THREE.WebGLRenderTargetCube.prototype.constructor = THREE.WebGLRenderTargetCube;
  13559. // File:src/renderers/webgl/WebGLBuffers.js
  13560. /**
  13561. * @author mrdoob / http://mrdoob.com/
  13562. */
  13563. THREE.WebGLBuffers = function ( gl, info, extensions, getBufferMaterial ) {
  13564. function initCustomAttributes ( object ) {
  13565. var geometry = object.geometry;
  13566. var material = object.material;
  13567. var nvertices = geometry.vertices.length;
  13568. if ( material.attributes ) {
  13569. if ( geometry.__webglCustomAttributesList === undefined ) {
  13570. geometry.__webglCustomAttributesList = [];
  13571. }
  13572. for ( var name in material.attributes ) {
  13573. var attribute = material.attributes[ name ];
  13574. if ( ! attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  13575. attribute.__webglInitialized = true;
  13576. var size = 1; // "f" and "i"
  13577. if ( attribute.type === 'v2' ) size = 2;
  13578. else if ( attribute.type === 'v3' ) size = 3;
  13579. else if ( attribute.type === 'v4' ) size = 4;
  13580. else if ( attribute.type === 'c' ) size = 3;
  13581. attribute.size = size;
  13582. attribute.array = new Float32Array( nvertices * size );
  13583. attribute.buffer = gl.createBuffer();
  13584. attribute.buffer.belongsToAttribute = name;
  13585. attribute.needsUpdate = true;
  13586. }
  13587. geometry.__webglCustomAttributesList.push( attribute );
  13588. }
  13589. }
  13590. };
  13591. this.initPointCloudBuffers = function ( geometry, object ) {
  13592. if ( geometry.__webglVertexBuffer !== undefined ) return;
  13593. geometry.__webglVertexBuffer = gl.createBuffer();
  13594. geometry.__webglColorBuffer = gl.createBuffer();
  13595. info.memory.geometries ++;
  13596. //
  13597. var nvertices = geometry.vertices.length;
  13598. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  13599. geometry.__colorArray = new Float32Array( nvertices * 3 );
  13600. geometry.__webglParticleCount = nvertices;
  13601. initCustomAttributes( object );
  13602. geometry.verticesNeedUpdate = true;
  13603. geometry.colorsNeedUpdate = true;
  13604. };
  13605. this.initLineBuffers = function ( geometry, object ) {
  13606. if ( geometry.__webglVertexBuffer !== undefined ) return;
  13607. geometry.__webglVertexBuffer = gl.createBuffer();
  13608. geometry.__webglColorBuffer = gl.createBuffer();
  13609. geometry.__webglLineDistanceBuffer = gl.createBuffer();
  13610. info.memory.geometries ++;
  13611. //
  13612. var nvertices = geometry.vertices.length;
  13613. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  13614. geometry.__colorArray = new Float32Array( nvertices * 3 );
  13615. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  13616. geometry.__webglLineCount = nvertices;
  13617. initCustomAttributes( object );
  13618. geometry.verticesNeedUpdate = true;
  13619. geometry.colorsNeedUpdate = true;
  13620. geometry.lineDistancesNeedUpdate = true;
  13621. };
  13622. this.initMeshBuffers = function ( geometryGroup, object ) {
  13623. geometryGroup.__webglVertexBuffer = gl.createBuffer();
  13624. geometryGroup.__webglNormalBuffer = gl.createBuffer();
  13625. geometryGroup.__webglTangentBuffer = gl.createBuffer();
  13626. geometryGroup.__webglColorBuffer = gl.createBuffer();
  13627. geometryGroup.__webglUVBuffer = gl.createBuffer();
  13628. geometryGroup.__webglUV2Buffer = gl.createBuffer();
  13629. geometryGroup.__webglSkinIndicesBuffer = gl.createBuffer();
  13630. geometryGroup.__webglSkinWeightsBuffer = gl.createBuffer();
  13631. geometryGroup.__webglFaceBuffer = gl.createBuffer();
  13632. geometryGroup.__webglLineBuffer = gl.createBuffer();
  13633. var numMorphTargets = geometryGroup.numMorphTargets;
  13634. if ( numMorphTargets ) {
  13635. geometryGroup.__webglMorphTargetsBuffers = [];
  13636. for ( var m = 0, ml = numMorphTargets; m < ml; m ++ ) {
  13637. geometryGroup.__webglMorphTargetsBuffers.push( gl.createBuffer() );
  13638. }
  13639. }
  13640. var numMorphNormals = geometryGroup.numMorphNormals;
  13641. if ( numMorphNormals ) {
  13642. geometryGroup.__webglMorphNormalsBuffers = [];
  13643. for ( var m = 0, ml = numMorphNormals; m < ml; m ++ ) {
  13644. geometryGroup.__webglMorphNormalsBuffers.push( gl.createBuffer() );
  13645. }
  13646. }
  13647. info.memory.geometries ++;
  13648. //
  13649. var geometry = object.geometry,
  13650. faces3 = geometryGroup.faces3,
  13651. nvertices = faces3.length * 3,
  13652. ntris = faces3.length * 1,
  13653. nlines = faces3.length * 3,
  13654. material = getBufferMaterial( object, geometryGroup );
  13655. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  13656. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  13657. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  13658. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  13659. if ( geometry.faceVertexUvs.length > 1 ) {
  13660. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  13661. }
  13662. if ( geometry.hasTangents ) {
  13663. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  13664. }
  13665. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  13666. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  13667. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  13668. }
  13669. var UintArray = extensions.get( 'OES_element_index_uint' ) !== null && ntris > 21845 ? Uint32Array : Uint16Array; // 65535 / 3
  13670. geometryGroup.__typeArray = UintArray;
  13671. geometryGroup.__faceArray = new UintArray( ntris * 3 );
  13672. geometryGroup.__lineArray = new UintArray( nlines * 2 );
  13673. if ( numMorphTargets ) {
  13674. geometryGroup.__morphTargetsArrays = [];
  13675. for ( var m = 0, ml = numMorphTargets; m < ml; m ++ ) {
  13676. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  13677. }
  13678. }
  13679. if ( numMorphNormals ) {
  13680. geometryGroup.__morphNormalsArrays = [];
  13681. for ( var m = 0, ml = numMorphNormals; m < ml; m ++ ) {
  13682. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  13683. }
  13684. }
  13685. geometryGroup.__webglFaceCount = ntris * 3;
  13686. geometryGroup.__webglLineCount = nlines * 2;
  13687. // custom attributes
  13688. if ( material.attributes ) {
  13689. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  13690. geometryGroup.__webglCustomAttributesList = [];
  13691. }
  13692. for ( var name in material.attributes ) {
  13693. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  13694. // attribute buffers which are correctly indexed in the setMeshBuffers function
  13695. var originalAttribute = material.attributes[ name ];
  13696. var attribute = {};
  13697. for ( var property in originalAttribute ) {
  13698. attribute[ property ] = originalAttribute[ property ];
  13699. }
  13700. if ( ! attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  13701. attribute.__webglInitialized = true;
  13702. var size = 1; // "f" and "i"
  13703. if ( attribute.type === 'v2' ) size = 2;
  13704. else if ( attribute.type === 'v3' ) size = 3;
  13705. else if ( attribute.type === 'v4' ) size = 4;
  13706. else if ( attribute.type === 'c' ) size = 3;
  13707. attribute.size = size;
  13708. attribute.array = new Float32Array( nvertices * size );
  13709. attribute.buffer = gl.createBuffer();
  13710. attribute.buffer.belongsToAttribute = name;
  13711. originalAttribute.needsUpdate = true;
  13712. attribute.__original = originalAttribute;
  13713. }
  13714. geometryGroup.__webglCustomAttributesList.push( attribute );
  13715. }
  13716. }
  13717. geometryGroup.__inittedArrays = true;
  13718. };
  13719. // Buffer setting
  13720. this.setPointCloudBuffers = function ( geometry, hint, object ) {
  13721. var v, c, vertex, offset, color,
  13722. vertices = geometry.vertices,
  13723. vl = vertices.length,
  13724. colors = geometry.colors,
  13725. cl = colors.length,
  13726. vertexArray = geometry.__vertexArray,
  13727. colorArray = geometry.__colorArray,
  13728. dirtyVertices = geometry.verticesNeedUpdate,
  13729. dirtyColors = geometry.colorsNeedUpdate,
  13730. customAttributes = geometry.__webglCustomAttributesList,
  13731. i, il,
  13732. ca, cal, value,
  13733. customAttribute;
  13734. if ( dirtyVertices ) {
  13735. for ( v = 0; v < vl; v ++ ) {
  13736. vertex = vertices[ v ];
  13737. offset = v * 3;
  13738. vertexArray[ offset ] = vertex.x;
  13739. vertexArray[ offset + 1 ] = vertex.y;
  13740. vertexArray[ offset + 2 ] = vertex.z;
  13741. }
  13742. gl.bindBuffer( gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  13743. gl.bufferData( gl.ARRAY_BUFFER, vertexArray, hint );
  13744. }
  13745. if ( dirtyColors ) {
  13746. for ( c = 0; c < cl; c ++ ) {
  13747. color = colors[ c ];
  13748. offset = c * 3;
  13749. colorArray[ offset ] = color.r;
  13750. colorArray[ offset + 1 ] = color.g;
  13751. colorArray[ offset + 2 ] = color.b;
  13752. }
  13753. gl.bindBuffer( gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  13754. gl.bufferData( gl.ARRAY_BUFFER, colorArray, hint );
  13755. }
  13756. if ( customAttributes ) {
  13757. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13758. customAttribute = customAttributes[ i ];
  13759. if ( customAttribute.needsUpdate && ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) ) {
  13760. cal = customAttribute.value.length;
  13761. offset = 0;
  13762. if ( customAttribute.size === 1 ) {
  13763. for ( ca = 0; ca < cal; ca ++ ) {
  13764. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  13765. }
  13766. } else if ( customAttribute.size === 2 ) {
  13767. for ( ca = 0; ca < cal; ca ++ ) {
  13768. value = customAttribute.value[ ca ];
  13769. customAttribute.array[ offset ] = value.x;
  13770. customAttribute.array[ offset + 1 ] = value.y;
  13771. offset += 2;
  13772. }
  13773. } else if ( customAttribute.size === 3 ) {
  13774. if ( customAttribute.type === 'c' ) {
  13775. for ( ca = 0; ca < cal; ca ++ ) {
  13776. value = customAttribute.value[ ca ];
  13777. customAttribute.array[ offset ] = value.r;
  13778. customAttribute.array[ offset + 1 ] = value.g;
  13779. customAttribute.array[ offset + 2 ] = value.b;
  13780. offset += 3;
  13781. }
  13782. } else {
  13783. for ( ca = 0; ca < cal; ca ++ ) {
  13784. value = customAttribute.value[ ca ];
  13785. customAttribute.array[ offset ] = value.x;
  13786. customAttribute.array[ offset + 1 ] = value.y;
  13787. customAttribute.array[ offset + 2 ] = value.z;
  13788. offset += 3;
  13789. }
  13790. }
  13791. } else if ( customAttribute.size === 4 ) {
  13792. for ( ca = 0; ca < cal; ca ++ ) {
  13793. value = customAttribute.value[ ca ];
  13794. customAttribute.array[ offset ] = value.x;
  13795. customAttribute.array[ offset + 1 ] = value.y;
  13796. customAttribute.array[ offset + 2 ] = value.z;
  13797. customAttribute.array[ offset + 3 ] = value.w;
  13798. offset += 4;
  13799. }
  13800. }
  13801. }
  13802. gl.bindBuffer( gl.ARRAY_BUFFER, customAttribute.buffer );
  13803. gl.bufferData( gl.ARRAY_BUFFER, customAttribute.array, hint );
  13804. customAttribute.needsUpdate = false;
  13805. }
  13806. }
  13807. }
  13808. this.setLineBuffers = function ( geometry, hint ) {
  13809. var v, c, d, vertex, offset, color,
  13810. vertices = geometry.vertices,
  13811. colors = geometry.colors,
  13812. lineDistances = geometry.lineDistances,
  13813. vl = vertices.length,
  13814. cl = colors.length,
  13815. dl = lineDistances.length,
  13816. vertexArray = geometry.__vertexArray,
  13817. colorArray = geometry.__colorArray,
  13818. lineDistanceArray = geometry.__lineDistanceArray,
  13819. dirtyVertices = geometry.verticesNeedUpdate,
  13820. dirtyColors = geometry.colorsNeedUpdate,
  13821. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  13822. customAttributes = geometry.__webglCustomAttributesList,
  13823. i, il,
  13824. ca, cal, value,
  13825. customAttribute;
  13826. if ( dirtyVertices ) {
  13827. for ( v = 0; v < vl; v ++ ) {
  13828. vertex = vertices[ v ];
  13829. offset = v * 3;
  13830. vertexArray[ offset ] = vertex.x;
  13831. vertexArray[ offset + 1 ] = vertex.y;
  13832. vertexArray[ offset + 2 ] = vertex.z;
  13833. }
  13834. gl.bindBuffer( gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  13835. gl.bufferData( gl.ARRAY_BUFFER, vertexArray, hint );
  13836. }
  13837. if ( dirtyColors ) {
  13838. for ( c = 0; c < cl; c ++ ) {
  13839. color = colors[ c ];
  13840. offset = c * 3;
  13841. colorArray[ offset ] = color.r;
  13842. colorArray[ offset + 1 ] = color.g;
  13843. colorArray[ offset + 2 ] = color.b;
  13844. }
  13845. gl.bindBuffer( gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  13846. gl.bufferData( gl.ARRAY_BUFFER, colorArray, hint );
  13847. }
  13848. if ( dirtyLineDistances ) {
  13849. for ( d = 0; d < dl; d ++ ) {
  13850. lineDistanceArray[ d ] = lineDistances[ d ];
  13851. }
  13852. gl.bindBuffer( gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  13853. gl.bufferData( gl.ARRAY_BUFFER, lineDistanceArray, hint );
  13854. }
  13855. if ( customAttributes ) {
  13856. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13857. customAttribute = customAttributes[ i ];
  13858. if ( customAttribute.needsUpdate && ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) ) {
  13859. offset = 0;
  13860. cal = customAttribute.value.length;
  13861. if ( customAttribute.size === 1 ) {
  13862. for ( ca = 0; ca < cal; ca ++ ) {
  13863. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  13864. }
  13865. } else if ( customAttribute.size === 2 ) {
  13866. for ( ca = 0; ca < cal; ca ++ ) {
  13867. value = customAttribute.value[ ca ];
  13868. customAttribute.array[ offset ] = value.x;
  13869. customAttribute.array[ offset + 1 ] = value.y;
  13870. offset += 2;
  13871. }
  13872. } else if ( customAttribute.size === 3 ) {
  13873. if ( customAttribute.type === 'c' ) {
  13874. for ( ca = 0; ca < cal; ca ++ ) {
  13875. value = customAttribute.value[ ca ];
  13876. customAttribute.array[ offset ] = value.r;
  13877. customAttribute.array[ offset + 1 ] = value.g;
  13878. customAttribute.array[ offset + 2 ] = value.b;
  13879. offset += 3;
  13880. }
  13881. } else {
  13882. for ( ca = 0; ca < cal; ca ++ ) {
  13883. value = customAttribute.value[ ca ];
  13884. customAttribute.array[ offset ] = value.x;
  13885. customAttribute.array[ offset + 1 ] = value.y;
  13886. customAttribute.array[ offset + 2 ] = value.z;
  13887. offset += 3;
  13888. }
  13889. }
  13890. } else if ( customAttribute.size === 4 ) {
  13891. for ( ca = 0; ca < cal; ca ++ ) {
  13892. value = customAttribute.value[ ca ];
  13893. customAttribute.array[ offset ] = value.x;
  13894. customAttribute.array[ offset + 1 ] = value.y;
  13895. customAttribute.array[ offset + 2 ] = value.z;
  13896. customAttribute.array[ offset + 3 ] = value.w;
  13897. offset += 4;
  13898. }
  13899. }
  13900. gl.bindBuffer( gl.ARRAY_BUFFER, customAttribute.buffer );
  13901. gl.bufferData( gl.ARRAY_BUFFER, customAttribute.array, hint );
  13902. customAttribute.needsUpdate = false;
  13903. }
  13904. }
  13905. }
  13906. }
  13907. function materialNeedsFaceNormals ( material ) {
  13908. return material instanceof THREE.MeshPhongMaterial === false && material.shading === THREE.FlatShading;
  13909. }
  13910. this.setMeshBuffers = function ( geometryGroup, object, hint, dispose, material ) {
  13911. if ( ! geometryGroup.__inittedArrays ) {
  13912. return;
  13913. }
  13914. var needsFaceNormals = materialNeedsFaceNormals( material );
  13915. var f, fl, fi, face,
  13916. vertexNormals, faceNormal,
  13917. vertexColors, faceColor,
  13918. vertexTangents,
  13919. uv, uv2, v1, v2, v3, t1, t2, t3, n1, n2, n3,
  13920. c1, c2, c3,
  13921. sw1, sw2, sw3,
  13922. si1, si2, si3,
  13923. i, il,
  13924. vn, uvi, uv2i,
  13925. vk, vkl, vka,
  13926. nka, chf, faceVertexNormals,
  13927. vertexIndex = 0,
  13928. offset = 0,
  13929. offset_uv = 0,
  13930. offset_uv2 = 0,
  13931. offset_face = 0,
  13932. offset_normal = 0,
  13933. offset_tangent = 0,
  13934. offset_line = 0,
  13935. offset_color = 0,
  13936. offset_skin = 0,
  13937. offset_morphTarget = 0,
  13938. offset_custom = 0,
  13939. value,
  13940. vertexArray = geometryGroup.__vertexArray,
  13941. uvArray = geometryGroup.__uvArray,
  13942. uv2Array = geometryGroup.__uv2Array,
  13943. normalArray = geometryGroup.__normalArray,
  13944. tangentArray = geometryGroup.__tangentArray,
  13945. colorArray = geometryGroup.__colorArray,
  13946. skinIndexArray = geometryGroup.__skinIndexArray,
  13947. skinWeightArray = geometryGroup.__skinWeightArray,
  13948. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  13949. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  13950. customAttributes = geometryGroup.__webglCustomAttributesList,
  13951. customAttribute,
  13952. faceArray = geometryGroup.__faceArray,
  13953. lineArray = geometryGroup.__lineArray,
  13954. geometry = object.geometry, // this is shared for all chunks
  13955. dirtyVertices = geometry.verticesNeedUpdate,
  13956. dirtyElements = geometry.elementsNeedUpdate,
  13957. dirtyUvs = geometry.uvsNeedUpdate,
  13958. dirtyNormals = geometry.normalsNeedUpdate,
  13959. dirtyTangents = geometry.tangentsNeedUpdate,
  13960. dirtyColors = geometry.colorsNeedUpdate,
  13961. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  13962. vertices = geometry.vertices,
  13963. chunk_faces3 = geometryGroup.faces3,
  13964. obj_faces = geometry.faces,
  13965. obj_uvs = geometry.faceVertexUvs[ 0 ],
  13966. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  13967. obj_skinIndices = geometry.skinIndices,
  13968. obj_skinWeights = geometry.skinWeights,
  13969. morphTargets = geometry.morphTargets,
  13970. morphNormals = geometry.morphNormals;
  13971. if ( dirtyVertices ) {
  13972. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13973. face = obj_faces[ chunk_faces3[ f ] ];
  13974. v1 = vertices[ face.a ];
  13975. v2 = vertices[ face.b ];
  13976. v3 = vertices[ face.c ];
  13977. vertexArray[ offset ] = v1.x;
  13978. vertexArray[ offset + 1 ] = v1.y;
  13979. vertexArray[ offset + 2 ] = v1.z;
  13980. vertexArray[ offset + 3 ] = v2.x;
  13981. vertexArray[ offset + 4 ] = v2.y;
  13982. vertexArray[ offset + 5 ] = v2.z;
  13983. vertexArray[ offset + 6 ] = v3.x;
  13984. vertexArray[ offset + 7 ] = v3.y;
  13985. vertexArray[ offset + 8 ] = v3.z;
  13986. offset += 9;
  13987. }
  13988. gl.bindBuffer( gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13989. gl.bufferData( gl.ARRAY_BUFFER, vertexArray, hint );
  13990. }
  13991. if ( dirtyMorphTargets ) {
  13992. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  13993. offset_morphTarget = 0;
  13994. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13995. chf = chunk_faces3[ f ];
  13996. face = obj_faces[ chf ];
  13997. // morph positions
  13998. v1 = morphTargets[ vk ].vertices[ face.a ];
  13999. v2 = morphTargets[ vk ].vertices[ face.b ];
  14000. v3 = morphTargets[ vk ].vertices[ face.c ];
  14001. vka = morphTargetsArrays[ vk ];
  14002. vka[ offset_morphTarget ] = v1.x;
  14003. vka[ offset_morphTarget + 1 ] = v1.y;
  14004. vka[ offset_morphTarget + 2 ] = v1.z;
  14005. vka[ offset_morphTarget + 3 ] = v2.x;
  14006. vka[ offset_morphTarget + 4 ] = v2.y;
  14007. vka[ offset_morphTarget + 5 ] = v2.z;
  14008. vka[ offset_morphTarget + 6 ] = v3.x;
  14009. vka[ offset_morphTarget + 7 ] = v3.y;
  14010. vka[ offset_morphTarget + 8 ] = v3.z;
  14011. // morph normals
  14012. if ( material.morphNormals ) {
  14013. if ( needsFaceNormals ) {
  14014. n1 = morphNormals[ vk ].faceNormals[ chf ];
  14015. n2 = n1;
  14016. n3 = n1;
  14017. } else {
  14018. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  14019. n1 = faceVertexNormals.a;
  14020. n2 = faceVertexNormals.b;
  14021. n3 = faceVertexNormals.c;
  14022. }
  14023. nka = morphNormalsArrays[ vk ];
  14024. nka[ offset_morphTarget ] = n1.x;
  14025. nka[ offset_morphTarget + 1 ] = n1.y;
  14026. nka[ offset_morphTarget + 2 ] = n1.z;
  14027. nka[ offset_morphTarget + 3 ] = n2.x;
  14028. nka[ offset_morphTarget + 4 ] = n2.y;
  14029. nka[ offset_morphTarget + 5 ] = n2.z;
  14030. nka[ offset_morphTarget + 6 ] = n3.x;
  14031. nka[ offset_morphTarget + 7 ] = n3.y;
  14032. nka[ offset_morphTarget + 8 ] = n3.z;
  14033. }
  14034. //
  14035. offset_morphTarget += 9;
  14036. }
  14037. gl.bindBuffer( gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  14038. gl.bufferData( gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  14039. if ( material.morphNormals ) {
  14040. gl.bindBuffer( gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  14041. gl.bufferData( gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  14042. }
  14043. }
  14044. }
  14045. if ( obj_skinWeights.length ) {
  14046. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14047. face = obj_faces[ chunk_faces3[ f ] ];
  14048. // weights
  14049. sw1 = obj_skinWeights[ face.a ];
  14050. sw2 = obj_skinWeights[ face.b ];
  14051. sw3 = obj_skinWeights[ face.c ];
  14052. skinWeightArray[ offset_skin ] = sw1.x;
  14053. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  14054. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  14055. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  14056. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  14057. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  14058. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  14059. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  14060. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  14061. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  14062. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  14063. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  14064. // indices
  14065. si1 = obj_skinIndices[ face.a ];
  14066. si2 = obj_skinIndices[ face.b ];
  14067. si3 = obj_skinIndices[ face.c ];
  14068. skinIndexArray[ offset_skin ] = si1.x;
  14069. skinIndexArray[ offset_skin + 1 ] = si1.y;
  14070. skinIndexArray[ offset_skin + 2 ] = si1.z;
  14071. skinIndexArray[ offset_skin + 3 ] = si1.w;
  14072. skinIndexArray[ offset_skin + 4 ] = si2.x;
  14073. skinIndexArray[ offset_skin + 5 ] = si2.y;
  14074. skinIndexArray[ offset_skin + 6 ] = si2.z;
  14075. skinIndexArray[ offset_skin + 7 ] = si2.w;
  14076. skinIndexArray[ offset_skin + 8 ] = si3.x;
  14077. skinIndexArray[ offset_skin + 9 ] = si3.y;
  14078. skinIndexArray[ offset_skin + 10 ] = si3.z;
  14079. skinIndexArray[ offset_skin + 11 ] = si3.w;
  14080. offset_skin += 12;
  14081. }
  14082. if ( offset_skin > 0 ) {
  14083. gl.bindBuffer( gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  14084. gl.bufferData( gl.ARRAY_BUFFER, skinIndexArray, hint );
  14085. gl.bindBuffer( gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  14086. gl.bufferData( gl.ARRAY_BUFFER, skinWeightArray, hint );
  14087. }
  14088. }
  14089. if ( dirtyColors ) {
  14090. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14091. face = obj_faces[ chunk_faces3[ f ] ];
  14092. vertexColors = face.vertexColors;
  14093. faceColor = face.color;
  14094. if ( vertexColors.length === 3 && material.vertexColors === THREE.VertexColors ) {
  14095. c1 = vertexColors[ 0 ];
  14096. c2 = vertexColors[ 1 ];
  14097. c3 = vertexColors[ 2 ];
  14098. } else {
  14099. c1 = faceColor;
  14100. c2 = faceColor;
  14101. c3 = faceColor;
  14102. }
  14103. colorArray[ offset_color ] = c1.r;
  14104. colorArray[ offset_color + 1 ] = c1.g;
  14105. colorArray[ offset_color + 2 ] = c1.b;
  14106. colorArray[ offset_color + 3 ] = c2.r;
  14107. colorArray[ offset_color + 4 ] = c2.g;
  14108. colorArray[ offset_color + 5 ] = c2.b;
  14109. colorArray[ offset_color + 6 ] = c3.r;
  14110. colorArray[ offset_color + 7 ] = c3.g;
  14111. colorArray[ offset_color + 8 ] = c3.b;
  14112. offset_color += 9;
  14113. }
  14114. if ( offset_color > 0 ) {
  14115. gl.bindBuffer( gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  14116. gl.bufferData( gl.ARRAY_BUFFER, colorArray, hint );
  14117. }
  14118. }
  14119. if ( dirtyTangents && geometry.hasTangents ) {
  14120. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14121. face = obj_faces[ chunk_faces3[ f ] ];
  14122. vertexTangents = face.vertexTangents;
  14123. t1 = vertexTangents[ 0 ];
  14124. t2 = vertexTangents[ 1 ];
  14125. t3 = vertexTangents[ 2 ];
  14126. tangentArray[ offset_tangent ] = t1.x;
  14127. tangentArray[ offset_tangent + 1 ] = t1.y;
  14128. tangentArray[ offset_tangent + 2 ] = t1.z;
  14129. tangentArray[ offset_tangent + 3 ] = t1.w;
  14130. tangentArray[ offset_tangent + 4 ] = t2.x;
  14131. tangentArray[ offset_tangent + 5 ] = t2.y;
  14132. tangentArray[ offset_tangent + 6 ] = t2.z;
  14133. tangentArray[ offset_tangent + 7 ] = t2.w;
  14134. tangentArray[ offset_tangent + 8 ] = t3.x;
  14135. tangentArray[ offset_tangent + 9 ] = t3.y;
  14136. tangentArray[ offset_tangent + 10 ] = t3.z;
  14137. tangentArray[ offset_tangent + 11 ] = t3.w;
  14138. offset_tangent += 12;
  14139. }
  14140. gl.bindBuffer( gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  14141. gl.bufferData( gl.ARRAY_BUFFER, tangentArray, hint );
  14142. }
  14143. if ( dirtyNormals ) {
  14144. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14145. face = obj_faces[ chunk_faces3[ f ] ];
  14146. vertexNormals = face.vertexNormals;
  14147. faceNormal = face.normal;
  14148. if ( vertexNormals.length === 3 && needsFaceNormals === false ) {
  14149. for ( i = 0; i < 3; i ++ ) {
  14150. vn = vertexNormals[ i ];
  14151. normalArray[ offset_normal ] = vn.x;
  14152. normalArray[ offset_normal + 1 ] = vn.y;
  14153. normalArray[ offset_normal + 2 ] = vn.z;
  14154. offset_normal += 3;
  14155. }
  14156. } else {
  14157. for ( i = 0; i < 3; i ++ ) {
  14158. normalArray[ offset_normal ] = faceNormal.x;
  14159. normalArray[ offset_normal + 1 ] = faceNormal.y;
  14160. normalArray[ offset_normal + 2 ] = faceNormal.z;
  14161. offset_normal += 3;
  14162. }
  14163. }
  14164. }
  14165. gl.bindBuffer( gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  14166. gl.bufferData( gl.ARRAY_BUFFER, normalArray, hint );
  14167. }
  14168. if ( dirtyUvs && obj_uvs ) {
  14169. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14170. fi = chunk_faces3[ f ];
  14171. uv = obj_uvs[ fi ];
  14172. if ( uv === undefined ) continue;
  14173. for ( i = 0; i < 3; i ++ ) {
  14174. uvi = uv[ i ];
  14175. uvArray[ offset_uv ] = uvi.x;
  14176. uvArray[ offset_uv + 1 ] = uvi.y;
  14177. offset_uv += 2;
  14178. }
  14179. }
  14180. if ( offset_uv > 0 ) {
  14181. gl.bindBuffer( gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  14182. gl.bufferData( gl.ARRAY_BUFFER, uvArray, hint );
  14183. }
  14184. }
  14185. if ( dirtyUvs && obj_uvs2 ) {
  14186. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14187. fi = chunk_faces3[ f ];
  14188. uv2 = obj_uvs2[ fi ];
  14189. if ( uv2 === undefined ) continue;
  14190. for ( i = 0; i < 3; i ++ ) {
  14191. uv2i = uv2[ i ];
  14192. uv2Array[ offset_uv2 ] = uv2i.x;
  14193. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  14194. offset_uv2 += 2;
  14195. }
  14196. }
  14197. if ( offset_uv2 > 0 ) {
  14198. gl.bindBuffer( gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  14199. gl.bufferData( gl.ARRAY_BUFFER, uv2Array, hint );
  14200. }
  14201. }
  14202. if ( dirtyElements ) {
  14203. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14204. faceArray[ offset_face ] = vertexIndex;
  14205. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  14206. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  14207. offset_face += 3;
  14208. lineArray[ offset_line ] = vertexIndex;
  14209. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  14210. lineArray[ offset_line + 2 ] = vertexIndex;
  14211. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  14212. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  14213. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  14214. offset_line += 6;
  14215. vertexIndex += 3;
  14216. }
  14217. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  14218. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  14219. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  14220. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  14221. }
  14222. if ( customAttributes ) {
  14223. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  14224. customAttribute = customAttributes[ i ];
  14225. if ( ! customAttribute.__original.needsUpdate ) continue;
  14226. offset_custom = 0;
  14227. if ( customAttribute.size === 1 ) {
  14228. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  14229. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14230. face = obj_faces[ chunk_faces3[ f ] ];
  14231. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  14232. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  14233. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  14234. offset_custom += 3;
  14235. }
  14236. } else if ( customAttribute.boundTo === 'faces' ) {
  14237. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14238. value = customAttribute.value[ chunk_faces3[ f ] ];
  14239. customAttribute.array[ offset_custom ] = value;
  14240. customAttribute.array[ offset_custom + 1 ] = value;
  14241. customAttribute.array[ offset_custom + 2 ] = value;
  14242. offset_custom += 3;
  14243. }
  14244. }
  14245. } else if ( customAttribute.size === 2 ) {
  14246. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  14247. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14248. face = obj_faces[ chunk_faces3[ f ] ];
  14249. v1 = customAttribute.value[ face.a ];
  14250. v2 = customAttribute.value[ face.b ];
  14251. v3 = customAttribute.value[ face.c ];
  14252. customAttribute.array[ offset_custom ] = v1.x;
  14253. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14254. customAttribute.array[ offset_custom + 2 ] = v2.x;
  14255. customAttribute.array[ offset_custom + 3 ] = v2.y;
  14256. customAttribute.array[ offset_custom + 4 ] = v3.x;
  14257. customAttribute.array[ offset_custom + 5 ] = v3.y;
  14258. offset_custom += 6;
  14259. }
  14260. } else if ( customAttribute.boundTo === 'faces' ) {
  14261. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14262. value = customAttribute.value[ chunk_faces3[ f ] ];
  14263. v1 = value;
  14264. v2 = value;
  14265. v3 = value;
  14266. customAttribute.array[ offset_custom ] = v1.x;
  14267. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14268. customAttribute.array[ offset_custom + 2 ] = v2.x;
  14269. customAttribute.array[ offset_custom + 3 ] = v2.y;
  14270. customAttribute.array[ offset_custom + 4 ] = v3.x;
  14271. customAttribute.array[ offset_custom + 5 ] = v3.y;
  14272. offset_custom += 6;
  14273. }
  14274. }
  14275. } else if ( customAttribute.size === 3 ) {
  14276. var pp;
  14277. if ( customAttribute.type === 'c' ) {
  14278. pp = [ 'r', 'g', 'b' ];
  14279. } else {
  14280. pp = [ 'x', 'y', 'z' ];
  14281. }
  14282. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  14283. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14284. face = obj_faces[ chunk_faces3[ f ] ];
  14285. v1 = customAttribute.value[ face.a ];
  14286. v2 = customAttribute.value[ face.b ];
  14287. v3 = customAttribute.value[ face.c ];
  14288. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  14289. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  14290. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  14291. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  14292. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  14293. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  14294. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  14295. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  14296. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  14297. offset_custom += 9;
  14298. }
  14299. } else if ( customAttribute.boundTo === 'faces' ) {
  14300. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14301. value = customAttribute.value[ chunk_faces3[ f ] ];
  14302. v1 = value;
  14303. v2 = value;
  14304. v3 = value;
  14305. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  14306. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  14307. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  14308. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  14309. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  14310. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  14311. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  14312. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  14313. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  14314. offset_custom += 9;
  14315. }
  14316. } else if ( customAttribute.boundTo === 'faceVertices' ) {
  14317. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14318. value = customAttribute.value[ chunk_faces3[ f ] ];
  14319. v1 = value[ 0 ];
  14320. v2 = value[ 1 ];
  14321. v3 = value[ 2 ];
  14322. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  14323. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  14324. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  14325. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  14326. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  14327. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  14328. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  14329. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  14330. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  14331. offset_custom += 9;
  14332. }
  14333. }
  14334. } else if ( customAttribute.size === 4 ) {
  14335. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  14336. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14337. face = obj_faces[ chunk_faces3[ f ] ];
  14338. v1 = customAttribute.value[ face.a ];
  14339. v2 = customAttribute.value[ face.b ];
  14340. v3 = customAttribute.value[ face.c ];
  14341. customAttribute.array[ offset_custom ] = v1.x;
  14342. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14343. customAttribute.array[ offset_custom + 2 ] = v1.z;
  14344. customAttribute.array[ offset_custom + 3 ] = v1.w;
  14345. customAttribute.array[ offset_custom + 4 ] = v2.x;
  14346. customAttribute.array[ offset_custom + 5 ] = v2.y;
  14347. customAttribute.array[ offset_custom + 6 ] = v2.z;
  14348. customAttribute.array[ offset_custom + 7 ] = v2.w;
  14349. customAttribute.array[ offset_custom + 8 ] = v3.x;
  14350. customAttribute.array[ offset_custom + 9 ] = v3.y;
  14351. customAttribute.array[ offset_custom + 10 ] = v3.z;
  14352. customAttribute.array[ offset_custom + 11 ] = v3.w;
  14353. offset_custom += 12;
  14354. }
  14355. } else if ( customAttribute.boundTo === 'faces' ) {
  14356. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14357. value = customAttribute.value[ chunk_faces3[ f ] ];
  14358. v1 = value;
  14359. v2 = value;
  14360. v3 = value;
  14361. customAttribute.array[ offset_custom ] = v1.x;
  14362. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14363. customAttribute.array[ offset_custom + 2 ] = v1.z;
  14364. customAttribute.array[ offset_custom + 3 ] = v1.w;
  14365. customAttribute.array[ offset_custom + 4 ] = v2.x;
  14366. customAttribute.array[ offset_custom + 5 ] = v2.y;
  14367. customAttribute.array[ offset_custom + 6 ] = v2.z;
  14368. customAttribute.array[ offset_custom + 7 ] = v2.w;
  14369. customAttribute.array[ offset_custom + 8 ] = v3.x;
  14370. customAttribute.array[ offset_custom + 9 ] = v3.y;
  14371. customAttribute.array[ offset_custom + 10 ] = v3.z;
  14372. customAttribute.array[ offset_custom + 11 ] = v3.w;
  14373. offset_custom += 12;
  14374. }
  14375. } else if ( customAttribute.boundTo === 'faceVertices' ) {
  14376. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14377. value = customAttribute.value[ chunk_faces3[ f ] ];
  14378. v1 = value[ 0 ];
  14379. v2 = value[ 1 ];
  14380. v3 = value[ 2 ];
  14381. customAttribute.array[ offset_custom ] = v1.x;
  14382. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14383. customAttribute.array[ offset_custom + 2 ] = v1.z;
  14384. customAttribute.array[ offset_custom + 3 ] = v1.w;
  14385. customAttribute.array[ offset_custom + 4 ] = v2.x;
  14386. customAttribute.array[ offset_custom + 5 ] = v2.y;
  14387. customAttribute.array[ offset_custom + 6 ] = v2.z;
  14388. customAttribute.array[ offset_custom + 7 ] = v2.w;
  14389. customAttribute.array[ offset_custom + 8 ] = v3.x;
  14390. customAttribute.array[ offset_custom + 9 ] = v3.y;
  14391. customAttribute.array[ offset_custom + 10 ] = v3.z;
  14392. customAttribute.array[ offset_custom + 11 ] = v3.w;
  14393. offset_custom += 12;
  14394. }
  14395. }
  14396. }
  14397. gl.bindBuffer( gl.ARRAY_BUFFER, customAttribute.buffer );
  14398. gl.bufferData( gl.ARRAY_BUFFER, customAttribute.array, hint );
  14399. }
  14400. }
  14401. if ( dispose ) {
  14402. delete geometryGroup.__inittedArrays;
  14403. delete geometryGroup.__colorArray;
  14404. delete geometryGroup.__normalArray;
  14405. delete geometryGroup.__tangentArray;
  14406. delete geometryGroup.__uvArray;
  14407. delete geometryGroup.__uv2Array;
  14408. delete geometryGroup.__faceArray;
  14409. delete geometryGroup.__vertexArray;
  14410. delete geometryGroup.__lineArray;
  14411. delete geometryGroup.__skinIndexArray;
  14412. delete geometryGroup.__skinWeightArray;
  14413. }
  14414. };
  14415. this.delete = function ( geometry ) {
  14416. var buffers = [
  14417. '__webglVertexBuffer',
  14418. '__webglNormalBuffer',
  14419. '__webglTangentBuffer',
  14420. '__webglColorBuffer',
  14421. '__webglUVBuffer',
  14422. '__webglUV2Buffer',
  14423. '__webglSkinIndicesBuffer',
  14424. '__webglSkinWeightsBuffer',
  14425. '__webglFaceBuffer',
  14426. '__webglLineBuffer',
  14427. '__webglLineDistanceBuffer'
  14428. ];
  14429. for ( var i = 0, l = buffers.length; i < l; i ++ ) {
  14430. var name = buffers[ i ];
  14431. if ( geometry[ name ] !== undefined ) {
  14432. gl.deleteBuffer( geometry[ name ] );
  14433. delete geometry[ name ];
  14434. }
  14435. }
  14436. // custom attributes
  14437. if ( geometry.__webglCustomAttributesList !== undefined ) {
  14438. for ( var name in geometry.__webglCustomAttributesList ) {
  14439. gl.deleteBuffer( geometry.__webglCustomAttributesList[ name ].buffer );
  14440. }
  14441. delete geometry.__webglCustomAttributesList;
  14442. }
  14443. info.memory.geometries --;
  14444. };
  14445. };
  14446. // File:src/renderers/webgl/WebGLExtensions.js
  14447. /**
  14448. * @author mrdoob / http://mrdoob.com/
  14449. */
  14450. THREE.WebGLExtensions = function ( gl ) {
  14451. var extensions = {};
  14452. this.get = function ( name ) {
  14453. if ( extensions[ name ] !== undefined ) {
  14454. return extensions[ name ];
  14455. }
  14456. var extension;
  14457. switch ( name ) {
  14458. case 'EXT_texture_filter_anisotropic':
  14459. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  14460. break;
  14461. case 'WEBGL_compressed_texture_s3tc':
  14462. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  14463. break;
  14464. case 'WEBGL_compressed_texture_pvrtc':
  14465. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  14466. break;
  14467. default:
  14468. extension = gl.getExtension( name );
  14469. }
  14470. if ( extension === null ) {
  14471. THREE.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  14472. }
  14473. extensions[ name ] = extension;
  14474. return extension;
  14475. };
  14476. };
  14477. // File:src/renderers/webgl/WebGLProgram.js
  14478. THREE.WebGLProgram = ( function () {
  14479. var programIdCount = 0;
  14480. var generateDefines = function ( defines ) {
  14481. var value, chunk, chunks = [];
  14482. for ( var d in defines ) {
  14483. value = defines[ d ];
  14484. if ( value === false ) continue;
  14485. chunk = '#define ' + d + ' ' + value;
  14486. chunks.push( chunk );
  14487. }
  14488. return chunks.join( '\n' );
  14489. };
  14490. var cacheUniformLocations = function ( gl, program, identifiers ) {
  14491. var uniforms = {};
  14492. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  14493. var id = identifiers[ i ];
  14494. uniforms[ id ] = gl.getUniformLocation( program, id );
  14495. }
  14496. return uniforms;
  14497. };
  14498. var cacheAttributeLocations = function ( gl, program, identifiers ) {
  14499. var attributes = {};
  14500. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  14501. var id = identifiers[ i ];
  14502. attributes[ id ] = gl.getAttribLocation( program, id );
  14503. }
  14504. return attributes;
  14505. };
  14506. return function ( renderer, code, material, parameters ) {
  14507. var _this = renderer;
  14508. var _gl = _this.context;
  14509. var defines = material.defines;
  14510. var uniforms = material.__webglShader.uniforms;
  14511. var attributes = material.attributes;
  14512. var vertexShader = material.__webglShader.vertexShader;
  14513. var fragmentShader = material.__webglShader.fragmentShader;
  14514. var index0AttributeName = material.index0AttributeName;
  14515. if ( index0AttributeName === undefined && parameters.morphTargets === true ) {
  14516. // programs with morphTargets displace position out of attribute 0
  14517. index0AttributeName = 'position';
  14518. }
  14519. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  14520. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  14521. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  14522. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  14523. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  14524. }
  14525. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  14526. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  14527. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  14528. if ( parameters.envMap ) {
  14529. switch ( material.envMap.mapping ) {
  14530. case THREE.CubeReflectionMapping:
  14531. case THREE.CubeRefractionMapping:
  14532. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  14533. break;
  14534. case THREE.EquirectangularReflectionMapping:
  14535. case THREE.EquirectangularRefractionMapping:
  14536. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  14537. break;
  14538. case THREE.SphericalReflectionMapping:
  14539. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  14540. break;
  14541. }
  14542. switch ( material.envMap.mapping ) {
  14543. case THREE.CubeRefractionMapping:
  14544. case THREE.EquirectangularRefractionMapping:
  14545. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  14546. break;
  14547. }
  14548. switch ( material.combine ) {
  14549. case THREE.MultiplyOperation:
  14550. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  14551. break;
  14552. case THREE.MixOperation:
  14553. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  14554. break;
  14555. case THREE.AddOperation:
  14556. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  14557. break;
  14558. }
  14559. }
  14560. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  14561. // THREE.log( 'building new program ' );
  14562. //
  14563. var customDefines = generateDefines( defines );
  14564. //
  14565. var program = _gl.createProgram();
  14566. var prefix_vertex, prefix_fragment;
  14567. if ( material instanceof THREE.RawShaderMaterial ) {
  14568. prefix_vertex = '';
  14569. prefix_fragment = '';
  14570. } else {
  14571. prefix_vertex = [
  14572. 'precision ' + parameters.precision + ' float;',
  14573. 'precision ' + parameters.precision + ' int;',
  14574. customDefines,
  14575. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  14576. _this.gammaInput ? '#define GAMMA_INPUT' : '',
  14577. _this.gammaOutput ? '#define GAMMA_OUTPUT' : '',
  14578. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  14579. '#define MAX_DIR_LIGHTS ' + parameters.maxDirLights,
  14580. '#define MAX_POINT_LIGHTS ' + parameters.maxPointLights,
  14581. '#define MAX_SPOT_LIGHTS ' + parameters.maxSpotLights,
  14582. '#define MAX_HEMI_LIGHTS ' + parameters.maxHemiLights,
  14583. '#define MAX_SHADOWS ' + parameters.maxShadows,
  14584. '#define MAX_BONES ' + parameters.maxBones,
  14585. parameters.map ? '#define USE_MAP' : '',
  14586. parameters.envMap ? '#define USE_ENVMAP' : '',
  14587. parameters.envMap ? '#define ' + envMapModeDefine : '',
  14588. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  14589. parameters.aoMap ? '#define USE_AOMAP' : '',
  14590. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  14591. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  14592. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  14593. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  14594. parameters.vertexColors ? '#define USE_COLOR' : '',
  14595. parameters.flatShading ? '#define FLAT_SHADED': '',
  14596. parameters.skinning ? '#define USE_SKINNING' : '',
  14597. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  14598. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  14599. parameters.morphNormals ? '#define USE_MORPHNORMALS' : '',
  14600. parameters.wrapAround ? '#define WRAP_AROUND' : '',
  14601. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  14602. parameters.flipSided ? '#define FLIP_SIDED' : '',
  14603. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  14604. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  14605. parameters.shadowMapDebug ? '#define SHADOWMAP_DEBUG' : '',
  14606. parameters.shadowMapCascade ? '#define SHADOWMAP_CASCADE' : '',
  14607. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  14608. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  14609. //_this._glExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '',
  14610. 'uniform mat4 modelMatrix;',
  14611. 'uniform mat4 modelViewMatrix;',
  14612. 'uniform mat4 projectionMatrix;',
  14613. 'uniform mat4 viewMatrix;',
  14614. 'uniform mat3 normalMatrix;',
  14615. 'uniform vec3 cameraPosition;',
  14616. 'attribute vec3 position;',
  14617. 'attribute vec3 normal;',
  14618. 'attribute vec2 uv;',
  14619. '#ifdef USE_COLOR',
  14620. ' attribute vec3 color;',
  14621. '#endif',
  14622. '#ifdef USE_MORPHTARGETS',
  14623. ' attribute vec3 morphTarget0;',
  14624. ' attribute vec3 morphTarget1;',
  14625. ' attribute vec3 morphTarget2;',
  14626. ' attribute vec3 morphTarget3;',
  14627. ' #ifdef USE_MORPHNORMALS',
  14628. ' attribute vec3 morphNormal0;',
  14629. ' attribute vec3 morphNormal1;',
  14630. ' attribute vec3 morphNormal2;',
  14631. ' attribute vec3 morphNormal3;',
  14632. ' #else',
  14633. ' attribute vec3 morphTarget4;',
  14634. ' attribute vec3 morphTarget5;',
  14635. ' attribute vec3 morphTarget6;',
  14636. ' attribute vec3 morphTarget7;',
  14637. ' #endif',
  14638. '#endif',
  14639. '#ifdef USE_SKINNING',
  14640. ' attribute vec4 skinIndex;',
  14641. ' attribute vec4 skinWeight;',
  14642. '#endif',
  14643. ''
  14644. ].join( '\n' );
  14645. prefix_fragment = [
  14646. 'precision ' + parameters.precision + ' float;',
  14647. 'precision ' + parameters.precision + ' int;',
  14648. ( parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  14649. customDefines,
  14650. '#define MAX_DIR_LIGHTS ' + parameters.maxDirLights,
  14651. '#define MAX_POINT_LIGHTS ' + parameters.maxPointLights,
  14652. '#define MAX_SPOT_LIGHTS ' + parameters.maxSpotLights,
  14653. '#define MAX_HEMI_LIGHTS ' + parameters.maxHemiLights,
  14654. '#define MAX_SHADOWS ' + parameters.maxShadows,
  14655. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  14656. _this.gammaInput ? '#define GAMMA_INPUT' : '',
  14657. _this.gammaOutput ? '#define GAMMA_OUTPUT' : '',
  14658. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  14659. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  14660. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  14661. parameters.map ? '#define USE_MAP' : '',
  14662. parameters.envMap ? '#define USE_ENVMAP' : '',
  14663. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  14664. parameters.envMap ? '#define ' + envMapModeDefine : '',
  14665. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  14666. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  14667. parameters.aoMap ? '#define USE_AOMAP' : '',
  14668. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  14669. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  14670. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  14671. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  14672. parameters.vertexColors ? '#define USE_COLOR' : '',
  14673. parameters.flatShading ? '#define FLAT_SHADED': '',
  14674. parameters.metal ? '#define METAL' : '',
  14675. parameters.wrapAround ? '#define WRAP_AROUND' : '',
  14676. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  14677. parameters.flipSided ? '#define FLIP_SIDED' : '',
  14678. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  14679. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  14680. parameters.shadowMapDebug ? '#define SHADOWMAP_DEBUG' : '',
  14681. parameters.shadowMapCascade ? '#define SHADOWMAP_CASCADE' : '',
  14682. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  14683. //_this._glExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '',
  14684. 'uniform mat4 viewMatrix;',
  14685. 'uniform vec3 cameraPosition;',
  14686. ''
  14687. ].join( '\n' );
  14688. }
  14689. var glVertexShader = new THREE.WebGLShader( _gl, _gl.VERTEX_SHADER, prefix_vertex + vertexShader );
  14690. var glFragmentShader = new THREE.WebGLShader( _gl, _gl.FRAGMENT_SHADER, prefix_fragment + fragmentShader );
  14691. _gl.attachShader( program, glVertexShader );
  14692. _gl.attachShader( program, glFragmentShader );
  14693. if ( index0AttributeName !== undefined ) {
  14694. // Force a particular attribute to index 0.
  14695. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  14696. // And, color, for example is often automatically bound to index 0 so disabling it
  14697. _gl.bindAttribLocation( program, 0, index0AttributeName );
  14698. }
  14699. _gl.linkProgram( program );
  14700. var programLogInfo = _gl.getProgramInfoLog( program );
  14701. var vertexErrorLogInfo = _gl.getShaderInfoLog( glVertexShader );
  14702. var fragmentErrorLogInfo = _gl.getShaderInfoLog( glFragmentShader );
  14703. if ( _gl.getProgramParameter( program, _gl.LINK_STATUS ) === false ) {
  14704. THREE.error( 'THREE.WebGLProgram: shader error: ', _gl.getError(), 'gl.VALIDATE_STATUS', _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLogInfo, vertexErrorLogInfo, fragmentErrorLogInfo );
  14705. }
  14706. if ( programLogInfo !== '' ) {
  14707. THREE.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLogInfo );
  14708. }
  14709. // clean up
  14710. _gl.deleteShader( glVertexShader );
  14711. _gl.deleteShader( glFragmentShader );
  14712. // cache uniform locations
  14713. var identifiers = [
  14714. 'viewMatrix',
  14715. 'modelViewMatrix',
  14716. 'projectionMatrix',
  14717. 'normalMatrix',
  14718. 'modelMatrix',
  14719. 'cameraPosition',
  14720. 'morphTargetInfluences',
  14721. 'bindMatrix',
  14722. 'bindMatrixInverse'
  14723. ];
  14724. if ( parameters.useVertexTexture ) {
  14725. identifiers.push( 'boneTexture' );
  14726. identifiers.push( 'boneTextureWidth' );
  14727. identifiers.push( 'boneTextureHeight' );
  14728. } else {
  14729. identifiers.push( 'boneGlobalMatrices' );
  14730. }
  14731. if ( parameters.logarithmicDepthBuffer ) {
  14732. identifiers.push('logDepthBufFC');
  14733. }
  14734. for ( var u in uniforms ) {
  14735. identifiers.push( u );
  14736. }
  14737. this.uniforms = cacheUniformLocations( _gl, program, identifiers );
  14738. // cache attributes locations
  14739. identifiers = [
  14740. 'position',
  14741. 'normal',
  14742. 'uv',
  14743. 'uv2',
  14744. 'tangent',
  14745. 'color',
  14746. 'skinIndex',
  14747. 'skinWeight',
  14748. 'lineDistance'
  14749. ];
  14750. for ( var i = 0; i < parameters.maxMorphTargets; i ++ ) {
  14751. identifiers.push( 'morphTarget' + i );
  14752. }
  14753. for ( var i = 0; i < parameters.maxMorphNormals; i ++ ) {
  14754. identifiers.push( 'morphNormal' + i );
  14755. }
  14756. for ( var a in attributes ) {
  14757. identifiers.push( a );
  14758. }
  14759. this.attributes = cacheAttributeLocations( _gl, program, identifiers );
  14760. this.attributesKeys = Object.keys( this.attributes );
  14761. //
  14762. this.id = programIdCount ++;
  14763. this.code = code;
  14764. this.usedTimes = 1;
  14765. this.program = program;
  14766. this.vertexShader = glVertexShader;
  14767. this.fragmentShader = glFragmentShader;
  14768. return this;
  14769. };
  14770. } )();
  14771. // File:src/renderers/webgl/WebGLShader.js
  14772. THREE.WebGLShader = ( function () {
  14773. var addLineNumbers = function ( string ) {
  14774. var lines = string.split( '\n' );
  14775. for ( var i = 0; i < lines.length; i ++ ) {
  14776. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  14777. }
  14778. return lines.join( '\n' );
  14779. };
  14780. return function ( gl, type, string ) {
  14781. var shader = gl.createShader( type );
  14782. gl.shaderSource( shader, string );
  14783. gl.compileShader( shader );
  14784. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  14785. THREE.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  14786. }
  14787. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  14788. THREE.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  14789. }
  14790. // --enable-privileged-webgl-extension
  14791. // THREE.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  14792. return shader;
  14793. };
  14794. } )();
  14795. // File:src/renderers/webgl/WebGLShadowMap.js
  14796. /**
  14797. * @author alteredq / http://alteredqualia.com/
  14798. * @author mrdoob / http://mrdoob.com/
  14799. */
  14800. THREE.WebGLShadowMap = function ( _renderer, _lights, _webglObjects, _webglObjectsImmediate ) {
  14801. var _gl = _renderer.context,
  14802. _frustum = new THREE.Frustum(),
  14803. _projScreenMatrix = new THREE.Matrix4(),
  14804. _min = new THREE.Vector3(),
  14805. _max = new THREE.Vector3(),
  14806. _matrixPosition = new THREE.Vector3(),
  14807. _renderList = [];
  14808. // init
  14809. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  14810. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  14811. var _depthMaterial = new THREE.ShaderMaterial( {
  14812. uniforms: depthUniforms,
  14813. vertexShader: depthShader.vertexShader,
  14814. fragmentShader: depthShader.fragmentShader
  14815. } );
  14816. var _depthMaterialMorph = new THREE.ShaderMaterial( {
  14817. uniforms: depthUniforms,
  14818. vertexShader: depthShader.vertexShader,
  14819. fragmentShader: depthShader.fragmentShader,
  14820. morphTargets: true
  14821. } );
  14822. var _depthMaterialSkin = new THREE.ShaderMaterial( {
  14823. uniforms: depthUniforms,
  14824. vertexShader: depthShader.vertexShader,
  14825. fragmentShader: depthShader.fragmentShader,
  14826. skinning: true
  14827. } );
  14828. var _depthMaterialMorphSkin = new THREE.ShaderMaterial( {
  14829. uniforms: depthUniforms,
  14830. vertexShader: depthShader.vertexShader,
  14831. fragmentShader: depthShader.fragmentShader,
  14832. morphTargets: true,
  14833. skinning: true
  14834. } );
  14835. _depthMaterial._shadowPass = true;
  14836. _depthMaterialMorph._shadowPass = true;
  14837. _depthMaterialSkin._shadowPass = true;
  14838. _depthMaterialMorphSkin._shadowPass = true;
  14839. //
  14840. var scope = this;
  14841. this.enabled = false;
  14842. this.type = THREE.PCFShadowMap;
  14843. this.cullFace = THREE.CullFaceFront;
  14844. this.debug = false;
  14845. this.cascade = false;
  14846. this.render = function ( scene, camera ) {
  14847. if ( scope.enabled === false ) return;
  14848. var i, il, j, jl, n,
  14849. shadowMap, shadowMatrix, shadowCamera,
  14850. buffer, material,
  14851. webglObject, object, light,
  14852. lights = [],
  14853. k = 0,
  14854. fog = null;
  14855. // set GL state for depth map
  14856. _gl.clearColor( 1, 1, 1, 1 );
  14857. _gl.disable( _gl.BLEND );
  14858. _gl.enable( _gl.CULL_FACE );
  14859. _gl.frontFace( _gl.CCW );
  14860. if ( scope.cullFace === THREE.CullFaceFront ) {
  14861. _gl.cullFace( _gl.FRONT );
  14862. } else {
  14863. _gl.cullFace( _gl.BACK );
  14864. }
  14865. _renderer.state.setDepthTest( true );
  14866. // preprocess lights
  14867. // - skip lights that are not casting shadows
  14868. // - create virtual lights for cascaded shadow maps
  14869. for ( i = 0, il = _lights.length; i < il; i ++ ) {
  14870. light = _lights[ i ];
  14871. if ( ! light.castShadow ) continue;
  14872. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  14873. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  14874. var virtualLight;
  14875. if ( ! light.shadowCascadeArray[ n ] ) {
  14876. virtualLight = createVirtualLight( light, n );
  14877. virtualLight.originalCamera = camera;
  14878. var gyro = new THREE.Gyroscope();
  14879. gyro.position.copy( light.shadowCascadeOffset );
  14880. gyro.add( virtualLight );
  14881. gyro.add( virtualLight.target );
  14882. camera.add( gyro );
  14883. light.shadowCascadeArray[ n ] = virtualLight;
  14884. //THREE.log( "Created virtualLight", virtualLight );
  14885. } else {
  14886. virtualLight = light.shadowCascadeArray[ n ];
  14887. }
  14888. updateVirtualLight( light, n );
  14889. lights[ k ] = virtualLight;
  14890. k ++;
  14891. }
  14892. } else {
  14893. lights[ k ] = light;
  14894. k ++;
  14895. }
  14896. }
  14897. // render depth map
  14898. for ( i = 0, il = lights.length; i < il; i ++ ) {
  14899. light = lights[ i ];
  14900. if ( ! light.shadowMap ) {
  14901. var shadowFilter = THREE.LinearFilter;
  14902. if ( scope.type === THREE.PCFSoftShadowMap ) {
  14903. shadowFilter = THREE.NearestFilter;
  14904. }
  14905. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  14906. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  14907. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  14908. light.shadowMatrix = new THREE.Matrix4();
  14909. }
  14910. if ( ! light.shadowCamera ) {
  14911. if ( light instanceof THREE.SpotLight ) {
  14912. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  14913. } else if ( light instanceof THREE.DirectionalLight ) {
  14914. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  14915. } else {
  14916. THREE.error( "THREE.ShadowMapPlugin: Unsupported light type for shadow", light );
  14917. continue;
  14918. }
  14919. scene.add( light.shadowCamera );
  14920. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  14921. }
  14922. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  14923. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  14924. scene.add( light.cameraHelper );
  14925. }
  14926. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  14927. updateShadowCamera( camera, light );
  14928. }
  14929. shadowMap = light.shadowMap;
  14930. shadowMatrix = light.shadowMatrix;
  14931. shadowCamera = light.shadowCamera;
  14932. //
  14933. shadowCamera.position.setFromMatrixPosition( light.matrixWorld );
  14934. _matrixPosition.setFromMatrixPosition( light.target.matrixWorld );
  14935. shadowCamera.lookAt( _matrixPosition );
  14936. shadowCamera.updateMatrixWorld();
  14937. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  14938. //
  14939. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  14940. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  14941. // compute shadow matrix
  14942. shadowMatrix.set(
  14943. 0.5, 0.0, 0.0, 0.5,
  14944. 0.0, 0.5, 0.0, 0.5,
  14945. 0.0, 0.0, 0.5, 0.5,
  14946. 0.0, 0.0, 0.0, 1.0
  14947. );
  14948. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  14949. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  14950. // update camera matrices and frustum
  14951. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  14952. _frustum.setFromMatrix( _projScreenMatrix );
  14953. // render shadow map
  14954. _renderer.setRenderTarget( shadowMap );
  14955. _renderer.clear();
  14956. // set object matrices & frustum culling
  14957. _renderList.length = 0;
  14958. projectObject( scene, scene, shadowCamera );
  14959. // render regular objects
  14960. var objectMaterial, useMorphing, useSkinning;
  14961. for ( j = 0, jl = _renderList.length; j < jl; j ++ ) {
  14962. webglObject = _renderList[ j ];
  14963. object = webglObject.object;
  14964. buffer = webglObject.buffer;
  14965. // culling is overriden globally for all objects
  14966. // while rendering depth map
  14967. // need to deal with MeshFaceMaterial somehow
  14968. // in that case just use the first of material.materials for now
  14969. // (proper solution would require to break objects by materials
  14970. // similarly to regular rendering and then set corresponding
  14971. // depth materials per each chunk instead of just once per object)
  14972. objectMaterial = getObjectMaterial( object );
  14973. useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  14974. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  14975. if ( object.customDepthMaterial ) {
  14976. material = object.customDepthMaterial;
  14977. } else if ( useSkinning ) {
  14978. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  14979. } else if ( useMorphing ) {
  14980. material = _depthMaterialMorph;
  14981. } else {
  14982. material = _depthMaterial;
  14983. }
  14984. _renderer.setMaterialFaces( objectMaterial );
  14985. if ( buffer instanceof THREE.BufferGeometry ) {
  14986. _renderer.renderBufferDirect( shadowCamera, _lights, fog, material, buffer, object );
  14987. } else {
  14988. _renderer.renderBuffer( shadowCamera, _lights, fog, material, buffer, object );
  14989. }
  14990. }
  14991. // set matrices and render immediate objects
  14992. for ( j = 0, jl = _webglObjectsImmediate.length; j < jl; j ++ ) {
  14993. webglObject = _webglObjectsImmediate[ j ];
  14994. object = webglObject.object;
  14995. if ( object.visible && object.castShadow ) {
  14996. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  14997. _renderer.renderImmediateObject( shadowCamera, _lights, fog, _depthMaterial, object );
  14998. }
  14999. }
  15000. }
  15001. // restore GL state
  15002. var clearColor = _renderer.getClearColor(),
  15003. clearAlpha = _renderer.getClearAlpha();
  15004. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  15005. _gl.enable( _gl.BLEND );
  15006. if ( scope.cullFace === THREE.CullFaceFront ) {
  15007. _gl.cullFace( _gl.BACK );
  15008. }
  15009. _renderer.resetGLState();
  15010. };
  15011. function projectObject( scene, object, shadowCamera ) {
  15012. if ( object.visible ) {
  15013. var webglObjects = _webglObjects[ object.id ];
  15014. if ( webglObjects && object.castShadow && (object.frustumCulled === false || _frustum.intersectsObject( object ) === true) ) {
  15015. for ( var i = 0, l = webglObjects.length; i < l; i ++ ) {
  15016. var webglObject = webglObjects[ i ];
  15017. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  15018. _renderList.push( webglObject );
  15019. }
  15020. }
  15021. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  15022. projectObject( scene, object.children[ i ], shadowCamera );
  15023. }
  15024. }
  15025. }
  15026. function createVirtualLight( light, cascade ) {
  15027. var virtualLight = new THREE.DirectionalLight();
  15028. virtualLight.isVirtual = true;
  15029. virtualLight.onlyShadow = true;
  15030. virtualLight.castShadow = true;
  15031. virtualLight.shadowCameraNear = light.shadowCameraNear;
  15032. virtualLight.shadowCameraFar = light.shadowCameraFar;
  15033. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  15034. virtualLight.shadowCameraRight = light.shadowCameraRight;
  15035. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  15036. virtualLight.shadowCameraTop = light.shadowCameraTop;
  15037. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  15038. virtualLight.shadowDarkness = light.shadowDarkness;
  15039. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  15040. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  15041. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  15042. virtualLight.pointsWorld = [];
  15043. virtualLight.pointsFrustum = [];
  15044. var pointsWorld = virtualLight.pointsWorld,
  15045. pointsFrustum = virtualLight.pointsFrustum;
  15046. for ( var i = 0; i < 8; i ++ ) {
  15047. pointsWorld[ i ] = new THREE.Vector3();
  15048. pointsFrustum[ i ] = new THREE.Vector3();
  15049. }
  15050. var nearZ = light.shadowCascadeNearZ[ cascade ];
  15051. var farZ = light.shadowCascadeFarZ[ cascade ];
  15052. pointsFrustum[ 0 ].set( - 1, - 1, nearZ );
  15053. pointsFrustum[ 1 ].set( 1, - 1, nearZ );
  15054. pointsFrustum[ 2 ].set( - 1, 1, nearZ );
  15055. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  15056. pointsFrustum[ 4 ].set( - 1, - 1, farZ );
  15057. pointsFrustum[ 5 ].set( 1, - 1, farZ );
  15058. pointsFrustum[ 6 ].set( - 1, 1, farZ );
  15059. pointsFrustum[ 7 ].set( 1, 1, farZ );
  15060. return virtualLight;
  15061. }
  15062. // Synchronize virtual light with the original light
  15063. function updateVirtualLight( light, cascade ) {
  15064. var virtualLight = light.shadowCascadeArray[ cascade ];
  15065. virtualLight.position.copy( light.position );
  15066. virtualLight.target.position.copy( light.target.position );
  15067. virtualLight.lookAt( virtualLight.target );
  15068. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  15069. virtualLight.shadowDarkness = light.shadowDarkness;
  15070. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  15071. var nearZ = light.shadowCascadeNearZ[ cascade ];
  15072. var farZ = light.shadowCascadeFarZ[ cascade ];
  15073. var pointsFrustum = virtualLight.pointsFrustum;
  15074. pointsFrustum[ 0 ].z = nearZ;
  15075. pointsFrustum[ 1 ].z = nearZ;
  15076. pointsFrustum[ 2 ].z = nearZ;
  15077. pointsFrustum[ 3 ].z = nearZ;
  15078. pointsFrustum[ 4 ].z = farZ;
  15079. pointsFrustum[ 5 ].z = farZ;
  15080. pointsFrustum[ 6 ].z = farZ;
  15081. pointsFrustum[ 7 ].z = farZ;
  15082. }
  15083. // Fit shadow camera's ortho frustum to camera frustum
  15084. function updateShadowCamera( camera, light ) {
  15085. var shadowCamera = light.shadowCamera,
  15086. pointsFrustum = light.pointsFrustum,
  15087. pointsWorld = light.pointsWorld;
  15088. _min.set( Infinity, Infinity, Infinity );
  15089. _max.set( - Infinity, - Infinity, - Infinity );
  15090. for ( var i = 0; i < 8; i ++ ) {
  15091. var p = pointsWorld[ i ];
  15092. p.copy( pointsFrustum[ i ] );
  15093. p.unproject( camera );
  15094. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  15095. if ( p.x < _min.x ) _min.x = p.x;
  15096. if ( p.x > _max.x ) _max.x = p.x;
  15097. if ( p.y < _min.y ) _min.y = p.y;
  15098. if ( p.y > _max.y ) _max.y = p.y;
  15099. if ( p.z < _min.z ) _min.z = p.z;
  15100. if ( p.z > _max.z ) _max.z = p.z;
  15101. }
  15102. shadowCamera.left = _min.x;
  15103. shadowCamera.right = _max.x;
  15104. shadowCamera.top = _max.y;
  15105. shadowCamera.bottom = _min.y;
  15106. // can't really fit near/far
  15107. //shadowCamera.near = _min.z;
  15108. //shadowCamera.far = _max.z;
  15109. shadowCamera.updateProjectionMatrix();
  15110. }
  15111. // For the moment just ignore objects that have multiple materials with different animation methods
  15112. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  15113. function getObjectMaterial( object ) {
  15114. return object.material instanceof THREE.MeshFaceMaterial
  15115. ? object.material.materials[ 0 ]
  15116. : object.material;
  15117. };
  15118. };
  15119. // File:src/renderers/webgl/WebGLState.js
  15120. /**
  15121. * @author mrdoob / http://mrdoob.com/
  15122. */
  15123. THREE.WebGLState = function ( gl, paramThreeToGL ) {
  15124. var newAttributes = new Uint8Array( 16 );
  15125. var enabledAttributes = new Uint8Array( 16 );
  15126. var currentBlending = null;
  15127. var currentBlendEquation = null;
  15128. var currentBlendSrc = null;
  15129. var currentBlendDst = null;
  15130. var currentBlendEquationAlpha = null;
  15131. var currentBlendSrcAlpha = null;
  15132. var currentBlendDstAlpha = null;
  15133. var currentDepthTest = null;
  15134. var currentDepthWrite = null;
  15135. var currentColorWrite = null;
  15136. var currentDoubleSided = null;
  15137. var currentFlipSided = null;
  15138. var currentLineWidth = null;
  15139. var currentPolygonOffset = null;
  15140. var currentPolygonOffsetFactor = null;
  15141. var currentPolygonOffsetUnits = null;
  15142. this.initAttributes = function () {
  15143. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  15144. newAttributes[ i ] = 0;
  15145. }
  15146. };
  15147. this.enableAttribute = function ( attribute ) {
  15148. newAttributes[ attribute ] = 1;
  15149. if ( enabledAttributes[ attribute ] === 0 ) {
  15150. gl.enableVertexAttribArray( attribute );
  15151. enabledAttributes[ attribute ] = 1;
  15152. }
  15153. };
  15154. this.disableUnusedAttributes = function () {
  15155. for ( var i = 0, l = enabledAttributes.length; i < l; i ++ ) {
  15156. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  15157. gl.disableVertexAttribArray( i );
  15158. enabledAttributes[ i ] = 0;
  15159. }
  15160. }
  15161. };
  15162. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha ) {
  15163. if ( blending !== currentBlending ) {
  15164. if ( blending === THREE.NoBlending ) {
  15165. gl.disable( gl.BLEND );
  15166. } else if ( blending === THREE.AdditiveBlending ) {
  15167. gl.enable( gl.BLEND );
  15168. gl.blendEquation( gl.FUNC_ADD );
  15169. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  15170. } else if ( blending === THREE.SubtractiveBlending ) {
  15171. // TODO: Find blendFuncSeparate() combination
  15172. gl.enable( gl.BLEND );
  15173. gl.blendEquation( gl.FUNC_ADD );
  15174. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  15175. } else if ( blending === THREE.MultiplyBlending ) {
  15176. // TODO: Find blendFuncSeparate() combination
  15177. gl.enable( gl.BLEND );
  15178. gl.blendEquation( gl.FUNC_ADD );
  15179. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  15180. } else if ( blending === THREE.CustomBlending ) {
  15181. gl.enable( gl.BLEND );
  15182. } else {
  15183. gl.enable( gl.BLEND );
  15184. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  15185. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  15186. }
  15187. currentBlending = blending;
  15188. }
  15189. if ( blending === THREE.CustomBlending ) {
  15190. blendEquationAlpha = blendEquationAlpha || blendEquation;
  15191. blendSrcAlpha = blendSrcAlpha || blendSrc;
  15192. blendDstAlpha = blendDstAlpha || blendDst;
  15193. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  15194. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  15195. currentBlendEquation = blendEquation;
  15196. currentBlendEquationAlpha = blendEquationAlpha;
  15197. }
  15198. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  15199. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  15200. currentBlendSrc = blendSrc;
  15201. currentBlendDst = blendDst;
  15202. currentBlendSrcAlpha = blendSrcAlpha;
  15203. currentBlendDstAlpha = blendDstAlpha;
  15204. }
  15205. } else {
  15206. currentBlendEquation = null;
  15207. currentBlendSrc = null;
  15208. currentBlendDst = null;
  15209. currentBlendEquationAlpha = null;
  15210. currentBlendSrcAlpha = null;
  15211. currentBlendDstAlpha = null;
  15212. }
  15213. };
  15214. this.setDepthTest = function ( depthTest ) {
  15215. if ( currentDepthTest !== depthTest ) {
  15216. if ( depthTest ) {
  15217. gl.enable( gl.DEPTH_TEST );
  15218. } else {
  15219. gl.disable( gl.DEPTH_TEST );
  15220. }
  15221. currentDepthTest = depthTest;
  15222. }
  15223. };
  15224. this.setDepthWrite = function ( depthWrite ) {
  15225. if ( currentDepthWrite !== depthWrite ) {
  15226. gl.depthMask( depthWrite );
  15227. currentDepthWrite = depthWrite;
  15228. }
  15229. };
  15230. this.setColorWrite = function ( colorWrite ) {
  15231. if ( currentColorWrite !== colorWrite ) {
  15232. gl.colorMask( colorWrite, colorWrite, colorWrite, colorWrite );
  15233. currentColorWrite = colorWrite;
  15234. }
  15235. };
  15236. this.setDoubleSided = function ( doubleSided ) {
  15237. if ( currentDoubleSided !== doubleSided ) {
  15238. if ( doubleSided ) {
  15239. gl.disable( gl.CULL_FACE );
  15240. } else {
  15241. gl.enable( gl.CULL_FACE );
  15242. }
  15243. currentDoubleSided = doubleSided;
  15244. }
  15245. };
  15246. this.setFlipSided = function ( flipSided ) {
  15247. if ( currentFlipSided !== flipSided ) {
  15248. if ( flipSided ) {
  15249. gl.frontFace( gl.CW );
  15250. } else {
  15251. gl.frontFace( gl.CCW );
  15252. }
  15253. currentFlipSided = flipSided;
  15254. }
  15255. };
  15256. this.setLineWidth = function ( width ) {
  15257. if ( width !== currentLineWidth ) {
  15258. gl.lineWidth( width );
  15259. currentLineWidth = width;
  15260. }
  15261. };
  15262. this.setPolygonOffset = function ( polygonoffset, factor, units ) {
  15263. if ( currentPolygonOffset !== polygonoffset ) {
  15264. if ( polygonoffset ) {
  15265. gl.enable( gl.POLYGON_OFFSET_FILL );
  15266. } else {
  15267. gl.disable( gl.POLYGON_OFFSET_FILL );
  15268. }
  15269. currentPolygonOffset = polygonoffset;
  15270. }
  15271. if ( polygonoffset && ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) ) {
  15272. gl.polygonOffset( factor, units );
  15273. currentPolygonOffsetFactor = factor;
  15274. currentPolygonOffsetUnits = units;
  15275. }
  15276. };
  15277. this.reset = function () {
  15278. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  15279. enabledAttributes[ i ] = 0;
  15280. }
  15281. currentBlending = null;
  15282. currentDepthTest = null;
  15283. currentDepthWrite = null;
  15284. currentColorWrite = null;
  15285. currentDoubleSided = null;
  15286. currentFlipSided = null;
  15287. };
  15288. };
  15289. // File:src/renderers/webgl/plugins/LensFlarePlugin.js
  15290. /**
  15291. * @author mikael emtinger / http://gomo.se/
  15292. * @author alteredq / http://alteredqualia.com/
  15293. */
  15294. THREE.LensFlarePlugin = function ( renderer, flares ) {
  15295. var gl = renderer.context;
  15296. var vertexBuffer, elementBuffer;
  15297. var program, attributes, uniforms;
  15298. var hasVertexTexture;
  15299. var tempTexture, occlusionTexture;
  15300. var init = function () {
  15301. var vertices = new Float32Array( [
  15302. -1, -1, 0, 0,
  15303. 1, -1, 1, 0,
  15304. 1, 1, 1, 1,
  15305. -1, 1, 0, 1
  15306. ] );
  15307. var faces = new Uint16Array( [
  15308. 0, 1, 2,
  15309. 0, 2, 3
  15310. ] );
  15311. // buffers
  15312. vertexBuffer = gl.createBuffer();
  15313. elementBuffer = gl.createBuffer();
  15314. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  15315. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  15316. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  15317. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  15318. // textures
  15319. tempTexture = gl.createTexture();
  15320. occlusionTexture = gl.createTexture();
  15321. gl.bindTexture( gl.TEXTURE_2D, tempTexture );
  15322. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  15323. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  15324. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  15325. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  15326. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  15327. gl.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  15328. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  15329. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  15330. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  15331. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  15332. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  15333. hasVertexTexture = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) > 0;
  15334. var shader;
  15335. if ( hasVertexTexture ) {
  15336. shader = {
  15337. vertexShader: [
  15338. "uniform lowp int renderType;",
  15339. "uniform vec3 screenPosition;",
  15340. "uniform vec2 scale;",
  15341. "uniform float rotation;",
  15342. "uniform sampler2D occlusionMap;",
  15343. "attribute vec2 position;",
  15344. "attribute vec2 uv;",
  15345. "varying vec2 vUV;",
  15346. "varying float vVisibility;",
  15347. "void main() {",
  15348. "vUV = uv;",
  15349. "vec2 pos = position;",
  15350. "if( renderType == 2 ) {",
  15351. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  15352. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  15353. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  15354. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  15355. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  15356. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  15357. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  15358. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  15359. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  15360. "vVisibility = visibility.r / 9.0;",
  15361. "vVisibility *= 1.0 - visibility.g / 9.0;",
  15362. "vVisibility *= visibility.b / 9.0;",
  15363. "vVisibility *= 1.0 - visibility.a / 9.0;",
  15364. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  15365. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  15366. "}",
  15367. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  15368. "}"
  15369. ].join( "\n" ),
  15370. fragmentShader: [
  15371. "uniform lowp int renderType;",
  15372. "uniform sampler2D map;",
  15373. "uniform float opacity;",
  15374. "uniform vec3 color;",
  15375. "varying vec2 vUV;",
  15376. "varying float vVisibility;",
  15377. "void main() {",
  15378. // pink square
  15379. "if( renderType == 0 ) {",
  15380. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  15381. // restore
  15382. "} else if( renderType == 1 ) {",
  15383. "gl_FragColor = texture2D( map, vUV );",
  15384. // flare
  15385. "} else {",
  15386. "vec4 texture = texture2D( map, vUV );",
  15387. "texture.a *= opacity * vVisibility;",
  15388. "gl_FragColor = texture;",
  15389. "gl_FragColor.rgb *= color;",
  15390. "}",
  15391. "}"
  15392. ].join( "\n" )
  15393. };
  15394. } else {
  15395. shader = {
  15396. vertexShader: [
  15397. "uniform lowp int renderType;",
  15398. "uniform vec3 screenPosition;",
  15399. "uniform vec2 scale;",
  15400. "uniform float rotation;",
  15401. "attribute vec2 position;",
  15402. "attribute vec2 uv;",
  15403. "varying vec2 vUV;",
  15404. "void main() {",
  15405. "vUV = uv;",
  15406. "vec2 pos = position;",
  15407. "if( renderType == 2 ) {",
  15408. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  15409. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  15410. "}",
  15411. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  15412. "}"
  15413. ].join( "\n" ),
  15414. fragmentShader: [
  15415. "precision mediump float;",
  15416. "uniform lowp int renderType;",
  15417. "uniform sampler2D map;",
  15418. "uniform sampler2D occlusionMap;",
  15419. "uniform float opacity;",
  15420. "uniform vec3 color;",
  15421. "varying vec2 vUV;",
  15422. "void main() {",
  15423. // pink square
  15424. "if( renderType == 0 ) {",
  15425. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  15426. // restore
  15427. "} else if( renderType == 1 ) {",
  15428. "gl_FragColor = texture2D( map, vUV );",
  15429. // flare
  15430. "} else {",
  15431. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  15432. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  15433. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  15434. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  15435. "visibility = ( 1.0 - visibility / 4.0 );",
  15436. "vec4 texture = texture2D( map, vUV );",
  15437. "texture.a *= opacity * visibility;",
  15438. "gl_FragColor = texture;",
  15439. "gl_FragColor.rgb *= color;",
  15440. "}",
  15441. "}"
  15442. ].join( "\n" )
  15443. };
  15444. }
  15445. program = createProgram( shader );
  15446. attributes = {
  15447. vertex: gl.getAttribLocation ( program, "position" ),
  15448. uv: gl.getAttribLocation ( program, "uv" )
  15449. }
  15450. uniforms = {
  15451. renderType: gl.getUniformLocation( program, "renderType" ),
  15452. map: gl.getUniformLocation( program, "map" ),
  15453. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  15454. opacity: gl.getUniformLocation( program, "opacity" ),
  15455. color: gl.getUniformLocation( program, "color" ),
  15456. scale: gl.getUniformLocation( program, "scale" ),
  15457. rotation: gl.getUniformLocation( program, "rotation" ),
  15458. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  15459. };
  15460. };
  15461. /*
  15462. * Render lens flares
  15463. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  15464. * reads these back and calculates occlusion.
  15465. */
  15466. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  15467. if ( flares.length === 0 ) return;
  15468. var tempPosition = new THREE.Vector3();
  15469. var invAspect = viewportHeight / viewportWidth,
  15470. halfViewportWidth = viewportWidth * 0.5,
  15471. halfViewportHeight = viewportHeight * 0.5;
  15472. var size = 16 / viewportHeight,
  15473. scale = new THREE.Vector2( size * invAspect, size );
  15474. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  15475. screenPositionPixels = new THREE.Vector2( 1, 1 );
  15476. if ( program === undefined ) {
  15477. init();
  15478. }
  15479. gl.useProgram( program );
  15480. gl.enableVertexAttribArray( attributes.vertex );
  15481. gl.enableVertexAttribArray( attributes.uv );
  15482. // loop through all lens flares to update their occlusion and positions
  15483. // setup gl and common used attribs/unforms
  15484. gl.uniform1i( uniforms.occlusionMap, 0 );
  15485. gl.uniform1i( uniforms.map, 1 );
  15486. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  15487. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  15488. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  15489. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  15490. gl.disable( gl.CULL_FACE );
  15491. gl.depthMask( false );
  15492. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  15493. size = 16 / viewportHeight;
  15494. scale.set( size * invAspect, size );
  15495. // calc object screen position
  15496. var flare = flares[ i ];
  15497. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  15498. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  15499. tempPosition.applyProjection( camera.projectionMatrix );
  15500. // setup arrays for gl programs
  15501. screenPosition.copy( tempPosition )
  15502. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  15503. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  15504. // screen cull
  15505. if ( hasVertexTexture || (
  15506. screenPositionPixels.x > 0 &&
  15507. screenPositionPixels.x < viewportWidth &&
  15508. screenPositionPixels.y > 0 &&
  15509. screenPositionPixels.y < viewportHeight ) ) {
  15510. // save current RGB to temp texture
  15511. gl.activeTexture( gl.TEXTURE1 );
  15512. gl.bindTexture( gl.TEXTURE_2D, tempTexture );
  15513. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  15514. // render pink quad
  15515. gl.uniform1i( uniforms.renderType, 0 );
  15516. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  15517. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  15518. gl.disable( gl.BLEND );
  15519. gl.enable( gl.DEPTH_TEST );
  15520. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  15521. // copy result to occlusionMap
  15522. gl.activeTexture( gl.TEXTURE0 );
  15523. gl.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  15524. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  15525. // restore graphics
  15526. gl.uniform1i( uniforms.renderType, 1 );
  15527. gl.disable( gl.DEPTH_TEST );
  15528. gl.activeTexture( gl.TEXTURE1 );
  15529. gl.bindTexture( gl.TEXTURE_2D, tempTexture );
  15530. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  15531. // update object positions
  15532. flare.positionScreen.copy( screenPosition )
  15533. if ( flare.customUpdateCallback ) {
  15534. flare.customUpdateCallback( flare );
  15535. } else {
  15536. flare.updateLensFlares();
  15537. }
  15538. // render flares
  15539. gl.uniform1i( uniforms.renderType, 2 );
  15540. gl.enable( gl.BLEND );
  15541. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  15542. var sprite = flare.lensFlares[ j ];
  15543. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  15544. screenPosition.x = sprite.x;
  15545. screenPosition.y = sprite.y;
  15546. screenPosition.z = sprite.z;
  15547. size = sprite.size * sprite.scale / viewportHeight;
  15548. scale.x = size * invAspect;
  15549. scale.y = size;
  15550. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  15551. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  15552. gl.uniform1f( uniforms.rotation, sprite.rotation );
  15553. gl.uniform1f( uniforms.opacity, sprite.opacity );
  15554. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  15555. renderer.state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  15556. renderer.setTexture( sprite.texture, 1 );
  15557. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  15558. }
  15559. }
  15560. }
  15561. }
  15562. // restore gl
  15563. gl.enable( gl.CULL_FACE );
  15564. gl.enable( gl.DEPTH_TEST );
  15565. gl.depthMask( true );
  15566. renderer.resetGLState();
  15567. };
  15568. function createProgram ( shader ) {
  15569. var program = gl.createProgram();
  15570. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  15571. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  15572. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  15573. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  15574. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  15575. gl.compileShader( fragmentShader );
  15576. gl.compileShader( vertexShader );
  15577. gl.attachShader( program, fragmentShader );
  15578. gl.attachShader( program, vertexShader );
  15579. gl.linkProgram( program );
  15580. return program;
  15581. }
  15582. };
  15583. // File:src/renderers/webgl/plugins/SpritePlugin.js
  15584. /**
  15585. * @author mikael emtinger / http://gomo.se/
  15586. * @author alteredq / http://alteredqualia.com/
  15587. */
  15588. THREE.SpritePlugin = function ( renderer, sprites ) {
  15589. var gl = renderer.context;
  15590. var vertexBuffer, elementBuffer;
  15591. var program, attributes, uniforms;
  15592. var texture;
  15593. // decompose matrixWorld
  15594. var spritePosition = new THREE.Vector3();
  15595. var spriteRotation = new THREE.Quaternion();
  15596. var spriteScale = new THREE.Vector3();
  15597. var init = function () {
  15598. var vertices = new Float32Array( [
  15599. - 0.5, - 0.5, 0, 0,
  15600. 0.5, - 0.5, 1, 0,
  15601. 0.5, 0.5, 1, 1,
  15602. - 0.5, 0.5, 0, 1
  15603. ] );
  15604. var faces = new Uint16Array( [
  15605. 0, 1, 2,
  15606. 0, 2, 3
  15607. ] );
  15608. vertexBuffer = gl.createBuffer();
  15609. elementBuffer = gl.createBuffer();
  15610. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  15611. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  15612. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  15613. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  15614. program = createProgram();
  15615. attributes = {
  15616. position: gl.getAttribLocation ( program, 'position' ),
  15617. uv: gl.getAttribLocation ( program, 'uv' )
  15618. };
  15619. uniforms = {
  15620. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  15621. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  15622. rotation: gl.getUniformLocation( program, 'rotation' ),
  15623. scale: gl.getUniformLocation( program, 'scale' ),
  15624. color: gl.getUniformLocation( program, 'color' ),
  15625. map: gl.getUniformLocation( program, 'map' ),
  15626. opacity: gl.getUniformLocation( program, 'opacity' ),
  15627. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  15628. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  15629. fogType: gl.getUniformLocation( program, 'fogType' ),
  15630. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  15631. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  15632. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  15633. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  15634. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  15635. };
  15636. var canvas = document.createElement( 'canvas' );
  15637. canvas.width = 8;
  15638. canvas.height = 8;
  15639. var context = canvas.getContext( '2d' );
  15640. context.fillStyle = 'white';
  15641. context.fillRect( 0, 0, 8, 8 );
  15642. texture = new THREE.Texture( canvas );
  15643. texture.needsUpdate = true;
  15644. };
  15645. this.render = function ( scene, camera ) {
  15646. if ( sprites.length === 0 ) return;
  15647. // setup gl
  15648. if ( program === undefined ) {
  15649. init();
  15650. }
  15651. gl.useProgram( program );
  15652. gl.enableVertexAttribArray( attributes.position );
  15653. gl.enableVertexAttribArray( attributes.uv );
  15654. gl.disable( gl.CULL_FACE );
  15655. gl.enable( gl.BLEND );
  15656. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  15657. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  15658. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  15659. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  15660. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  15661. gl.activeTexture( gl.TEXTURE0 );
  15662. gl.uniform1i( uniforms.map, 0 );
  15663. var oldFogType = 0;
  15664. var sceneFogType = 0;
  15665. var fog = scene.fog;
  15666. if ( fog ) {
  15667. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  15668. if ( fog instanceof THREE.Fog ) {
  15669. gl.uniform1f( uniforms.fogNear, fog.near );
  15670. gl.uniform1f( uniforms.fogFar, fog.far );
  15671. gl.uniform1i( uniforms.fogType, 1 );
  15672. oldFogType = 1;
  15673. sceneFogType = 1;
  15674. } else if ( fog instanceof THREE.FogExp2 ) {
  15675. gl.uniform1f( uniforms.fogDensity, fog.density );
  15676. gl.uniform1i( uniforms.fogType, 2 );
  15677. oldFogType = 2;
  15678. sceneFogType = 2;
  15679. }
  15680. } else {
  15681. gl.uniform1i( uniforms.fogType, 0 );
  15682. oldFogType = 0;
  15683. sceneFogType = 0;
  15684. }
  15685. // update positions and sort
  15686. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  15687. var sprite = sprites[ i ];
  15688. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  15689. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  15690. }
  15691. sprites.sort( painterSortStable );
  15692. // render all sprites
  15693. var scale = [];
  15694. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  15695. var sprite = sprites[ i ];
  15696. var material = sprite.material;
  15697. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  15698. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  15699. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  15700. scale[ 0 ] = spriteScale.x;
  15701. scale[ 1 ] = spriteScale.y;
  15702. var fogType = 0;
  15703. if ( scene.fog && material.fog ) {
  15704. fogType = sceneFogType;
  15705. }
  15706. if ( oldFogType !== fogType ) {
  15707. gl.uniform1i( uniforms.fogType, fogType );
  15708. oldFogType = fogType;
  15709. }
  15710. if ( material.map !== null ) {
  15711. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  15712. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  15713. } else {
  15714. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  15715. gl.uniform2f( uniforms.uvScale, 1, 1 );
  15716. }
  15717. gl.uniform1f( uniforms.opacity, material.opacity );
  15718. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  15719. gl.uniform1f( uniforms.rotation, material.rotation );
  15720. gl.uniform2fv( uniforms.scale, scale );
  15721. renderer.state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  15722. renderer.state.setDepthTest( material.depthTest );
  15723. renderer.state.setDepthWrite( material.depthWrite );
  15724. if ( material.map && material.map.image && material.map.image.width ) {
  15725. renderer.setTexture( material.map, 0 );
  15726. } else {
  15727. renderer.setTexture( texture, 0 );
  15728. }
  15729. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  15730. }
  15731. // restore gl
  15732. gl.enable( gl.CULL_FACE );
  15733. renderer.resetGLState();
  15734. };
  15735. function createProgram () {
  15736. var program = gl.createProgram();
  15737. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  15738. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  15739. gl.shaderSource( vertexShader, [
  15740. 'precision ' + renderer.getPrecision() + ' float;',
  15741. 'uniform mat4 modelViewMatrix;',
  15742. 'uniform mat4 projectionMatrix;',
  15743. 'uniform float rotation;',
  15744. 'uniform vec2 scale;',
  15745. 'uniform vec2 uvOffset;',
  15746. 'uniform vec2 uvScale;',
  15747. 'attribute vec2 position;',
  15748. 'attribute vec2 uv;',
  15749. 'varying vec2 vUV;',
  15750. 'void main() {',
  15751. 'vUV = uvOffset + uv * uvScale;',
  15752. 'vec2 alignedPosition = position * scale;',
  15753. 'vec2 rotatedPosition;',
  15754. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  15755. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  15756. 'vec4 finalPosition;',
  15757. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  15758. 'finalPosition.xy += rotatedPosition;',
  15759. 'finalPosition = projectionMatrix * finalPosition;',
  15760. 'gl_Position = finalPosition;',
  15761. '}'
  15762. ].join( '\n' ) );
  15763. gl.shaderSource( fragmentShader, [
  15764. 'precision ' + renderer.getPrecision() + ' float;',
  15765. 'uniform vec3 color;',
  15766. 'uniform sampler2D map;',
  15767. 'uniform float opacity;',
  15768. 'uniform int fogType;',
  15769. 'uniform vec3 fogColor;',
  15770. 'uniform float fogDensity;',
  15771. 'uniform float fogNear;',
  15772. 'uniform float fogFar;',
  15773. 'uniform float alphaTest;',
  15774. 'varying vec2 vUV;',
  15775. 'void main() {',
  15776. 'vec4 texture = texture2D( map, vUV );',
  15777. 'if ( texture.a < alphaTest ) discard;',
  15778. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  15779. 'if ( fogType > 0 ) {',
  15780. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  15781. 'float fogFactor = 0.0;',
  15782. 'if ( fogType == 1 ) {',
  15783. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  15784. '} else {',
  15785. 'const float LOG2 = 1.442695;',
  15786. 'float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  15787. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  15788. '}',
  15789. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  15790. '}',
  15791. '}'
  15792. ].join( '\n' ) );
  15793. gl.compileShader( vertexShader );
  15794. gl.compileShader( fragmentShader );
  15795. gl.attachShader( program, vertexShader );
  15796. gl.attachShader( program, fragmentShader );
  15797. gl.linkProgram( program );
  15798. return program;
  15799. };
  15800. function painterSortStable ( a, b ) {
  15801. if ( a.z !== b.z ) {
  15802. return b.z - a.z;
  15803. } else {
  15804. return b.id - a.id;
  15805. }
  15806. };
  15807. };
  15808. // File:src/extras/GeometryUtils.js
  15809. /**
  15810. * @author mrdoob / http://mrdoob.com/
  15811. */
  15812. THREE.GeometryUtils = {
  15813. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  15814. THREE.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  15815. var matrix;
  15816. if ( geometry2 instanceof THREE.Mesh ) {
  15817. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  15818. matrix = geometry2.matrix;
  15819. geometry2 = geometry2.geometry;
  15820. }
  15821. geometry1.merge( geometry2, matrix, materialIndexOffset );
  15822. },
  15823. center: function ( geometry ) {
  15824. THREE.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  15825. return geometry.center();
  15826. }
  15827. };
  15828. // File:src/extras/ImageUtils.js
  15829. /**
  15830. * @author alteredq / http://alteredqualia.com/
  15831. * @author mrdoob / http://mrdoob.com/
  15832. * @author Daosheng Mu / https://github.com/DaoshengMu/
  15833. */
  15834. THREE.ImageUtils = {
  15835. crossOrigin: undefined,
  15836. loadTexture: function ( url, mapping, onLoad, onError ) {
  15837. var loader = new THREE.ImageLoader();
  15838. loader.crossOrigin = this.crossOrigin;
  15839. var texture = new THREE.Texture( undefined, mapping );
  15840. loader.load( url, function ( image ) {
  15841. texture.image = image;
  15842. texture.needsUpdate = true;
  15843. if ( onLoad ) onLoad( texture );
  15844. }, undefined, function ( event ) {
  15845. if ( onError ) onError( event );
  15846. } );
  15847. texture.sourceFile = url;
  15848. return texture;
  15849. },
  15850. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15851. var images = [];
  15852. var loader = new THREE.ImageLoader();
  15853. loader.crossOrigin = this.crossOrigin;
  15854. var texture = new THREE.CubeTexture( images, mapping );
  15855. // no flipping needed for cube textures
  15856. texture.flipY = false;
  15857. var loaded = 0;
  15858. var loadTexture = function ( i ) {
  15859. loader.load( array[ i ], function ( image ) {
  15860. texture.images[ i ] = image;
  15861. loaded += 1;
  15862. if ( loaded === 6 ) {
  15863. texture.needsUpdate = true;
  15864. if ( onLoad ) onLoad( texture );
  15865. }
  15866. }, undefined, onError );
  15867. }
  15868. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15869. loadTexture( i );
  15870. }
  15871. return texture;
  15872. },
  15873. loadCompressedTexture: function () {
  15874. THREE.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' )
  15875. },
  15876. loadCompressedTextureCube: function () {
  15877. THREE.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' )
  15878. },
  15879. getNormalMap: function ( image, depth ) {
  15880. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  15881. var cross = function ( a, b ) {
  15882. 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 ] ];
  15883. }
  15884. var subtract = function ( a, b ) {
  15885. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  15886. }
  15887. var normalize = function ( a ) {
  15888. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  15889. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  15890. }
  15891. depth = depth | 1;
  15892. var width = image.width;
  15893. var height = image.height;
  15894. var canvas = document.createElement( 'canvas' );
  15895. canvas.width = width;
  15896. canvas.height = height;
  15897. var context = canvas.getContext( '2d' );
  15898. context.drawImage( image, 0, 0 );
  15899. var data = context.getImageData( 0, 0, width, height ).data;
  15900. var imageData = context.createImageData( width, height );
  15901. var output = imageData.data;
  15902. for ( var x = 0; x < width; x ++ ) {
  15903. for ( var y = 0; y < height; y ++ ) {
  15904. var ly = y - 1 < 0 ? 0 : y - 1;
  15905. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  15906. var lx = x - 1 < 0 ? 0 : x - 1;
  15907. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  15908. var points = [];
  15909. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  15910. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  15911. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  15912. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  15913. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  15914. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  15915. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  15916. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  15917. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  15918. var normals = [];
  15919. var num_points = points.length;
  15920. for ( var i = 0; i < num_points; i ++ ) {
  15921. var v1 = points[ i ];
  15922. var v2 = points[ ( i + 1 ) % num_points ];
  15923. v1 = subtract( v1, origin );
  15924. v2 = subtract( v2, origin );
  15925. normals.push( normalize( cross( v1, v2 ) ) );
  15926. }
  15927. var normal = [ 0, 0, 0 ];
  15928. for ( var i = 0; i < normals.length; i ++ ) {
  15929. normal[ 0 ] += normals[ i ][ 0 ];
  15930. normal[ 1 ] += normals[ i ][ 1 ];
  15931. normal[ 2 ] += normals[ i ][ 2 ];
  15932. }
  15933. normal[ 0 ] /= normals.length;
  15934. normal[ 1 ] /= normals.length;
  15935. normal[ 2 ] /= normals.length;
  15936. var idx = ( y * width + x ) * 4;
  15937. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15938. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15939. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  15940. output[ idx + 3 ] = 255;
  15941. }
  15942. }
  15943. context.putImageData( imageData, 0, 0 );
  15944. return canvas;
  15945. },
  15946. generateDataTexture: function ( width, height, color ) {
  15947. var size = width * height;
  15948. var data = new Uint8Array( 3 * size );
  15949. var r = Math.floor( color.r * 255 );
  15950. var g = Math.floor( color.g * 255 );
  15951. var b = Math.floor( color.b * 255 );
  15952. for ( var i = 0; i < size; i ++ ) {
  15953. data[ i * 3 ] = r;
  15954. data[ i * 3 + 1 ] = g;
  15955. data[ i * 3 + 2 ] = b;
  15956. }
  15957. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  15958. texture.needsUpdate = true;
  15959. return texture;
  15960. }
  15961. };
  15962. // File:src/extras/SceneUtils.js
  15963. /**
  15964. * @author alteredq / http://alteredqualia.com/
  15965. */
  15966. THREE.SceneUtils = {
  15967. createMultiMaterialObject: function ( geometry, materials ) {
  15968. var group = new THREE.Object3D();
  15969. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  15970. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  15971. }
  15972. return group;
  15973. },
  15974. detach: function ( child, parent, scene ) {
  15975. child.applyMatrix( parent.matrixWorld );
  15976. parent.remove( child );
  15977. scene.add( child );
  15978. },
  15979. attach: function ( child, scene, parent ) {
  15980. var matrixWorldInverse = new THREE.Matrix4();
  15981. matrixWorldInverse.getInverse( parent.matrixWorld );
  15982. child.applyMatrix( matrixWorldInverse );
  15983. scene.remove( child );
  15984. parent.add( child );
  15985. }
  15986. };
  15987. // File:src/extras/FontUtils.js
  15988. /**
  15989. * @author zz85 / http://www.lab4games.net/zz85/blog
  15990. * @author alteredq / http://alteredqualia.com/
  15991. *
  15992. * For Text operations in three.js (See TextGeometry)
  15993. *
  15994. * It uses techniques used in:
  15995. *
  15996. * typeface.js and canvastext
  15997. * For converting fonts and rendering with javascript
  15998. * http://typeface.neocracy.org
  15999. *
  16000. * Triangulation ported from AS3
  16001. * Simple Polygon Triangulation
  16002. * http://actionsnippet.com/?p=1462
  16003. *
  16004. * A Method to triangulate shapes with holes
  16005. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16006. *
  16007. */
  16008. THREE.FontUtils = {
  16009. faces: {},
  16010. // Just for now. face[weight][style]
  16011. face: 'helvetiker',
  16012. weight: 'normal',
  16013. style: 'normal',
  16014. size: 150,
  16015. divisions: 10,
  16016. getFace: function () {
  16017. try {
  16018. return this.faces[ this.face ][ this.weight ][ this.style ];
  16019. } catch (e) {
  16020. throw "The font " + this.face + " with " + this.weight + " weight and " + this.style + " style is missing."
  16021. };
  16022. },
  16023. loadFace: function ( data ) {
  16024. var family = data.familyName.toLowerCase();
  16025. var ThreeFont = this;
  16026. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16027. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16028. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16029. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16030. return data;
  16031. },
  16032. drawText: function ( text ) {
  16033. // RenderText
  16034. var i,
  16035. face = this.getFace(),
  16036. scale = this.size / face.resolution,
  16037. offset = 0,
  16038. chars = String( text ).split( '' ),
  16039. length = chars.length;
  16040. var fontPaths = [];
  16041. for ( i = 0; i < length; i ++ ) {
  16042. var path = new THREE.Path();
  16043. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16044. offset += ret.offset;
  16045. fontPaths.push( ret.path );
  16046. }
  16047. // get the width
  16048. var width = offset / 2;
  16049. //
  16050. // for ( p = 0; p < allPts.length; p++ ) {
  16051. //
  16052. // allPts[ p ].x -= width;
  16053. //
  16054. // }
  16055. //var extract = this.extractPoints( allPts, characterPts );
  16056. //extract.contour = allPts;
  16057. //extract.paths = fontPaths;
  16058. //extract.offset = width;
  16059. return { paths: fontPaths, offset: width };
  16060. },
  16061. extractGlyphPoints: function ( c, face, scale, offset, path ) {
  16062. var pts = [];
  16063. var i, i2, divisions,
  16064. outline, action, length,
  16065. scaleX, scaleY,
  16066. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16067. laste,
  16068. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16069. if ( ! glyph ) return;
  16070. if ( glyph.o ) {
  16071. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16072. length = outline.length;
  16073. scaleX = scale;
  16074. scaleY = scale;
  16075. for ( i = 0; i < length; ) {
  16076. action = outline[ i ++ ];
  16077. //THREE.log( action );
  16078. switch ( action ) {
  16079. case 'm':
  16080. // Move To
  16081. x = outline[ i ++ ] * scaleX + offset;
  16082. y = outline[ i ++ ] * scaleY;
  16083. path.moveTo( x, y );
  16084. break;
  16085. case 'l':
  16086. // Line To
  16087. x = outline[ i ++ ] * scaleX + offset;
  16088. y = outline[ i ++ ] * scaleY;
  16089. path.lineTo( x, y );
  16090. break;
  16091. case 'q':
  16092. // QuadraticCurveTo
  16093. cpx = outline[ i ++ ] * scaleX + offset;
  16094. cpy = outline[ i ++ ] * scaleY;
  16095. cpx1 = outline[ i ++ ] * scaleX + offset;
  16096. cpy1 = outline[ i ++ ] * scaleY;
  16097. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  16098. laste = pts[ pts.length - 1 ];
  16099. if ( laste ) {
  16100. cpx0 = laste.x;
  16101. cpy0 = laste.y;
  16102. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16103. var t = i2 / divisions;
  16104. THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16105. THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16106. }
  16107. }
  16108. break;
  16109. case 'b':
  16110. // Cubic Bezier Curve
  16111. cpx = outline[ i ++ ] * scaleX + offset;
  16112. cpy = outline[ i ++ ] * scaleY;
  16113. cpx1 = outline[ i ++ ] * scaleX + offset;
  16114. cpy1 = outline[ i ++ ] * scaleY;
  16115. cpx2 = outline[ i ++ ] * scaleX + offset;
  16116. cpy2 = outline[ i ++ ] * scaleY;
  16117. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  16118. laste = pts[ pts.length - 1 ];
  16119. if ( laste ) {
  16120. cpx0 = laste.x;
  16121. cpy0 = laste.y;
  16122. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16123. var t = i2 / divisions;
  16124. THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16125. THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16126. }
  16127. }
  16128. break;
  16129. }
  16130. }
  16131. }
  16132. return { offset: glyph.ha * scale, path:path };
  16133. }
  16134. };
  16135. THREE.FontUtils.generateShapes = function ( text, parameters ) {
  16136. // Parameters
  16137. parameters = parameters || {};
  16138. var size = parameters.size !== undefined ? parameters.size : 100;
  16139. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments : 4;
  16140. var font = parameters.font !== undefined ? parameters.font : 'helvetiker';
  16141. var weight = parameters.weight !== undefined ? parameters.weight : 'normal';
  16142. var style = parameters.style !== undefined ? parameters.style : 'normal';
  16143. THREE.FontUtils.size = size;
  16144. THREE.FontUtils.divisions = curveSegments;
  16145. THREE.FontUtils.face = font;
  16146. THREE.FontUtils.weight = weight;
  16147. THREE.FontUtils.style = style;
  16148. // Get a Font data json object
  16149. var data = THREE.FontUtils.drawText( text );
  16150. var paths = data.paths;
  16151. var shapes = [];
  16152. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16153. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16154. }
  16155. return shapes;
  16156. };
  16157. /**
  16158. * This code is a quick port of code written in C++ which was submitted to
  16159. * flipcode.com by John W. Ratcliff // July 22, 2000
  16160. * See original code and more information here:
  16161. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16162. *
  16163. * ported to actionscript by Zevan Rosser
  16164. * www.actionsnippet.com
  16165. *
  16166. * ported to javascript by Joshua Koo
  16167. * http://www.lab4games.net/zz85/blog
  16168. *
  16169. */
  16170. ( function ( namespace ) {
  16171. var EPSILON = 0.0000000001;
  16172. // takes in an contour array and returns
  16173. var process = function ( contour, indices ) {
  16174. var n = contour.length;
  16175. if ( n < 3 ) return null;
  16176. var result = [],
  16177. verts = [],
  16178. vertIndices = [];
  16179. /* we want a counter-clockwise polygon in verts */
  16180. var u, v, w;
  16181. if ( area( contour ) > 0.0 ) {
  16182. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  16183. } else {
  16184. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  16185. }
  16186. var nv = n;
  16187. /* remove nv - 2 vertices, creating 1 triangle every time */
  16188. var count = 2 * nv; /* error detection */
  16189. for ( v = nv - 1; nv > 2; ) {
  16190. /* if we loop, it is probably a non-simple polygon */
  16191. if ( ( count -- ) <= 0 ) {
  16192. //** Triangulate: ERROR - probable bad polygon!
  16193. //throw ( "Warning, unable to triangulate polygon!" );
  16194. //return null;
  16195. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16196. THREE.warn( 'THREE.FontUtils: Warning, unable to triangulate polygon! in Triangulate.process()' );
  16197. if ( indices ) return vertIndices;
  16198. return result;
  16199. }
  16200. /* three consecutive vertices in current polygon, <u,v,w> */
  16201. u = v; if ( nv <= u ) u = 0; /* previous */
  16202. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16203. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16204. if ( snip( contour, u, v, w, nv, verts ) ) {
  16205. var a, b, c, s, t;
  16206. /* true names of the vertices */
  16207. a = verts[ u ];
  16208. b = verts[ v ];
  16209. c = verts[ w ];
  16210. /* output Triangle */
  16211. result.push( [ contour[ a ],
  16212. contour[ b ],
  16213. contour[ c ] ] );
  16214. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16215. /* remove v from the remaining polygon */
  16216. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  16217. verts[ s ] = verts[ t ];
  16218. }
  16219. nv --;
  16220. /* reset error detection counter */
  16221. count = 2 * nv;
  16222. }
  16223. }
  16224. if ( indices ) return vertIndices;
  16225. return result;
  16226. };
  16227. // calculate area of the contour polygon
  16228. var area = function ( contour ) {
  16229. var n = contour.length;
  16230. var a = 0.0;
  16231. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  16232. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16233. }
  16234. return a * 0.5;
  16235. };
  16236. var snip = function ( contour, u, v, w, n, verts ) {
  16237. var p;
  16238. var ax, ay, bx, by;
  16239. var cx, cy, px, py;
  16240. ax = contour[ verts[ u ] ].x;
  16241. ay = contour[ verts[ u ] ].y;
  16242. bx = contour[ verts[ v ] ].x;
  16243. by = contour[ verts[ v ] ].y;
  16244. cx = contour[ verts[ w ] ].x;
  16245. cy = contour[ verts[ w ] ].y;
  16246. if ( EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false;
  16247. var aX, aY, bX, bY, cX, cY;
  16248. var apx, apy, bpx, bpy, cpx, cpy;
  16249. var cCROSSap, bCROSScp, aCROSSbp;
  16250. aX = cx - bx; aY = cy - by;
  16251. bX = ax - cx; bY = ay - cy;
  16252. cX = bx - ax; cY = by - ay;
  16253. for ( p = 0; p < n; p ++ ) {
  16254. px = contour[ verts[ p ] ].x
  16255. py = contour[ verts[ p ] ].y
  16256. if ( ( ( px === ax ) && ( py === ay ) ) ||
  16257. ( ( px === bx ) && ( py === by ) ) ||
  16258. ( ( px === cx ) && ( py === cy ) ) ) continue;
  16259. apx = px - ax; apy = py - ay;
  16260. bpx = px - bx; bpy = py - by;
  16261. cpx = px - cx; cpy = py - cy;
  16262. // see if p is inside triangle abc
  16263. aCROSSbp = aX * bpy - aY * bpx;
  16264. cCROSSap = cX * apy - cY * apx;
  16265. bCROSScp = bX * cpy - bY * cpx;
  16266. if ( ( aCROSSbp >= - EPSILON ) && ( bCROSScp >= - EPSILON ) && ( cCROSSap >= - EPSILON ) ) return false;
  16267. }
  16268. return true;
  16269. };
  16270. namespace.Triangulate = process;
  16271. namespace.Triangulate.area = area;
  16272. return namespace;
  16273. } )( THREE.FontUtils );
  16274. // To use the typeface.js face files, hook up the API
  16275. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  16276. THREE.typeface_js = self._typeface_js;
  16277. // File:src/extras/audio/Audio.js
  16278. /**
  16279. * @author mrdoob / http://mrdoob.com/
  16280. */
  16281. THREE.Audio = function ( listener ) {
  16282. THREE.Object3D.call( this );
  16283. this.type = 'Audio';
  16284. this.context = listener.context;
  16285. this.source = this.context.createBufferSource();
  16286. this.source.onended = this.onEnded.bind(this);
  16287. this.gain = this.context.createGain();
  16288. this.gain.connect( this.context.destination );
  16289. this.panner = this.context.createPanner();
  16290. this.panner.connect( this.gain );
  16291. this.autoplay = false;
  16292. this.startTime = 0;
  16293. this.isPlaying = false;
  16294. };
  16295. THREE.Audio.prototype = Object.create( THREE.Object3D.prototype );
  16296. THREE.Audio.prototype.constructor = THREE.Audio;
  16297. THREE.Audio.prototype.load = function ( file ) {
  16298. var scope = this;
  16299. var request = new XMLHttpRequest();
  16300. request.open( 'GET', file, true );
  16301. request.responseType = 'arraybuffer';
  16302. request.onload = function ( e ) {
  16303. scope.context.decodeAudioData( this.response, function ( buffer ) {
  16304. scope.source.buffer = buffer;
  16305. if( scope.autoplay ) scope.play();
  16306. } );
  16307. };
  16308. request.send();
  16309. return this;
  16310. };
  16311. THREE.Audio.prototype.play = function () {
  16312. if ( this.isPlaying === true ) {
  16313. THREE.warn( 'THREE.Audio: Audio is already playing.' );
  16314. return;
  16315. }
  16316. var source = this.context.createBufferSource();
  16317. source.buffer = this.source.buffer;
  16318. source.loop = this.source.loop;
  16319. source.onended = this.source.onended;
  16320. source.connect( this.panner );
  16321. source.start( 0, this.startTime );
  16322. this.isPlaying = true;
  16323. this.source = source;
  16324. };
  16325. THREE.Audio.prototype.pause = function () {
  16326. this.source.stop();
  16327. this.startTime = this.context.currentTime;
  16328. };
  16329. THREE.Audio.prototype.stop = function () {
  16330. this.source.stop();
  16331. this.startTime = 0;
  16332. };
  16333. THREE.Audio.prototype.onEnded = function() {
  16334. this.isPlaying = false;
  16335. };
  16336. THREE.Audio.prototype.setLoop = function ( value ) {
  16337. this.source.loop = value;
  16338. };
  16339. THREE.Audio.prototype.setRefDistance = function ( value ) {
  16340. this.panner.refDistance = value;
  16341. };
  16342. THREE.Audio.prototype.setRolloffFactor = function ( value ) {
  16343. this.panner.rolloffFactor = value;
  16344. };
  16345. THREE.Audio.prototype.setVolume = function ( value ) {
  16346. this.gain.gain.value = value;
  16347. };
  16348. THREE.Audio.prototype.updateMatrixWorld = ( function () {
  16349. var position = new THREE.Vector3();
  16350. return function ( force ) {
  16351. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  16352. position.setFromMatrixPosition( this.matrixWorld );
  16353. this.panner.setPosition( position.x, position.y, position.z );
  16354. };
  16355. } )();
  16356. // File:src/extras/audio/AudioListener.js
  16357. /**
  16358. * @author mrdoob / http://mrdoob.com/
  16359. */
  16360. THREE.AudioListener = function () {
  16361. THREE.Object3D.call( this );
  16362. this.type = 'AudioListener';
  16363. this.context = new ( window.AudioContext || window.webkitAudioContext )();
  16364. };
  16365. THREE.AudioListener.prototype = Object.create( THREE.Object3D.prototype );
  16366. THREE.AudioListener.prototype.constructor = THREE.AudioListener;
  16367. THREE.AudioListener.prototype.updateMatrixWorld = ( function () {
  16368. var position = new THREE.Vector3();
  16369. var quaternion = new THREE.Quaternion();
  16370. var scale = new THREE.Vector3();
  16371. var orientation = new THREE.Vector3();
  16372. return function ( force ) {
  16373. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  16374. var listener = this.context.listener;
  16375. var up = this.up;
  16376. this.matrixWorld.decompose( position, quaternion, scale );
  16377. orientation.set( 0, 0, -1 ).applyQuaternion( quaternion );
  16378. listener.setPosition( position.x, position.y, position.z );
  16379. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  16380. };
  16381. } )();
  16382. // File:src/extras/core/Curve.js
  16383. /**
  16384. * @author zz85 / http://www.lab4games.net/zz85/blog
  16385. * Extensible curve object
  16386. *
  16387. * Some common of Curve methods
  16388. * .getPoint(t), getTangent(t)
  16389. * .getPointAt(u), getTagentAt(u)
  16390. * .getPoints(), .getSpacedPoints()
  16391. * .getLength()
  16392. * .updateArcLengths()
  16393. *
  16394. * This following classes subclasses THREE.Curve:
  16395. *
  16396. * -- 2d classes --
  16397. * THREE.LineCurve
  16398. * THREE.QuadraticBezierCurve
  16399. * THREE.CubicBezierCurve
  16400. * THREE.SplineCurve
  16401. * THREE.ArcCurve
  16402. * THREE.EllipseCurve
  16403. *
  16404. * -- 3d classes --
  16405. * THREE.LineCurve3
  16406. * THREE.QuadraticBezierCurve3
  16407. * THREE.CubicBezierCurve3
  16408. * THREE.SplineCurve3
  16409. * THREE.ClosedSplineCurve3
  16410. *
  16411. * A series of curves can be represented as a THREE.CurvePath
  16412. *
  16413. **/
  16414. /**************************************************************
  16415. * Abstract Curve base class
  16416. **************************************************************/
  16417. THREE.Curve = function () {
  16418. };
  16419. // Virtual base class method to overwrite and implement in subclasses
  16420. // - t [0 .. 1]
  16421. THREE.Curve.prototype.getPoint = function ( t ) {
  16422. THREE.warn( "THREE.Curve: Warning, getPoint() not implemented!" );
  16423. return null;
  16424. };
  16425. // Get point at relative position in curve according to arc length
  16426. // - u [0 .. 1]
  16427. THREE.Curve.prototype.getPointAt = function ( u ) {
  16428. var t = this.getUtoTmapping( u );
  16429. return this.getPoint( t );
  16430. };
  16431. // Get sequence of points using getPoint( t )
  16432. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16433. if ( ! divisions ) divisions = 5;
  16434. var d, pts = [];
  16435. for ( d = 0; d <= divisions; d ++ ) {
  16436. pts.push( this.getPoint( d / divisions ) );
  16437. }
  16438. return pts;
  16439. };
  16440. // Get sequence of points using getPointAt( u )
  16441. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16442. if ( ! divisions ) divisions = 5;
  16443. var d, pts = [];
  16444. for ( d = 0; d <= divisions; d ++ ) {
  16445. pts.push( this.getPointAt( d / divisions ) );
  16446. }
  16447. return pts;
  16448. };
  16449. // Get total curve arc length
  16450. THREE.Curve.prototype.getLength = function () {
  16451. var lengths = this.getLengths();
  16452. return lengths[ lengths.length - 1 ];
  16453. };
  16454. // Get list of cumulative segment lengths
  16455. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16456. if ( ! divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions) : 200;
  16457. if ( this.cacheArcLengths
  16458. && ( this.cacheArcLengths.length == divisions + 1 )
  16459. && ! this.needsUpdate) {
  16460. //THREE.log( "cached", this.cacheArcLengths );
  16461. return this.cacheArcLengths;
  16462. }
  16463. this.needsUpdate = false;
  16464. var cache = [];
  16465. var current, last = this.getPoint( 0 );
  16466. var p, sum = 0;
  16467. cache.push( 0 );
  16468. for ( p = 1; p <= divisions; p ++ ) {
  16469. current = this.getPoint ( p / divisions );
  16470. sum += current.distanceTo( last );
  16471. cache.push( sum );
  16472. last = current;
  16473. }
  16474. this.cacheArcLengths = cache;
  16475. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16476. };
  16477. THREE.Curve.prototype.updateArcLengths = function() {
  16478. this.needsUpdate = true;
  16479. this.getLengths();
  16480. };
  16481. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16482. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16483. var arcLengths = this.getLengths();
  16484. var i = 0, il = arcLengths.length;
  16485. var targetArcLength; // The targeted u distance value to get
  16486. if ( distance ) {
  16487. targetArcLength = distance;
  16488. } else {
  16489. targetArcLength = u * arcLengths[ il - 1 ];
  16490. }
  16491. //var time = Date.now();
  16492. // binary search for the index with largest value smaller than target u distance
  16493. var low = 0, high = il - 1, comparison;
  16494. while ( low <= high ) {
  16495. 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
  16496. comparison = arcLengths[ i ] - targetArcLength;
  16497. if ( comparison < 0 ) {
  16498. low = i + 1;
  16499. } else if ( comparison > 0 ) {
  16500. high = i - 1;
  16501. } else {
  16502. high = i;
  16503. break;
  16504. // DONE
  16505. }
  16506. }
  16507. i = high;
  16508. //THREE.log('b' , i, low, high, Date.now()- time);
  16509. if ( arcLengths[ i ] == targetArcLength ) {
  16510. var t = i / ( il - 1 );
  16511. return t;
  16512. }
  16513. // we could get finer grain at lengths, or use simple interpolatation between two points
  16514. var lengthBefore = arcLengths[ i ];
  16515. var lengthAfter = arcLengths[ i + 1 ];
  16516. var segmentLength = lengthAfter - lengthBefore;
  16517. // determine where we are between the 'before' and 'after' points
  16518. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16519. // add that fractional amount to t
  16520. var t = ( i + segmentFraction ) / ( il - 1 );
  16521. return t;
  16522. };
  16523. // Returns a unit vector tangent at t
  16524. // In case any sub curve does not implement its tangent derivation,
  16525. // 2 points a small delta apart will be used to find its gradient
  16526. // which seems to give a reasonable approximation
  16527. THREE.Curve.prototype.getTangent = function( t ) {
  16528. var delta = 0.0001;
  16529. var t1 = t - delta;
  16530. var t2 = t + delta;
  16531. // Capping in case of danger
  16532. if ( t1 < 0 ) t1 = 0;
  16533. if ( t2 > 1 ) t2 = 1;
  16534. var pt1 = this.getPoint( t1 );
  16535. var pt2 = this.getPoint( t2 );
  16536. var vec = pt2.clone().sub(pt1);
  16537. return vec.normalize();
  16538. };
  16539. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16540. var t = this.getUtoTmapping( u );
  16541. return this.getTangent( t );
  16542. };
  16543. /**************************************************************
  16544. * Utils
  16545. **************************************************************/
  16546. THREE.Curve.Utils = {
  16547. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16548. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16549. },
  16550. // Puay Bing, thanks for helping with this derivative!
  16551. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16552. return - 3 * p0 * (1 - t) * (1 - t) +
  16553. 3 * p1 * (1 - t) * (1 - t) - 6 * t * p1 * (1 - t) +
  16554. 6 * t * p2 * (1 - t) - 3 * t * t * p2 +
  16555. 3 * t * t * p3;
  16556. },
  16557. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16558. // To check if my formulas are correct
  16559. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16560. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16561. var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2
  16562. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16563. return h00 + h10 + h01 + h11;
  16564. },
  16565. // Catmull-Rom
  16566. interpolate: function( p0, p1, p2, p3, t ) {
  16567. var v0 = ( p2 - p0 ) * 0.5;
  16568. var v1 = ( p3 - p1 ) * 0.5;
  16569. var t2 = t * t;
  16570. var t3 = t * t2;
  16571. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16572. }
  16573. };
  16574. // TODO: Transformation for Curves?
  16575. /**************************************************************
  16576. * 3D Curves
  16577. **************************************************************/
  16578. // A Factory method for creating new curve subclasses
  16579. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16580. constructor.prototype = Object.create( THREE.Curve.prototype );
  16581. constructor.prototype.constructor = constructor;
  16582. constructor.prototype.getPoint = getPointFunc;
  16583. return constructor;
  16584. };
  16585. // File:src/extras/core/CurvePath.js
  16586. /**
  16587. * @author zz85 / http://www.lab4games.net/zz85/blog
  16588. *
  16589. **/
  16590. /**************************************************************
  16591. * Curved Path - a curve path is simply a array of connected
  16592. * curves, but retains the api of a curve
  16593. **************************************************************/
  16594. THREE.CurvePath = function () {
  16595. this.curves = [];
  16596. this.bends = [];
  16597. this.autoClose = false; // Automatically closes the path
  16598. };
  16599. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16600. THREE.CurvePath.prototype.constructor = THREE.CurvePath;
  16601. THREE.CurvePath.prototype.add = function ( curve ) {
  16602. this.curves.push( curve );
  16603. };
  16604. THREE.CurvePath.prototype.checkConnection = function() {
  16605. // TODO
  16606. // If the ending of curve is not connected to the starting
  16607. // or the next curve, then, this is not a real path
  16608. };
  16609. THREE.CurvePath.prototype.closePath = function() {
  16610. // TODO Test
  16611. // and verify for vector3 (needs to implement equals)
  16612. // Add a line curve if start and end of lines are not connected
  16613. var startPoint = this.curves[0].getPoint(0);
  16614. var endPoint = this.curves[this.curves.length - 1].getPoint(1);
  16615. if (! startPoint.equals(endPoint)) {
  16616. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16617. }
  16618. };
  16619. // To get accurate point with reference to
  16620. // entire path distance at time t,
  16621. // following has to be done:
  16622. // 1. Length of each sub path have to be known
  16623. // 2. Locate and identify type of curve
  16624. // 3. Get t for the curve
  16625. // 4. Return curve.getPointAt(t')
  16626. THREE.CurvePath.prototype.getPoint = function( t ) {
  16627. var d = t * this.getLength();
  16628. var curveLengths = this.getCurveLengths();
  16629. var i = 0, diff, curve;
  16630. // To think about boundaries points.
  16631. while ( i < curveLengths.length ) {
  16632. if ( curveLengths[ i ] >= d ) {
  16633. diff = curveLengths[ i ] - d;
  16634. curve = this.curves[ i ];
  16635. var u = 1 - diff / curve.getLength();
  16636. return curve.getPointAt( u );
  16637. }
  16638. i ++;
  16639. }
  16640. return null;
  16641. // loop where sum != 0, sum > d , sum+1 <d
  16642. };
  16643. /*
  16644. THREE.CurvePath.prototype.getTangent = function( t ) {
  16645. };*/
  16646. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16647. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16648. // getPoint() depends on getLength
  16649. THREE.CurvePath.prototype.getLength = function() {
  16650. var lens = this.getCurveLengths();
  16651. return lens[ lens.length - 1 ];
  16652. };
  16653. // Compute lengths and cache them
  16654. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16655. THREE.CurvePath.prototype.getCurveLengths = function() {
  16656. // We use cache values if curves and cache array are same length
  16657. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16658. return this.cacheLengths;
  16659. };
  16660. // Get length of subsurve
  16661. // Push sums into cached array
  16662. var lengths = [], sums = 0;
  16663. var i, il = this.curves.length;
  16664. for ( i = 0; i < il; i ++ ) {
  16665. sums += this.curves[ i ].getLength();
  16666. lengths.push( sums );
  16667. }
  16668. this.cacheLengths = lengths;
  16669. return lengths;
  16670. };
  16671. // Returns min and max coordinates
  16672. THREE.CurvePath.prototype.getBoundingBox = function () {
  16673. var points = this.getPoints();
  16674. var maxX, maxY, maxZ;
  16675. var minX, minY, minZ;
  16676. maxX = maxY = Number.NEGATIVE_INFINITY;
  16677. minX = minY = Number.POSITIVE_INFINITY;
  16678. var p, i, il, sum;
  16679. var v3 = points[0] instanceof THREE.Vector3;
  16680. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16681. for ( i = 0, il = points.length; i < il; i ++ ) {
  16682. p = points[ i ];
  16683. if ( p.x > maxX ) maxX = p.x;
  16684. else if ( p.x < minX ) minX = p.x;
  16685. if ( p.y > maxY ) maxY = p.y;
  16686. else if ( p.y < minY ) minY = p.y;
  16687. if ( v3 ) {
  16688. if ( p.z > maxZ ) maxZ = p.z;
  16689. else if ( p.z < minZ ) minZ = p.z;
  16690. }
  16691. sum.add( p );
  16692. }
  16693. var ret = {
  16694. minX: minX,
  16695. minY: minY,
  16696. maxX: maxX,
  16697. maxY: maxY
  16698. };
  16699. if ( v3 ) {
  16700. ret.maxZ = maxZ;
  16701. ret.minZ = minZ;
  16702. }
  16703. return ret;
  16704. };
  16705. /**************************************************************
  16706. * Create Geometries Helpers
  16707. **************************************************************/
  16708. /// Generate geometry from path points (for Line or Points objects)
  16709. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16710. var pts = this.getPoints( divisions, true );
  16711. return this.createGeometry( pts );
  16712. };
  16713. // Generate geometry from equidistance sampling along the path
  16714. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16715. var pts = this.getSpacedPoints( divisions, true );
  16716. return this.createGeometry( pts );
  16717. };
  16718. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16719. var geometry = new THREE.Geometry();
  16720. for ( var i = 0; i < points.length; i ++ ) {
  16721. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16722. }
  16723. return geometry;
  16724. };
  16725. /**************************************************************
  16726. * Bend / Wrap Helper Methods
  16727. **************************************************************/
  16728. // Wrap path / Bend modifiers?
  16729. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16730. this.bends.push( bendpath );
  16731. };
  16732. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16733. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16734. var i, il;
  16735. if ( ! bends ) {
  16736. bends = this.bends;
  16737. }
  16738. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16739. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16740. }
  16741. return oldPts;
  16742. };
  16743. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16744. var oldPts = this.getSpacedPoints( segments );
  16745. var i, il;
  16746. if ( ! bends ) {
  16747. bends = this.bends;
  16748. }
  16749. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16750. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16751. }
  16752. return oldPts;
  16753. };
  16754. // This returns getPoints() bend/wrapped around the contour of a path.
  16755. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16756. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16757. var bounds = this.getBoundingBox();
  16758. var i, il, p, oldX, oldY, xNorm;
  16759. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16760. p = oldPts[ i ];
  16761. oldX = p.x;
  16762. oldY = p.y;
  16763. xNorm = oldX / bounds.maxX;
  16764. // If using actual distance, for length > path, requires line extrusions
  16765. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16766. xNorm = path.getUtoTmapping( xNorm, oldX );
  16767. // check for out of bounds?
  16768. var pathPt = path.getPoint( xNorm );
  16769. var normal = path.getTangent( xNorm );
  16770. normal.set( - normal.y, normal.x ).multiplyScalar( oldY );
  16771. p.x = pathPt.x + normal.x;
  16772. p.y = pathPt.y + normal.y;
  16773. }
  16774. return oldPts;
  16775. };
  16776. // File:src/extras/core/Gyroscope.js
  16777. /**
  16778. * @author alteredq / http://alteredqualia.com/
  16779. */
  16780. THREE.Gyroscope = function () {
  16781. THREE.Object3D.call( this );
  16782. };
  16783. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16784. THREE.Gyroscope.prototype.constructor = THREE.Gyroscope;
  16785. THREE.Gyroscope.prototype.updateMatrixWorld = ( function () {
  16786. var translationObject = new THREE.Vector3();
  16787. var quaternionObject = new THREE.Quaternion();
  16788. var scaleObject = new THREE.Vector3();
  16789. var translationWorld = new THREE.Vector3();
  16790. var quaternionWorld = new THREE.Quaternion();
  16791. var scaleWorld = new THREE.Vector3();
  16792. return function ( force ) {
  16793. this.matrixAutoUpdate && this.updateMatrix();
  16794. // update matrixWorld
  16795. if ( this.matrixWorldNeedsUpdate || force ) {
  16796. if ( this.parent ) {
  16797. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  16798. this.matrixWorld.decompose( translationWorld, quaternionWorld, scaleWorld );
  16799. this.matrix.decompose( translationObject, quaternionObject, scaleObject );
  16800. this.matrixWorld.compose( translationWorld, quaternionObject, scaleWorld );
  16801. } else {
  16802. this.matrixWorld.copy( this.matrix );
  16803. }
  16804. this.matrixWorldNeedsUpdate = false;
  16805. force = true;
  16806. }
  16807. // update children
  16808. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16809. this.children[ i ].updateMatrixWorld( force );
  16810. }
  16811. };
  16812. }() );
  16813. // File:src/extras/core/Path.js
  16814. /**
  16815. * @author zz85 / http://www.lab4games.net/zz85/blog
  16816. * Creates free form 2d path using series of points, lines or curves.
  16817. *
  16818. **/
  16819. THREE.Path = function ( points ) {
  16820. THREE.CurvePath.call(this);
  16821. this.actions = [];
  16822. if ( points ) {
  16823. this.fromPoints( points );
  16824. }
  16825. };
  16826. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16827. THREE.Path.prototype.constructor = THREE.Path;
  16828. THREE.PathActions = {
  16829. MOVE_TO: 'moveTo',
  16830. LINE_TO: 'lineTo',
  16831. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16832. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16833. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16834. ARC: 'arc', // Circle
  16835. ELLIPSE: 'ellipse'
  16836. };
  16837. // TODO Clean up PATH API
  16838. // Create path using straight lines to connect all points
  16839. // - vectors: array of Vector2
  16840. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16841. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16842. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16843. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16844. };
  16845. };
  16846. // startPath() endPath()?
  16847. THREE.Path.prototype.moveTo = function ( x, y ) {
  16848. var args = Array.prototype.slice.call( arguments );
  16849. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16850. };
  16851. THREE.Path.prototype.lineTo = function ( x, y ) {
  16852. var args = Array.prototype.slice.call( arguments );
  16853. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16854. var x0 = lastargs[ lastargs.length - 2 ];
  16855. var y0 = lastargs[ lastargs.length - 1 ];
  16856. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16857. this.curves.push( curve );
  16858. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16859. };
  16860. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16861. var args = Array.prototype.slice.call( arguments );
  16862. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16863. var x0 = lastargs[ lastargs.length - 2 ];
  16864. var y0 = lastargs[ lastargs.length - 1 ];
  16865. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16866. new THREE.Vector2( aCPx, aCPy ),
  16867. new THREE.Vector2( aX, aY ) );
  16868. this.curves.push( curve );
  16869. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16870. };
  16871. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16872. aCP2x, aCP2y,
  16873. aX, aY ) {
  16874. var args = Array.prototype.slice.call( arguments );
  16875. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16876. var x0 = lastargs[ lastargs.length - 2 ];
  16877. var y0 = lastargs[ lastargs.length - 1 ];
  16878. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16879. new THREE.Vector2( aCP1x, aCP1y ),
  16880. new THREE.Vector2( aCP2x, aCP2y ),
  16881. new THREE.Vector2( aX, aY ) );
  16882. this.curves.push( curve );
  16883. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16884. };
  16885. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16886. var args = Array.prototype.slice.call( arguments );
  16887. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16888. var x0 = lastargs[ lastargs.length - 2 ];
  16889. var y0 = lastargs[ lastargs.length - 1 ];
  16890. //---
  16891. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16892. Array.prototype.push.apply( npts, pts );
  16893. var curve = new THREE.SplineCurve( npts );
  16894. this.curves.push( curve );
  16895. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16896. };
  16897. // FUTURE: Change the API or follow canvas API?
  16898. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16899. aStartAngle, aEndAngle, aClockwise ) {
  16900. var lastargs = this.actions[ this.actions.length - 1].args;
  16901. var x0 = lastargs[ lastargs.length - 2 ];
  16902. var y0 = lastargs[ lastargs.length - 1 ];
  16903. this.absarc(aX + x0, aY + y0, aRadius,
  16904. aStartAngle, aEndAngle, aClockwise );
  16905. };
  16906. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16907. aStartAngle, aEndAngle, aClockwise ) {
  16908. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16909. };
  16910. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16911. aStartAngle, aEndAngle, aClockwise ) {
  16912. var lastargs = this.actions[ this.actions.length - 1].args;
  16913. var x0 = lastargs[ lastargs.length - 2 ];
  16914. var y0 = lastargs[ lastargs.length - 1 ];
  16915. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16916. aStartAngle, aEndAngle, aClockwise );
  16917. };
  16918. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16919. aStartAngle, aEndAngle, aClockwise ) {
  16920. var args = Array.prototype.slice.call( arguments );
  16921. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16922. aStartAngle, aEndAngle, aClockwise );
  16923. this.curves.push( curve );
  16924. var lastPoint = curve.getPoint(1);
  16925. args.push(lastPoint.x);
  16926. args.push(lastPoint.y);
  16927. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16928. };
  16929. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16930. if ( ! divisions ) divisions = 40;
  16931. var points = [];
  16932. for ( var i = 0; i < divisions; i ++ ) {
  16933. points.push( this.getPoint( i / divisions ) );
  16934. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16935. }
  16936. // if ( closedPath ) {
  16937. //
  16938. // points.push( points[ 0 ] );
  16939. //
  16940. // }
  16941. return points;
  16942. };
  16943. /* Return an array of vectors based on contour of the path */
  16944. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  16945. if (this.useSpacedPoints) {
  16946. THREE.log('tata');
  16947. return this.getSpacedPoints( divisions, closedPath );
  16948. }
  16949. divisions = divisions || 12;
  16950. var points = [];
  16951. var i, il, item, action, args;
  16952. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  16953. laste, j,
  16954. t, tx, ty;
  16955. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16956. item = this.actions[ i ];
  16957. action = item.action;
  16958. args = item.args;
  16959. switch ( action ) {
  16960. case THREE.PathActions.MOVE_TO:
  16961. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16962. break;
  16963. case THREE.PathActions.LINE_TO:
  16964. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16965. break;
  16966. case THREE.PathActions.QUADRATIC_CURVE_TO:
  16967. cpx = args[ 2 ];
  16968. cpy = args[ 3 ];
  16969. cpx1 = args[ 0 ];
  16970. cpy1 = args[ 1 ];
  16971. if ( points.length > 0 ) {
  16972. laste = points[ points.length - 1 ];
  16973. cpx0 = laste.x;
  16974. cpy0 = laste.y;
  16975. } else {
  16976. laste = this.actions[ i - 1 ].args;
  16977. cpx0 = laste[ laste.length - 2 ];
  16978. cpy0 = laste[ laste.length - 1 ];
  16979. }
  16980. for ( j = 1; j <= divisions; j ++ ) {
  16981. t = j / divisions;
  16982. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16983. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16984. points.push( new THREE.Vector2( tx, ty ) );
  16985. }
  16986. break;
  16987. case THREE.PathActions.BEZIER_CURVE_TO:
  16988. cpx = args[ 4 ];
  16989. cpy = args[ 5 ];
  16990. cpx1 = args[ 0 ];
  16991. cpy1 = args[ 1 ];
  16992. cpx2 = args[ 2 ];
  16993. cpy2 = args[ 3 ];
  16994. if ( points.length > 0 ) {
  16995. laste = points[ points.length - 1 ];
  16996. cpx0 = laste.x;
  16997. cpy0 = laste.y;
  16998. } else {
  16999. laste = this.actions[ i - 1 ].args;
  17000. cpx0 = laste[ laste.length - 2 ];
  17001. cpy0 = laste[ laste.length - 1 ];
  17002. }
  17003. for ( j = 1; j <= divisions; j ++ ) {
  17004. t = j / divisions;
  17005. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17006. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17007. points.push( new THREE.Vector2( tx, ty ) );
  17008. }
  17009. break;
  17010. case THREE.PathActions.CSPLINE_THRU:
  17011. laste = this.actions[ i - 1 ].args;
  17012. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17013. var spts = [ last ];
  17014. var n = divisions * args[ 0 ].length;
  17015. spts = spts.concat( args[ 0 ] );
  17016. var spline = new THREE.SplineCurve( spts );
  17017. for ( j = 1; j <= n; j ++ ) {
  17018. points.push( spline.getPointAt( j / n ) ) ;
  17019. }
  17020. break;
  17021. case THREE.PathActions.ARC:
  17022. var aX = args[ 0 ], aY = args[ 1 ],
  17023. aRadius = args[ 2 ],
  17024. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17025. aClockwise = !! args[ 5 ];
  17026. var deltaAngle = aEndAngle - aStartAngle;
  17027. var angle;
  17028. var tdivisions = divisions * 2;
  17029. for ( j = 1; j <= tdivisions; j ++ ) {
  17030. t = j / tdivisions;
  17031. if ( ! aClockwise ) {
  17032. t = 1 - t;
  17033. }
  17034. angle = aStartAngle + t * deltaAngle;
  17035. tx = aX + aRadius * Math.cos( angle );
  17036. ty = aY + aRadius * Math.sin( angle );
  17037. //THREE.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17038. points.push( new THREE.Vector2( tx, ty ) );
  17039. }
  17040. //THREE.log(points);
  17041. break;
  17042. case THREE.PathActions.ELLIPSE:
  17043. var aX = args[ 0 ], aY = args[ 1 ],
  17044. xRadius = args[ 2 ],
  17045. yRadius = args[ 3 ],
  17046. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17047. aClockwise = !! args[ 6 ];
  17048. var deltaAngle = aEndAngle - aStartAngle;
  17049. var angle;
  17050. var tdivisions = divisions * 2;
  17051. for ( j = 1; j <= tdivisions; j ++ ) {
  17052. t = j / tdivisions;
  17053. if ( ! aClockwise ) {
  17054. t = 1 - t;
  17055. }
  17056. angle = aStartAngle + t * deltaAngle;
  17057. tx = aX + xRadius * Math.cos( angle );
  17058. ty = aY + yRadius * Math.sin( angle );
  17059. //THREE.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17060. points.push( new THREE.Vector2( tx, ty ) );
  17061. }
  17062. //THREE.log(points);
  17063. break;
  17064. } // end switch
  17065. }
  17066. // Normalize to remove the closing point by default.
  17067. var lastPoint = points[ points.length - 1];
  17068. var EPSILON = 0.0000000001;
  17069. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17070. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17071. points.splice( points.length - 1, 1);
  17072. if ( closedPath ) {
  17073. points.push( points[ 0 ] );
  17074. }
  17075. return points;
  17076. };
  17077. //
  17078. // Breaks path into shapes
  17079. //
  17080. // Assumptions (if parameter isCCW==true the opposite holds):
  17081. // - solid shapes are defined clockwise (CW)
  17082. // - holes are defined counterclockwise (CCW)
  17083. //
  17084. // If parameter noHoles==true:
  17085. // - all subPaths are regarded as solid shapes
  17086. // - definition order CW/CCW has no relevance
  17087. //
  17088. THREE.Path.prototype.toShapes = function( isCCW, noHoles ) {
  17089. function extractSubpaths( inActions ) {
  17090. var i, il, item, action, args;
  17091. var subPaths = [], lastPath = new THREE.Path();
  17092. for ( i = 0, il = inActions.length; i < il; i ++ ) {
  17093. item = inActions[ i ];
  17094. args = item.args;
  17095. action = item.action;
  17096. if ( action == THREE.PathActions.MOVE_TO ) {
  17097. if ( lastPath.actions.length != 0 ) {
  17098. subPaths.push( lastPath );
  17099. lastPath = new THREE.Path();
  17100. }
  17101. }
  17102. lastPath[ action ].apply( lastPath, args );
  17103. }
  17104. if ( lastPath.actions.length != 0 ) {
  17105. subPaths.push( lastPath );
  17106. }
  17107. // THREE.log(subPaths);
  17108. return subPaths;
  17109. }
  17110. function toShapesNoHoles( inSubpaths ) {
  17111. var shapes = [];
  17112. for ( var i = 0, il = inSubpaths.length; i < il; i ++ ) {
  17113. var tmpPath = inSubpaths[ i ];
  17114. var tmpShape = new THREE.Shape();
  17115. tmpShape.actions = tmpPath.actions;
  17116. tmpShape.curves = tmpPath.curves;
  17117. shapes.push( tmpShape );
  17118. }
  17119. //THREE.log("shape", shapes);
  17120. return shapes;
  17121. };
  17122. function isPointInsidePolygon( inPt, inPolygon ) {
  17123. var EPSILON = 0.0000000001;
  17124. var polyLen = inPolygon.length;
  17125. // inPt on polygon contour => immediate success or
  17126. // toggling of inside/outside at every single! intersection point of an edge
  17127. // with the horizontal line through inPt, left of inPt
  17128. // not counting lowerY endpoints of edges and whole edges on that line
  17129. var inside = false;
  17130. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  17131. var edgeLowPt = inPolygon[ p ];
  17132. var edgeHighPt = inPolygon[ q ];
  17133. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  17134. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  17135. if ( Math.abs(edgeDy) > EPSILON ) { // not parallel
  17136. if ( edgeDy < 0 ) {
  17137. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  17138. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  17139. }
  17140. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  17141. if ( inPt.y == edgeLowPt.y ) {
  17142. if ( inPt.x == edgeLowPt.x ) return true; // inPt is on contour ?
  17143. // continue; // no intersection or edgeLowPt => doesn't count !!!
  17144. } else {
  17145. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  17146. if ( perpEdge == 0 ) return true; // inPt is on contour ?
  17147. if ( perpEdge < 0 ) continue;
  17148. inside = ! inside; // true intersection left of inPt
  17149. }
  17150. } else { // parallel or colinear
  17151. if ( inPt.y != edgeLowPt.y ) continue; // parallel
  17152. // egde lies on the same horizontal line as inPt
  17153. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  17154. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  17155. // continue;
  17156. }
  17157. }
  17158. return inside;
  17159. }
  17160. var subPaths = extractSubpaths( this.actions );
  17161. if ( subPaths.length == 0 ) return [];
  17162. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  17163. var solid, tmpPath, tmpShape, shapes = [];
  17164. if ( subPaths.length == 1) {
  17165. tmpPath = subPaths[0];
  17166. tmpShape = new THREE.Shape();
  17167. tmpShape.actions = tmpPath.actions;
  17168. tmpShape.curves = tmpPath.curves;
  17169. shapes.push( tmpShape );
  17170. return shapes;
  17171. }
  17172. var holesFirst = ! THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17173. holesFirst = isCCW ? ! holesFirst : holesFirst;
  17174. // THREE.log("Holes first", holesFirst);
  17175. var betterShapeHoles = [];
  17176. var newShapes = [];
  17177. var newShapeHoles = [];
  17178. var mainIdx = 0;
  17179. var tmpPoints;
  17180. newShapes[mainIdx] = undefined;
  17181. newShapeHoles[mainIdx] = [];
  17182. var i, il;
  17183. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17184. tmpPath = subPaths[ i ];
  17185. tmpPoints = tmpPath.getPoints();
  17186. solid = THREE.Shape.Utils.isClockWise( tmpPoints );
  17187. solid = isCCW ? ! solid : solid;
  17188. if ( solid ) {
  17189. if ( (! holesFirst ) && ( newShapes[mainIdx] ) ) mainIdx ++;
  17190. newShapes[mainIdx] = { s: new THREE.Shape(), p: tmpPoints };
  17191. newShapes[mainIdx].s.actions = tmpPath.actions;
  17192. newShapes[mainIdx].s.curves = tmpPath.curves;
  17193. if ( holesFirst ) mainIdx ++;
  17194. newShapeHoles[mainIdx] = [];
  17195. //THREE.log('cw', i);
  17196. } else {
  17197. newShapeHoles[mainIdx].push( { h: tmpPath, p: tmpPoints[0] } );
  17198. //THREE.log('ccw', i);
  17199. }
  17200. }
  17201. // only Holes? -> probably all Shapes with wrong orientation
  17202. if ( ! newShapes[0] ) return toShapesNoHoles( subPaths );
  17203. if ( newShapes.length > 1 ) {
  17204. var ambigious = false;
  17205. var toChange = [];
  17206. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  17207. betterShapeHoles[sIdx] = [];
  17208. }
  17209. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  17210. var sho = newShapeHoles[sIdx];
  17211. for (var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  17212. var ho = sho[hIdx];
  17213. var hole_unassigned = true;
  17214. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  17215. if ( isPointInsidePolygon( ho.p, newShapes[s2Idx].p ) ) {
  17216. if ( sIdx != s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  17217. if ( hole_unassigned ) {
  17218. hole_unassigned = false;
  17219. betterShapeHoles[s2Idx].push( ho );
  17220. } else {
  17221. ambigious = true;
  17222. }
  17223. }
  17224. }
  17225. if ( hole_unassigned ) { betterShapeHoles[sIdx].push( ho ); }
  17226. }
  17227. }
  17228. // THREE.log("ambigious: ", ambigious);
  17229. if ( toChange.length > 0 ) {
  17230. // THREE.log("to change: ", toChange);
  17231. if (! ambigious) newShapeHoles = betterShapeHoles;
  17232. }
  17233. }
  17234. var tmpHoles, j, jl;
  17235. for ( i = 0, il = newShapes.length; i < il; i ++ ) {
  17236. tmpShape = newShapes[i].s;
  17237. shapes.push( tmpShape );
  17238. tmpHoles = newShapeHoles[i];
  17239. for ( j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  17240. tmpShape.holes.push( tmpHoles[j].h );
  17241. }
  17242. }
  17243. //THREE.log("shape", shapes);
  17244. return shapes;
  17245. };
  17246. // File:src/extras/core/Shape.js
  17247. /**
  17248. * @author zz85 / http://www.lab4games.net/zz85/blog
  17249. * Defines a 2d shape plane using paths.
  17250. **/
  17251. // STEP 1 Create a path.
  17252. // STEP 2 Turn path into shape.
  17253. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17254. // STEP 3a - Extract points from each shape, turn to vertices
  17255. // STEP 3b - Triangulate each shape, add faces.
  17256. THREE.Shape = function () {
  17257. THREE.Path.apply( this, arguments );
  17258. this.holes = [];
  17259. };
  17260. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17261. THREE.Shape.prototype.constructor = THREE.Shape;
  17262. // Convenience method to return ExtrudeGeometry
  17263. THREE.Shape.prototype.extrude = function ( options ) {
  17264. var extruded = new THREE.ExtrudeGeometry( this, options );
  17265. return extruded;
  17266. };
  17267. // Convenience method to return ShapeGeometry
  17268. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17269. var geometry = new THREE.ShapeGeometry( this, options );
  17270. return geometry;
  17271. };
  17272. // Get points of holes
  17273. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17274. var i, il = this.holes.length, holesPts = [];
  17275. for ( i = 0; i < il; i ++ ) {
  17276. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17277. }
  17278. return holesPts;
  17279. };
  17280. // Get points of holes (spaced by regular distance)
  17281. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17282. var i, il = this.holes.length, holesPts = [];
  17283. for ( i = 0; i < il; i ++ ) {
  17284. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17285. }
  17286. return holesPts;
  17287. };
  17288. // Get points of shape and holes (keypoints based on segments parameter)
  17289. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17290. return {
  17291. shape: this.getTransformedPoints( divisions ),
  17292. holes: this.getPointsHoles( divisions )
  17293. };
  17294. };
  17295. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17296. if (this.useSpacedPoints) {
  17297. return this.extractAllSpacedPoints(divisions);
  17298. }
  17299. return this.extractAllPoints(divisions);
  17300. };
  17301. //
  17302. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17303. //
  17304. // return {
  17305. //
  17306. // shape: this.transform( bend, divisions ),
  17307. // holes: this.getPointsHoles( divisions, bend )
  17308. //
  17309. // };
  17310. //
  17311. // };
  17312. // Get points of shape and holes (spaced by regular distance)
  17313. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17314. return {
  17315. shape: this.getTransformedSpacedPoints( divisions ),
  17316. holes: this.getSpacedPointsHoles( divisions )
  17317. };
  17318. };
  17319. /**************************************************************
  17320. * Utils
  17321. **************************************************************/
  17322. THREE.Shape.Utils = {
  17323. triangulateShape: function ( contour, holes ) {
  17324. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  17325. // inOtherPt needs to be colinear to the inSegment
  17326. if ( inSegPt1.x != inSegPt2.x ) {
  17327. if ( inSegPt1.x < inSegPt2.x ) {
  17328. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  17329. } else {
  17330. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  17331. }
  17332. } else {
  17333. if ( inSegPt1.y < inSegPt2.y ) {
  17334. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  17335. } else {
  17336. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  17337. }
  17338. }
  17339. }
  17340. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  17341. var EPSILON = 0.0000000001;
  17342. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  17343. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  17344. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  17345. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  17346. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  17347. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  17348. if ( Math.abs(limit) > EPSILON ) { // not parallel
  17349. var perpSeg2;
  17350. if ( limit > 0 ) {
  17351. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  17352. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17353. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  17354. } else {
  17355. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  17356. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17357. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  17358. }
  17359. // i.e. to reduce rounding errors
  17360. // intersection at endpoint of segment#1?
  17361. if ( perpSeg2 == 0 ) {
  17362. if ( ( inExcludeAdjacentSegs ) &&
  17363. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17364. return [ inSeg1Pt1 ];
  17365. }
  17366. if ( perpSeg2 == limit ) {
  17367. if ( ( inExcludeAdjacentSegs ) &&
  17368. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17369. return [ inSeg1Pt2 ];
  17370. }
  17371. // intersection at endpoint of segment#2?
  17372. if ( perpSeg1 == 0 ) return [ inSeg2Pt1 ];
  17373. if ( perpSeg1 == limit ) return [ inSeg2Pt2 ];
  17374. // return real intersection point
  17375. var factorSeg1 = perpSeg2 / limit;
  17376. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  17377. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  17378. } else { // parallel or colinear
  17379. if ( ( perpSeg1 != 0 ) ||
  17380. ( seg2dy * seg1seg2dx != seg2dx * seg1seg2dy ) ) return [];
  17381. // they are collinear or degenerate
  17382. var seg1Pt = ( (seg1dx == 0) && (seg1dy == 0) ); // segment1 ist just a point?
  17383. var seg2Pt = ( (seg2dx == 0) && (seg2dy == 0) ); // segment2 ist just a point?
  17384. // both segments are points
  17385. if ( seg1Pt && seg2Pt ) {
  17386. if ( (inSeg1Pt1.x != inSeg2Pt1.x) ||
  17387. (inSeg1Pt1.y != inSeg2Pt1.y) ) return []; // they are distinct points
  17388. return [ inSeg1Pt1 ]; // they are the same point
  17389. }
  17390. // segment#1 is a single point
  17391. if ( seg1Pt ) {
  17392. if (! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  17393. return [ inSeg1Pt1 ];
  17394. }
  17395. // segment#2 is a single point
  17396. if ( seg2Pt ) {
  17397. if (! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  17398. return [ inSeg2Pt1 ];
  17399. }
  17400. // they are collinear segments, which might overlap
  17401. var seg1min, seg1max, seg1minVal, seg1maxVal;
  17402. var seg2min, seg2max, seg2minVal, seg2maxVal;
  17403. if (seg1dx != 0) { // the segments are NOT on a vertical line
  17404. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  17405. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  17406. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  17407. } else {
  17408. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  17409. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  17410. }
  17411. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  17412. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  17413. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  17414. } else {
  17415. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  17416. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  17417. }
  17418. } else { // the segments are on a vertical line
  17419. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  17420. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  17421. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  17422. } else {
  17423. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  17424. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  17425. }
  17426. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  17427. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  17428. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  17429. } else {
  17430. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  17431. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  17432. }
  17433. }
  17434. if ( seg1minVal <= seg2minVal ) {
  17435. if ( seg1maxVal < seg2minVal ) return [];
  17436. if ( seg1maxVal == seg2minVal ) {
  17437. if ( inExcludeAdjacentSegs ) return [];
  17438. return [ seg2min ];
  17439. }
  17440. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  17441. return [ seg2min, seg2max ];
  17442. } else {
  17443. if ( seg1minVal > seg2maxVal ) return [];
  17444. if ( seg1minVal == seg2maxVal ) {
  17445. if ( inExcludeAdjacentSegs ) return [];
  17446. return [ seg1min ];
  17447. }
  17448. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  17449. return [ seg1min, seg2max ];
  17450. }
  17451. }
  17452. }
  17453. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  17454. // The order of legs is important
  17455. var EPSILON = 0.0000000001;
  17456. // translation of all points, so that Vertex is at (0,0)
  17457. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  17458. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  17459. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  17460. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  17461. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  17462. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  17463. if ( Math.abs(from2toAngle) > EPSILON ) { // angle != 180 deg.
  17464. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  17465. // THREE.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  17466. if ( from2toAngle > 0 ) { // main angle < 180 deg.
  17467. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  17468. } else { // main angle > 180 deg.
  17469. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  17470. }
  17471. } else { // angle == 180 deg.
  17472. // THREE.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  17473. return ( from2otherAngle > 0 );
  17474. }
  17475. }
  17476. function removeHoles( contour, holes ) {
  17477. var shape = contour.concat(); // work on this shape
  17478. var hole;
  17479. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  17480. // Check if hole point lies within angle around shape point
  17481. var lastShapeIdx = shape.length - 1;
  17482. var prevShapeIdx = inShapeIdx - 1;
  17483. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  17484. var nextShapeIdx = inShapeIdx + 1;
  17485. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  17486. var insideAngle = isPointInsideAngle( shape[inShapeIdx], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[inHoleIdx] );
  17487. if (! insideAngle ) {
  17488. // THREE.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  17489. return false;
  17490. }
  17491. // Check if shape point lies within angle around hole point
  17492. var lastHoleIdx = hole.length - 1;
  17493. var prevHoleIdx = inHoleIdx - 1;
  17494. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  17495. var nextHoleIdx = inHoleIdx + 1;
  17496. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  17497. insideAngle = isPointInsideAngle( hole[inHoleIdx], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[inShapeIdx] );
  17498. if (! insideAngle ) {
  17499. // THREE.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  17500. return false;
  17501. }
  17502. return true;
  17503. }
  17504. function intersectsShapeEdge( inShapePt, inHolePt ) {
  17505. // checks for intersections with shape edges
  17506. var sIdx, nextIdx, intersection;
  17507. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  17508. nextIdx = sIdx + 1; nextIdx %= shape.length;
  17509. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[sIdx], shape[nextIdx], true );
  17510. if ( intersection.length > 0 ) return true;
  17511. }
  17512. return false;
  17513. }
  17514. var indepHoles = [];
  17515. function intersectsHoleEdge( inShapePt, inHolePt ) {
  17516. // checks for intersections with hole edges
  17517. var ihIdx, chkHole,
  17518. hIdx, nextIdx, intersection;
  17519. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  17520. chkHole = holes[indepHoles[ihIdx]];
  17521. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  17522. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  17523. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[hIdx], chkHole[nextIdx], true );
  17524. if ( intersection.length > 0 ) return true;
  17525. }
  17526. }
  17527. return false;
  17528. }
  17529. var holeIndex, shapeIndex,
  17530. shapePt, holePt,
  17531. holeIdx, cutKey, failedCuts = [],
  17532. tmpShape1, tmpShape2,
  17533. tmpHole1, tmpHole2;
  17534. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17535. indepHoles.push( h );
  17536. }
  17537. var minShapeIndex = 0;
  17538. var counter = indepHoles.length * 2;
  17539. while ( indepHoles.length > 0 ) {
  17540. counter --;
  17541. if ( counter < 0 ) {
  17542. THREE.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  17543. break;
  17544. }
  17545. // search for shape-vertex and hole-vertex,
  17546. // which can be connected without intersections
  17547. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  17548. shapePt = shape[ shapeIndex ];
  17549. holeIndex = - 1;
  17550. // search for hole which can be reached without intersections
  17551. for ( var h = 0; h < indepHoles.length; h ++ ) {
  17552. holeIdx = indepHoles[h];
  17553. // prevent multiple checks
  17554. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  17555. if ( failedCuts[cutKey] !== undefined ) continue;
  17556. hole = holes[holeIdx];
  17557. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  17558. holePt = hole[ h2 ];
  17559. if (! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  17560. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  17561. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  17562. holeIndex = h2;
  17563. indepHoles.splice(h, 1);
  17564. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  17565. tmpShape2 = shape.slice( shapeIndex );
  17566. tmpHole1 = hole.slice( holeIndex );
  17567. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  17568. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17569. minShapeIndex = shapeIndex;
  17570. // Debug only, to show the selected cuts
  17571. // glob_CutLines.push( [ shapePt, holePt ] );
  17572. break;
  17573. }
  17574. if ( holeIndex >= 0 ) break; // hole-vertex found
  17575. failedCuts[cutKey] = true; // remember failure
  17576. }
  17577. if ( holeIndex >= 0 ) break; // hole-vertex found
  17578. }
  17579. }
  17580. return shape; /* shape with no holes */
  17581. }
  17582. var i, il, f, face,
  17583. key, index,
  17584. allPointsMap = {};
  17585. // 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.
  17586. var allpoints = contour.concat();
  17587. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17588. Array.prototype.push.apply( allpoints, holes[h] );
  17589. }
  17590. //THREE.log( "allpoints",allpoints, allpoints.length );
  17591. // prepare all points map
  17592. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17593. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17594. if ( allPointsMap[ key ] !== undefined ) {
  17595. THREE.warn( "THREE.Shape: Duplicate point", key );
  17596. }
  17597. allPointsMap[ key ] = i;
  17598. }
  17599. // remove holes by cutting paths to holes and adding them to the shape
  17600. var shapeWithoutHoles = removeHoles( contour, holes );
  17601. var triangles = THREE.FontUtils.Triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  17602. //THREE.log( "triangles",triangles, triangles.length );
  17603. // check all face vertices against all points map
  17604. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17605. face = triangles[ i ];
  17606. for ( f = 0; f < 3; f ++ ) {
  17607. key = face[ f ].x + ":" + face[ f ].y;
  17608. index = allPointsMap[ key ];
  17609. if ( index !== undefined ) {
  17610. face[ f ] = index;
  17611. }
  17612. }
  17613. }
  17614. return triangles.concat();
  17615. },
  17616. isClockWise: function ( pts ) {
  17617. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17618. },
  17619. // Bezier Curves formulas obtained from
  17620. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17621. // Quad Bezier Functions
  17622. b2p0: function ( t, p ) {
  17623. var k = 1 - t;
  17624. return k * k * p;
  17625. },
  17626. b2p1: function ( t, p ) {
  17627. return 2 * ( 1 - t ) * t * p;
  17628. },
  17629. b2p2: function ( t, p ) {
  17630. return t * t * p;
  17631. },
  17632. b2: function ( t, p0, p1, p2 ) {
  17633. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17634. },
  17635. // Cubic Bezier Functions
  17636. b3p0: function ( t, p ) {
  17637. var k = 1 - t;
  17638. return k * k * k * p;
  17639. },
  17640. b3p1: function ( t, p ) {
  17641. var k = 1 - t;
  17642. return 3 * k * k * t * p;
  17643. },
  17644. b3p2: function ( t, p ) {
  17645. var k = 1 - t;
  17646. return 3 * k * t * t * p;
  17647. },
  17648. b3p3: function ( t, p ) {
  17649. return t * t * t * p;
  17650. },
  17651. b3: function ( t, p0, p1, p2, p3 ) {
  17652. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17653. }
  17654. };
  17655. // File:src/extras/curves/LineCurve.js
  17656. /**************************************************************
  17657. * Line
  17658. **************************************************************/
  17659. THREE.LineCurve = function ( v1, v2 ) {
  17660. this.v1 = v1;
  17661. this.v2 = v2;
  17662. };
  17663. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  17664. THREE.LineCurve.prototype.constructor = THREE.LineCurve;
  17665. THREE.LineCurve.prototype.getPoint = function ( t ) {
  17666. var point = this.v2.clone().sub(this.v1);
  17667. point.multiplyScalar( t ).add( this.v1 );
  17668. return point;
  17669. };
  17670. // Line curve is linear, so we can overwrite default getPointAt
  17671. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  17672. return this.getPoint( u );
  17673. };
  17674. THREE.LineCurve.prototype.getTangent = function( t ) {
  17675. var tangent = this.v2.clone().sub(this.v1);
  17676. return tangent.normalize();
  17677. };
  17678. // File:src/extras/curves/QuadraticBezierCurve.js
  17679. /**************************************************************
  17680. * Quadratic Bezier curve
  17681. **************************************************************/
  17682. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  17683. this.v0 = v0;
  17684. this.v1 = v1;
  17685. this.v2 = v2;
  17686. };
  17687. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17688. THREE.QuadraticBezierCurve.prototype.constructor = THREE.QuadraticBezierCurve;
  17689. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  17690. var vector = new THREE.Vector2();
  17691. vector.x = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17692. vector.y = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17693. return vector;
  17694. };
  17695. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  17696. var vector = new THREE.Vector2();
  17697. vector.x = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  17698. vector.y = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  17699. // returns unit vector
  17700. return vector.normalize();
  17701. };
  17702. // File:src/extras/curves/CubicBezierCurve.js
  17703. /**************************************************************
  17704. * Cubic Bezier curve
  17705. **************************************************************/
  17706. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  17707. this.v0 = v0;
  17708. this.v1 = v1;
  17709. this.v2 = v2;
  17710. this.v3 = v3;
  17711. };
  17712. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17713. THREE.CubicBezierCurve.prototype.constructor = THREE.CubicBezierCurve;
  17714. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  17715. var tx, ty;
  17716. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17717. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17718. return new THREE.Vector2( tx, ty );
  17719. };
  17720. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  17721. var tx, ty;
  17722. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17723. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17724. var tangent = new THREE.Vector2( tx, ty );
  17725. tangent.normalize();
  17726. return tangent;
  17727. };
  17728. // File:src/extras/curves/SplineCurve.js
  17729. /**************************************************************
  17730. * Spline curve
  17731. **************************************************************/
  17732. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  17733. this.points = ( points == undefined ) ? [] : points;
  17734. };
  17735. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  17736. THREE.SplineCurve.prototype.constructor = THREE.SplineCurve;
  17737. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  17738. var points = this.points;
  17739. var point = ( points.length - 1 ) * t;
  17740. var intPoint = Math.floor( point );
  17741. var weight = point - intPoint;
  17742. var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ]
  17743. var point1 = points[ intPoint ]
  17744. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]
  17745. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]
  17746. var vector = new THREE.Vector2();
  17747. vector.x = THREE.Curve.Utils.interpolate( point0.x, point1.x, point2.x, point3.x, weight );
  17748. vector.y = THREE.Curve.Utils.interpolate( point0.y, point1.y, point2.y, point3.y, weight );
  17749. return vector;
  17750. };
  17751. // File:src/extras/curves/EllipseCurve.js
  17752. /**************************************************************
  17753. * Ellipse curve
  17754. **************************************************************/
  17755. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) {
  17756. this.aX = aX;
  17757. this.aY = aY;
  17758. this.xRadius = xRadius;
  17759. this.yRadius = yRadius;
  17760. this.aStartAngle = aStartAngle;
  17761. this.aEndAngle = aEndAngle;
  17762. this.aClockwise = aClockwise;
  17763. };
  17764. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  17765. THREE.EllipseCurve.prototype.constructor = THREE.EllipseCurve;
  17766. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  17767. var deltaAngle = this.aEndAngle - this.aStartAngle;
  17768. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  17769. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  17770. var angle;
  17771. if ( this.aClockwise === true ) {
  17772. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  17773. } else {
  17774. angle = this.aStartAngle + t * deltaAngle;
  17775. }
  17776. var vector = new THREE.Vector2();
  17777. vector.x = this.aX + this.xRadius * Math.cos( angle );
  17778. vector.y = this.aY + this.yRadius * Math.sin( angle );
  17779. return vector;
  17780. };
  17781. // File:src/extras/curves/ArcCurve.js
  17782. /**************************************************************
  17783. * Arc curve
  17784. **************************************************************/
  17785. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  17786. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  17787. };
  17788. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  17789. THREE.ArcCurve.prototype.constructor = THREE.ArcCurve;
  17790. // File:src/extras/curves/LineCurve3.js
  17791. /**************************************************************
  17792. * Line3D
  17793. **************************************************************/
  17794. THREE.LineCurve3 = THREE.Curve.create(
  17795. function ( v1, v2 ) {
  17796. this.v1 = v1;
  17797. this.v2 = v2;
  17798. },
  17799. function ( t ) {
  17800. var vector = new THREE.Vector3();
  17801. vector.subVectors( this.v2, this.v1 ); // diff
  17802. vector.multiplyScalar( t );
  17803. vector.add( this.v1 );
  17804. return vector;
  17805. }
  17806. );
  17807. // File:src/extras/curves/QuadraticBezierCurve3.js
  17808. /**************************************************************
  17809. * Quadratic Bezier 3D curve
  17810. **************************************************************/
  17811. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  17812. function ( v0, v1, v2 ) {
  17813. this.v0 = v0;
  17814. this.v1 = v1;
  17815. this.v2 = v2;
  17816. },
  17817. function ( t ) {
  17818. var vector = new THREE.Vector3();
  17819. vector.x = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17820. vector.y = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17821. vector.z = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  17822. return vector;
  17823. }
  17824. );
  17825. // File:src/extras/curves/CubicBezierCurve3.js
  17826. /**************************************************************
  17827. * Cubic Bezier 3D curve
  17828. **************************************************************/
  17829. THREE.CubicBezierCurve3 = THREE.Curve.create(
  17830. function ( v0, v1, v2, v3 ) {
  17831. this.v0 = v0;
  17832. this.v1 = v1;
  17833. this.v2 = v2;
  17834. this.v3 = v3;
  17835. },
  17836. function ( t ) {
  17837. var vector = new THREE.Vector3();
  17838. vector.x = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17839. vector.y = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17840. vector.z = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  17841. return vector;
  17842. }
  17843. );
  17844. // File:src/extras/curves/SplineCurve3.js
  17845. /**************************************************************
  17846. * Spline 3D curve
  17847. **************************************************************/
  17848. THREE.SplineCurve3 = THREE.Curve.create(
  17849. function ( points /* array of Vector3 */) {
  17850. this.points = ( points == undefined ) ? [] : points;
  17851. },
  17852. function ( t ) {
  17853. var points = this.points;
  17854. var point = ( points.length - 1 ) * t;
  17855. var intPoint = Math.floor( point );
  17856. var weight = point - intPoint;
  17857. var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ];
  17858. var point1 = points[ intPoint ];
  17859. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  17860. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  17861. var vector = new THREE.Vector3();
  17862. vector.x = THREE.Curve.Utils.interpolate( point0.x, point1.x, point2.x, point3.x, weight );
  17863. vector.y = THREE.Curve.Utils.interpolate( point0.y, point1.y, point2.y, point3.y, weight );
  17864. vector.z = THREE.Curve.Utils.interpolate( point0.z, point1.z, point2.z, point3.z, weight );
  17865. return vector;
  17866. }
  17867. );
  17868. // File:src/extras/curves/ClosedSplineCurve3.js
  17869. /**************************************************************
  17870. * Closed Spline 3D curve
  17871. **************************************************************/
  17872. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  17873. function ( points /* array of Vector3 */) {
  17874. this.points = ( points == undefined ) ? [] : points;
  17875. },
  17876. function ( t ) {
  17877. var points = this.points;
  17878. var point = ( points.length - 0 ) * t; // This needs to be from 0-length +1
  17879. var intPoint = Math.floor( point );
  17880. var weight = point - intPoint;
  17881. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  17882. var point0 = points[ ( intPoint - 1 ) % points.length ];
  17883. var point1 = points[ ( intPoint ) % points.length ];
  17884. var point2 = points[ ( intPoint + 1 ) % points.length ];
  17885. var point3 = points[ ( intPoint + 2 ) % points.length ];
  17886. var vector = new THREE.Vector3();
  17887. vector.x = THREE.Curve.Utils.interpolate( point0.x, point1.x, point2.x, point3.x, weight );
  17888. vector.y = THREE.Curve.Utils.interpolate( point0.y, point1.y, point2.y, point3.y, weight );
  17889. vector.z = THREE.Curve.Utils.interpolate( point0.z, point1.z, point2.z, point3.z, weight );
  17890. return vector;
  17891. }
  17892. );
  17893. // File:src/extras/animation/AnimationHandler.js
  17894. /**
  17895. * @author mikael emtinger / http://gomo.se/
  17896. */
  17897. THREE.AnimationHandler = {
  17898. LINEAR: 0,
  17899. CATMULLROM: 1,
  17900. CATMULLROM_FORWARD: 2,
  17901. //
  17902. add: function () { THREE.warn( 'THREE.AnimationHandler.add() has been deprecated.' ); },
  17903. get: function () { THREE.warn( 'THREE.AnimationHandler.get() has been deprecated.' ); },
  17904. remove: function () { THREE.warn( 'THREE.AnimationHandler.remove() has been deprecated.' ); },
  17905. //
  17906. animations: [],
  17907. init: function ( data ) {
  17908. if ( data.initialized === true ) return data;
  17909. // loop through all keys
  17910. for ( var h = 0; h < data.hierarchy.length; h ++ ) {
  17911. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17912. // remove minus times
  17913. if ( data.hierarchy[ h ].keys[ k ].time < 0 ) {
  17914. data.hierarchy[ h ].keys[ k ].time = 0;
  17915. }
  17916. // create quaternions
  17917. if ( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17918. ! ( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17919. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17920. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion().fromArray( quat );
  17921. }
  17922. }
  17923. // prepare morph target keys
  17924. if ( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17925. // get all used
  17926. var usedMorphTargets = {};
  17927. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17928. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17929. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17930. usedMorphTargets[ morphTargetName ] = - 1;
  17931. }
  17932. }
  17933. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17934. // set all used on all frames
  17935. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17936. var influences = {};
  17937. for ( var morphTargetName in usedMorphTargets ) {
  17938. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17939. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17940. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17941. break;
  17942. }
  17943. }
  17944. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17945. influences[ morphTargetName ] = 0;
  17946. }
  17947. }
  17948. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17949. }
  17950. }
  17951. // remove all keys that are on the same time
  17952. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17953. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17954. data.hierarchy[ h ].keys.splice( k, 1 );
  17955. k --;
  17956. }
  17957. }
  17958. // set index
  17959. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17960. data.hierarchy[ h ].keys[ k ].index = k;
  17961. }
  17962. }
  17963. data.initialized = true;
  17964. return data;
  17965. },
  17966. parse: function ( root ) {
  17967. var parseRecurseHierarchy = function ( root, hierarchy ) {
  17968. hierarchy.push( root );
  17969. for ( var c = 0; c < root.children.length; c ++ )
  17970. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17971. };
  17972. // setup hierarchy
  17973. var hierarchy = [];
  17974. if ( root instanceof THREE.SkinnedMesh ) {
  17975. for ( var b = 0; b < root.skeleton.bones.length; b ++ ) {
  17976. hierarchy.push( root.skeleton.bones[ b ] );
  17977. }
  17978. } else {
  17979. parseRecurseHierarchy( root, hierarchy );
  17980. }
  17981. return hierarchy;
  17982. },
  17983. play: function ( animation ) {
  17984. if ( this.animations.indexOf( animation ) === - 1 ) {
  17985. this.animations.push( animation );
  17986. }
  17987. },
  17988. stop: function ( animation ) {
  17989. var index = this.animations.indexOf( animation );
  17990. if ( index !== - 1 ) {
  17991. this.animations.splice( index, 1 );
  17992. }
  17993. },
  17994. update: function ( deltaTimeMS ) {
  17995. for ( var i = 0; i < this.animations.length; i ++ ) {
  17996. this.animations[ i ].resetBlendWeights( );
  17997. }
  17998. for ( var i = 0; i < this.animations.length; i ++ ) {
  17999. this.animations[ i ].update( deltaTimeMS );
  18000. }
  18001. }
  18002. };
  18003. // File:src/extras/animation/Animation.js
  18004. /**
  18005. * @author mikael emtinger / http://gomo.se/
  18006. * @author mrdoob / http://mrdoob.com/
  18007. * @author alteredq / http://alteredqualia.com/
  18008. */
  18009. THREE.Animation = function ( root, data ) {
  18010. this.root = root;
  18011. this.data = THREE.AnimationHandler.init( data );
  18012. this.hierarchy = THREE.AnimationHandler.parse( root );
  18013. this.currentTime = 0;
  18014. this.timeScale = 1;
  18015. this.isPlaying = false;
  18016. this.loop = true;
  18017. this.weight = 0;
  18018. this.interpolationType = THREE.AnimationHandler.LINEAR;
  18019. };
  18020. THREE.Animation.prototype = {
  18021. constructor: THREE.Animation,
  18022. keyTypes: [ "pos", "rot", "scl" ],
  18023. play: function ( startTime, weight ) {
  18024. this.currentTime = startTime !== undefined ? startTime : 0;
  18025. this.weight = weight !== undefined ? weight : 1;
  18026. this.isPlaying = true;
  18027. this.reset();
  18028. THREE.AnimationHandler.play( this );
  18029. },
  18030. stop: function() {
  18031. this.isPlaying = false;
  18032. THREE.AnimationHandler.stop( this );
  18033. },
  18034. reset: function () {
  18035. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18036. var object = this.hierarchy[ h ];
  18037. if ( object.animationCache === undefined ) {
  18038. object.animationCache = {
  18039. animations: {},
  18040. blending: {
  18041. positionWeight: 0.0,
  18042. quaternionWeight: 0.0,
  18043. scaleWeight: 0.0
  18044. }
  18045. };
  18046. }
  18047. var name = this.data.name;
  18048. var animations = object.animationCache.animations;
  18049. var animationCache = animations[ name ];
  18050. if ( animationCache === undefined ) {
  18051. animationCache = {
  18052. prevKey: { pos: 0, rot: 0, scl: 0 },
  18053. nextKey: { pos: 0, rot: 0, scl: 0 },
  18054. originalMatrix: object.matrix
  18055. };
  18056. animations[ name ] = animationCache;
  18057. }
  18058. // Get keys to match our current time
  18059. for ( var t = 0; t < 3; t ++ ) {
  18060. var type = this.keyTypes[ t ];
  18061. var prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18062. var nextKey = this.getNextKeyWith( type, h, 1 );
  18063. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18064. prevKey = nextKey;
  18065. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18066. }
  18067. animationCache.prevKey[ type ] = prevKey;
  18068. animationCache.nextKey[ type ] = nextKey;
  18069. }
  18070. }
  18071. },
  18072. resetBlendWeights: function () {
  18073. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18074. var object = this.hierarchy[ h ];
  18075. var animationCache = object.animationCache;
  18076. if ( animationCache !== undefined ) {
  18077. var blending = animationCache.blending;
  18078. blending.positionWeight = 0.0;
  18079. blending.quaternionWeight = 0.0;
  18080. blending.scaleWeight = 0.0;
  18081. }
  18082. }
  18083. },
  18084. update: ( function() {
  18085. var points = [];
  18086. var target = new THREE.Vector3();
  18087. var newVector = new THREE.Vector3();
  18088. var newQuat = new THREE.Quaternion();
  18089. // Catmull-Rom spline
  18090. var interpolateCatmullRom = function ( points, scale ) {
  18091. var c = [], v3 = [],
  18092. point, intPoint, weight, w2, w3,
  18093. pa, pb, pc, pd;
  18094. point = ( points.length - 1 ) * scale;
  18095. intPoint = Math.floor( point );
  18096. weight = point - intPoint;
  18097. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18098. c[ 1 ] = intPoint;
  18099. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18100. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18101. pa = points[ c[ 0 ] ];
  18102. pb = points[ c[ 1 ] ];
  18103. pc = points[ c[ 2 ] ];
  18104. pd = points[ c[ 3 ] ];
  18105. w2 = weight * weight;
  18106. w3 = weight * w2;
  18107. v3[ 0 ] = interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18108. v3[ 1 ] = interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18109. v3[ 2 ] = interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18110. return v3;
  18111. };
  18112. var interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18113. var v0 = ( p2 - p0 ) * 0.5,
  18114. v1 = ( p3 - p1 ) * 0.5;
  18115. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18116. };
  18117. return function ( delta ) {
  18118. if ( this.isPlaying === false ) return;
  18119. this.currentTime += delta * this.timeScale;
  18120. if ( this.weight === 0 )
  18121. return;
  18122. //
  18123. var duration = this.data.length;
  18124. if ( this.currentTime > duration || this.currentTime < 0 ) {
  18125. if ( this.loop ) {
  18126. this.currentTime %= duration;
  18127. if ( this.currentTime < 0 )
  18128. this.currentTime += duration;
  18129. this.reset();
  18130. } else {
  18131. this.stop();
  18132. }
  18133. }
  18134. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18135. var object = this.hierarchy[ h ];
  18136. var animationCache = object.animationCache.animations[this.data.name];
  18137. var blending = object.animationCache.blending;
  18138. // loop through pos/rot/scl
  18139. for ( var t = 0; t < 3; t ++ ) {
  18140. // get keys
  18141. var type = this.keyTypes[ t ];
  18142. var prevKey = animationCache.prevKey[ type ];
  18143. var nextKey = animationCache.nextKey[ type ];
  18144. if ( ( this.timeScale > 0 && nextKey.time <= this.currentTime ) ||
  18145. ( this.timeScale < 0 && prevKey.time >= this.currentTime ) ) {
  18146. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18147. nextKey = this.getNextKeyWith( type, h, 1 );
  18148. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18149. prevKey = nextKey;
  18150. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18151. }
  18152. animationCache.prevKey[ type ] = prevKey;
  18153. animationCache.nextKey[ type ] = nextKey;
  18154. }
  18155. var scale = ( this.currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18156. var prevXYZ = prevKey[ type ];
  18157. var nextXYZ = nextKey[ type ];
  18158. if ( scale < 0 ) scale = 0;
  18159. if ( scale > 1 ) scale = 1;
  18160. // interpolate
  18161. if ( type === "pos" ) {
  18162. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18163. newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18164. newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18165. newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18166. // blend
  18167. var proportionalWeight = this.weight / ( this.weight + blending.positionWeight );
  18168. object.position.lerp( newVector, proportionalWeight );
  18169. blending.positionWeight += this.weight;
  18170. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18171. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18172. points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18173. points[ 1 ] = prevXYZ;
  18174. points[ 2 ] = nextXYZ;
  18175. points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18176. scale = scale * 0.33 + 0.33;
  18177. var currentPoint = interpolateCatmullRom( points, scale );
  18178. var proportionalWeight = this.weight / ( this.weight + blending.positionWeight );
  18179. blending.positionWeight += this.weight;
  18180. // blend
  18181. var vector = object.position;
  18182. vector.x = vector.x + ( currentPoint[ 0 ] - vector.x ) * proportionalWeight;
  18183. vector.y = vector.y + ( currentPoint[ 1 ] - vector.y ) * proportionalWeight;
  18184. vector.z = vector.z + ( currentPoint[ 2 ] - vector.z ) * proportionalWeight;
  18185. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18186. var forwardPoint = interpolateCatmullRom( points, scale * 1.01 );
  18187. target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18188. target.sub( vector );
  18189. target.y = 0;
  18190. target.normalize();
  18191. var angle = Math.atan2( target.x, target.z );
  18192. object.rotation.set( 0, angle, 0 );
  18193. }
  18194. }
  18195. } else if ( type === "rot" ) {
  18196. THREE.Quaternion.slerp( prevXYZ, nextXYZ, newQuat, scale );
  18197. // Avoid paying the cost of an additional slerp if we don't have to
  18198. if ( blending.quaternionWeight === 0 ) {
  18199. object.quaternion.copy(newQuat);
  18200. blending.quaternionWeight = this.weight;
  18201. } else {
  18202. var proportionalWeight = this.weight / ( this.weight + blending.quaternionWeight );
  18203. THREE.Quaternion.slerp( object.quaternion, newQuat, object.quaternion, proportionalWeight );
  18204. blending.quaternionWeight += this.weight;
  18205. }
  18206. } else if ( type === "scl" ) {
  18207. newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18208. newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18209. newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18210. var proportionalWeight = this.weight / ( this.weight + blending.scaleWeight );
  18211. object.scale.lerp( newVector, proportionalWeight );
  18212. blending.scaleWeight += this.weight;
  18213. }
  18214. }
  18215. }
  18216. return true;
  18217. };
  18218. } )(),
  18219. getNextKeyWith: function ( type, h, key ) {
  18220. var keys = this.data.hierarchy[ h ].keys;
  18221. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18222. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18223. key = key < keys.length - 1 ? key : keys.length - 1;
  18224. } else {
  18225. key = key % keys.length;
  18226. }
  18227. for ( ; key < keys.length; key ++ ) {
  18228. if ( keys[ key ][ type ] !== undefined ) {
  18229. return keys[ key ];
  18230. }
  18231. }
  18232. return this.data.hierarchy[ h ].keys[ 0 ];
  18233. },
  18234. getPrevKeyWith: function ( type, h, key ) {
  18235. var keys = this.data.hierarchy[ h ].keys;
  18236. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18237. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18238. key = key > 0 ? key : 0;
  18239. } else {
  18240. key = key >= 0 ? key : key + keys.length;
  18241. }
  18242. for ( ; key >= 0; key -- ) {
  18243. if ( keys[ key ][ type ] !== undefined ) {
  18244. return keys[ key ];
  18245. }
  18246. }
  18247. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18248. }
  18249. };
  18250. // File:src/extras/animation/KeyFrameAnimation.js
  18251. /**
  18252. * @author mikael emtinger / http://gomo.se/
  18253. * @author mrdoob / http://mrdoob.com/
  18254. * @author alteredq / http://alteredqualia.com/
  18255. * @author khang duong
  18256. * @author erik kitson
  18257. */
  18258. THREE.KeyFrameAnimation = function ( data ) {
  18259. this.root = data.node;
  18260. this.data = THREE.AnimationHandler.init( data );
  18261. this.hierarchy = THREE.AnimationHandler.parse( this.root );
  18262. this.currentTime = 0;
  18263. this.timeScale = 0.001;
  18264. this.isPlaying = false;
  18265. this.isPaused = true;
  18266. this.loop = true;
  18267. // initialize to first keyframes
  18268. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18269. var keys = this.data.hierarchy[h].keys,
  18270. sids = this.data.hierarchy[h].sids,
  18271. obj = this.hierarchy[h];
  18272. if ( keys.length && sids ) {
  18273. for ( var s = 0; s < sids.length; s ++ ) {
  18274. var sid = sids[ s ],
  18275. next = this.getNextKeyWith( sid, h, 0 );
  18276. if ( next ) {
  18277. next.apply( sid );
  18278. }
  18279. }
  18280. obj.matrixAutoUpdate = false;
  18281. this.data.hierarchy[h].node.updateMatrix();
  18282. obj.matrixWorldNeedsUpdate = true;
  18283. }
  18284. }
  18285. };
  18286. THREE.KeyFrameAnimation.prototype = {
  18287. constructor: THREE.KeyFrameAnimation,
  18288. play: function ( startTime ) {
  18289. this.currentTime = startTime !== undefined ? startTime : 0;
  18290. if ( this.isPlaying === false ) {
  18291. this.isPlaying = true;
  18292. // reset key cache
  18293. var h, hl = this.hierarchy.length,
  18294. object,
  18295. node;
  18296. for ( h = 0; h < hl; h ++ ) {
  18297. object = this.hierarchy[ h ];
  18298. node = this.data.hierarchy[ h ];
  18299. if ( node.animationCache === undefined ) {
  18300. node.animationCache = {};
  18301. node.animationCache.prevKey = null;
  18302. node.animationCache.nextKey = null;
  18303. node.animationCache.originalMatrix = object.matrix;
  18304. }
  18305. var keys = this.data.hierarchy[h].keys;
  18306. if (keys.length) {
  18307. node.animationCache.prevKey = keys[ 0 ];
  18308. node.animationCache.nextKey = keys[ 1 ];
  18309. this.startTime = Math.min( keys[0].time, this.startTime );
  18310. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18311. }
  18312. }
  18313. this.update( 0 );
  18314. }
  18315. this.isPaused = false;
  18316. THREE.AnimationHandler.play( this );
  18317. },
  18318. stop: function () {
  18319. this.isPlaying = false;
  18320. this.isPaused = false;
  18321. THREE.AnimationHandler.stop( this );
  18322. // reset JIT matrix and remove cache
  18323. for ( var h = 0; h < this.data.hierarchy.length; h ++ ) {
  18324. var obj = this.hierarchy[ h ];
  18325. var node = this.data.hierarchy[ h ];
  18326. if ( node.animationCache !== undefined ) {
  18327. var original = node.animationCache.originalMatrix;
  18328. original.copy( obj.matrix );
  18329. obj.matrix = original;
  18330. delete node.animationCache;
  18331. }
  18332. }
  18333. },
  18334. update: function ( delta ) {
  18335. if ( this.isPlaying === false ) return;
  18336. this.currentTime += delta * this.timeScale;
  18337. //
  18338. var duration = this.data.length;
  18339. if ( this.loop === true && this.currentTime > duration ) {
  18340. this.currentTime %= duration;
  18341. }
  18342. this.currentTime = Math.min( this.currentTime, duration );
  18343. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18344. var object = this.hierarchy[ h ];
  18345. var node = this.data.hierarchy[ h ];
  18346. var keys = node.keys,
  18347. animationCache = node.animationCache;
  18348. if ( keys.length ) {
  18349. var prevKey = animationCache.prevKey;
  18350. var nextKey = animationCache.nextKey;
  18351. if ( nextKey.time <= this.currentTime ) {
  18352. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18353. prevKey = nextKey;
  18354. nextKey = keys[ prevKey.index + 1 ];
  18355. }
  18356. animationCache.prevKey = prevKey;
  18357. animationCache.nextKey = nextKey;
  18358. }
  18359. if ( nextKey.time >= this.currentTime ) {
  18360. prevKey.interpolate( nextKey, this.currentTime );
  18361. } else {
  18362. prevKey.interpolate( nextKey, nextKey.time );
  18363. }
  18364. this.data.hierarchy[ h ].node.updateMatrix();
  18365. object.matrixWorldNeedsUpdate = true;
  18366. }
  18367. }
  18368. },
  18369. getNextKeyWith: function ( sid, h, key ) {
  18370. var keys = this.data.hierarchy[ h ].keys;
  18371. key = key % keys.length;
  18372. for ( ; key < keys.length; key ++ ) {
  18373. if ( keys[ key ].hasTarget( sid ) ) {
  18374. return keys[ key ];
  18375. }
  18376. }
  18377. return keys[ 0 ];
  18378. },
  18379. getPrevKeyWith: function ( sid, h, key ) {
  18380. var keys = this.data.hierarchy[ h ].keys;
  18381. key = key >= 0 ? key : key + keys.length;
  18382. for ( ; key >= 0; key -- ) {
  18383. if ( keys[ key ].hasTarget( sid ) ) {
  18384. return keys[ key ];
  18385. }
  18386. }
  18387. return keys[ keys.length - 1 ];
  18388. }
  18389. };
  18390. // File:src/extras/animation/MorphAnimation.js
  18391. /**
  18392. * @author mrdoob / http://mrdoob.com
  18393. * @author willy-vvu / http://willy-vvu.github.io
  18394. */
  18395. THREE.MorphAnimation = function ( mesh ) {
  18396. this.mesh = mesh;
  18397. this.frames = mesh.morphTargetInfluences.length;
  18398. this.currentTime = 0;
  18399. this.duration = 1000;
  18400. this.loop = true;
  18401. this.lastFrame = 0;
  18402. this.currentFrame = 0;
  18403. this.isPlaying = false;
  18404. };
  18405. THREE.MorphAnimation.prototype = {
  18406. constructor: THREE.MorphAnimation,
  18407. play: function () {
  18408. this.isPlaying = true;
  18409. },
  18410. pause: function () {
  18411. this.isPlaying = false;
  18412. },
  18413. update: function ( delta ) {
  18414. if ( this.isPlaying === false ) return;
  18415. this.currentTime += delta;
  18416. if ( this.loop === true && this.currentTime > this.duration ) {
  18417. this.currentTime %= this.duration;
  18418. }
  18419. this.currentTime = Math.min( this.currentTime, this.duration );
  18420. var interpolation = this.duration / this.frames;
  18421. var frame = Math.floor( this.currentTime / interpolation );
  18422. var influences = this.mesh.morphTargetInfluences;
  18423. if ( frame != this.currentFrame ) {
  18424. influences[ this.lastFrame ] = 0;
  18425. influences[ this.currentFrame ] = 1;
  18426. influences[ frame ] = 0;
  18427. this.lastFrame = this.currentFrame;
  18428. this.currentFrame = frame;
  18429. }
  18430. influences[ frame ] = ( this.currentTime % interpolation ) / interpolation;
  18431. influences[ this.lastFrame ] = 1 - influences[ frame ];
  18432. }
  18433. };
  18434. // File:src/extras/geometries/BoxGeometry.js
  18435. /**
  18436. * @author mrdoob / http://mrdoob.com/
  18437. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18438. */
  18439. THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18440. THREE.Geometry.call( this );
  18441. this.type = 'BoxGeometry';
  18442. this.parameters = {
  18443. width: width,
  18444. height: height,
  18445. depth: depth,
  18446. widthSegments: widthSegments,
  18447. heightSegments: heightSegments,
  18448. depthSegments: depthSegments
  18449. };
  18450. this.widthSegments = widthSegments || 1;
  18451. this.heightSegments = heightSegments || 1;
  18452. this.depthSegments = depthSegments || 1;
  18453. var scope = this;
  18454. var width_half = width / 2;
  18455. var height_half = height / 2;
  18456. var depth_half = depth / 2;
  18457. buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, 0 ); // px
  18458. buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, 1 ); // nx
  18459. buildPlane( 'x', 'z', 1, 1, width, depth, height_half, 2 ); // py
  18460. buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, 3 ); // ny
  18461. buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, 4 ); // pz
  18462. buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, 5 ); // nz
  18463. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18464. var w, ix, iy,
  18465. gridX = scope.widthSegments,
  18466. gridY = scope.heightSegments,
  18467. width_half = width / 2,
  18468. height_half = height / 2,
  18469. offset = scope.vertices.length;
  18470. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18471. w = 'z';
  18472. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18473. w = 'y';
  18474. gridY = scope.depthSegments;
  18475. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18476. w = 'x';
  18477. gridX = scope.depthSegments;
  18478. }
  18479. var gridX1 = gridX + 1,
  18480. gridY1 = gridY + 1,
  18481. segment_width = width / gridX,
  18482. segment_height = height / gridY,
  18483. normal = new THREE.Vector3();
  18484. normal[ w ] = depth > 0 ? 1 : - 1;
  18485. for ( iy = 0; iy < gridY1; iy ++ ) {
  18486. for ( ix = 0; ix < gridX1; ix ++ ) {
  18487. var vector = new THREE.Vector3();
  18488. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18489. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18490. vector[ w ] = depth;
  18491. scope.vertices.push( vector );
  18492. }
  18493. }
  18494. for ( iy = 0; iy < gridY; iy ++ ) {
  18495. for ( ix = 0; ix < gridX; ix ++ ) {
  18496. var a = ix + gridX1 * iy;
  18497. var b = ix + gridX1 * ( iy + 1 );
  18498. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18499. var d = ( ix + 1 ) + gridX1 * iy;
  18500. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  18501. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  18502. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  18503. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  18504. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  18505. face.normal.copy( normal );
  18506. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18507. face.materialIndex = materialIndex;
  18508. scope.faces.push( face );
  18509. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  18510. face = new THREE.Face3( b + offset, c + offset, d + offset );
  18511. face.normal.copy( normal );
  18512. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18513. face.materialIndex = materialIndex;
  18514. scope.faces.push( face );
  18515. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  18516. }
  18517. }
  18518. }
  18519. this.mergeVertices();
  18520. };
  18521. THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18522. THREE.BoxGeometry.prototype.constructor = THREE.BoxGeometry;
  18523. THREE.CubeGeometry = THREE.BoxGeometry; // backwards compatibility
  18524. // File:src/extras/geometries/CircleGeometry.js
  18525. /**
  18526. * @author hughes
  18527. */
  18528. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18529. THREE.Geometry.call( this );
  18530. this.type = 'CircleGeometry';
  18531. this.parameters = {
  18532. radius: radius,
  18533. segments: segments,
  18534. thetaStart: thetaStart,
  18535. thetaLength: thetaLength
  18536. };
  18537. radius = radius || 50;
  18538. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18539. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18540. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18541. var i, uvs = [],
  18542. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18543. this.vertices.push(center);
  18544. uvs.push( centerUV );
  18545. for ( i = 0; i <= segments; i ++ ) {
  18546. var vertex = new THREE.Vector3();
  18547. var segment = thetaStart + i / segments * thetaLength;
  18548. vertex.x = radius * Math.cos( segment );
  18549. vertex.y = radius * Math.sin( segment );
  18550. this.vertices.push( vertex );
  18551. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  18552. }
  18553. var n = new THREE.Vector3( 0, 0, 1 );
  18554. for ( i = 1; i <= segments; i ++ ) {
  18555. this.faces.push( new THREE.Face3( i, i + 1, 0, [ n.clone(), n.clone(), n.clone() ] ) );
  18556. this.faceVertexUvs[ 0 ].push( [ uvs[ i ].clone(), uvs[ i + 1 ].clone(), centerUV.clone() ] );
  18557. }
  18558. this.computeFaceNormals();
  18559. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18560. };
  18561. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18562. THREE.CircleGeometry.prototype.constructor = THREE.CircleGeometry;
  18563. // File:src/extras/geometries/CylinderGeometry.js
  18564. /**
  18565. * @author mrdoob / http://mrdoob.com/
  18566. */
  18567. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  18568. THREE.Geometry.call( this );
  18569. this.type = 'CylinderGeometry';
  18570. this.parameters = {
  18571. radiusTop: radiusTop,
  18572. radiusBottom: radiusBottom,
  18573. height: height,
  18574. radialSegments: radialSegments,
  18575. heightSegments: heightSegments,
  18576. openEnded: openEnded,
  18577. thetaStart: thetaStart,
  18578. thetaLength: thetaLength
  18579. };
  18580. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18581. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18582. height = height !== undefined ? height : 100;
  18583. radialSegments = radialSegments || 8;
  18584. heightSegments = heightSegments || 1;
  18585. openEnded = openEnded !== undefined ? openEnded : false;
  18586. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18587. thetaLength = thetaLength !== undefined ? thetaLength : 2 * Math.PI;
  18588. var heightHalf = height / 2;
  18589. var x, y, vertices = [], uvs = [];
  18590. for ( y = 0; y <= heightSegments; y ++ ) {
  18591. var verticesRow = [];
  18592. var uvsRow = [];
  18593. var v = y / heightSegments;
  18594. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18595. for ( x = 0; x <= radialSegments; x ++ ) {
  18596. var u = x / radialSegments;
  18597. var vertex = new THREE.Vector3();
  18598. vertex.x = radius * Math.sin( u * thetaLength + thetaStart );
  18599. vertex.y = - v * height + heightHalf;
  18600. vertex.z = radius * Math.cos( u * thetaLength + thetaStart );
  18601. this.vertices.push( vertex );
  18602. verticesRow.push( this.vertices.length - 1 );
  18603. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18604. }
  18605. vertices.push( verticesRow );
  18606. uvs.push( uvsRow );
  18607. }
  18608. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18609. var na, nb;
  18610. for ( x = 0; x < radialSegments; x ++ ) {
  18611. if ( radiusTop !== 0 ) {
  18612. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18613. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18614. } else {
  18615. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18616. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18617. }
  18618. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18619. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18620. for ( y = 0; y < heightSegments; y ++ ) {
  18621. var v1 = vertices[ y ][ x ];
  18622. var v2 = vertices[ y + 1 ][ x ];
  18623. var v3 = vertices[ y + 1 ][ x + 1 ];
  18624. var v4 = vertices[ y ][ x + 1 ];
  18625. var n1 = na.clone();
  18626. var n2 = na.clone();
  18627. var n3 = nb.clone();
  18628. var n4 = nb.clone();
  18629. var uv1 = uvs[ y ][ x ].clone();
  18630. var uv2 = uvs[ y + 1 ][ x ].clone();
  18631. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18632. var uv4 = uvs[ y ][ x + 1 ].clone();
  18633. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  18634. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  18635. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  18636. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  18637. }
  18638. }
  18639. // top cap
  18640. if ( openEnded === false && radiusTop > 0 ) {
  18641. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18642. for ( x = 0; x < radialSegments; x ++ ) {
  18643. var v1 = vertices[ 0 ][ x ];
  18644. var v2 = vertices[ 0 ][ x + 1 ];
  18645. var v3 = this.vertices.length - 1;
  18646. var n1 = new THREE.Vector3( 0, 1, 0 );
  18647. var n2 = new THREE.Vector3( 0, 1, 0 );
  18648. var n3 = new THREE.Vector3( 0, 1, 0 );
  18649. var uv1 = uvs[ 0 ][ x ].clone();
  18650. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18651. var uv3 = new THREE.Vector2( uv2.x, 0 );
  18652. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18653. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18654. }
  18655. }
  18656. // bottom cap
  18657. if ( openEnded === false && radiusBottom > 0 ) {
  18658. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18659. for ( x = 0; x < radialSegments; x ++ ) {
  18660. var v1 = vertices[ heightSegments ][ x + 1 ];
  18661. var v2 = vertices[ heightSegments ][ x ];
  18662. var v3 = this.vertices.length - 1;
  18663. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18664. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18665. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18666. var uv1 = uvs[ heightSegments ][ x + 1 ].clone();
  18667. var uv2 = uvs[ heightSegments ][ x ].clone();
  18668. var uv3 = new THREE.Vector2( uv2.x, 1 );
  18669. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18670. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18671. }
  18672. }
  18673. this.computeFaceNormals();
  18674. };
  18675. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18676. THREE.CylinderGeometry.prototype.constructor = THREE.CylinderGeometry;
  18677. // File:src/extras/geometries/EdgesGeometry.js
  18678. /**
  18679. * @author WestLangley / http://github.com/WestLangley
  18680. */
  18681. THREE.EdgesGeometry = function ( geometry, thresholdAngle ) {
  18682. THREE.BufferGeometry.call( this );
  18683. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  18684. var thresholdDot = Math.cos( THREE.Math.degToRad( thresholdAngle ) );
  18685. var edge = [ 0, 0 ], hash = {};
  18686. var sortFunction = function ( a, b ) { return a - b };
  18687. var keys = [ 'a', 'b', 'c' ];
  18688. var geometry2;
  18689. if ( geometry instanceof THREE.BufferGeometry ) {
  18690. geometry2 = new THREE.Geometry();
  18691. geometry2.fromBufferGeometry( geometry );
  18692. } else {
  18693. geometry2 = geometry.clone();
  18694. }
  18695. geometry2.mergeVertices();
  18696. geometry2.computeFaceNormals();
  18697. var vertices = geometry2.vertices;
  18698. var faces = geometry2.faces;
  18699. var numEdges = 0;
  18700. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  18701. var face = faces[ i ];
  18702. for ( var j = 0; j < 3; j ++ ) {
  18703. edge[ 0 ] = face[ keys[ j ] ];
  18704. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  18705. edge.sort( sortFunction );
  18706. var key = edge.toString();
  18707. if ( hash[ key ] === undefined ) {
  18708. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  18709. numEdges ++;
  18710. } else {
  18711. hash[ key ].face2 = i;
  18712. }
  18713. }
  18714. }
  18715. var coords = new Float32Array( numEdges * 2 * 3 );
  18716. var index = 0;
  18717. for ( var key in hash ) {
  18718. var h = hash[ key ];
  18719. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) {
  18720. var vertex = vertices[ h.vert1 ];
  18721. coords[ index ++ ] = vertex.x;
  18722. coords[ index ++ ] = vertex.y;
  18723. coords[ index ++ ] = vertex.z;
  18724. vertex = vertices[ h.vert2 ];
  18725. coords[ index ++ ] = vertex.x;
  18726. coords[ index ++ ] = vertex.y;
  18727. coords[ index ++ ] = vertex.z;
  18728. }
  18729. }
  18730. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  18731. };
  18732. THREE.EdgesGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  18733. THREE.EdgesGeometry.prototype.constructor = THREE.EdgesGeometry;
  18734. // File:src/extras/geometries/ExtrudeGeometry.js
  18735. /**
  18736. * @author zz85 / http://www.lab4games.net/zz85/blog
  18737. *
  18738. * Creates extruded geometry from a path shape.
  18739. *
  18740. * parameters = {
  18741. *
  18742. * curveSegments: <int>, // number of points on the curves
  18743. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18744. * amount: <int>, // Depth to extrude the shape
  18745. *
  18746. * bevelEnabled: <bool>, // turn on bevel
  18747. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18748. * bevelSize: <float>, // how far from shape outline is bevel
  18749. * bevelSegments: <int>, // number of bevel layers
  18750. *
  18751. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18752. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18753. *
  18754. * material: <int> // material index for front and back faces
  18755. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18756. * uvGenerator: <Object> // object that provides UV generator functions
  18757. *
  18758. * }
  18759. **/
  18760. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18761. if ( typeof( shapes ) === "undefined" ) {
  18762. shapes = [];
  18763. return;
  18764. }
  18765. THREE.Geometry.call( this );
  18766. this.type = 'ExtrudeGeometry';
  18767. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18768. this.addShapeList( shapes, options );
  18769. this.computeFaceNormals();
  18770. // can't really use automatic vertex normals
  18771. // as then front and back sides get smoothed too
  18772. // should do separate smoothing just for sides
  18773. //this.computeVertexNormals();
  18774. //THREE.log( "took", ( Date.now() - startTime ) );
  18775. };
  18776. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18777. THREE.ExtrudeGeometry.prototype.constructor = THREE.ExtrudeGeometry;
  18778. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18779. var sl = shapes.length;
  18780. for ( var s = 0; s < sl; s ++ ) {
  18781. var shape = shapes[ s ];
  18782. this.addShape( shape, options );
  18783. }
  18784. };
  18785. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18786. var amount = options.amount !== undefined ? options.amount : 100;
  18787. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18788. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18789. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18790. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18791. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18792. var steps = options.steps !== undefined ? options.steps : 1;
  18793. var extrudePath = options.extrudePath;
  18794. var extrudePts, extrudeByPath = false;
  18795. var material = options.material;
  18796. var extrudeMaterial = options.extrudeMaterial;
  18797. // Use default WorldUVGenerator if no UV generators are specified.
  18798. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18799. var splineTube, binormal, normal, position2;
  18800. if ( extrudePath ) {
  18801. extrudePts = extrudePath.getSpacedPoints( steps );
  18802. extrudeByPath = true;
  18803. bevelEnabled = false; // bevels not supported for path extrusion
  18804. // SETUP TNB variables
  18805. // Reuse TNB from TubeGeomtry for now.
  18806. // TODO1 - have a .isClosed in spline?
  18807. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18808. // THREE.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18809. binormal = new THREE.Vector3();
  18810. normal = new THREE.Vector3();
  18811. position2 = new THREE.Vector3();
  18812. }
  18813. // Safeguards if bevels are not enabled
  18814. if ( ! bevelEnabled ) {
  18815. bevelSegments = 0;
  18816. bevelThickness = 0;
  18817. bevelSize = 0;
  18818. }
  18819. // Variables initalization
  18820. var ahole, h, hl; // looping of holes
  18821. var scope = this;
  18822. var shapesOffset = this.vertices.length;
  18823. var shapePoints = shape.extractPoints( curveSegments );
  18824. var vertices = shapePoints.shape;
  18825. var holes = shapePoints.holes;
  18826. var reverse = ! THREE.Shape.Utils.isClockWise( vertices ) ;
  18827. if ( reverse ) {
  18828. vertices = vertices.reverse();
  18829. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18830. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18831. ahole = holes[ h ];
  18832. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18833. holes[ h ] = ahole.reverse();
  18834. }
  18835. }
  18836. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18837. }
  18838. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18839. /* Vertices */
  18840. var contour = vertices; // vertices has all points but contour has only points of circumference
  18841. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18842. ahole = holes[ h ];
  18843. vertices = vertices.concat( ahole );
  18844. }
  18845. function scalePt2 ( pt, vec, size ) {
  18846. if ( ! vec ) THREE.error( "THREE.ExtrudeGeometry: vec does not exist" );
  18847. return vec.clone().multiplyScalar( size ).add( pt );
  18848. }
  18849. var b, bs, t, z,
  18850. vert, vlen = vertices.length,
  18851. face, flen = faces.length;
  18852. // Find directions for point movement
  18853. function getBevelVec( inPt, inPrev, inNext ) {
  18854. var EPSILON = 0.0000000001;
  18855. // computes for inPt the corresponding point inPt' on a new contour
  18856. // shiftet by 1 unit (length of normalized vector) to the left
  18857. // if we walk along contour clockwise, this new contour is outside the old one
  18858. //
  18859. // inPt' is the intersection of the two lines parallel to the two
  18860. // adjacent edges of inPt at a distance of 1 unit on the left side.
  18861. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  18862. // good reading for geometry algorithms (here: line-line intersection)
  18863. // http://geomalgorithms.com/a05-_intersect-1.html
  18864. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  18865. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  18866. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  18867. // check for colinear edges
  18868. var colinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18869. if ( Math.abs( colinear0 ) > EPSILON ) { // not colinear
  18870. // length of vectors for normalizing
  18871. var v_prev_len = Math.sqrt( v_prev_lensq );
  18872. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  18873. // shift adjacent points by unit vectors to the left
  18874. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  18875. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  18876. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  18877. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  18878. // scaling factor for v_prev to intersection point
  18879. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  18880. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  18881. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18882. // vector from inPt to intersection point
  18883. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  18884. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  18885. // Don't normalize!, otherwise sharp corners become ugly
  18886. // but prevent crazy spikes
  18887. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y )
  18888. if ( v_trans_lensq <= 2 ) {
  18889. return new THREE.Vector2( v_trans_x, v_trans_y );
  18890. } else {
  18891. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  18892. }
  18893. } else { // handle special case of colinear edges
  18894. var direction_eq = false; // assumes: opposite
  18895. if ( v_prev_x > EPSILON ) {
  18896. if ( v_next_x > EPSILON ) { direction_eq = true; }
  18897. } else {
  18898. if ( v_prev_x < - EPSILON ) {
  18899. if ( v_next_x < - EPSILON ) { direction_eq = true; }
  18900. } else {
  18901. if ( Math.sign(v_prev_y) == Math.sign(v_next_y) ) { direction_eq = true; }
  18902. }
  18903. }
  18904. if ( direction_eq ) {
  18905. // THREE.log("Warning: lines are a straight sequence");
  18906. v_trans_x = - v_prev_y;
  18907. v_trans_y = v_prev_x;
  18908. shrink_by = Math.sqrt( v_prev_lensq );
  18909. } else {
  18910. // THREE.log("Warning: lines are a straight spike");
  18911. v_trans_x = v_prev_x;
  18912. v_trans_y = v_prev_y;
  18913. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  18914. }
  18915. }
  18916. return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  18917. }
  18918. var contourMovements = [];
  18919. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18920. if ( j === il ) j = 0;
  18921. if ( k === il ) k = 0;
  18922. // (j)---(i)---(k)
  18923. // THREE.log('i,j,k', i, j , k)
  18924. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18925. }
  18926. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18927. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18928. ahole = holes[ h ];
  18929. oneHoleMovements = [];
  18930. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18931. if ( j === il ) j = 0;
  18932. if ( k === il ) k = 0;
  18933. // (j)---(i)---(k)
  18934. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18935. }
  18936. holesMovements.push( oneHoleMovements );
  18937. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18938. }
  18939. // Loop bevelSegments, 1 for the front, 1 for the back
  18940. for ( b = 0; b < bevelSegments; b ++ ) {
  18941. //for ( b = bevelSegments; b > 0; b -- ) {
  18942. t = b / bevelSegments;
  18943. z = bevelThickness * ( 1 - t );
  18944. //z = bevelThickness * t;
  18945. bs = bevelSize * ( Math.sin ( t * Math.PI / 2 ) ) ; // curved
  18946. //bs = bevelSize * t ; // linear
  18947. // contract shape
  18948. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18949. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18950. v( vert.x, vert.y, - z );
  18951. }
  18952. // expand holes
  18953. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18954. ahole = holes[ h ];
  18955. oneHoleMovements = holesMovements[ h ];
  18956. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18957. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18958. v( vert.x, vert.y, - z );
  18959. }
  18960. }
  18961. }
  18962. bs = bevelSize;
  18963. // Back facing vertices
  18964. for ( i = 0; i < vlen; i ++ ) {
  18965. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18966. if ( ! extrudeByPath ) {
  18967. v( vert.x, vert.y, 0 );
  18968. } else {
  18969. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18970. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18971. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18972. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  18973. v( position2.x, position2.y, position2.z );
  18974. }
  18975. }
  18976. // Add stepped vertices...
  18977. // Including front facing vertices
  18978. var s;
  18979. for ( s = 1; s <= steps; s ++ ) {
  18980. for ( i = 0; i < vlen; i ++ ) {
  18981. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18982. if ( ! extrudeByPath ) {
  18983. v( vert.x, vert.y, amount / steps * s );
  18984. } else {
  18985. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18986. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18987. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18988. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  18989. v( position2.x, position2.y, position2.z );
  18990. }
  18991. }
  18992. }
  18993. // Add bevel segments planes
  18994. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18995. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18996. t = b / bevelSegments;
  18997. z = bevelThickness * ( 1 - t );
  18998. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18999. bs = bevelSize * Math.sin ( t * Math.PI / 2 ) ;
  19000. // contract shape
  19001. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19002. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19003. v( vert.x, vert.y, amount + z );
  19004. }
  19005. // expand holes
  19006. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19007. ahole = holes[ h ];
  19008. oneHoleMovements = holesMovements[ h ];
  19009. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19010. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19011. if ( ! extrudeByPath ) {
  19012. v( vert.x, vert.y, amount + z );
  19013. } else {
  19014. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19015. }
  19016. }
  19017. }
  19018. }
  19019. /* Faces */
  19020. // Top and bottom faces
  19021. buildLidFaces();
  19022. // Sides faces
  19023. buildSideFaces();
  19024. ///// Internal functions
  19025. function buildLidFaces() {
  19026. if ( bevelEnabled ) {
  19027. var layer = 0 ; // steps + 1
  19028. var offset = vlen * layer;
  19029. // Bottom faces
  19030. for ( i = 0; i < flen; i ++ ) {
  19031. face = faces[ i ];
  19032. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  19033. }
  19034. layer = steps + bevelSegments * 2;
  19035. offset = vlen * layer;
  19036. // Top faces
  19037. for ( i = 0; i < flen; i ++ ) {
  19038. face = faces[ i ];
  19039. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  19040. }
  19041. } else {
  19042. // Bottom faces
  19043. for ( i = 0; i < flen; i ++ ) {
  19044. face = faces[ i ];
  19045. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  19046. }
  19047. // Top faces
  19048. for ( i = 0; i < flen; i ++ ) {
  19049. face = faces[ i ];
  19050. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  19051. }
  19052. }
  19053. }
  19054. // Create faces for the z-sides of the shape
  19055. function buildSideFaces() {
  19056. var layeroffset = 0;
  19057. sidewalls( contour, layeroffset );
  19058. layeroffset += contour.length;
  19059. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19060. ahole = holes[ h ];
  19061. sidewalls( ahole, layeroffset );
  19062. //, true
  19063. layeroffset += ahole.length;
  19064. }
  19065. }
  19066. function sidewalls( contour, layeroffset ) {
  19067. var j, k;
  19068. i = contour.length;
  19069. while ( -- i >= 0 ) {
  19070. j = i;
  19071. k = i - 1;
  19072. if ( k < 0 ) k = contour.length - 1;
  19073. //THREE.log('b', i,j, i-1, k,vertices.length);
  19074. var s = 0, sl = steps + bevelSegments * 2;
  19075. for ( s = 0; s < sl; s ++ ) {
  19076. var slen1 = vlen * s;
  19077. var slen2 = vlen * ( s + 1 );
  19078. var a = layeroffset + j + slen1,
  19079. b = layeroffset + k + slen1,
  19080. c = layeroffset + k + slen2,
  19081. d = layeroffset + j + slen2;
  19082. f4( a, b, c, d, contour, s, sl, j, k );
  19083. }
  19084. }
  19085. }
  19086. function v( x, y, z ) {
  19087. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19088. }
  19089. function f3( a, b, c ) {
  19090. a += shapesOffset;
  19091. b += shapesOffset;
  19092. c += shapesOffset;
  19093. // normal, color, material
  19094. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19095. var uvs = uvgen.generateTopUV( scope, a, b, c );
  19096. scope.faceVertexUvs[ 0 ].push( uvs );
  19097. }
  19098. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19099. a += shapesOffset;
  19100. b += shapesOffset;
  19101. c += shapesOffset;
  19102. d += shapesOffset;
  19103. scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) );
  19104. scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) );
  19105. var uvs = uvgen.generateSideWallUV( scope, a, b, c, d );
  19106. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  19107. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  19108. }
  19109. };
  19110. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19111. generateTopUV: function ( geometry, indexA, indexB, indexC ) {
  19112. var vertices = geometry.vertices;
  19113. var a = vertices[ indexA ];
  19114. var b = vertices[ indexB ];
  19115. var c = vertices[ indexC ];
  19116. return [
  19117. new THREE.Vector2( a.x, a.y ),
  19118. new THREE.Vector2( b.x, b.y ),
  19119. new THREE.Vector2( c.x, c.y )
  19120. ];
  19121. },
  19122. generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) {
  19123. var vertices = geometry.vertices;
  19124. var a = vertices[ indexA ];
  19125. var b = vertices[ indexB ];
  19126. var c = vertices[ indexC ];
  19127. var d = vertices[ indexD ];
  19128. if ( Math.abs( a.y - b.y ) < 0.01 ) {
  19129. return [
  19130. new THREE.Vector2( a.x, 1 - a.z ),
  19131. new THREE.Vector2( b.x, 1 - b.z ),
  19132. new THREE.Vector2( c.x, 1 - c.z ),
  19133. new THREE.Vector2( d.x, 1 - d.z )
  19134. ];
  19135. } else {
  19136. return [
  19137. new THREE.Vector2( a.y, 1 - a.z ),
  19138. new THREE.Vector2( b.y, 1 - b.z ),
  19139. new THREE.Vector2( c.y, 1 - c.z ),
  19140. new THREE.Vector2( d.y, 1 - d.z )
  19141. ];
  19142. }
  19143. }
  19144. };
  19145. // File:src/extras/geometries/ShapeGeometry.js
  19146. /**
  19147. * @author jonobr1 / http://jonobr1.com
  19148. *
  19149. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19150. * ExtrudeGeometry.
  19151. *
  19152. * parameters = {
  19153. *
  19154. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19155. *
  19156. * material: <int> // material index for front and back faces
  19157. * uvGenerator: <Object> // object that provides UV generator functions
  19158. *
  19159. * }
  19160. **/
  19161. THREE.ShapeGeometry = function ( shapes, options ) {
  19162. THREE.Geometry.call( this );
  19163. this.type = 'ShapeGeometry';
  19164. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19165. this.addShapeList( shapes, options );
  19166. this.computeFaceNormals();
  19167. };
  19168. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19169. THREE.ShapeGeometry.prototype.constructor = THREE.ShapeGeometry;
  19170. /**
  19171. * Add an array of shapes to THREE.ShapeGeometry.
  19172. */
  19173. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19174. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  19175. this.addShape( shapes[ i ], options );
  19176. }
  19177. return this;
  19178. };
  19179. /**
  19180. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19181. */
  19182. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19183. if ( options === undefined ) options = {};
  19184. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19185. var material = options.material;
  19186. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19187. //
  19188. var i, l, hole;
  19189. var shapesOffset = this.vertices.length;
  19190. var shapePoints = shape.extractPoints( curveSegments );
  19191. var vertices = shapePoints.shape;
  19192. var holes = shapePoints.holes;
  19193. var reverse = ! THREE.Shape.Utils.isClockWise( vertices );
  19194. if ( reverse ) {
  19195. vertices = vertices.reverse();
  19196. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19197. for ( i = 0, l = holes.length; i < l; i ++ ) {
  19198. hole = holes[ i ];
  19199. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19200. holes[ i ] = hole.reverse();
  19201. }
  19202. }
  19203. reverse = false;
  19204. }
  19205. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19206. // Vertices
  19207. var contour = vertices;
  19208. for ( i = 0, l = holes.length; i < l; i ++ ) {
  19209. hole = holes[ i ];
  19210. vertices = vertices.concat( hole );
  19211. }
  19212. //
  19213. var vert, vlen = vertices.length;
  19214. var face, flen = faces.length;
  19215. for ( i = 0; i < vlen; i ++ ) {
  19216. vert = vertices[ i ];
  19217. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19218. }
  19219. for ( i = 0; i < flen; i ++ ) {
  19220. face = faces[ i ];
  19221. var a = face[ 0 ] + shapesOffset;
  19222. var b = face[ 1 ] + shapesOffset;
  19223. var c = face[ 2 ] + shapesOffset;
  19224. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19225. this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) );
  19226. }
  19227. };
  19228. // File:src/extras/geometries/LatheGeometry.js
  19229. /**
  19230. * @author astrodud / http://astrodud.isgreat.org/
  19231. * @author zz85 / https://github.com/zz85
  19232. * @author bhouston / http://exocortex.com
  19233. */
  19234. // points - to create a closed torus, one must use a set of points
  19235. // like so: [ a, b, c, d, a ], see first is the same as last.
  19236. // segments - the number of circumference segments to create
  19237. // phiStart - the starting radian
  19238. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19239. // 2*pi is a closed lathe, less than 2PI is a portion.
  19240. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19241. THREE.Geometry.call( this );
  19242. this.type = 'LatheGeometry';
  19243. this.parameters = {
  19244. points: points,
  19245. segments: segments,
  19246. phiStart: phiStart,
  19247. phiLength: phiLength
  19248. };
  19249. segments = segments || 12;
  19250. phiStart = phiStart || 0;
  19251. phiLength = phiLength || 2 * Math.PI;
  19252. var inversePointLength = 1.0 / ( points.length - 1 );
  19253. var inverseSegments = 1.0 / segments;
  19254. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19255. var phi = phiStart + i * inverseSegments * phiLength;
  19256. var c = Math.cos( phi ),
  19257. s = Math.sin( phi );
  19258. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19259. var pt = points[ j ];
  19260. var vertex = new THREE.Vector3();
  19261. vertex.x = c * pt.x - s * pt.y;
  19262. vertex.y = s * pt.x + c * pt.y;
  19263. vertex.z = pt.z;
  19264. this.vertices.push( vertex );
  19265. }
  19266. }
  19267. var np = points.length;
  19268. for ( var i = 0, il = segments; i < il; i ++ ) {
  19269. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19270. var base = j + np * i;
  19271. var a = base;
  19272. var b = base + np;
  19273. var c = base + 1 + np;
  19274. var d = base + 1;
  19275. var u0 = i * inverseSegments;
  19276. var v0 = j * inversePointLength;
  19277. var u1 = u0 + inverseSegments;
  19278. var v1 = v0 + inversePointLength;
  19279. this.faces.push( new THREE.Face3( a, b, d ) );
  19280. this.faceVertexUvs[ 0 ].push( [
  19281. new THREE.Vector2( u0, v0 ),
  19282. new THREE.Vector2( u1, v0 ),
  19283. new THREE.Vector2( u0, v1 )
  19284. ] );
  19285. this.faces.push( new THREE.Face3( b, c, d ) );
  19286. this.faceVertexUvs[ 0 ].push( [
  19287. new THREE.Vector2( u1, v0 ),
  19288. new THREE.Vector2( u1, v1 ),
  19289. new THREE.Vector2( u0, v1 )
  19290. ] );
  19291. }
  19292. }
  19293. this.mergeVertices();
  19294. this.computeFaceNormals();
  19295. this.computeVertexNormals();
  19296. };
  19297. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19298. THREE.LatheGeometry.prototype.constructor = THREE.LatheGeometry;
  19299. // File:src/extras/geometries/PlaneGeometry.js
  19300. /**
  19301. * @author mrdoob / http://mrdoob.com/
  19302. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19303. */
  19304. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19305. THREE.log( 'THREE.PlaneGeometry: Consider using THREE.PlaneBufferGeometry for lower memory footprint.' );
  19306. THREE.Geometry.call( this );
  19307. this.type = 'PlaneGeometry';
  19308. this.parameters = {
  19309. width: width,
  19310. height: height,
  19311. widthSegments: widthSegments,
  19312. heightSegments: heightSegments
  19313. };
  19314. this.fromBufferGeometry( new THREE.PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  19315. };
  19316. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19317. THREE.PlaneGeometry.prototype.constructor = THREE.PlaneGeometry;
  19318. // File:src/extras/geometries/PlaneBufferGeometry.js
  19319. /**
  19320. * @author mrdoob / http://mrdoob.com/
  19321. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19322. */
  19323. THREE.PlaneBufferGeometry = function ( width, height, widthSegments, heightSegments ) {
  19324. THREE.BufferGeometry.call( this );
  19325. this.type = 'PlaneBufferGeometry';
  19326. this.parameters = {
  19327. width: width,
  19328. height: height,
  19329. widthSegments: widthSegments,
  19330. heightSegments: heightSegments
  19331. };
  19332. var width_half = width / 2;
  19333. var height_half = height / 2;
  19334. var gridX = widthSegments || 1;
  19335. var gridY = heightSegments || 1;
  19336. var gridX1 = gridX + 1;
  19337. var gridY1 = gridY + 1;
  19338. var segment_width = width / gridX;
  19339. var segment_height = height / gridY;
  19340. var vertices = new Float32Array( gridX1 * gridY1 * 3 );
  19341. var normals = new Float32Array( gridX1 * gridY1 * 3 );
  19342. var uvs = new Float32Array( gridX1 * gridY1 * 2 );
  19343. var offset = 0;
  19344. var offset2 = 0;
  19345. for ( var iy = 0; iy < gridY1; iy ++ ) {
  19346. var y = iy * segment_height - height_half;
  19347. for ( var ix = 0; ix < gridX1; ix ++ ) {
  19348. var x = ix * segment_width - width_half;
  19349. vertices[ offset ] = x;
  19350. vertices[ offset + 1 ] = - y;
  19351. normals[ offset + 2 ] = 1;
  19352. uvs[ offset2 ] = ix / gridX;
  19353. uvs[ offset2 + 1 ] = 1 - ( iy / gridY );
  19354. offset += 3;
  19355. offset2 += 2;
  19356. }
  19357. }
  19358. offset = 0;
  19359. var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 );
  19360. for ( var iy = 0; iy < gridY; iy ++ ) {
  19361. for ( var ix = 0; ix < gridX; ix ++ ) {
  19362. var a = ix + gridX1 * iy;
  19363. var b = ix + gridX1 * ( iy + 1 );
  19364. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  19365. var d = ( ix + 1 ) + gridX1 * iy;
  19366. indices[ offset ] = a;
  19367. indices[ offset + 1 ] = b;
  19368. indices[ offset + 2 ] = d;
  19369. indices[ offset + 3 ] = b;
  19370. indices[ offset + 4 ] = c;
  19371. indices[ offset + 5 ] = d;
  19372. offset += 6;
  19373. }
  19374. }
  19375. this.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) );
  19376. this.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  19377. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  19378. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  19379. };
  19380. THREE.PlaneBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  19381. THREE.PlaneBufferGeometry.prototype.constructor = THREE.PlaneBufferGeometry;
  19382. // File:src/extras/geometries/RingGeometry.js
  19383. /**
  19384. * @author Kaleb Murphy
  19385. */
  19386. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19387. THREE.Geometry.call( this );
  19388. this.type = 'RingGeometry';
  19389. this.parameters = {
  19390. innerRadius: innerRadius,
  19391. outerRadius: outerRadius,
  19392. thetaSegments: thetaSegments,
  19393. phiSegments: phiSegments,
  19394. thetaStart: thetaStart,
  19395. thetaLength: thetaLength
  19396. };
  19397. innerRadius = innerRadius || 0;
  19398. outerRadius = outerRadius || 50;
  19399. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19400. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19401. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19402. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 8;
  19403. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19404. for ( i = 0; i < phiSegments + 1; i ++ ) { // concentric circles inside ring
  19405. for ( o = 0; o < thetaSegments + 1; o ++ ) { // number of segments per circle
  19406. var vertex = new THREE.Vector3();
  19407. var segment = thetaStart + o / thetaSegments * thetaLength;
  19408. vertex.x = radius * Math.cos( segment );
  19409. vertex.y = radius * Math.sin( segment );
  19410. this.vertices.push( vertex );
  19411. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  19412. }
  19413. radius += radiusStep;
  19414. }
  19415. var n = new THREE.Vector3( 0, 0, 1 );
  19416. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19417. var thetaSegment = i * (thetaSegments + 1);
  19418. for ( o = 0; o < thetaSegments ; o ++ ) { // number of segments per circle
  19419. var segment = o + thetaSegment;
  19420. var v1 = segment;
  19421. var v2 = segment + thetaSegments + 1;
  19422. var v3 = segment + thetaSegments + 2;
  19423. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19424. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19425. v1 = segment;
  19426. v2 = segment + thetaSegments + 2;
  19427. v3 = segment + 1;
  19428. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19429. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19430. }
  19431. }
  19432. this.computeFaceNormals();
  19433. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19434. };
  19435. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19436. THREE.RingGeometry.prototype.constructor = THREE.RingGeometry;
  19437. // File:src/extras/geometries/SphereGeometry.js
  19438. /**
  19439. * @author mrdoob / http://mrdoob.com/
  19440. */
  19441. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19442. THREE.Geometry.call( this );
  19443. this.type = 'SphereGeometry';
  19444. this.parameters = {
  19445. radius: radius,
  19446. widthSegments: widthSegments,
  19447. heightSegments: heightSegments,
  19448. phiStart: phiStart,
  19449. phiLength: phiLength,
  19450. thetaStart: thetaStart,
  19451. thetaLength: thetaLength
  19452. };
  19453. radius = radius || 50;
  19454. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19455. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19456. phiStart = phiStart !== undefined ? phiStart : 0;
  19457. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19458. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19459. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19460. var x, y, vertices = [], uvs = [];
  19461. for ( y = 0; y <= heightSegments; y ++ ) {
  19462. var verticesRow = [];
  19463. var uvsRow = [];
  19464. for ( x = 0; x <= widthSegments; x ++ ) {
  19465. var u = x / widthSegments;
  19466. var v = y / heightSegments;
  19467. var vertex = new THREE.Vector3();
  19468. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19469. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19470. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19471. this.vertices.push( vertex );
  19472. verticesRow.push( this.vertices.length - 1 );
  19473. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19474. }
  19475. vertices.push( verticesRow );
  19476. uvs.push( uvsRow );
  19477. }
  19478. for ( y = 0; y < heightSegments; y ++ ) {
  19479. for ( x = 0; x < widthSegments; x ++ ) {
  19480. var v1 = vertices[ y ][ x + 1 ];
  19481. var v2 = vertices[ y ][ x ];
  19482. var v3 = vertices[ y + 1 ][ x ];
  19483. var v4 = vertices[ y + 1 ][ x + 1 ];
  19484. var n1 = this.vertices[ v1 ].clone().normalize();
  19485. var n2 = this.vertices[ v2 ].clone().normalize();
  19486. var n3 = this.vertices[ v3 ].clone().normalize();
  19487. var n4 = this.vertices[ v4 ].clone().normalize();
  19488. var uv1 = uvs[ y ][ x + 1 ].clone();
  19489. var uv2 = uvs[ y ][ x ].clone();
  19490. var uv3 = uvs[ y + 1 ][ x ].clone();
  19491. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19492. if ( Math.abs( this.vertices[ v1 ].y ) === radius ) {
  19493. uv1.x = ( uv1.x + uv2.x ) / 2;
  19494. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19495. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19496. } else if ( Math.abs( this.vertices[ v3 ].y ) === radius ) {
  19497. uv3.x = ( uv3.x + uv4.x ) / 2;
  19498. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19499. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19500. } else {
  19501. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19502. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19503. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  19504. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  19505. }
  19506. }
  19507. }
  19508. this.computeFaceNormals();
  19509. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19510. };
  19511. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19512. THREE.SphereGeometry.prototype.constructor = THREE.SphereGeometry;
  19513. // File:src/extras/geometries/TextGeometry.js
  19514. /**
  19515. * @author zz85 / http://www.lab4games.net/zz85/blog
  19516. * @author alteredq / http://alteredqualia.com/
  19517. *
  19518. * For creating 3D text geometry in three.js
  19519. *
  19520. * Text = 3D Text
  19521. *
  19522. * parameters = {
  19523. * size: <float>, // size of the text
  19524. * height: <float>, // thickness to extrude text
  19525. * curveSegments: <int>, // number of points on the curves
  19526. *
  19527. * font: <string>, // font name
  19528. * weight: <string>, // font weight (normal, bold)
  19529. * style: <string>, // font style (normal, italics)
  19530. *
  19531. * bevelEnabled: <bool>, // turn on bevel
  19532. * bevelThickness: <float>, // how deep into text bevel goes
  19533. * bevelSize: <float>, // how far from text outline is bevel
  19534. * }
  19535. *
  19536. */
  19537. /* Usage Examples
  19538. // TextGeometry wrapper
  19539. var text3d = new TextGeometry( text, options );
  19540. // Complete manner
  19541. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19542. var text3d = new ExtrudeGeometry( textShapes, options );
  19543. */
  19544. THREE.TextGeometry = function ( text, parameters ) {
  19545. parameters = parameters || {};
  19546. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19547. // translate parameters to ExtrudeGeometry API
  19548. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19549. // defaults
  19550. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19551. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19552. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19553. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19554. this.type = 'TextGeometry';
  19555. };
  19556. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19557. THREE.TextGeometry.prototype.constructor = THREE.TextGeometry;
  19558. // File:src/extras/geometries/TorusGeometry.js
  19559. /**
  19560. * @author oosmoxiecode
  19561. * @author mrdoob / http://mrdoob.com/
  19562. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19563. */
  19564. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19565. THREE.Geometry.call( this );
  19566. this.type = 'TorusGeometry';
  19567. this.parameters = {
  19568. radius: radius,
  19569. tube: tube,
  19570. radialSegments: radialSegments,
  19571. tubularSegments: tubularSegments,
  19572. arc: arc
  19573. };
  19574. radius = radius || 100;
  19575. tube = tube || 40;
  19576. radialSegments = radialSegments || 8;
  19577. tubularSegments = tubularSegments || 6;
  19578. arc = arc || Math.PI * 2;
  19579. var center = new THREE.Vector3(), uvs = [], normals = [];
  19580. for ( var j = 0; j <= radialSegments; j ++ ) {
  19581. for ( var i = 0; i <= tubularSegments; i ++ ) {
  19582. var u = i / tubularSegments * arc;
  19583. var v = j / radialSegments * Math.PI * 2;
  19584. center.x = radius * Math.cos( u );
  19585. center.y = radius * Math.sin( u );
  19586. var vertex = new THREE.Vector3();
  19587. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  19588. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  19589. vertex.z = tube * Math.sin( v );
  19590. this.vertices.push( vertex );
  19591. uvs.push( new THREE.Vector2( i / tubularSegments, j / radialSegments ) );
  19592. normals.push( vertex.clone().sub( center ).normalize() );
  19593. }
  19594. }
  19595. for ( var j = 1; j <= radialSegments; j ++ ) {
  19596. for ( var i = 1; i <= tubularSegments; i ++ ) {
  19597. var a = ( tubularSegments + 1 ) * j + i - 1;
  19598. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19599. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  19600. var d = ( tubularSegments + 1 ) * j + i;
  19601. var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
  19602. this.faces.push( face );
  19603. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  19604. face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
  19605. this.faces.push( face );
  19606. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19607. }
  19608. }
  19609. this.computeFaceNormals();
  19610. };
  19611. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19612. THREE.TorusGeometry.prototype.constructor = THREE.TorusGeometry;
  19613. // File:src/extras/geometries/TorusKnotGeometry.js
  19614. /**
  19615. * @author oosmoxiecode
  19616. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19617. */
  19618. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19619. THREE.Geometry.call( this );
  19620. this.type = 'TorusKnotGeometry';
  19621. this.parameters = {
  19622. radius: radius,
  19623. tube: tube,
  19624. radialSegments: radialSegments,
  19625. tubularSegments: tubularSegments,
  19626. p: p,
  19627. q: q,
  19628. heightScale: heightScale
  19629. };
  19630. radius = radius || 100;
  19631. tube = tube || 40;
  19632. radialSegments = radialSegments || 64;
  19633. tubularSegments = tubularSegments || 8;
  19634. p = p || 2;
  19635. q = q || 3;
  19636. heightScale = heightScale || 1;
  19637. var grid = new Array( radialSegments );
  19638. var tang = new THREE.Vector3();
  19639. var n = new THREE.Vector3();
  19640. var bitan = new THREE.Vector3();
  19641. for ( var i = 0; i < radialSegments; ++ i ) {
  19642. grid[ i ] = new Array( tubularSegments );
  19643. var u = i / radialSegments * 2 * p * Math.PI;
  19644. var p1 = getPos( u, q, p, radius, heightScale );
  19645. var p2 = getPos( u + 0.01, q, p, radius, heightScale );
  19646. tang.subVectors( p2, p1 );
  19647. n.addVectors( p2, p1 );
  19648. bitan.crossVectors( tang, n );
  19649. n.crossVectors( bitan, tang );
  19650. bitan.normalize();
  19651. n.normalize();
  19652. for ( var j = 0; j < tubularSegments; ++ j ) {
  19653. var v = j / tubularSegments * 2 * Math.PI;
  19654. var cx = - tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19655. var cy = tube * Math.sin( v );
  19656. var pos = new THREE.Vector3();
  19657. pos.x = p1.x + cx * n.x + cy * bitan.x;
  19658. pos.y = p1.y + cx * n.y + cy * bitan.y;
  19659. pos.z = p1.z + cx * n.z + cy * bitan.z;
  19660. grid[ i ][ j ] = this.vertices.push( pos ) - 1;
  19661. }
  19662. }
  19663. for ( var i = 0; i < radialSegments; ++ i ) {
  19664. for ( var j = 0; j < tubularSegments; ++ j ) {
  19665. var ip = ( i + 1 ) % radialSegments;
  19666. var jp = ( j + 1 ) % tubularSegments;
  19667. var a = grid[ i ][ j ];
  19668. var b = grid[ ip ][ j ];
  19669. var c = grid[ ip ][ jp ];
  19670. var d = grid[ i ][ jp ];
  19671. var uva = new THREE.Vector2( i / radialSegments, j / tubularSegments );
  19672. var uvb = new THREE.Vector2( ( i + 1 ) / radialSegments, j / tubularSegments );
  19673. var uvc = new THREE.Vector2( ( i + 1 ) / radialSegments, ( j + 1 ) / tubularSegments );
  19674. var uvd = new THREE.Vector2( i / radialSegments, ( j + 1 ) / tubularSegments );
  19675. this.faces.push( new THREE.Face3( a, b, d ) );
  19676. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19677. this.faces.push( new THREE.Face3( b, c, d ) );
  19678. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19679. }
  19680. }
  19681. this.computeFaceNormals();
  19682. this.computeVertexNormals();
  19683. function getPos( u, in_q, in_p, radius, heightScale ) {
  19684. var cu = Math.cos( u );
  19685. var su = Math.sin( u );
  19686. var quOverP = in_q / in_p * u;
  19687. var cs = Math.cos( quOverP );
  19688. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19689. var ty = radius * ( 2 + cs ) * su * 0.5;
  19690. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19691. return new THREE.Vector3( tx, ty, tz );
  19692. }
  19693. };
  19694. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19695. THREE.TorusKnotGeometry.prototype.constructor = THREE.TorusKnotGeometry;
  19696. // File:src/extras/geometries/TubeGeometry.js
  19697. /**
  19698. * @author WestLangley / https://github.com/WestLangley
  19699. * @author zz85 / https://github.com/zz85
  19700. * @author miningold / https://github.com/miningold
  19701. * @author jonobr1 / https://github.com/jonobr1
  19702. *
  19703. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19704. *
  19705. * Creates a tube which extrudes along a 3d spline
  19706. *
  19707. * Uses parallel transport frames as described in
  19708. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19709. */
  19710. THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, taper ) {
  19711. THREE.Geometry.call( this );
  19712. this.type = 'TubeGeometry';
  19713. this.parameters = {
  19714. path: path,
  19715. segments: segments,
  19716. radius: radius,
  19717. radialSegments: radialSegments,
  19718. closed: closed
  19719. };
  19720. segments = segments || 64;
  19721. radius = radius || 1;
  19722. radialSegments = radialSegments || 8;
  19723. closed = closed || false;
  19724. taper = taper || THREE.TubeGeometry.NoTaper;
  19725. var grid = [];
  19726. var scope = this,
  19727. tangent,
  19728. normal,
  19729. binormal,
  19730. numpoints = segments + 1,
  19731. u, v, r,
  19732. cx, cy,
  19733. pos, pos2 = new THREE.Vector3(),
  19734. i, j,
  19735. ip, jp,
  19736. a, b, c, d,
  19737. uva, uvb, uvc, uvd;
  19738. var frames = new THREE.TubeGeometry.FrenetFrames( path, segments, closed ),
  19739. tangents = frames.tangents,
  19740. normals = frames.normals,
  19741. binormals = frames.binormals;
  19742. // proxy internals
  19743. this.tangents = tangents;
  19744. this.normals = normals;
  19745. this.binormals = binormals;
  19746. function vert( x, y, z ) {
  19747. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19748. }
  19749. // consruct the grid
  19750. for ( i = 0; i < numpoints; i ++ ) {
  19751. grid[ i ] = [];
  19752. u = i / ( numpoints - 1 );
  19753. pos = path.getPointAt( u );
  19754. tangent = tangents[ i ];
  19755. normal = normals[ i ];
  19756. binormal = binormals[ i ];
  19757. r = radius * taper( u );
  19758. for ( j = 0; j < radialSegments; j ++ ) {
  19759. v = j / radialSegments * 2 * Math.PI;
  19760. cx = - r * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19761. cy = r * Math.sin( v );
  19762. pos2.copy( pos );
  19763. pos2.x += cx * normal.x + cy * binormal.x;
  19764. pos2.y += cx * normal.y + cy * binormal.y;
  19765. pos2.z += cx * normal.z + cy * binormal.z;
  19766. grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19767. }
  19768. }
  19769. // construct the mesh
  19770. for ( i = 0; i < segments; i ++ ) {
  19771. for ( j = 0; j < radialSegments; j ++ ) {
  19772. ip = ( closed ) ? (i + 1) % segments : i + 1;
  19773. jp = (j + 1) % radialSegments;
  19774. a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19775. b = grid[ ip ][ j ];
  19776. c = grid[ ip ][ jp ];
  19777. d = grid[ i ][ jp ];
  19778. uva = new THREE.Vector2( i / segments, j / radialSegments );
  19779. uvb = new THREE.Vector2( ( i + 1 ) / segments, j / radialSegments );
  19780. uvc = new THREE.Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments );
  19781. uvd = new THREE.Vector2( i / segments, ( j + 1 ) / radialSegments );
  19782. this.faces.push( new THREE.Face3( a, b, d ) );
  19783. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19784. this.faces.push( new THREE.Face3( b, c, d ) );
  19785. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19786. }
  19787. }
  19788. this.computeFaceNormals();
  19789. this.computeVertexNormals();
  19790. };
  19791. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19792. THREE.TubeGeometry.prototype.constructor = THREE.TubeGeometry;
  19793. THREE.TubeGeometry.NoTaper = function ( u ) {
  19794. return 1;
  19795. };
  19796. THREE.TubeGeometry.SinusoidalTaper = function ( u ) {
  19797. return Math.sin( Math.PI * u );
  19798. };
  19799. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19800. THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) {
  19801. var normal = new THREE.Vector3(),
  19802. tangents = [],
  19803. normals = [],
  19804. binormals = [],
  19805. vec = new THREE.Vector3(),
  19806. mat = new THREE.Matrix4(),
  19807. numpoints = segments + 1,
  19808. theta,
  19809. epsilon = 0.0001,
  19810. smallest,
  19811. tx, ty, tz,
  19812. i, u;
  19813. // expose internals
  19814. this.tangents = tangents;
  19815. this.normals = normals;
  19816. this.binormals = binormals;
  19817. // compute the tangent vectors for each segment on the path
  19818. for ( i = 0; i < numpoints; i ++ ) {
  19819. u = i / ( numpoints - 1 );
  19820. tangents[ i ] = path.getTangentAt( u );
  19821. tangents[ i ].normalize();
  19822. }
  19823. initialNormal3();
  19824. /*
  19825. function initialNormal1(lastBinormal) {
  19826. // fixed start binormal. Has dangers of 0 vectors
  19827. normals[ 0 ] = new THREE.Vector3();
  19828. binormals[ 0 ] = new THREE.Vector3();
  19829. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19830. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19831. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19832. }
  19833. function initialNormal2() {
  19834. // This uses the Frenet-Serret formula for deriving binormal
  19835. var t2 = path.getTangentAt( epsilon );
  19836. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  19837. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  19838. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19839. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19840. }
  19841. */
  19842. function initialNormal3() {
  19843. // select an initial normal vector perpenicular to the first tangent vector,
  19844. // and in the direction of the smallest tangent xyz component
  19845. normals[ 0 ] = new THREE.Vector3();
  19846. binormals[ 0 ] = new THREE.Vector3();
  19847. smallest = Number.MAX_VALUE;
  19848. tx = Math.abs( tangents[ 0 ].x );
  19849. ty = Math.abs( tangents[ 0 ].y );
  19850. tz = Math.abs( tangents[ 0 ].z );
  19851. if ( tx <= smallest ) {
  19852. smallest = tx;
  19853. normal.set( 1, 0, 0 );
  19854. }
  19855. if ( ty <= smallest ) {
  19856. smallest = ty;
  19857. normal.set( 0, 1, 0 );
  19858. }
  19859. if ( tz <= smallest ) {
  19860. normal.set( 0, 0, 1 );
  19861. }
  19862. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19863. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19864. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19865. }
  19866. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19867. for ( i = 1; i < numpoints; i ++ ) {
  19868. normals[ i ] = normals[ i - 1 ].clone();
  19869. binormals[ i ] = binormals[ i - 1 ].clone();
  19870. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  19871. if ( vec.length() > epsilon ) {
  19872. vec.normalize();
  19873. theta = Math.acos( THREE.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  19874. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19875. }
  19876. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19877. }
  19878. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19879. if ( closed ) {
  19880. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) );
  19881. theta /= ( numpoints - 1 );
  19882. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) {
  19883. theta = - theta;
  19884. }
  19885. for ( i = 1; i < numpoints; i ++ ) {
  19886. // twist a little...
  19887. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19888. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19889. }
  19890. }
  19891. };
  19892. // File:src/extras/geometries/PolyhedronGeometry.js
  19893. /**
  19894. * @author clockworkgeek / https://github.com/clockworkgeek
  19895. * @author timothypratley / https://github.com/timothypratley
  19896. * @author WestLangley / http://github.com/WestLangley
  19897. */
  19898. THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) {
  19899. THREE.Geometry.call( this );
  19900. this.type = 'PolyhedronGeometry';
  19901. this.parameters = {
  19902. vertices: vertices,
  19903. indices: indices,
  19904. radius: radius,
  19905. detail: detail
  19906. };
  19907. radius = radius || 1;
  19908. detail = detail || 0;
  19909. var that = this;
  19910. for ( var i = 0, l = vertices.length; i < l; i += 3 ) {
  19911. prepare( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  19912. }
  19913. var p = this.vertices;
  19914. var faces = [];
  19915. for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) {
  19916. var v1 = p[ indices[ i ] ];
  19917. var v2 = p[ indices[ i + 1 ] ];
  19918. var v3 = p[ indices[ i + 2 ] ];
  19919. faces[ j ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19920. }
  19921. var centroid = new THREE.Vector3();
  19922. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19923. subdivide( faces[ i ], detail );
  19924. }
  19925. // Handle case when face straddles the seam
  19926. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  19927. var uvs = this.faceVertexUvs[ 0 ][ i ];
  19928. var x0 = uvs[ 0 ].x;
  19929. var x1 = uvs[ 1 ].x;
  19930. var x2 = uvs[ 2 ].x;
  19931. var max = Math.max( x0, Math.max( x1, x2 ) );
  19932. var min = Math.min( x0, Math.min( x1, x2 ) );
  19933. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  19934. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  19935. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  19936. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  19937. }
  19938. }
  19939. // Apply radius
  19940. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19941. this.vertices[ i ].multiplyScalar( radius );
  19942. }
  19943. // Merge vertices
  19944. this.mergeVertices();
  19945. this.computeFaceNormals();
  19946. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19947. // Project vector onto sphere's surface
  19948. function prepare( vector ) {
  19949. var vertex = vector.normalize().clone();
  19950. vertex.index = that.vertices.push( vertex ) - 1;
  19951. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19952. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19953. var v = inclination( vector ) / Math.PI + 0.5;
  19954. vertex.uv = new THREE.Vector2( u, 1 - v );
  19955. return vertex;
  19956. }
  19957. // Approximate a curved face with recursively sub-divided triangles.
  19958. function make( v1, v2, v3 ) {
  19959. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19960. that.faces.push( face );
  19961. centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  19962. var azi = azimuth( centroid );
  19963. that.faceVertexUvs[ 0 ].push( [
  19964. correctUV( v1.uv, v1, azi ),
  19965. correctUV( v2.uv, v2, azi ),
  19966. correctUV( v3.uv, v3, azi )
  19967. ] );
  19968. }
  19969. // Analytically subdivide a face to the required detail level.
  19970. function subdivide( face, detail ) {
  19971. var cols = Math.pow(2, detail);
  19972. var a = prepare( that.vertices[ face.a ] );
  19973. var b = prepare( that.vertices[ face.b ] );
  19974. var c = prepare( that.vertices[ face.c ] );
  19975. var v = [];
  19976. // Construct all of the vertices for this subdivision.
  19977. for ( var i = 0 ; i <= cols; i ++ ) {
  19978. v[ i ] = [];
  19979. var aj = prepare( a.clone().lerp( c, i / cols ) );
  19980. var bj = prepare( b.clone().lerp( c, i / cols ) );
  19981. var rows = cols - i;
  19982. for ( var j = 0; j <= rows; j ++) {
  19983. if ( j == 0 && i == cols ) {
  19984. v[ i ][ j ] = aj;
  19985. } else {
  19986. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  19987. }
  19988. }
  19989. }
  19990. // Construct all of the faces.
  19991. for ( var i = 0; i < cols ; i ++ ) {
  19992. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  19993. var k = Math.floor( j / 2 );
  19994. if ( j % 2 == 0 ) {
  19995. make(
  19996. v[ i ][ k + 1],
  19997. v[ i + 1 ][ k ],
  19998. v[ i ][ k ]
  19999. );
  20000. } else {
  20001. make(
  20002. v[ i ][ k + 1 ],
  20003. v[ i + 1][ k + 1],
  20004. v[ i + 1 ][ k ]
  20005. );
  20006. }
  20007. }
  20008. }
  20009. }
  20010. // Angle around the Y axis, counter-clockwise when looking from above.
  20011. function azimuth( vector ) {
  20012. return Math.atan2( vector.z, - vector.x );
  20013. }
  20014. // Angle above the XZ plane.
  20015. function inclination( vector ) {
  20016. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20017. }
  20018. // Texture fixing helper. Spheres have some odd behaviours.
  20019. function correctUV( uv, vector, azimuth ) {
  20020. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  20021. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  20022. return uv.clone();
  20023. }
  20024. };
  20025. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20026. THREE.PolyhedronGeometry.prototype.constructor = THREE.PolyhedronGeometry;
  20027. // File:src/extras/geometries/DodecahedronGeometry.js
  20028. /**
  20029. * @author Abe Pazos / https://hamoid.com
  20030. */
  20031. THREE.DodecahedronGeometry = function ( radius, detail ) {
  20032. this.parameters = {
  20033. radius: radius,
  20034. detail: detail
  20035. };
  20036. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20037. var r = 1 / t;
  20038. var vertices = [
  20039. // (±1, ±1, ±1)
  20040. -1, -1, -1, -1, -1, 1,
  20041. -1, 1, -1, -1, 1, 1,
  20042. 1, -1, -1, 1, -1, 1,
  20043. 1, 1, -1, 1, 1, 1,
  20044. // (0, ±1/φ, ±φ)
  20045. 0, -r, -t, 0, -r, t,
  20046. 0, r, -t, 0, r, t,
  20047. // (±1/φ, ±φ, 0)
  20048. -r, -t, 0, -r, t, 0,
  20049. r, -t, 0, r, t, 0,
  20050. // (±φ, 0, ±1/φ)
  20051. -t, 0, -r, t, 0, -r,
  20052. -t, 0, r, t, 0, r
  20053. ];
  20054. var indices = [
  20055. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  20056. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  20057. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  20058. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  20059. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  20060. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  20061. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  20062. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  20063. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  20064. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  20065. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  20066. 1, 12, 14, 1, 14, 5, 1, 5, 9
  20067. ];
  20068. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  20069. };
  20070. THREE.DodecahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20071. THREE.DodecahedronGeometry.prototype.constructor = THREE.DodecahedronGeometry;
  20072. // File:src/extras/geometries/IcosahedronGeometry.js
  20073. /**
  20074. * @author timothypratley / https://github.com/timothypratley
  20075. */
  20076. THREE.IcosahedronGeometry = function ( radius, detail ) {
  20077. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20078. var vertices = [
  20079. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  20080. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  20081. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  20082. ];
  20083. var indices = [
  20084. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  20085. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  20086. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  20087. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  20088. ];
  20089. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  20090. this.type = 'IcosahedronGeometry';
  20091. this.parameters = {
  20092. radius: radius,
  20093. detail: detail
  20094. };
  20095. };
  20096. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20097. THREE.IcosahedronGeometry.prototype.constructor = THREE.IcosahedronGeometry;
  20098. // File:src/extras/geometries/OctahedronGeometry.js
  20099. /**
  20100. * @author timothypratley / https://github.com/timothypratley
  20101. */
  20102. THREE.OctahedronGeometry = function ( radius, detail ) {
  20103. this.parameters = {
  20104. radius: radius,
  20105. detail: detail
  20106. };
  20107. var vertices = [
  20108. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0,- 1, 0, 0, 0, 1, 0, 0,- 1
  20109. ];
  20110. var indices = [
  20111. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  20112. ];
  20113. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  20114. this.type = 'OctahedronGeometry';
  20115. this.parameters = {
  20116. radius: radius,
  20117. detail: detail
  20118. };
  20119. };
  20120. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20121. THREE.OctahedronGeometry.prototype.constructor = THREE.OctahedronGeometry;
  20122. // File:src/extras/geometries/TetrahedronGeometry.js
  20123. /**
  20124. * @author timothypratley / https://github.com/timothypratley
  20125. */
  20126. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20127. var vertices = [
  20128. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  20129. ];
  20130. var indices = [
  20131. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  20132. ];
  20133. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  20134. this.type = 'TetrahedronGeometry';
  20135. this.parameters = {
  20136. radius: radius,
  20137. detail: detail
  20138. };
  20139. };
  20140. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20141. THREE.TetrahedronGeometry.prototype.constructor = THREE.TetrahedronGeometry;
  20142. // File:src/extras/geometries/ParametricGeometry.js
  20143. /**
  20144. * @author zz85 / https://github.com/zz85
  20145. * Parametric Surfaces Geometry
  20146. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20147. *
  20148. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  20149. *
  20150. */
  20151. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  20152. THREE.Geometry.call( this );
  20153. this.type = 'ParametricGeometry';
  20154. this.parameters = {
  20155. func: func,
  20156. slices: slices,
  20157. stacks: stacks
  20158. };
  20159. var verts = this.vertices;
  20160. var faces = this.faces;
  20161. var uvs = this.faceVertexUvs[ 0 ];
  20162. var i, j, p;
  20163. var u, v;
  20164. var sliceCount = slices + 1;
  20165. for ( i = 0; i <= stacks; i ++ ) {
  20166. v = i / stacks;
  20167. for ( j = 0; j <= slices; j ++ ) {
  20168. u = j / slices;
  20169. p = func( u, v );
  20170. verts.push( p );
  20171. }
  20172. }
  20173. var a, b, c, d;
  20174. var uva, uvb, uvc, uvd;
  20175. for ( i = 0; i < stacks; i ++ ) {
  20176. for ( j = 0; j < slices; j ++ ) {
  20177. a = i * sliceCount + j;
  20178. b = i * sliceCount + j + 1;
  20179. c = (i + 1) * sliceCount + j + 1;
  20180. d = (i + 1) * sliceCount + j;
  20181. uva = new THREE.Vector2( j / slices, i / stacks );
  20182. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20183. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20184. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20185. faces.push( new THREE.Face3( a, b, d ) );
  20186. uvs.push( [ uva, uvb, uvd ] );
  20187. faces.push( new THREE.Face3( b, c, d ) );
  20188. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  20189. }
  20190. }
  20191. // THREE.log(this);
  20192. // magic bullet
  20193. // var diff = this.mergeVertices();
  20194. // THREE.log('removed ', diff, ' vertices by merging');
  20195. this.computeFaceNormals();
  20196. this.computeVertexNormals();
  20197. };
  20198. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20199. THREE.ParametricGeometry.prototype.constructor = THREE.ParametricGeometry;
  20200. // File:src/extras/geometries/WireframeGeometry.js
  20201. /**
  20202. * @author mrdoob / http://mrdoob.com/
  20203. */
  20204. THREE.WireframeGeometry = function ( geometry ) {
  20205. THREE.BufferGeometry.call( this );
  20206. var edge = [ 0, 0 ], hash = {};
  20207. var sortFunction = function ( a, b ) { return a - b };
  20208. var keys = [ 'a', 'b', 'c' ];
  20209. if ( geometry instanceof THREE.Geometry ) {
  20210. var vertices = geometry.vertices;
  20211. var faces = geometry.faces;
  20212. var numEdges = 0;
  20213. // allocate maximal size
  20214. var edges = new Uint32Array( 6 * faces.length );
  20215. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20216. var face = faces[ i ];
  20217. for ( var j = 0; j < 3; j ++ ) {
  20218. edge[ 0 ] = face[ keys[ j ] ];
  20219. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20220. edge.sort( sortFunction );
  20221. var key = edge.toString();
  20222. if ( hash[ key ] === undefined ) {
  20223. edges[ 2 * numEdges ] = edge[ 0 ];
  20224. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  20225. hash[ key ] = true;
  20226. numEdges ++;
  20227. }
  20228. }
  20229. }
  20230. var coords = new Float32Array( numEdges * 2 * 3 );
  20231. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  20232. for ( var j = 0; j < 2; j ++ ) {
  20233. var vertex = vertices[ edges [ 2 * i + j] ];
  20234. var index = 6 * i + 3 * j;
  20235. coords[ index + 0 ] = vertex.x;
  20236. coords[ index + 1 ] = vertex.y;
  20237. coords[ index + 2 ] = vertex.z;
  20238. }
  20239. }
  20240. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20241. } else if ( geometry instanceof THREE.BufferGeometry ) {
  20242. if ( geometry.attributes.index !== undefined ) { // Indexed BufferGeometry
  20243. var vertices = geometry.attributes.position.array;
  20244. var indices = geometry.attributes.index.array;
  20245. var drawcalls = geometry.drawcalls;
  20246. var numEdges = 0;
  20247. if ( drawcalls.length === 0 ) {
  20248. drawcalls = [ { count : indices.length, index : 0, start : 0 } ];
  20249. }
  20250. // allocate maximal size
  20251. var edges = new Uint32Array( 2 * indices.length );
  20252. for ( var o = 0, ol = drawcalls.length; o < ol; ++ o ) {
  20253. var start = drawcalls[ o ].start;
  20254. var count = drawcalls[ o ].count;
  20255. var index = drawcalls[ o ].index;
  20256. for ( var i = start, il = start + count; i < il; i += 3 ) {
  20257. for ( var j = 0; j < 3; j ++ ) {
  20258. edge[ 0 ] = index + indices[ i + j ];
  20259. edge[ 1 ] = index + indices[ i + ( j + 1 ) % 3 ];
  20260. edge.sort( sortFunction );
  20261. var key = edge.toString();
  20262. if ( hash[ key ] === undefined ) {
  20263. edges[ 2 * numEdges ] = edge[ 0 ];
  20264. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  20265. hash[ key ] = true;
  20266. numEdges ++;
  20267. }
  20268. }
  20269. }
  20270. }
  20271. var coords = new Float32Array( numEdges * 2 * 3 );
  20272. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  20273. for ( var j = 0; j < 2; j ++ ) {
  20274. var index = 6 * i + 3 * j;
  20275. var index2 = 3 * edges[ 2 * i + j];
  20276. coords[ index + 0 ] = vertices[ index2 ];
  20277. coords[ index + 1 ] = vertices[ index2 + 1 ];
  20278. coords[ index + 2 ] = vertices[ index2 + 2 ];
  20279. }
  20280. }
  20281. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20282. } else { // non-indexed BufferGeometry
  20283. var vertices = geometry.attributes.position.array;
  20284. var numEdges = vertices.length / 3;
  20285. var numTris = numEdges / 3;
  20286. var coords = new Float32Array( numEdges * 2 * 3 );
  20287. for ( var i = 0, l = numTris; i < l; i ++ ) {
  20288. for ( var j = 0; j < 3; j ++ ) {
  20289. var index = 18 * i + 6 * j;
  20290. var index1 = 9 * i + 3 * j;
  20291. coords[ index + 0 ] = vertices[ index1 ];
  20292. coords[ index + 1 ] = vertices[ index1 + 1 ];
  20293. coords[ index + 2 ] = vertices[ index1 + 2 ];
  20294. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  20295. coords[ index + 3 ] = vertices[ index2 ];
  20296. coords[ index + 4 ] = vertices[ index2 + 1 ];
  20297. coords[ index + 5 ] = vertices[ index2 + 2 ];
  20298. }
  20299. }
  20300. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20301. }
  20302. }
  20303. };
  20304. THREE.WireframeGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  20305. THREE.WireframeGeometry.prototype.constructor = THREE.WireframeGeometry;
  20306. // File:src/extras/helpers/AxisHelper.js
  20307. /**
  20308. * @author sroucheray / http://sroucheray.org/
  20309. * @author mrdoob / http://mrdoob.com/
  20310. */
  20311. THREE.AxisHelper = function ( size ) {
  20312. size = size || 1;
  20313. var vertices = new Float32Array( [
  20314. 0, 0, 0, size, 0, 0,
  20315. 0, 0, 0, 0, size, 0,
  20316. 0, 0, 0, 0, 0, size
  20317. ] );
  20318. var colors = new Float32Array( [
  20319. 1, 0, 0, 1, 0.6, 0,
  20320. 0, 1, 0, 0.6, 1, 0,
  20321. 0, 0, 1, 0, 0.6, 1
  20322. ] );
  20323. var geometry = new THREE.BufferGeometry();
  20324. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  20325. geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
  20326. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20327. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20328. };
  20329. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20330. THREE.AxisHelper.prototype.constructor = THREE.AxisHelper;
  20331. // File:src/extras/helpers/ArrowHelper.js
  20332. /**
  20333. * @author WestLangley / http://github.com/WestLangley
  20334. * @author zz85 / http://github.com/zz85
  20335. * @author bhouston / http://exocortex.com
  20336. *
  20337. * Creates an arrow for visualizing directions
  20338. *
  20339. * Parameters:
  20340. * dir - Vector3
  20341. * origin - Vector3
  20342. * length - Number
  20343. * color - color in hex value
  20344. * headLength - Number
  20345. * headWidth - Number
  20346. */
  20347. THREE.ArrowHelper = ( function () {
  20348. var lineGeometry = new THREE.Geometry();
  20349. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) );
  20350. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  20351. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  20352. return function ( dir, origin, length, color, headLength, headWidth ) {
  20353. // dir is assumed to be normalized
  20354. THREE.Object3D.call( this );
  20355. if ( color === undefined ) color = 0xffff00;
  20356. if ( length === undefined ) length = 1;
  20357. if ( headLength === undefined ) headLength = 0.2 * length;
  20358. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20359. this.position.copy( origin );
  20360. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: color } ) );
  20361. this.line.matrixAutoUpdate = false;
  20362. this.add( this.line );
  20363. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: color } ) );
  20364. this.cone.matrixAutoUpdate = false;
  20365. this.add( this.cone );
  20366. this.setDirection( dir );
  20367. this.setLength( length, headLength, headWidth );
  20368. }
  20369. }() );
  20370. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20371. THREE.ArrowHelper.prototype.constructor = THREE.ArrowHelper;
  20372. THREE.ArrowHelper.prototype.setDirection = ( function () {
  20373. var axis = new THREE.Vector3();
  20374. var radians;
  20375. return function ( dir ) {
  20376. // dir is assumed to be normalized
  20377. if ( dir.y > 0.99999 ) {
  20378. this.quaternion.set( 0, 0, 0, 1 );
  20379. } else if ( dir.y < - 0.99999 ) {
  20380. this.quaternion.set( 1, 0, 0, 0 );
  20381. } else {
  20382. axis.set( dir.z, 0, - dir.x ).normalize();
  20383. radians = Math.acos( dir.y );
  20384. this.quaternion.setFromAxisAngle( axis, radians );
  20385. }
  20386. };
  20387. }() );
  20388. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  20389. if ( headLength === undefined ) headLength = 0.2 * length;
  20390. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20391. this.line.scale.set( 1, length - headLength, 1 );
  20392. this.line.updateMatrix();
  20393. this.cone.scale.set( headWidth, headLength, headWidth );
  20394. this.cone.position.y = length;
  20395. this.cone.updateMatrix();
  20396. };
  20397. THREE.ArrowHelper.prototype.setColor = function ( color ) {
  20398. this.line.material.color.set( color );
  20399. this.cone.material.color.set( color );
  20400. };
  20401. // File:src/extras/helpers/BoxHelper.js
  20402. /**
  20403. * @author mrdoob / http://mrdoob.com/
  20404. */
  20405. THREE.BoxHelper = function ( object ) {
  20406. var geometry = new THREE.BufferGeometry();
  20407. geometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( 72 ), 3 ) );
  20408. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  20409. if ( object !== undefined ) {
  20410. this.update( object );
  20411. }
  20412. };
  20413. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20414. THREE.BoxHelper.prototype.constructor = THREE.BoxHelper;
  20415. THREE.BoxHelper.prototype.update = function ( object ) {
  20416. var geometry = object.geometry;
  20417. if ( geometry.boundingBox === null ) {
  20418. geometry.computeBoundingBox();
  20419. }
  20420. var min = geometry.boundingBox.min;
  20421. var max = geometry.boundingBox.max;
  20422. /*
  20423. 5____4
  20424. 1/___0/|
  20425. | 6__|_7
  20426. 2/___3/
  20427. 0: max.x, max.y, max.z
  20428. 1: min.x, max.y, max.z
  20429. 2: min.x, min.y, max.z
  20430. 3: max.x, min.y, max.z
  20431. 4: max.x, max.y, min.z
  20432. 5: min.x, max.y, min.z
  20433. 6: min.x, min.y, min.z
  20434. 7: max.x, min.y, min.z
  20435. */
  20436. var vertices = this.geometry.attributes.position.array;
  20437. vertices[ 0 ] = max.x; vertices[ 1 ] = max.y; vertices[ 2 ] = max.z;
  20438. vertices[ 3 ] = min.x; vertices[ 4 ] = max.y; vertices[ 5 ] = max.z;
  20439. vertices[ 6 ] = min.x; vertices[ 7 ] = max.y; vertices[ 8 ] = max.z;
  20440. vertices[ 9 ] = min.x; vertices[ 10 ] = min.y; vertices[ 11 ] = max.z;
  20441. vertices[ 12 ] = min.x; vertices[ 13 ] = min.y; vertices[ 14 ] = max.z;
  20442. vertices[ 15 ] = max.x; vertices[ 16 ] = min.y; vertices[ 17 ] = max.z;
  20443. vertices[ 18 ] = max.x; vertices[ 19 ] = min.y; vertices[ 20 ] = max.z;
  20444. vertices[ 21 ] = max.x; vertices[ 22 ] = max.y; vertices[ 23 ] = max.z;
  20445. //
  20446. vertices[ 24 ] = max.x; vertices[ 25 ] = max.y; vertices[ 26 ] = min.z;
  20447. vertices[ 27 ] = min.x; vertices[ 28 ] = max.y; vertices[ 29 ] = min.z;
  20448. vertices[ 30 ] = min.x; vertices[ 31 ] = max.y; vertices[ 32 ] = min.z;
  20449. vertices[ 33 ] = min.x; vertices[ 34 ] = min.y; vertices[ 35 ] = min.z;
  20450. vertices[ 36 ] = min.x; vertices[ 37 ] = min.y; vertices[ 38 ] = min.z;
  20451. vertices[ 39 ] = max.x; vertices[ 40 ] = min.y; vertices[ 41 ] = min.z;
  20452. vertices[ 42 ] = max.x; vertices[ 43 ] = min.y; vertices[ 44 ] = min.z;
  20453. vertices[ 45 ] = max.x; vertices[ 46 ] = max.y; vertices[ 47 ] = min.z;
  20454. //
  20455. vertices[ 48 ] = max.x; vertices[ 49 ] = max.y; vertices[ 50 ] = max.z;
  20456. vertices[ 51 ] = max.x; vertices[ 52 ] = max.y; vertices[ 53 ] = min.z;
  20457. vertices[ 54 ] = min.x; vertices[ 55 ] = max.y; vertices[ 56 ] = max.z;
  20458. vertices[ 57 ] = min.x; vertices[ 58 ] = max.y; vertices[ 59 ] = min.z;
  20459. vertices[ 60 ] = min.x; vertices[ 61 ] = min.y; vertices[ 62 ] = max.z;
  20460. vertices[ 63 ] = min.x; vertices[ 64 ] = min.y; vertices[ 65 ] = min.z;
  20461. vertices[ 66 ] = max.x; vertices[ 67 ] = min.y; vertices[ 68 ] = max.z;
  20462. vertices[ 69 ] = max.x; vertices[ 70 ] = min.y; vertices[ 71 ] = min.z;
  20463. this.geometry.attributes.position.needsUpdate = true;
  20464. this.geometry.computeBoundingSphere();
  20465. this.matrix = object.matrixWorld;
  20466. this.matrixAutoUpdate = false;
  20467. };
  20468. // File:src/extras/helpers/BoundingBoxHelper.js
  20469. /**
  20470. * @author WestLangley / http://github.com/WestLangley
  20471. */
  20472. // a helper to show the world-axis-aligned bounding box for an object
  20473. THREE.BoundingBoxHelper = function ( object, hex ) {
  20474. var color = ( hex !== undefined ) ? hex : 0x888888;
  20475. this.object = object;
  20476. this.box = new THREE.Box3();
  20477. THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20478. };
  20479. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20480. THREE.BoundingBoxHelper.prototype.constructor = THREE.BoundingBoxHelper;
  20481. THREE.BoundingBoxHelper.prototype.update = function () {
  20482. this.box.setFromObject( this.object );
  20483. this.box.size( this.scale );
  20484. this.box.center( this.position );
  20485. };
  20486. // File:src/extras/helpers/CameraHelper.js
  20487. /**
  20488. * @author alteredq / http://alteredqualia.com/
  20489. *
  20490. * - shows frustum, line of sight and up of the camera
  20491. * - suitable for fast updates
  20492. * - based on frustum visualization in lightgl.js shadowmap example
  20493. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20494. */
  20495. THREE.CameraHelper = function ( camera ) {
  20496. var geometry = new THREE.Geometry();
  20497. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20498. var pointMap = {};
  20499. // colors
  20500. var hexFrustum = 0xffaa00;
  20501. var hexCone = 0xff0000;
  20502. var hexUp = 0x00aaff;
  20503. var hexTarget = 0xffffff;
  20504. var hexCross = 0x333333;
  20505. // near
  20506. addLine( "n1", "n2", hexFrustum );
  20507. addLine( "n2", "n4", hexFrustum );
  20508. addLine( "n4", "n3", hexFrustum );
  20509. addLine( "n3", "n1", hexFrustum );
  20510. // far
  20511. addLine( "f1", "f2", hexFrustum );
  20512. addLine( "f2", "f4", hexFrustum );
  20513. addLine( "f4", "f3", hexFrustum );
  20514. addLine( "f3", "f1", hexFrustum );
  20515. // sides
  20516. addLine( "n1", "f1", hexFrustum );
  20517. addLine( "n2", "f2", hexFrustum );
  20518. addLine( "n3", "f3", hexFrustum );
  20519. addLine( "n4", "f4", hexFrustum );
  20520. // cone
  20521. addLine( "p", "n1", hexCone );
  20522. addLine( "p", "n2", hexCone );
  20523. addLine( "p", "n3", hexCone );
  20524. addLine( "p", "n4", hexCone );
  20525. // up
  20526. addLine( "u1", "u2", hexUp );
  20527. addLine( "u2", "u3", hexUp );
  20528. addLine( "u3", "u1", hexUp );
  20529. // target
  20530. addLine( "c", "t", hexTarget );
  20531. addLine( "p", "c", hexCross );
  20532. // cross
  20533. addLine( "cn1", "cn2", hexCross );
  20534. addLine( "cn3", "cn4", hexCross );
  20535. addLine( "cf1", "cf2", hexCross );
  20536. addLine( "cf3", "cf4", hexCross );
  20537. function addLine( a, b, hex ) {
  20538. addPoint( a, hex );
  20539. addPoint( b, hex );
  20540. }
  20541. function addPoint( id, hex ) {
  20542. geometry.vertices.push( new THREE.Vector3() );
  20543. geometry.colors.push( new THREE.Color( hex ) );
  20544. if ( pointMap[ id ] === undefined ) {
  20545. pointMap[ id ] = [];
  20546. }
  20547. pointMap[ id ].push( geometry.vertices.length - 1 );
  20548. }
  20549. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20550. this.camera = camera;
  20551. this.matrix = camera.matrixWorld;
  20552. this.matrixAutoUpdate = false;
  20553. this.pointMap = pointMap;
  20554. this.update();
  20555. };
  20556. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20557. THREE.CameraHelper.prototype.constructor = THREE.CameraHelper;
  20558. THREE.CameraHelper.prototype.update = function () {
  20559. var geometry, pointMap;
  20560. var vector = new THREE.Vector3();
  20561. var camera = new THREE.Camera();
  20562. var setPoint = function ( point, x, y, z ) {
  20563. vector.set( x, y, z ).unproject( camera );
  20564. var points = pointMap[ point ];
  20565. if ( points !== undefined ) {
  20566. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20567. geometry.vertices[ points[ i ] ].copy( vector );
  20568. }
  20569. }
  20570. };
  20571. return function () {
  20572. geometry = this.geometry;
  20573. pointMap = this.pointMap;
  20574. var w = 1, h = 1;
  20575. // we need just camera projection matrix
  20576. // world matrix must be identity
  20577. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20578. // center / target
  20579. setPoint( "c", 0, 0, - 1 );
  20580. setPoint( "t", 0, 0, 1 );
  20581. // near
  20582. setPoint( "n1", - w, - h, - 1 );
  20583. setPoint( "n2", w, - h, - 1 );
  20584. setPoint( "n3", - w, h, - 1 );
  20585. setPoint( "n4", w, h, - 1 );
  20586. // far
  20587. setPoint( "f1", - w, - h, 1 );
  20588. setPoint( "f2", w, - h, 1 );
  20589. setPoint( "f3", - w, h, 1 );
  20590. setPoint( "f4", w, h, 1 );
  20591. // up
  20592. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  20593. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  20594. setPoint( "u3", 0, h * 2, - 1 );
  20595. // cross
  20596. setPoint( "cf1", - w, 0, 1 );
  20597. setPoint( "cf2", w, 0, 1 );
  20598. setPoint( "cf3", 0, - h, 1 );
  20599. setPoint( "cf4", 0, h, 1 );
  20600. setPoint( "cn1", - w, 0, - 1 );
  20601. setPoint( "cn2", w, 0, - 1 );
  20602. setPoint( "cn3", 0, - h, - 1 );
  20603. setPoint( "cn4", 0, h, - 1 );
  20604. geometry.verticesNeedUpdate = true;
  20605. };
  20606. }();
  20607. // File:src/extras/helpers/DirectionalLightHelper.js
  20608. /**
  20609. * @author alteredq / http://alteredqualia.com/
  20610. * @author mrdoob / http://mrdoob.com/
  20611. * @author WestLangley / http://github.com/WestLangley
  20612. */
  20613. THREE.DirectionalLightHelper = function ( light, size ) {
  20614. THREE.Object3D.call( this );
  20615. this.light = light;
  20616. this.light.updateMatrixWorld();
  20617. this.matrix = light.matrixWorld;
  20618. this.matrixAutoUpdate = false;
  20619. size = size || 1;
  20620. var geometry = new THREE.Geometry();
  20621. geometry.vertices.push(
  20622. new THREE.Vector3( - size, size, 0 ),
  20623. new THREE.Vector3( size, size, 0 ),
  20624. new THREE.Vector3( size, - size, 0 ),
  20625. new THREE.Vector3( - size, - size, 0 ),
  20626. new THREE.Vector3( - size, size, 0 )
  20627. );
  20628. var material = new THREE.LineBasicMaterial( { fog: false } );
  20629. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20630. this.lightPlane = new THREE.Line( geometry, material );
  20631. this.add( this.lightPlane );
  20632. geometry = new THREE.Geometry();
  20633. geometry.vertices.push(
  20634. new THREE.Vector3(),
  20635. new THREE.Vector3()
  20636. );
  20637. material = new THREE.LineBasicMaterial( { fog: false } );
  20638. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20639. this.targetLine = new THREE.Line( geometry, material );
  20640. this.add( this.targetLine );
  20641. this.update();
  20642. };
  20643. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20644. THREE.DirectionalLightHelper.prototype.constructor = THREE.DirectionalLightHelper;
  20645. THREE.DirectionalLightHelper.prototype.dispose = function () {
  20646. this.lightPlane.geometry.dispose();
  20647. this.lightPlane.material.dispose();
  20648. this.targetLine.geometry.dispose();
  20649. this.targetLine.material.dispose();
  20650. };
  20651. THREE.DirectionalLightHelper.prototype.update = function () {
  20652. var v1 = new THREE.Vector3();
  20653. var v2 = new THREE.Vector3();
  20654. var v3 = new THREE.Vector3();
  20655. return function () {
  20656. v1.setFromMatrixPosition( this.light.matrixWorld );
  20657. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20658. v3.subVectors( v2, v1 );
  20659. this.lightPlane.lookAt( v3 );
  20660. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20661. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  20662. this.targetLine.geometry.verticesNeedUpdate = true;
  20663. this.targetLine.material.color.copy( this.lightPlane.material.color );
  20664. };
  20665. }();
  20666. // File:src/extras/helpers/EdgesHelper.js
  20667. /**
  20668. * @author WestLangley / http://github.com/WestLangley
  20669. * @param object THREE.Mesh whose geometry will be used
  20670. * @param hex line color
  20671. * @param thresholdAngle the minimim angle (in degrees),
  20672. * between the face normals of adjacent faces,
  20673. * that is required to render an edge. A value of 10 means
  20674. * an edge is only rendered if the angle is at least 10 degrees.
  20675. */
  20676. THREE.EdgesHelper = function ( object, hex, thresholdAngle ) {
  20677. var color = ( hex !== undefined ) ? hex : 0xffffff;
  20678. THREE.Line.call( this, new THREE.EdgesGeometry( object.geometry, thresholdAngle ), new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  20679. this.matrix = object.matrixWorld;
  20680. this.matrixAutoUpdate = false;
  20681. };
  20682. THREE.EdgesHelper.prototype = Object.create( THREE.Line.prototype );
  20683. THREE.EdgesHelper.prototype.constructor = THREE.EdgesHelper;
  20684. // File:src/extras/helpers/FaceNormalsHelper.js
  20685. /**
  20686. * @author mrdoob / http://mrdoob.com/
  20687. * @author WestLangley / http://github.com/WestLangley
  20688. */
  20689. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  20690. this.object = object;
  20691. this.size = ( size !== undefined ) ? size : 1;
  20692. var color = ( hex !== undefined ) ? hex : 0xffff00;
  20693. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20694. var geometry = new THREE.Geometry();
  20695. var faces = this.object.geometry.faces;
  20696. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20697. geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() );
  20698. }
  20699. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20700. this.matrixAutoUpdate = false;
  20701. this.normalMatrix = new THREE.Matrix3();
  20702. this.update();
  20703. };
  20704. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20705. THREE.FaceNormalsHelper.prototype.constructor = THREE.FaceNormalsHelper;
  20706. THREE.FaceNormalsHelper.prototype.update = function () {
  20707. var vertices = this.geometry.vertices;
  20708. var object = this.object;
  20709. var objectVertices = object.geometry.vertices;
  20710. var objectFaces = object.geometry.faces;
  20711. var objectWorldMatrix = object.matrixWorld;
  20712. object.updateMatrixWorld( true );
  20713. this.normalMatrix.getNormalMatrix( objectWorldMatrix );
  20714. for ( var i = 0, i2 = 0, l = objectFaces.length; i < l; i ++, i2 += 2 ) {
  20715. var face = objectFaces[ i ];
  20716. vertices[ i2 ].copy( objectVertices[ face.a ] )
  20717. .add( objectVertices[ face.b ] )
  20718. .add( objectVertices[ face.c ] )
  20719. .divideScalar( 3 )
  20720. .applyMatrix4( objectWorldMatrix );
  20721. vertices[ i2 + 1 ].copy( face.normal )
  20722. .applyMatrix3( this.normalMatrix )
  20723. .normalize()
  20724. .multiplyScalar( this.size )
  20725. .add( vertices[ i2 ] );
  20726. }
  20727. this.geometry.verticesNeedUpdate = true;
  20728. return this;
  20729. };
  20730. // File:src/extras/helpers/GridHelper.js
  20731. /**
  20732. * @author mrdoob / http://mrdoob.com/
  20733. */
  20734. THREE.GridHelper = function ( size, step ) {
  20735. var geometry = new THREE.Geometry();
  20736. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20737. this.color1 = new THREE.Color( 0x444444 );
  20738. this.color2 = new THREE.Color( 0x888888 );
  20739. for ( var i = - size; i <= size; i += step ) {
  20740. geometry.vertices.push(
  20741. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  20742. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  20743. );
  20744. var color = i === 0 ? this.color1 : this.color2;
  20745. geometry.colors.push( color, color, color, color );
  20746. }
  20747. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20748. };
  20749. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  20750. THREE.GridHelper.prototype.constructor = THREE.GridHelper;
  20751. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  20752. this.color1.set( colorCenterLine );
  20753. this.color2.set( colorGrid );
  20754. this.geometry.colorsNeedUpdate = true;
  20755. }
  20756. // File:src/extras/helpers/HemisphereLightHelper.js
  20757. /**
  20758. * @author alteredq / http://alteredqualia.com/
  20759. * @author mrdoob / http://mrdoob.com/
  20760. */
  20761. THREE.HemisphereLightHelper = function ( light, sphereSize ) {
  20762. THREE.Object3D.call( this );
  20763. this.light = light;
  20764. this.light.updateMatrixWorld();
  20765. this.matrix = light.matrixWorld;
  20766. this.matrixAutoUpdate = false;
  20767. this.colors = [ new THREE.Color(), new THREE.Color() ];
  20768. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20769. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20770. for ( var i = 0, il = 8; i < il; i ++ ) {
  20771. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  20772. }
  20773. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  20774. this.lightSphere = new THREE.Mesh( geometry, material );
  20775. this.add( this.lightSphere );
  20776. this.update();
  20777. };
  20778. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20779. THREE.HemisphereLightHelper.prototype.constructor = THREE.HemisphereLightHelper;
  20780. THREE.HemisphereLightHelper.prototype.dispose = function () {
  20781. this.lightSphere.geometry.dispose();
  20782. this.lightSphere.material.dispose();
  20783. };
  20784. THREE.HemisphereLightHelper.prototype.update = function () {
  20785. var vector = new THREE.Vector3();
  20786. return function () {
  20787. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  20788. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  20789. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20790. this.lightSphere.geometry.colorsNeedUpdate = true;
  20791. }
  20792. }();
  20793. // File:src/extras/helpers/PointLightHelper.js
  20794. /**
  20795. * @author alteredq / http://alteredqualia.com/
  20796. * @author mrdoob / http://mrdoob.com/
  20797. */
  20798. THREE.PointLightHelper = function ( light, sphereSize ) {
  20799. this.light = light;
  20800. this.light.updateMatrixWorld();
  20801. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20802. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20803. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20804. THREE.Mesh.call( this, geometry, material );
  20805. this.matrix = this.light.matrixWorld;
  20806. this.matrixAutoUpdate = false;
  20807. /*
  20808. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20809. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20810. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20811. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20812. var d = light.distance;
  20813. if ( d === 0.0 ) {
  20814. this.lightDistance.visible = false;
  20815. } else {
  20816. this.lightDistance.scale.set( d, d, d );
  20817. }
  20818. this.add( this.lightDistance );
  20819. */
  20820. };
  20821. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  20822. THREE.PointLightHelper.prototype.constructor = THREE.PointLightHelper;
  20823. THREE.PointLightHelper.prototype.dispose = function () {
  20824. this.geometry.dispose();
  20825. this.material.dispose();
  20826. };
  20827. THREE.PointLightHelper.prototype.update = function () {
  20828. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20829. /*
  20830. var d = this.light.distance;
  20831. if ( d === 0.0 ) {
  20832. this.lightDistance.visible = false;
  20833. } else {
  20834. this.lightDistance.visible = true;
  20835. this.lightDistance.scale.set( d, d, d );
  20836. }
  20837. */
  20838. };
  20839. // File:src/extras/helpers/SkeletonHelper.js
  20840. /**
  20841. * @author Sean Griffin / http://twitter.com/sgrif
  20842. * @author Michael Guerrero / http://realitymeltdown.com
  20843. * @author mrdoob / http://mrdoob.com/
  20844. * @author ikerr / http://verold.com
  20845. */
  20846. THREE.SkeletonHelper = function ( object ) {
  20847. this.bones = this.getBoneList( object );
  20848. var geometry = new THREE.Geometry();
  20849. for ( var i = 0; i < this.bones.length; i ++ ) {
  20850. var bone = this.bones[ i ];
  20851. if ( bone.parent instanceof THREE.Bone ) {
  20852. geometry.vertices.push( new THREE.Vector3() );
  20853. geometry.vertices.push( new THREE.Vector3() );
  20854. geometry.colors.push( new THREE.Color( 0, 0, 1 ) );
  20855. geometry.colors.push( new THREE.Color( 0, 1, 0 ) );
  20856. }
  20857. }
  20858. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  20859. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20860. this.root = object;
  20861. this.matrix = object.matrixWorld;
  20862. this.matrixAutoUpdate = false;
  20863. this.update();
  20864. };
  20865. THREE.SkeletonHelper.prototype = Object.create( THREE.Line.prototype );
  20866. THREE.SkeletonHelper.prototype.constructor = THREE.SkeletonHelper;
  20867. THREE.SkeletonHelper.prototype.getBoneList = function( object ) {
  20868. var boneList = [];
  20869. if ( object instanceof THREE.Bone ) {
  20870. boneList.push( object );
  20871. }
  20872. for ( var i = 0; i < object.children.length; i ++ ) {
  20873. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  20874. }
  20875. return boneList;
  20876. };
  20877. THREE.SkeletonHelper.prototype.update = function () {
  20878. var geometry = this.geometry;
  20879. var matrixWorldInv = new THREE.Matrix4().getInverse( this.root.matrixWorld );
  20880. var boneMatrix = new THREE.Matrix4();
  20881. var j = 0;
  20882. for ( var i = 0; i < this.bones.length; i ++ ) {
  20883. var bone = this.bones[ i ];
  20884. if ( bone.parent instanceof THREE.Bone ) {
  20885. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  20886. geometry.vertices[ j ].setFromMatrixPosition( boneMatrix );
  20887. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  20888. geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix );
  20889. j += 2;
  20890. }
  20891. }
  20892. geometry.verticesNeedUpdate = true;
  20893. geometry.computeBoundingSphere();
  20894. };
  20895. // File:src/extras/helpers/SpotLightHelper.js
  20896. /**
  20897. * @author alteredq / http://alteredqualia.com/
  20898. * @author mrdoob / http://mrdoob.com/
  20899. * @author WestLangley / http://github.com/WestLangley
  20900. */
  20901. THREE.SpotLightHelper = function ( light ) {
  20902. THREE.Object3D.call( this );
  20903. this.light = light;
  20904. this.light.updateMatrixWorld();
  20905. this.matrix = light.matrixWorld;
  20906. this.matrixAutoUpdate = false;
  20907. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  20908. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  20909. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20910. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20911. this.cone = new THREE.Mesh( geometry, material );
  20912. this.add( this.cone );
  20913. this.update();
  20914. };
  20915. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20916. THREE.SpotLightHelper.prototype.constructor = THREE.SpotLightHelper;
  20917. THREE.SpotLightHelper.prototype.dispose = function () {
  20918. this.cone.geometry.dispose();
  20919. this.cone.material.dispose();
  20920. };
  20921. THREE.SpotLightHelper.prototype.update = function () {
  20922. var vector = new THREE.Vector3();
  20923. var vector2 = new THREE.Vector3();
  20924. return function () {
  20925. var coneLength = this.light.distance ? this.light.distance : 10000;
  20926. var coneWidth = coneLength * Math.tan( this.light.angle );
  20927. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20928. vector.setFromMatrixPosition( this.light.matrixWorld );
  20929. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  20930. this.cone.lookAt( vector2.sub( vector ) );
  20931. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20932. };
  20933. }();
  20934. // File:src/extras/helpers/VertexNormalsHelper.js
  20935. /**
  20936. * @author mrdoob / http://mrdoob.com/
  20937. * @author WestLangley / http://github.com/WestLangley
  20938. */
  20939. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  20940. this.object = object;
  20941. this.size = ( size !== undefined ) ? size : 1;
  20942. var color = ( hex !== undefined ) ? hex : 0xff0000;
  20943. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20944. var geometry = new THREE.Geometry();
  20945. var faces = object.geometry.faces;
  20946. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20947. var face = faces[ i ];
  20948. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20949. geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() );
  20950. }
  20951. }
  20952. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20953. this.matrixAutoUpdate = false;
  20954. this.normalMatrix = new THREE.Matrix3();
  20955. this.update();
  20956. };
  20957. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20958. THREE.VertexNormalsHelper.prototype.constructor = THREE.VertexNormalsHelper;
  20959. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  20960. var v1 = new THREE.Vector3();
  20961. return function( object ) {
  20962. var keys = [ 'a', 'b', 'c', 'd' ];
  20963. this.object.updateMatrixWorld( true );
  20964. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20965. var vertices = this.geometry.vertices;
  20966. var verts = this.object.geometry.vertices;
  20967. var faces = this.object.geometry.faces;
  20968. var worldMatrix = this.object.matrixWorld;
  20969. var idx = 0;
  20970. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20971. var face = faces[ i ];
  20972. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20973. var vertexId = face[ keys[ j ] ];
  20974. var vertex = verts[ vertexId ];
  20975. var normal = face.vertexNormals[ j ];
  20976. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20977. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20978. v1.add( vertices[ idx ] );
  20979. idx = idx + 1;
  20980. vertices[ idx ].copy( v1 );
  20981. idx = idx + 1;
  20982. }
  20983. }
  20984. this.geometry.verticesNeedUpdate = true;
  20985. return this;
  20986. }
  20987. }());
  20988. // File:src/extras/helpers/VertexTangentsHelper.js
  20989. /**
  20990. * @author mrdoob / http://mrdoob.com/
  20991. * @author WestLangley / http://github.com/WestLangley
  20992. */
  20993. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  20994. this.object = object;
  20995. this.size = ( size !== undefined ) ? size : 1;
  20996. var color = ( hex !== undefined ) ? hex : 0x0000ff;
  20997. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20998. var geometry = new THREE.Geometry();
  20999. var faces = object.geometry.faces;
  21000. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21001. var face = faces[ i ];
  21002. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21003. geometry.vertices.push( new THREE.Vector3() );
  21004. geometry.vertices.push( new THREE.Vector3() );
  21005. }
  21006. }
  21007. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21008. this.matrixAutoUpdate = false;
  21009. this.update();
  21010. };
  21011. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  21012. THREE.VertexTangentsHelper.prototype.constructor = THREE.VertexTangentsHelper;
  21013. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  21014. var v1 = new THREE.Vector3();
  21015. return function( object ) {
  21016. var keys = [ 'a', 'b', 'c', 'd' ];
  21017. this.object.updateMatrixWorld( true );
  21018. var vertices = this.geometry.vertices;
  21019. var verts = this.object.geometry.vertices;
  21020. var faces = this.object.geometry.faces;
  21021. var worldMatrix = this.object.matrixWorld;
  21022. var idx = 0;
  21023. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21024. var face = faces[ i ];
  21025. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21026. var vertexId = face[ keys[ j ] ];
  21027. var vertex = verts[ vertexId ];
  21028. var tangent = face.vertexTangents[ j ];
  21029. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21030. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  21031. v1.add( vertices[ idx ] );
  21032. idx = idx + 1;
  21033. vertices[ idx ].copy( v1 );
  21034. idx = idx + 1;
  21035. }
  21036. }
  21037. this.geometry.verticesNeedUpdate = true;
  21038. return this;
  21039. }
  21040. }());
  21041. // File:src/extras/helpers/WireframeHelper.js
  21042. /**
  21043. * @author mrdoob / http://mrdoob.com/
  21044. */
  21045. THREE.WireframeHelper = function ( object, hex ) {
  21046. var color = ( hex !== undefined ) ? hex : 0xffffff;
  21047. THREE.Line.call( this, new THREE.WireframeGeometry( object.geometry ), new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  21048. this.matrix = object.matrixWorld;
  21049. this.matrixAutoUpdate = false;
  21050. };
  21051. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  21052. THREE.WireframeHelper.prototype.constructor = THREE.WireframeHelper;
  21053. // File:src/extras/objects/ImmediateRenderObject.js
  21054. /**
  21055. * @author alteredq / http://alteredqualia.com/
  21056. */
  21057. THREE.ImmediateRenderObject = function () {
  21058. THREE.Object3D.call( this );
  21059. this.render = function ( renderCallback ) {};
  21060. };
  21061. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  21062. THREE.ImmediateRenderObject.prototype.constructor = THREE.ImmediateRenderObject;
  21063. // File:src/extras/objects/MorphBlendMesh.js
  21064. /**
  21065. * @author alteredq / http://alteredqualia.com/
  21066. */
  21067. THREE.MorphBlendMesh = function( geometry, material ) {
  21068. THREE.Mesh.call( this, geometry, material );
  21069. this.animationsMap = {};
  21070. this.animationsList = [];
  21071. // prepare default animation
  21072. // (all frames played together in 1 second)
  21073. var numFrames = this.geometry.morphTargets.length;
  21074. var name = "__default";
  21075. var startFrame = 0;
  21076. var endFrame = numFrames - 1;
  21077. var fps = numFrames / 1;
  21078. this.createAnimation( name, startFrame, endFrame, fps );
  21079. this.setAnimationWeight( name, 1 );
  21080. };
  21081. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  21082. THREE.MorphBlendMesh.prototype.constructor = THREE.MorphBlendMesh;
  21083. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  21084. var animation = {
  21085. startFrame: start,
  21086. endFrame: end,
  21087. length: end - start + 1,
  21088. fps: fps,
  21089. duration: ( end - start ) / fps,
  21090. lastFrame: 0,
  21091. currentFrame: 0,
  21092. active: false,
  21093. time: 0,
  21094. direction: 1,
  21095. weight: 1,
  21096. directionBackwards: false,
  21097. mirroredLoop: false
  21098. };
  21099. this.animationsMap[ name ] = animation;
  21100. this.animationsList.push( animation );
  21101. };
  21102. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21103. var pattern = /([a-z]+)_?(\d+)/;
  21104. var firstAnimation, frameRanges = {};
  21105. var geometry = this.geometry;
  21106. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21107. var morph = geometry.morphTargets[ i ];
  21108. var chunks = morph.name.match( pattern );
  21109. if ( chunks && chunks.length > 1 ) {
  21110. var name = chunks[ 1 ];
  21111. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  21112. var range = frameRanges[ name ];
  21113. if ( i < range.start ) range.start = i;
  21114. if ( i > range.end ) range.end = i;
  21115. if ( ! firstAnimation ) firstAnimation = name;
  21116. }
  21117. }
  21118. for ( var name in frameRanges ) {
  21119. var range = frameRanges[ name ];
  21120. this.createAnimation( name, range.start, range.end, fps );
  21121. }
  21122. this.firstAnimation = firstAnimation;
  21123. };
  21124. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  21125. var animation = this.animationsMap[ name ];
  21126. if ( animation ) {
  21127. animation.direction = 1;
  21128. animation.directionBackwards = false;
  21129. }
  21130. };
  21131. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  21132. var animation = this.animationsMap[ name ];
  21133. if ( animation ) {
  21134. animation.direction = - 1;
  21135. animation.directionBackwards = true;
  21136. }
  21137. };
  21138. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  21139. var animation = this.animationsMap[ name ];
  21140. if ( animation ) {
  21141. animation.fps = fps;
  21142. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21143. }
  21144. };
  21145. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21146. var animation = this.animationsMap[ name ];
  21147. if ( animation ) {
  21148. animation.duration = duration;
  21149. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21150. }
  21151. };
  21152. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21153. var animation = this.animationsMap[ name ];
  21154. if ( animation ) {
  21155. animation.weight = weight;
  21156. }
  21157. };
  21158. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21159. var animation = this.animationsMap[ name ];
  21160. if ( animation ) {
  21161. animation.time = time;
  21162. }
  21163. };
  21164. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21165. var time = 0;
  21166. var animation = this.animationsMap[ name ];
  21167. if ( animation ) {
  21168. time = animation.time;
  21169. }
  21170. return time;
  21171. };
  21172. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21173. var duration = - 1;
  21174. var animation = this.animationsMap[ name ];
  21175. if ( animation ) {
  21176. duration = animation.duration;
  21177. }
  21178. return duration;
  21179. };
  21180. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21181. var animation = this.animationsMap[ name ];
  21182. if ( animation ) {
  21183. animation.time = 0;
  21184. animation.active = true;
  21185. } else {
  21186. THREE.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  21187. }
  21188. };
  21189. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21190. var animation = this.animationsMap[ name ];
  21191. if ( animation ) {
  21192. animation.active = false;
  21193. }
  21194. };
  21195. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  21196. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21197. var animation = this.animationsList[ i ];
  21198. if ( ! animation.active ) continue;
  21199. var frameTime = animation.duration / animation.length;
  21200. animation.time += animation.direction * delta;
  21201. if ( animation.mirroredLoop ) {
  21202. if ( animation.time > animation.duration || animation.time < 0 ) {
  21203. animation.direction *= - 1;
  21204. if ( animation.time > animation.duration ) {
  21205. animation.time = animation.duration;
  21206. animation.directionBackwards = true;
  21207. }
  21208. if ( animation.time < 0 ) {
  21209. animation.time = 0;
  21210. animation.directionBackwards = false;
  21211. }
  21212. }
  21213. } else {
  21214. animation.time = animation.time % animation.duration;
  21215. if ( animation.time < 0 ) animation.time += animation.duration;
  21216. }
  21217. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21218. var weight = animation.weight;
  21219. if ( keyframe !== animation.currentFrame ) {
  21220. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21221. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21222. this.morphTargetInfluences[ keyframe ] = 0;
  21223. animation.lastFrame = animation.currentFrame;
  21224. animation.currentFrame = keyframe;
  21225. }
  21226. var mix = ( animation.time % frameTime ) / frameTime;
  21227. if ( animation.directionBackwards ) mix = 1 - mix;
  21228. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21229. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21230. }
  21231. };