three.js 785 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890
  1. // File:src/Three.js
  2. /**
  3. * @author mrdoob / http://mrdoob.com/
  4. */
  5. var THREE = { REVISION: '71dev' };
  6. // browserify support
  7. if ( typeof module === 'object' ) {
  8. module.exports = THREE;
  9. }
  10. // polyfills
  11. if ( Math.sign === undefined ) {
  12. Math.sign = function ( x ) {
  13. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : 0;
  14. };
  15. }
  16. // set the default log handlers
  17. THREE.log = function() { console.log.apply( console, arguments ); }
  18. THREE.warn = function() { console.warn.apply( console, arguments ); }
  19. THREE.error = function() { console.error.apply( console, arguments ); }
  20. // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.button
  21. THREE.MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  22. // GL STATE CONSTANTS
  23. THREE.CullFaceNone = 0;
  24. THREE.CullFaceBack = 1;
  25. THREE.CullFaceFront = 2;
  26. THREE.CullFaceFrontBack = 3;
  27. THREE.FrontFaceDirectionCW = 0;
  28. THREE.FrontFaceDirectionCCW = 1;
  29. // SHADOWING TYPES
  30. THREE.BasicShadowMap = 0;
  31. THREE.PCFShadowMap = 1;
  32. THREE.PCFSoftShadowMap = 2;
  33. // MATERIAL CONSTANTS
  34. // side
  35. THREE.FrontSide = 0;
  36. THREE.BackSide = 1;
  37. THREE.DoubleSide = 2;
  38. // shading
  39. THREE.NoShading = 0;
  40. THREE.FlatShading = 1;
  41. THREE.SmoothShading = 2;
  42. // colors
  43. THREE.NoColors = 0;
  44. THREE.FaceColors = 1;
  45. THREE.VertexColors = 2;
  46. // blending modes
  47. THREE.NoBlending = 0;
  48. THREE.NormalBlending = 1;
  49. THREE.AdditiveBlending = 2;
  50. THREE.SubtractiveBlending = 3;
  51. THREE.MultiplyBlending = 4;
  52. THREE.CustomBlending = 5;
  53. // custom blending equations
  54. // (numbers start from 100 not to clash with other
  55. // mappings to OpenGL constants defined in Texture.js)
  56. THREE.AddEquation = 100;
  57. THREE.SubtractEquation = 101;
  58. THREE.ReverseSubtractEquation = 102;
  59. THREE.MinEquation = 103;
  60. THREE.MaxEquation = 104;
  61. // custom blending destination factors
  62. THREE.ZeroFactor = 200;
  63. THREE.OneFactor = 201;
  64. THREE.SrcColorFactor = 202;
  65. THREE.OneMinusSrcColorFactor = 203;
  66. THREE.SrcAlphaFactor = 204;
  67. THREE.OneMinusSrcAlphaFactor = 205;
  68. THREE.DstAlphaFactor = 206;
  69. THREE.OneMinusDstAlphaFactor = 207;
  70. // custom blending source factors
  71. //THREE.ZeroFactor = 200;
  72. //THREE.OneFactor = 201;
  73. //THREE.SrcAlphaFactor = 204;
  74. //THREE.OneMinusSrcAlphaFactor = 205;
  75. //THREE.DstAlphaFactor = 206;
  76. //THREE.OneMinusDstAlphaFactor = 207;
  77. THREE.DstColorFactor = 208;
  78. THREE.OneMinusDstColorFactor = 209;
  79. THREE.SrcAlphaSaturateFactor = 210;
  80. // TEXTURE CONSTANTS
  81. THREE.MultiplyOperation = 0;
  82. THREE.MixOperation = 1;
  83. THREE.AddOperation = 2;
  84. // Mapping modes
  85. THREE.UVMapping = 300;
  86. THREE.CubeReflectionMapping = 301;
  87. THREE.CubeRefractionMapping = 302;
  88. THREE.EquirectangularReflectionMapping = 303;
  89. THREE.EquirectangularRefractionMapping = 304;
  90. THREE.SphericalReflectionMapping = 305;
  91. // Wrapping modes
  92. THREE.RepeatWrapping = 1000;
  93. THREE.ClampToEdgeWrapping = 1001;
  94. THREE.MirroredRepeatWrapping = 1002;
  95. // Filters
  96. THREE.NearestFilter = 1003;
  97. THREE.NearestMipMapNearestFilter = 1004;
  98. THREE.NearestMipMapLinearFilter = 1005;
  99. THREE.LinearFilter = 1006;
  100. THREE.LinearMipMapNearestFilter = 1007;
  101. THREE.LinearMipMapLinearFilter = 1008;
  102. // Data types
  103. THREE.UnsignedByteType = 1009;
  104. THREE.ByteType = 1010;
  105. THREE.ShortType = 1011;
  106. THREE.UnsignedShortType = 1012;
  107. THREE.IntType = 1013;
  108. THREE.UnsignedIntType = 1014;
  109. THREE.FloatType = 1015;
  110. THREE.HalfFloatType = 1025;
  111. // Pixel types
  112. //THREE.UnsignedByteType = 1009;
  113. THREE.UnsignedShort4444Type = 1016;
  114. THREE.UnsignedShort5551Type = 1017;
  115. THREE.UnsignedShort565Type = 1018;
  116. // Pixel formats
  117. THREE.AlphaFormat = 1019;
  118. THREE.RGBFormat = 1020;
  119. THREE.RGBAFormat = 1021;
  120. THREE.LuminanceFormat = 1022;
  121. THREE.LuminanceAlphaFormat = 1023;
  122. // THREE.RGBEFormat handled as THREE.RGBAFormat in shaders
  123. THREE.RGBEFormat = THREE.RGBAFormat; //1024;
  124. // DDS / ST3C Compressed texture formats
  125. THREE.RGB_S3TC_DXT1_Format = 2001;
  126. THREE.RGBA_S3TC_DXT1_Format = 2002;
  127. THREE.RGBA_S3TC_DXT3_Format = 2003;
  128. THREE.RGBA_S3TC_DXT5_Format = 2004;
  129. // PVRTC compressed texture formats
  130. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  131. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  132. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  133. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  134. // DEPRECATED
  135. THREE.Projector = function () {
  136. THREE.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  137. this.projectVector = function ( vector, camera ) {
  138. THREE.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  139. vector.project( camera );
  140. };
  141. this.unprojectVector = function ( vector, camera ) {
  142. THREE.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  143. vector.unproject( camera );
  144. };
  145. this.pickingRay = function ( vector, camera ) {
  146. THREE.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  147. };
  148. };
  149. THREE.CanvasRenderer = function () {
  150. THREE.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  151. this.domElement = document.createElement( 'canvas' );
  152. this.clear = function () {};
  153. this.render = function () {};
  154. this.setClearColor = function () {};
  155. this.setSize = function () {};
  156. };
  157. // File:src/math/Color.js
  158. /**
  159. * @author mrdoob / http://mrdoob.com/
  160. */
  161. THREE.Color = function ( color ) {
  162. if ( arguments.length === 3 ) {
  163. return this.setRGB( arguments[ 0 ], arguments[ 1 ], arguments[ 2 ] );
  164. }
  165. return this.set( color )
  166. };
  167. THREE.Color.prototype = {
  168. constructor: THREE.Color,
  169. r: 1, g: 1, b: 1,
  170. set: function ( value ) {
  171. if ( value instanceof THREE.Color ) {
  172. this.copy( value );
  173. } else if ( typeof value === 'number' ) {
  174. this.setHex( value );
  175. } else if ( typeof value === 'string' ) {
  176. this.setStyle( value );
  177. }
  178. return this;
  179. },
  180. setHex: function ( hex ) {
  181. hex = Math.floor( hex );
  182. this.r = ( hex >> 16 & 255 ) / 255;
  183. this.g = ( hex >> 8 & 255 ) / 255;
  184. this.b = ( hex & 255 ) / 255;
  185. return this;
  186. },
  187. setRGB: function ( r, g, b ) {
  188. this.r = r;
  189. this.g = g;
  190. this.b = b;
  191. return this;
  192. },
  193. setHSL: function ( h, s, l ) {
  194. // h,s,l ranges are in 0.0 - 1.0
  195. if ( s === 0 ) {
  196. this.r = this.g = this.b = l;
  197. } else {
  198. var hue2rgb = function ( p, q, t ) {
  199. if ( t < 0 ) t += 1;
  200. if ( t > 1 ) t -= 1;
  201. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  202. if ( t < 1 / 2 ) return q;
  203. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  204. return p;
  205. };
  206. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  207. var q = ( 2 * l ) - p;
  208. this.r = hue2rgb( q, p, h + 1 / 3 );
  209. this.g = hue2rgb( q, p, h );
  210. this.b = hue2rgb( q, p, h - 1 / 3 );
  211. }
  212. return this;
  213. },
  214. setStyle: function ( style ) {
  215. // rgb(255,0,0)
  216. if ( /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.test( style ) ) {
  217. var color = /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.exec( style );
  218. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  219. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  220. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  221. return this;
  222. }
  223. // rgb(100%,0%,0%)
  224. if ( /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.test( style ) ) {
  225. var color = /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.exec( style );
  226. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  227. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  228. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  229. return this;
  230. }
  231. // #ff0000
  232. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  233. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  234. this.setHex( parseInt( color[ 1 ], 16 ) );
  235. return this;
  236. }
  237. // #f00
  238. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  239. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  240. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  241. return this;
  242. }
  243. // red
  244. if ( /^(\w+)$/i.test( style ) ) {
  245. this.setHex( THREE.ColorKeywords[ style ] );
  246. return this;
  247. }
  248. },
  249. copy: function ( color ) {
  250. this.r = color.r;
  251. this.g = color.g;
  252. this.b = color.b;
  253. return this;
  254. },
  255. copyGammaToLinear: function ( color, gammaFactor ) {
  256. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  257. this.r = Math.pow( color.r, gammaFactor );
  258. this.g = Math.pow( color.g, gammaFactor );
  259. this.b = Math.pow( color.b, gammaFactor );
  260. return this;
  261. },
  262. copyLinearToGamma: function ( color, gammaFactor ) {
  263. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  264. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  265. this.r = Math.pow( color.r, safeInverse );
  266. this.g = Math.pow( color.g, safeInverse );
  267. this.b = Math.pow( color.b, safeInverse );
  268. return this;
  269. },
  270. convertGammaToLinear: function () {
  271. var r = this.r, g = this.g, b = this.b;
  272. this.r = r * r;
  273. this.g = g * g;
  274. this.b = b * b;
  275. return this;
  276. },
  277. convertLinearToGamma: function () {
  278. this.r = Math.sqrt( this.r );
  279. this.g = Math.sqrt( this.g );
  280. this.b = Math.sqrt( this.b );
  281. return this;
  282. },
  283. getHex: function () {
  284. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  285. },
  286. getHexString: function () {
  287. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  288. },
  289. getHSL: function ( optionalTarget ) {
  290. // h,s,l ranges are in 0.0 - 1.0
  291. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  292. var r = this.r, g = this.g, b = this.b;
  293. var max = Math.max( r, g, b );
  294. var min = Math.min( r, g, b );
  295. var hue, saturation;
  296. var lightness = ( min + max ) / 2.0;
  297. if ( min === max ) {
  298. hue = 0;
  299. saturation = 0;
  300. } else {
  301. var delta = max - min;
  302. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  303. switch ( max ) {
  304. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  305. case g: hue = ( b - r ) / delta + 2; break;
  306. case b: hue = ( r - g ) / delta + 4; break;
  307. }
  308. hue /= 6;
  309. }
  310. hsl.h = hue;
  311. hsl.s = saturation;
  312. hsl.l = lightness;
  313. return hsl;
  314. },
  315. getStyle: function () {
  316. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  317. },
  318. offsetHSL: function ( h, s, l ) {
  319. var hsl = this.getHSL();
  320. hsl.h += h; hsl.s += s; hsl.l += l;
  321. this.setHSL( hsl.h, hsl.s, hsl.l );
  322. return this;
  323. },
  324. add: function ( color ) {
  325. this.r += color.r;
  326. this.g += color.g;
  327. this.b += color.b;
  328. return this;
  329. },
  330. addColors: function ( color1, color2 ) {
  331. this.r = color1.r + color2.r;
  332. this.g = color1.g + color2.g;
  333. this.b = color1.b + color2.b;
  334. return this;
  335. },
  336. addScalar: function ( s ) {
  337. this.r += s;
  338. this.g += s;
  339. this.b += s;
  340. return this;
  341. },
  342. multiply: function ( color ) {
  343. this.r *= color.r;
  344. this.g *= color.g;
  345. this.b *= color.b;
  346. return this;
  347. },
  348. multiplyScalar: function ( s ) {
  349. this.r *= s;
  350. this.g *= s;
  351. this.b *= s;
  352. return this;
  353. },
  354. lerp: function ( color, alpha ) {
  355. this.r += ( color.r - this.r ) * alpha;
  356. this.g += ( color.g - this.g ) * alpha;
  357. this.b += ( color.b - this.b ) * alpha;
  358. return this;
  359. },
  360. equals: function ( c ) {
  361. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  362. },
  363. fromArray: function ( array ) {
  364. this.r = array[ 0 ];
  365. this.g = array[ 1 ];
  366. this.b = array[ 2 ];
  367. return this;
  368. },
  369. toArray: function ( array, offset ) {
  370. if ( array === undefined ) array = [];
  371. if ( offset === undefined ) offset = 0;
  372. array[ offset ] = this.r;
  373. array[ offset + 1 ] = this.g;
  374. array[ offset + 2 ] = this.b;
  375. return array;
  376. },
  377. clone: function () {
  378. return new THREE.Color().setRGB( this.r, this.g, this.b );
  379. }
  380. };
  381. THREE.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  382. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  383. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  384. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  385. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  386. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  387. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  388. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  389. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  390. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  391. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  392. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  393. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  394. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  395. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  396. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  397. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  398. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  399. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  400. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  401. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  402. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  403. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  404. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  405. // File:src/math/Quaternion.js
  406. /**
  407. * @author mikael emtinger / http://gomo.se/
  408. * @author alteredq / http://alteredqualia.com/
  409. * @author WestLangley / http://github.com/WestLangley
  410. * @author bhouston / http://exocortex.com
  411. */
  412. THREE.Quaternion = function ( x, y, z, w ) {
  413. this._x = x || 0;
  414. this._y = y || 0;
  415. this._z = z || 0;
  416. this._w = ( w !== undefined ) ? w : 1;
  417. };
  418. THREE.Quaternion.prototype = {
  419. constructor: THREE.Quaternion,
  420. _x: 0,_y: 0, _z: 0, _w: 0,
  421. get x () {
  422. return this._x;
  423. },
  424. set x ( value ) {
  425. this._x = value;
  426. this.onChangeCallback();
  427. },
  428. get y () {
  429. return this._y;
  430. },
  431. set y ( value ) {
  432. this._y = value;
  433. this.onChangeCallback();
  434. },
  435. get z () {
  436. return this._z;
  437. },
  438. set z ( value ) {
  439. this._z = value;
  440. this.onChangeCallback();
  441. },
  442. get w () {
  443. return this._w;
  444. },
  445. set w ( value ) {
  446. this._w = value;
  447. this.onChangeCallback();
  448. },
  449. set: function ( x, y, z, w ) {
  450. this._x = x;
  451. this._y = y;
  452. this._z = z;
  453. this._w = w;
  454. this.onChangeCallback();
  455. return this;
  456. },
  457. copy: function ( quaternion ) {
  458. this._x = quaternion.x;
  459. this._y = quaternion.y;
  460. this._z = quaternion.z;
  461. this._w = quaternion.w;
  462. this.onChangeCallback();
  463. return this;
  464. },
  465. setFromEuler: function ( euler, update ) {
  466. if ( euler instanceof THREE.Euler === false ) {
  467. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  468. }
  469. // http://www.mathworks.com/matlabcentral/fileexchange/
  470. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  471. // content/SpinCalc.m
  472. var c1 = Math.cos( euler._x / 2 );
  473. var c2 = Math.cos( euler._y / 2 );
  474. var c3 = Math.cos( euler._z / 2 );
  475. var s1 = Math.sin( euler._x / 2 );
  476. var s2 = Math.sin( euler._y / 2 );
  477. var s3 = Math.sin( euler._z / 2 );
  478. if ( euler.order === 'XYZ' ) {
  479. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  480. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  481. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  482. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  483. } else if ( euler.order === 'YXZ' ) {
  484. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  485. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  486. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  487. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  488. } else if ( euler.order === 'ZXY' ) {
  489. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  490. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  491. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  492. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  493. } else if ( euler.order === 'ZYX' ) {
  494. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  495. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  496. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  497. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  498. } else if ( euler.order === 'YZX' ) {
  499. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  500. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  501. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  502. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  503. } else if ( euler.order === 'XZY' ) {
  504. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  505. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  506. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  507. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  508. }
  509. if ( update !== false ) this.onChangeCallback();
  510. return this;
  511. },
  512. setFromAxisAngle: function ( axis, angle ) {
  513. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  514. // assumes axis is normalized
  515. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  516. this._x = axis.x * s;
  517. this._y = axis.y * s;
  518. this._z = axis.z * s;
  519. this._w = Math.cos( halfAngle );
  520. this.onChangeCallback();
  521. return this;
  522. },
  523. setFromRotationMatrix: function ( m ) {
  524. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  525. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  526. var te = m.elements,
  527. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  528. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  529. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  530. trace = m11 + m22 + m33,
  531. s;
  532. if ( trace > 0 ) {
  533. s = 0.5 / Math.sqrt( trace + 1.0 );
  534. this._w = 0.25 / s;
  535. this._x = ( m32 - m23 ) * s;
  536. this._y = ( m13 - m31 ) * s;
  537. this._z = ( m21 - m12 ) * s;
  538. } else if ( m11 > m22 && m11 > m33 ) {
  539. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  540. this._w = ( m32 - m23 ) / s;
  541. this._x = 0.25 * s;
  542. this._y = ( m12 + m21 ) / s;
  543. this._z = ( m13 + m31 ) / s;
  544. } else if ( m22 > m33 ) {
  545. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  546. this._w = ( m13 - m31 ) / s;
  547. this._x = ( m12 + m21 ) / s;
  548. this._y = 0.25 * s;
  549. this._z = ( m23 + m32 ) / s;
  550. } else {
  551. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  552. this._w = ( m21 - m12 ) / s;
  553. this._x = ( m13 + m31 ) / s;
  554. this._y = ( m23 + m32 ) / s;
  555. this._z = 0.25 * s;
  556. }
  557. this.onChangeCallback();
  558. return this;
  559. },
  560. setFromUnitVectors: function () {
  561. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  562. // assumes direction vectors vFrom and vTo are normalized
  563. var v1, r;
  564. var EPS = 0.000001;
  565. return function ( vFrom, vTo ) {
  566. if ( v1 === undefined ) v1 = new THREE.Vector3();
  567. r = vFrom.dot( vTo ) + 1;
  568. if ( r < EPS ) {
  569. r = 0;
  570. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  571. v1.set( - vFrom.y, vFrom.x, 0 );
  572. } else {
  573. v1.set( 0, - vFrom.z, vFrom.y );
  574. }
  575. } else {
  576. v1.crossVectors( vFrom, vTo );
  577. }
  578. this._x = v1.x;
  579. this._y = v1.y;
  580. this._z = v1.z;
  581. this._w = r;
  582. this.normalize();
  583. return this;
  584. }
  585. }(),
  586. inverse: function () {
  587. this.conjugate().normalize();
  588. return this;
  589. },
  590. conjugate: function () {
  591. this._x *= - 1;
  592. this._y *= - 1;
  593. this._z *= - 1;
  594. this.onChangeCallback();
  595. return this;
  596. },
  597. dot: function ( v ) {
  598. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  599. },
  600. lengthSq: function () {
  601. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  602. },
  603. length: function () {
  604. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  605. },
  606. normalize: function () {
  607. var l = this.length();
  608. if ( l === 0 ) {
  609. this._x = 0;
  610. this._y = 0;
  611. this._z = 0;
  612. this._w = 1;
  613. } else {
  614. l = 1 / l;
  615. this._x = this._x * l;
  616. this._y = this._y * l;
  617. this._z = this._z * l;
  618. this._w = this._w * l;
  619. }
  620. this.onChangeCallback();
  621. return this;
  622. },
  623. multiply: function ( q, p ) {
  624. if ( p !== undefined ) {
  625. THREE.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  626. return this.multiplyQuaternions( q, p );
  627. }
  628. return this.multiplyQuaternions( this, q );
  629. },
  630. multiplyQuaternions: function ( a, b ) {
  631. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  632. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  633. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  634. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  635. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  636. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  637. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  638. this.onChangeCallback();
  639. return this;
  640. },
  641. multiplyVector3: function ( vector ) {
  642. THREE.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  643. return vector.applyQuaternion( this );
  644. },
  645. slerp: function ( qb, t ) {
  646. if ( t === 0 ) return this;
  647. if ( t === 1 ) return this.copy( qb );
  648. var x = this._x, y = this._y, z = this._z, w = this._w;
  649. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  650. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  651. if ( cosHalfTheta < 0 ) {
  652. this._w = - qb._w;
  653. this._x = - qb._x;
  654. this._y = - qb._y;
  655. this._z = - qb._z;
  656. cosHalfTheta = - cosHalfTheta;
  657. } else {
  658. this.copy( qb );
  659. }
  660. if ( cosHalfTheta >= 1.0 ) {
  661. this._w = w;
  662. this._x = x;
  663. this._y = y;
  664. this._z = z;
  665. return this;
  666. }
  667. var halfTheta = Math.acos( cosHalfTheta );
  668. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  669. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  670. this._w = 0.5 * ( w + this._w );
  671. this._x = 0.5 * ( x + this._x );
  672. this._y = 0.5 * ( y + this._y );
  673. this._z = 0.5 * ( z + this._z );
  674. return this;
  675. }
  676. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  677. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  678. this._w = ( w * ratioA + this._w * ratioB );
  679. this._x = ( x * ratioA + this._x * ratioB );
  680. this._y = ( y * ratioA + this._y * ratioB );
  681. this._z = ( z * ratioA + this._z * ratioB );
  682. this.onChangeCallback();
  683. return this;
  684. },
  685. equals: function ( quaternion ) {
  686. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  687. },
  688. fromArray: function ( array, offset ) {
  689. if ( offset === undefined ) offset = 0;
  690. this._x = array[ offset ];
  691. this._y = array[ offset + 1 ];
  692. this._z = array[ offset + 2 ];
  693. this._w = array[ offset + 3 ];
  694. this.onChangeCallback();
  695. return this;
  696. },
  697. toArray: function ( array, offset ) {
  698. if ( array === undefined ) array = [];
  699. if ( offset === undefined ) offset = 0;
  700. array[ offset ] = this._x;
  701. array[ offset + 1 ] = this._y;
  702. array[ offset + 2 ] = this._z;
  703. array[ offset + 3 ] = this._w;
  704. return array;
  705. },
  706. onChange: function ( callback ) {
  707. this.onChangeCallback = callback;
  708. return this;
  709. },
  710. onChangeCallback: function () {},
  711. clone: function () {
  712. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  713. }
  714. };
  715. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  716. return qm.copy( qa ).slerp( qb, t );
  717. }
  718. // File:src/math/Vector2.js
  719. /**
  720. * @author mrdoob / http://mrdoob.com/
  721. * @author philogb / http://blog.thejit.org/
  722. * @author egraether / http://egraether.com/
  723. * @author zz85 / http://www.lab4games.net/zz85/blog
  724. */
  725. THREE.Vector2 = function ( x, y ) {
  726. this.x = x || 0;
  727. this.y = y || 0;
  728. };
  729. THREE.Vector2.prototype = {
  730. constructor: THREE.Vector2,
  731. set: function ( x, y ) {
  732. this.x = x;
  733. this.y = y;
  734. return this;
  735. },
  736. setX: function ( x ) {
  737. this.x = x;
  738. return this;
  739. },
  740. setY: function ( y ) {
  741. this.y = y;
  742. return this;
  743. },
  744. setComponent: function ( index, value ) {
  745. switch ( index ) {
  746. case 0: this.x = value; break;
  747. case 1: this.y = value; break;
  748. default: throw new Error( 'index is out of range: ' + index );
  749. }
  750. },
  751. getComponent: function ( index ) {
  752. switch ( index ) {
  753. case 0: return this.x;
  754. case 1: return this.y;
  755. default: throw new Error( 'index is out of range: ' + index );
  756. }
  757. },
  758. copy: function ( v ) {
  759. this.x = v.x;
  760. this.y = v.y;
  761. return this;
  762. },
  763. add: function ( v, w ) {
  764. if ( w !== undefined ) {
  765. THREE.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  766. return this.addVectors( v, w );
  767. }
  768. this.x += v.x;
  769. this.y += v.y;
  770. return this;
  771. },
  772. addVectors: function ( a, b ) {
  773. this.x = a.x + b.x;
  774. this.y = a.y + b.y;
  775. return this;
  776. },
  777. addScalar: function ( s ) {
  778. this.x += s;
  779. this.y += s;
  780. return this;
  781. },
  782. sub: function ( v, w ) {
  783. if ( w !== undefined ) {
  784. THREE.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  785. return this.subVectors( v, w );
  786. }
  787. this.x -= v.x;
  788. this.y -= v.y;
  789. return this;
  790. },
  791. subVectors: function ( a, b ) {
  792. this.x = a.x - b.x;
  793. this.y = a.y - b.y;
  794. return this;
  795. },
  796. multiply: function ( v ) {
  797. this.x *= v.x;
  798. this.y *= v.y;
  799. return this;
  800. },
  801. multiplyScalar: function ( s ) {
  802. this.x *= s;
  803. this.y *= s;
  804. return this;
  805. },
  806. divide: function ( v ) {
  807. this.x /= v.x;
  808. this.y /= v.y;
  809. return this;
  810. },
  811. divideScalar: function ( scalar ) {
  812. if ( scalar !== 0 ) {
  813. var invScalar = 1 / scalar;
  814. this.x *= invScalar;
  815. this.y *= invScalar;
  816. } else {
  817. this.x = 0;
  818. this.y = 0;
  819. }
  820. return this;
  821. },
  822. min: function ( v ) {
  823. if ( this.x > v.x ) {
  824. this.x = v.x;
  825. }
  826. if ( this.y > v.y ) {
  827. this.y = v.y;
  828. }
  829. return this;
  830. },
  831. max: function ( v ) {
  832. if ( this.x < v.x ) {
  833. this.x = v.x;
  834. }
  835. if ( this.y < v.y ) {
  836. this.y = v.y;
  837. }
  838. return this;
  839. },
  840. clamp: function ( min, max ) {
  841. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  842. if ( this.x < min.x ) {
  843. this.x = min.x;
  844. } else if ( this.x > max.x ) {
  845. this.x = max.x;
  846. }
  847. if ( this.y < min.y ) {
  848. this.y = min.y;
  849. } else if ( this.y > max.y ) {
  850. this.y = max.y;
  851. }
  852. return this;
  853. },
  854. clampScalar: ( function () {
  855. var min, max;
  856. return function ( minVal, maxVal ) {
  857. if ( min === undefined ) {
  858. min = new THREE.Vector2();
  859. max = new THREE.Vector2();
  860. }
  861. min.set( minVal, minVal );
  862. max.set( maxVal, maxVal );
  863. return this.clamp( min, max );
  864. };
  865. } )(),
  866. floor: function () {
  867. this.x = Math.floor( this.x );
  868. this.y = Math.floor( this.y );
  869. return this;
  870. },
  871. ceil: function () {
  872. this.x = Math.ceil( this.x );
  873. this.y = Math.ceil( this.y );
  874. return this;
  875. },
  876. round: function () {
  877. this.x = Math.round( this.x );
  878. this.y = Math.round( this.y );
  879. return this;
  880. },
  881. roundToZero: function () {
  882. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  883. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  884. return this;
  885. },
  886. negate: function () {
  887. this.x = - this.x;
  888. this.y = - this.y;
  889. return this;
  890. },
  891. dot: function ( v ) {
  892. return this.x * v.x + this.y * v.y;
  893. },
  894. lengthSq: function () {
  895. return this.x * this.x + this.y * this.y;
  896. },
  897. length: function () {
  898. return Math.sqrt( this.x * this.x + this.y * this.y );
  899. },
  900. normalize: function () {
  901. return this.divideScalar( this.length() );
  902. },
  903. distanceTo: function ( v ) {
  904. return Math.sqrt( this.distanceToSquared( v ) );
  905. },
  906. distanceToSquared: function ( v ) {
  907. var dx = this.x - v.x, dy = this.y - v.y;
  908. return dx * dx + dy * dy;
  909. },
  910. setLength: function ( l ) {
  911. var oldLength = this.length();
  912. if ( oldLength !== 0 && l !== oldLength ) {
  913. this.multiplyScalar( l / oldLength );
  914. }
  915. return this;
  916. },
  917. lerp: function ( v, alpha ) {
  918. this.x += ( v.x - this.x ) * alpha;
  919. this.y += ( v.y - this.y ) * alpha;
  920. return this;
  921. },
  922. lerpVectors: function ( v1, v2, alpha ) {
  923. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  924. return this;
  925. },
  926. equals: function ( v ) {
  927. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  928. },
  929. fromArray: function ( array, offset ) {
  930. if ( offset === undefined ) offset = 0;
  931. this.x = array[ offset ];
  932. this.y = array[ offset + 1 ];
  933. return this;
  934. },
  935. toArray: function ( array, offset ) {
  936. if ( array === undefined ) array = [];
  937. if ( offset === undefined ) offset = 0;
  938. array[ offset ] = this.x;
  939. array[ offset + 1 ] = this.y;
  940. return array;
  941. },
  942. fromAttribute: function ( attribute, index, offset ) {
  943. if ( offset === undefined ) offset = 0;
  944. index = index * attribute.itemSize + offset;
  945. this.x = attribute.array[ index ];
  946. this.y = attribute.array[ index + 1 ];
  947. return this;
  948. },
  949. clone: function () {
  950. return new THREE.Vector2( this.x, this.y );
  951. }
  952. };
  953. // File:src/math/Vector3.js
  954. /**
  955. * @author mrdoob / http://mrdoob.com/
  956. * @author *kile / http://kile.stravaganza.org/
  957. * @author philogb / http://blog.thejit.org/
  958. * @author mikael emtinger / http://gomo.se/
  959. * @author egraether / http://egraether.com/
  960. * @author WestLangley / http://github.com/WestLangley
  961. */
  962. THREE.Vector3 = function ( x, y, z ) {
  963. this.x = x || 0;
  964. this.y = y || 0;
  965. this.z = z || 0;
  966. };
  967. THREE.Vector3.prototype = {
  968. constructor: THREE.Vector3,
  969. set: function ( x, y, z ) {
  970. this.x = x;
  971. this.y = y;
  972. this.z = z;
  973. return this;
  974. },
  975. setX: function ( x ) {
  976. this.x = x;
  977. return this;
  978. },
  979. setY: function ( y ) {
  980. this.y = y;
  981. return this;
  982. },
  983. setZ: function ( z ) {
  984. this.z = z;
  985. return this;
  986. },
  987. setComponent: function ( index, value ) {
  988. switch ( index ) {
  989. case 0: this.x = value; break;
  990. case 1: this.y = value; break;
  991. case 2: this.z = value; break;
  992. default: throw new Error( 'index is out of range: ' + index );
  993. }
  994. },
  995. getComponent: function ( index ) {
  996. switch ( index ) {
  997. case 0: return this.x;
  998. case 1: return this.y;
  999. case 2: return this.z;
  1000. default: throw new Error( 'index is out of range: ' + index );
  1001. }
  1002. },
  1003. copy: function ( v ) {
  1004. this.x = v.x;
  1005. this.y = v.y;
  1006. this.z = v.z;
  1007. return this;
  1008. },
  1009. add: function ( v, w ) {
  1010. if ( w !== undefined ) {
  1011. THREE.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1012. return this.addVectors( v, w );
  1013. }
  1014. this.x += v.x;
  1015. this.y += v.y;
  1016. this.z += v.z;
  1017. return this;
  1018. },
  1019. addScalar: function ( s ) {
  1020. this.x += s;
  1021. this.y += s;
  1022. this.z += s;
  1023. return this;
  1024. },
  1025. addVectors: function ( a, b ) {
  1026. this.x = a.x + b.x;
  1027. this.y = a.y + b.y;
  1028. this.z = a.z + b.z;
  1029. return this;
  1030. },
  1031. sub: function ( v, w ) {
  1032. if ( w !== undefined ) {
  1033. THREE.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1034. return this.subVectors( v, w );
  1035. }
  1036. this.x -= v.x;
  1037. this.y -= v.y;
  1038. this.z -= v.z;
  1039. return this;
  1040. },
  1041. subVectors: function ( a, b ) {
  1042. this.x = a.x - b.x;
  1043. this.y = a.y - b.y;
  1044. this.z = a.z - b.z;
  1045. return this;
  1046. },
  1047. multiply: function ( v, w ) {
  1048. if ( w !== undefined ) {
  1049. THREE.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  1050. return this.multiplyVectors( v, w );
  1051. }
  1052. this.x *= v.x;
  1053. this.y *= v.y;
  1054. this.z *= v.z;
  1055. return this;
  1056. },
  1057. multiplyScalar: function ( scalar ) {
  1058. this.x *= scalar;
  1059. this.y *= scalar;
  1060. this.z *= scalar;
  1061. return this;
  1062. },
  1063. multiplyVectors: function ( a, b ) {
  1064. this.x = a.x * b.x;
  1065. this.y = a.y * b.y;
  1066. this.z = a.z * b.z;
  1067. return this;
  1068. },
  1069. applyEuler: function () {
  1070. var quaternion;
  1071. return function ( euler ) {
  1072. if ( euler instanceof THREE.Euler === false ) {
  1073. THREE.error( 'THREE.Vector3: .applyEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  1074. }
  1075. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1076. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1077. return this;
  1078. };
  1079. }(),
  1080. applyAxisAngle: function () {
  1081. var quaternion;
  1082. return function ( axis, angle ) {
  1083. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1084. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1085. return this;
  1086. };
  1087. }(),
  1088. applyMatrix3: function ( m ) {
  1089. var x = this.x;
  1090. var y = this.y;
  1091. var z = this.z;
  1092. var e = m.elements;
  1093. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1094. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1095. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1096. return this;
  1097. },
  1098. applyMatrix4: function ( m ) {
  1099. // input: THREE.Matrix4 affine matrix
  1100. var x = this.x, y = this.y, z = this.z;
  1101. var e = m.elements;
  1102. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  1103. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  1104. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  1105. return this;
  1106. },
  1107. applyProjection: function ( m ) {
  1108. // input: THREE.Matrix4 projection matrix
  1109. var x = this.x, y = this.y, z = this.z;
  1110. var e = m.elements;
  1111. var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide
  1112. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d;
  1113. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d;
  1114. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d;
  1115. return this;
  1116. },
  1117. applyQuaternion: function ( q ) {
  1118. var x = this.x;
  1119. var y = this.y;
  1120. var z = this.z;
  1121. var qx = q.x;
  1122. var qy = q.y;
  1123. var qz = q.z;
  1124. var qw = q.w;
  1125. // calculate quat * vector
  1126. var ix = qw * x + qy * z - qz * y;
  1127. var iy = qw * y + qz * x - qx * z;
  1128. var iz = qw * z + qx * y - qy * x;
  1129. var iw = - qx * x - qy * y - qz * z;
  1130. // calculate result * inverse quat
  1131. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1132. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1133. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1134. return this;
  1135. },
  1136. project: function () {
  1137. var matrix;
  1138. return function ( camera ) {
  1139. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1140. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1141. return this.applyProjection( matrix );
  1142. };
  1143. }(),
  1144. unproject: function () {
  1145. var matrix;
  1146. return function ( camera ) {
  1147. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1148. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1149. return this.applyProjection( matrix );
  1150. };
  1151. }(),
  1152. transformDirection: function ( m ) {
  1153. // input: THREE.Matrix4 affine matrix
  1154. // vector interpreted as a direction
  1155. var x = this.x, y = this.y, z = this.z;
  1156. var e = m.elements;
  1157. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1158. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1159. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1160. this.normalize();
  1161. return this;
  1162. },
  1163. divide: function ( v ) {
  1164. this.x /= v.x;
  1165. this.y /= v.y;
  1166. this.z /= v.z;
  1167. return this;
  1168. },
  1169. divideScalar: function ( scalar ) {
  1170. if ( scalar !== 0 ) {
  1171. var invScalar = 1 / scalar;
  1172. this.x *= invScalar;
  1173. this.y *= invScalar;
  1174. this.z *= invScalar;
  1175. } else {
  1176. this.x = 0;
  1177. this.y = 0;
  1178. this.z = 0;
  1179. }
  1180. return this;
  1181. },
  1182. min: function ( v ) {
  1183. if ( this.x > v.x ) {
  1184. this.x = v.x;
  1185. }
  1186. if ( this.y > v.y ) {
  1187. this.y = v.y;
  1188. }
  1189. if ( this.z > v.z ) {
  1190. this.z = v.z;
  1191. }
  1192. return this;
  1193. },
  1194. max: 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. clamp: function ( min, max ) {
  1207. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1208. if ( this.x < min.x ) {
  1209. this.x = min.x;
  1210. } else if ( this.x > max.x ) {
  1211. this.x = max.x;
  1212. }
  1213. if ( this.y < min.y ) {
  1214. this.y = min.y;
  1215. } else if ( this.y > max.y ) {
  1216. this.y = max.y;
  1217. }
  1218. if ( this.z < min.z ) {
  1219. this.z = min.z;
  1220. } else if ( this.z > max.z ) {
  1221. this.z = max.z;
  1222. }
  1223. return this;
  1224. },
  1225. clampScalar: ( function () {
  1226. var min, max;
  1227. return function ( minVal, maxVal ) {
  1228. if ( min === undefined ) {
  1229. min = new THREE.Vector3();
  1230. max = new THREE.Vector3();
  1231. }
  1232. min.set( minVal, minVal, minVal );
  1233. max.set( maxVal, maxVal, maxVal );
  1234. return this.clamp( min, max );
  1235. };
  1236. } )(),
  1237. floor: function () {
  1238. this.x = Math.floor( this.x );
  1239. this.y = Math.floor( this.y );
  1240. this.z = Math.floor( this.z );
  1241. return this;
  1242. },
  1243. ceil: function () {
  1244. this.x = Math.ceil( this.x );
  1245. this.y = Math.ceil( this.y );
  1246. this.z = Math.ceil( this.z );
  1247. return this;
  1248. },
  1249. round: function () {
  1250. this.x = Math.round( this.x );
  1251. this.y = Math.round( this.y );
  1252. this.z = Math.round( this.z );
  1253. return this;
  1254. },
  1255. roundToZero: function () {
  1256. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1257. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1258. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1259. return this;
  1260. },
  1261. negate: function () {
  1262. this.x = - this.x;
  1263. this.y = - this.y;
  1264. this.z = - this.z;
  1265. return this;
  1266. },
  1267. dot: function ( v ) {
  1268. return this.x * v.x + this.y * v.y + this.z * v.z;
  1269. },
  1270. lengthSq: function () {
  1271. return this.x * this.x + this.y * this.y + this.z * this.z;
  1272. },
  1273. length: function () {
  1274. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1275. },
  1276. lengthManhattan: function () {
  1277. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1278. },
  1279. normalize: function () {
  1280. return this.divideScalar( this.length() );
  1281. },
  1282. setLength: function ( l ) {
  1283. var oldLength = this.length();
  1284. if ( oldLength !== 0 && l !== oldLength ) {
  1285. this.multiplyScalar( l / oldLength );
  1286. }
  1287. return this;
  1288. },
  1289. lerp: function ( v, alpha ) {
  1290. this.x += ( v.x - this.x ) * alpha;
  1291. this.y += ( v.y - this.y ) * alpha;
  1292. this.z += ( v.z - this.z ) * alpha;
  1293. return this;
  1294. },
  1295. lerpVectors: function ( v1, v2, alpha ) {
  1296. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1297. return this;
  1298. },
  1299. cross: function ( v, w ) {
  1300. if ( w !== undefined ) {
  1301. THREE.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1302. return this.crossVectors( v, w );
  1303. }
  1304. var x = this.x, y = this.y, z = this.z;
  1305. this.x = y * v.z - z * v.y;
  1306. this.y = z * v.x - x * v.z;
  1307. this.z = x * v.y - y * v.x;
  1308. return this;
  1309. },
  1310. crossVectors: function ( a, b ) {
  1311. var ax = a.x, ay = a.y, az = a.z;
  1312. var bx = b.x, by = b.y, bz = b.z;
  1313. this.x = ay * bz - az * by;
  1314. this.y = az * bx - ax * bz;
  1315. this.z = ax * by - ay * bx;
  1316. return this;
  1317. },
  1318. projectOnVector: function () {
  1319. var v1, dot;
  1320. return function ( vector ) {
  1321. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1322. v1.copy( vector ).normalize();
  1323. dot = this.dot( v1 );
  1324. return this.copy( v1 ).multiplyScalar( dot );
  1325. };
  1326. }(),
  1327. projectOnPlane: function () {
  1328. var v1;
  1329. return function ( planeNormal ) {
  1330. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1331. v1.copy( this ).projectOnVector( planeNormal );
  1332. return this.sub( v1 );
  1333. }
  1334. }(),
  1335. reflect: function () {
  1336. // reflect incident vector off plane orthogonal to normal
  1337. // normal is assumed to have unit length
  1338. var v1;
  1339. return function ( normal ) {
  1340. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1341. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1342. }
  1343. }(),
  1344. angleTo: function ( v ) {
  1345. var theta = this.dot( v ) / ( this.length() * v.length() );
  1346. // clamp, to handle numerical problems
  1347. return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) );
  1348. },
  1349. distanceTo: function ( v ) {
  1350. return Math.sqrt( this.distanceToSquared( v ) );
  1351. },
  1352. distanceToSquared: function ( v ) {
  1353. var dx = this.x - v.x;
  1354. var dy = this.y - v.y;
  1355. var dz = this.z - v.z;
  1356. return dx * dx + dy * dy + dz * dz;
  1357. },
  1358. setEulerFromRotationMatrix: function ( m, order ) {
  1359. THREE.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  1360. },
  1361. setEulerFromQuaternion: function ( q, order ) {
  1362. THREE.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  1363. },
  1364. getPositionFromMatrix: function ( m ) {
  1365. THREE.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  1366. return this.setFromMatrixPosition( m );
  1367. },
  1368. getScaleFromMatrix: function ( m ) {
  1369. THREE.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  1370. return this.setFromMatrixScale( m );
  1371. },
  1372. getColumnFromMatrix: function ( index, matrix ) {
  1373. THREE.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  1374. return this.setFromMatrixColumn( index, matrix );
  1375. },
  1376. setFromMatrixPosition: function ( m ) {
  1377. this.x = m.elements[ 12 ];
  1378. this.y = m.elements[ 13 ];
  1379. this.z = m.elements[ 14 ];
  1380. return this;
  1381. },
  1382. setFromMatrixScale: function ( m ) {
  1383. var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
  1384. var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
  1385. var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
  1386. this.x = sx;
  1387. this.y = sy;
  1388. this.z = sz;
  1389. return this;
  1390. },
  1391. setFromMatrixColumn: function ( index, matrix ) {
  1392. var offset = index * 4;
  1393. var me = matrix.elements;
  1394. this.x = me[ offset ];
  1395. this.y = me[ offset + 1 ];
  1396. this.z = me[ offset + 2 ];
  1397. return this;
  1398. },
  1399. equals: function ( v ) {
  1400. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1401. },
  1402. fromArray: function ( array, offset ) {
  1403. if ( offset === undefined ) offset = 0;
  1404. this.x = array[ offset ];
  1405. this.y = array[ offset + 1 ];
  1406. this.z = array[ offset + 2 ];
  1407. return this;
  1408. },
  1409. toArray: function ( array, offset ) {
  1410. if ( array === undefined ) array = [];
  1411. if ( offset === undefined ) offset = 0;
  1412. array[ offset ] = this.x;
  1413. array[ offset + 1 ] = this.y;
  1414. array[ offset + 2 ] = this.z;
  1415. return array;
  1416. },
  1417. fromAttribute: function ( attribute, index, offset ) {
  1418. if ( offset === undefined ) offset = 0;
  1419. index = index * attribute.itemSize + offset;
  1420. this.x = attribute.array[ index ];
  1421. this.y = attribute.array[ index + 1 ];
  1422. this.z = attribute.array[ index + 2 ];
  1423. return this;
  1424. },
  1425. clone: function () {
  1426. return new THREE.Vector3( this.x, this.y, this.z );
  1427. }
  1428. };
  1429. // File:src/math/Vector4.js
  1430. /**
  1431. * @author supereggbert / http://www.paulbrunt.co.uk/
  1432. * @author philogb / http://blog.thejit.org/
  1433. * @author mikael emtinger / http://gomo.se/
  1434. * @author egraether / http://egraether.com/
  1435. * @author WestLangley / http://github.com/WestLangley
  1436. */
  1437. THREE.Vector4 = function ( x, y, z, w ) {
  1438. this.x = x || 0;
  1439. this.y = y || 0;
  1440. this.z = z || 0;
  1441. this.w = ( w !== undefined ) ? w : 1;
  1442. };
  1443. THREE.Vector4.prototype = {
  1444. constructor: THREE.Vector4,
  1445. set: function ( x, y, z, w ) {
  1446. this.x = x;
  1447. this.y = y;
  1448. this.z = z;
  1449. this.w = w;
  1450. return this;
  1451. },
  1452. setX: function ( x ) {
  1453. this.x = x;
  1454. return this;
  1455. },
  1456. setY: function ( y ) {
  1457. this.y = y;
  1458. return this;
  1459. },
  1460. setZ: function ( z ) {
  1461. this.z = z;
  1462. return this;
  1463. },
  1464. setW: function ( w ) {
  1465. this.w = w;
  1466. return this;
  1467. },
  1468. setComponent: function ( index, value ) {
  1469. switch ( index ) {
  1470. case 0: this.x = value; break;
  1471. case 1: this.y = value; break;
  1472. case 2: this.z = value; break;
  1473. case 3: this.w = value; break;
  1474. default: throw new Error( 'index is out of range: ' + index );
  1475. }
  1476. },
  1477. getComponent: function ( index ) {
  1478. switch ( index ) {
  1479. case 0: return this.x;
  1480. case 1: return this.y;
  1481. case 2: return this.z;
  1482. case 3: return this.w;
  1483. default: throw new Error( 'index is out of range: ' + index );
  1484. }
  1485. },
  1486. copy: function ( v ) {
  1487. this.x = v.x;
  1488. this.y = v.y;
  1489. this.z = v.z;
  1490. this.w = ( v.w !== undefined ) ? v.w : 1;
  1491. return this;
  1492. },
  1493. add: function ( v, w ) {
  1494. if ( w !== undefined ) {
  1495. THREE.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1496. return this.addVectors( v, w );
  1497. }
  1498. this.x += v.x;
  1499. this.y += v.y;
  1500. this.z += v.z;
  1501. this.w += v.w;
  1502. return this;
  1503. },
  1504. addScalar: function ( s ) {
  1505. this.x += s;
  1506. this.y += s;
  1507. this.z += s;
  1508. this.w += s;
  1509. return this;
  1510. },
  1511. addVectors: function ( a, b ) {
  1512. this.x = a.x + b.x;
  1513. this.y = a.y + b.y;
  1514. this.z = a.z + b.z;
  1515. this.w = a.w + b.w;
  1516. return this;
  1517. },
  1518. sub: function ( v, w ) {
  1519. if ( w !== undefined ) {
  1520. THREE.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1521. return this.subVectors( v, w );
  1522. }
  1523. this.x -= v.x;
  1524. this.y -= v.y;
  1525. this.z -= v.z;
  1526. this.w -= v.w;
  1527. return this;
  1528. },
  1529. subVectors: function ( a, b ) {
  1530. this.x = a.x - b.x;
  1531. this.y = a.y - b.y;
  1532. this.z = a.z - b.z;
  1533. this.w = a.w - b.w;
  1534. return this;
  1535. },
  1536. multiplyScalar: function ( scalar ) {
  1537. this.x *= scalar;
  1538. this.y *= scalar;
  1539. this.z *= scalar;
  1540. this.w *= scalar;
  1541. return this;
  1542. },
  1543. applyMatrix4: function ( m ) {
  1544. var x = this.x;
  1545. var y = this.y;
  1546. var z = this.z;
  1547. var w = this.w;
  1548. var e = m.elements;
  1549. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1550. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1551. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1552. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1553. return this;
  1554. },
  1555. divideScalar: function ( scalar ) {
  1556. if ( scalar !== 0 ) {
  1557. var invScalar = 1 / scalar;
  1558. this.x *= invScalar;
  1559. this.y *= invScalar;
  1560. this.z *= invScalar;
  1561. this.w *= invScalar;
  1562. } else {
  1563. this.x = 0;
  1564. this.y = 0;
  1565. this.z = 0;
  1566. this.w = 1;
  1567. }
  1568. return this;
  1569. },
  1570. setAxisAngleFromQuaternion: function ( q ) {
  1571. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1572. // q is assumed to be normalized
  1573. this.w = 2 * Math.acos( q.w );
  1574. var s = Math.sqrt( 1 - q.w * q.w );
  1575. if ( s < 0.0001 ) {
  1576. this.x = 1;
  1577. this.y = 0;
  1578. this.z = 0;
  1579. } else {
  1580. this.x = q.x / s;
  1581. this.y = q.y / s;
  1582. this.z = q.z / s;
  1583. }
  1584. return this;
  1585. },
  1586. setAxisAngleFromRotationMatrix: function ( m ) {
  1587. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1588. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1589. var angle, x, y, z, // variables for result
  1590. epsilon = 0.01, // margin to allow for rounding errors
  1591. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1592. te = m.elements,
  1593. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1594. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1595. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1596. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1597. && ( Math.abs( m13 - m31 ) < epsilon )
  1598. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1599. // singularity found
  1600. // first check for identity matrix which must have +1 for all terms
  1601. // in leading diagonal and zero in other terms
  1602. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1603. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1604. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1605. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1606. // this singularity is identity matrix so angle = 0
  1607. this.set( 1, 0, 0, 0 );
  1608. return this; // zero angle, arbitrary axis
  1609. }
  1610. // otherwise this singularity is angle = 180
  1611. angle = Math.PI;
  1612. var xx = ( m11 + 1 ) / 2;
  1613. var yy = ( m22 + 1 ) / 2;
  1614. var zz = ( m33 + 1 ) / 2;
  1615. var xy = ( m12 + m21 ) / 4;
  1616. var xz = ( m13 + m31 ) / 4;
  1617. var yz = ( m23 + m32 ) / 4;
  1618. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1619. if ( xx < epsilon ) {
  1620. x = 0;
  1621. y = 0.707106781;
  1622. z = 0.707106781;
  1623. } else {
  1624. x = Math.sqrt( xx );
  1625. y = xy / x;
  1626. z = xz / x;
  1627. }
  1628. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1629. if ( yy < epsilon ) {
  1630. x = 0.707106781;
  1631. y = 0;
  1632. z = 0.707106781;
  1633. } else {
  1634. y = Math.sqrt( yy );
  1635. x = xy / y;
  1636. z = yz / y;
  1637. }
  1638. } else { // m33 is the largest diagonal term so base result on this
  1639. if ( zz < epsilon ) {
  1640. x = 0.707106781;
  1641. y = 0.707106781;
  1642. z = 0;
  1643. } else {
  1644. z = Math.sqrt( zz );
  1645. x = xz / z;
  1646. y = yz / z;
  1647. }
  1648. }
  1649. this.set( x, y, z, angle );
  1650. return this; // return 180 deg rotation
  1651. }
  1652. // as we have reached here there are no singularities so we can handle normally
  1653. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1654. + ( m13 - m31 ) * ( m13 - m31 )
  1655. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1656. if ( Math.abs( s ) < 0.001 ) s = 1;
  1657. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1658. // caught by singularity test above, but I've left it in just in case
  1659. this.x = ( m32 - m23 ) / s;
  1660. this.y = ( m13 - m31 ) / s;
  1661. this.z = ( m21 - m12 ) / s;
  1662. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1663. return this;
  1664. },
  1665. min: function ( v ) {
  1666. if ( this.x > v.x ) {
  1667. this.x = v.x;
  1668. }
  1669. if ( this.y > v.y ) {
  1670. this.y = v.y;
  1671. }
  1672. if ( this.z > v.z ) {
  1673. this.z = v.z;
  1674. }
  1675. if ( this.w > v.w ) {
  1676. this.w = v.w;
  1677. }
  1678. return this;
  1679. },
  1680. max: function ( v ) {
  1681. if ( this.x < v.x ) {
  1682. this.x = v.x;
  1683. }
  1684. if ( this.y < v.y ) {
  1685. this.y = v.y;
  1686. }
  1687. if ( this.z < v.z ) {
  1688. this.z = v.z;
  1689. }
  1690. if ( this.w < v.w ) {
  1691. this.w = v.w;
  1692. }
  1693. return this;
  1694. },
  1695. clamp: function ( min, max ) {
  1696. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1697. if ( this.x < min.x ) {
  1698. this.x = min.x;
  1699. } else if ( this.x > max.x ) {
  1700. this.x = max.x;
  1701. }
  1702. if ( this.y < min.y ) {
  1703. this.y = min.y;
  1704. } else if ( this.y > max.y ) {
  1705. this.y = max.y;
  1706. }
  1707. if ( this.z < min.z ) {
  1708. this.z = min.z;
  1709. } else if ( this.z > max.z ) {
  1710. this.z = max.z;
  1711. }
  1712. if ( this.w < min.w ) {
  1713. this.w = min.w;
  1714. } else if ( this.w > max.w ) {
  1715. this.w = max.w;
  1716. }
  1717. return this;
  1718. },
  1719. clampScalar: ( function () {
  1720. var min, max;
  1721. return function ( minVal, maxVal ) {
  1722. if ( min === undefined ) {
  1723. min = new THREE.Vector4();
  1724. max = new THREE.Vector4();
  1725. }
  1726. min.set( minVal, minVal, minVal, minVal );
  1727. max.set( maxVal, maxVal, maxVal, maxVal );
  1728. return this.clamp( min, max );
  1729. };
  1730. } )(),
  1731. floor: function () {
  1732. this.x = Math.floor( this.x );
  1733. this.y = Math.floor( this.y );
  1734. this.z = Math.floor( this.z );
  1735. this.w = Math.floor( this.w );
  1736. return this;
  1737. },
  1738. ceil: function () {
  1739. this.x = Math.ceil( this.x );
  1740. this.y = Math.ceil( this.y );
  1741. this.z = Math.ceil( this.z );
  1742. this.w = Math.ceil( this.w );
  1743. return this;
  1744. },
  1745. round: function () {
  1746. this.x = Math.round( this.x );
  1747. this.y = Math.round( this.y );
  1748. this.z = Math.round( this.z );
  1749. this.w = Math.round( this.w );
  1750. return this;
  1751. },
  1752. roundToZero: function () {
  1753. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1754. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1755. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1756. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1757. return this;
  1758. },
  1759. negate: function () {
  1760. this.x = - this.x;
  1761. this.y = - this.y;
  1762. this.z = - this.z;
  1763. this.w = - this.w;
  1764. return this;
  1765. },
  1766. dot: function ( v ) {
  1767. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1768. },
  1769. lengthSq: function () {
  1770. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1771. },
  1772. length: function () {
  1773. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1774. },
  1775. lengthManhattan: function () {
  1776. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1777. },
  1778. normalize: function () {
  1779. return this.divideScalar( this.length() );
  1780. },
  1781. setLength: function ( l ) {
  1782. var oldLength = this.length();
  1783. if ( oldLength !== 0 && l !== oldLength ) {
  1784. this.multiplyScalar( l / oldLength );
  1785. }
  1786. return this;
  1787. },
  1788. lerp: function ( v, alpha ) {
  1789. this.x += ( v.x - this.x ) * alpha;
  1790. this.y += ( v.y - this.y ) * alpha;
  1791. this.z += ( v.z - this.z ) * alpha;
  1792. this.w += ( v.w - this.w ) * alpha;
  1793. return this;
  1794. },
  1795. lerpVectors: function ( v1, v2, alpha ) {
  1796. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1797. return this;
  1798. },
  1799. equals: function ( v ) {
  1800. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1801. },
  1802. fromArray: function ( array, offset ) {
  1803. if ( offset === undefined ) offset = 0;
  1804. this.x = array[ offset ];
  1805. this.y = array[ offset + 1 ];
  1806. this.z = array[ offset + 2 ];
  1807. this.w = array[ offset + 3 ];
  1808. return this;
  1809. },
  1810. toArray: function ( array, offset ) {
  1811. if ( array === undefined ) array = [];
  1812. if ( offset === undefined ) offset = 0;
  1813. array[ offset ] = this.x;
  1814. array[ offset + 1 ] = this.y;
  1815. array[ offset + 2 ] = this.z;
  1816. array[ offset + 3 ] = this.w;
  1817. return array;
  1818. },
  1819. fromAttribute: function ( attribute, index, offset ) {
  1820. if ( offset === undefined ) offset = 0;
  1821. index = index * attribute.itemSize + offset;
  1822. this.x = attribute.array[ index ];
  1823. this.y = attribute.array[ index + 1 ];
  1824. this.z = attribute.array[ index + 2 ];
  1825. this.w = attribute.array[ index + 3 ];
  1826. return this;
  1827. },
  1828. clone: function () {
  1829. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1830. }
  1831. };
  1832. // File:src/math/Euler.js
  1833. /**
  1834. * @author mrdoob / http://mrdoob.com/
  1835. * @author WestLangley / http://github.com/WestLangley
  1836. * @author bhouston / http://exocortex.com
  1837. */
  1838. THREE.Euler = function ( x, y, z, order ) {
  1839. this._x = x || 0;
  1840. this._y = y || 0;
  1841. this._z = z || 0;
  1842. this._order = order || THREE.Euler.DefaultOrder;
  1843. };
  1844. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1845. THREE.Euler.DefaultOrder = 'XYZ';
  1846. THREE.Euler.prototype = {
  1847. constructor: THREE.Euler,
  1848. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1849. get x () {
  1850. return this._x;
  1851. },
  1852. set x ( value ) {
  1853. this._x = value;
  1854. this.onChangeCallback();
  1855. },
  1856. get y () {
  1857. return this._y;
  1858. },
  1859. set y ( value ) {
  1860. this._y = value;
  1861. this.onChangeCallback();
  1862. },
  1863. get z () {
  1864. return this._z;
  1865. },
  1866. set z ( value ) {
  1867. this._z = value;
  1868. this.onChangeCallback();
  1869. },
  1870. get order () {
  1871. return this._order;
  1872. },
  1873. set order ( value ) {
  1874. this._order = value;
  1875. this.onChangeCallback();
  1876. },
  1877. set: function ( x, y, z, order ) {
  1878. this._x = x;
  1879. this._y = y;
  1880. this._z = z;
  1881. this._order = order || this._order;
  1882. this.onChangeCallback();
  1883. return this;
  1884. },
  1885. copy: function ( euler ) {
  1886. this._x = euler._x;
  1887. this._y = euler._y;
  1888. this._z = euler._z;
  1889. this._order = euler._order;
  1890. this.onChangeCallback();
  1891. return this;
  1892. },
  1893. setFromRotationMatrix: function ( m, order, update ) {
  1894. var clamp = THREE.Math.clamp;
  1895. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1896. var te = m.elements;
  1897. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  1898. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  1899. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1900. order = order || this._order;
  1901. if ( order === 'XYZ' ) {
  1902. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  1903. if ( Math.abs( m13 ) < 0.99999 ) {
  1904. this._x = Math.atan2( - m23, m33 );
  1905. this._z = Math.atan2( - m12, m11 );
  1906. } else {
  1907. this._x = Math.atan2( m32, m22 );
  1908. this._z = 0;
  1909. }
  1910. } else if ( order === 'YXZ' ) {
  1911. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  1912. if ( Math.abs( m23 ) < 0.99999 ) {
  1913. this._y = Math.atan2( m13, m33 );
  1914. this._z = Math.atan2( m21, m22 );
  1915. } else {
  1916. this._y = Math.atan2( - m31, m11 );
  1917. this._z = 0;
  1918. }
  1919. } else if ( order === 'ZXY' ) {
  1920. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  1921. if ( Math.abs( m32 ) < 0.99999 ) {
  1922. this._y = Math.atan2( - m31, m33 );
  1923. this._z = Math.atan2( - m12, m22 );
  1924. } else {
  1925. this._y = 0;
  1926. this._z = Math.atan2( m21, m11 );
  1927. }
  1928. } else if ( order === 'ZYX' ) {
  1929. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  1930. if ( Math.abs( m31 ) < 0.99999 ) {
  1931. this._x = Math.atan2( m32, m33 );
  1932. this._z = Math.atan2( m21, m11 );
  1933. } else {
  1934. this._x = 0;
  1935. this._z = Math.atan2( - m12, m22 );
  1936. }
  1937. } else if ( order === 'YZX' ) {
  1938. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  1939. if ( Math.abs( m21 ) < 0.99999 ) {
  1940. this._x = Math.atan2( - m23, m22 );
  1941. this._y = Math.atan2( - m31, m11 );
  1942. } else {
  1943. this._x = 0;
  1944. this._y = Math.atan2( m13, m33 );
  1945. }
  1946. } else if ( order === 'XZY' ) {
  1947. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  1948. if ( Math.abs( m12 ) < 0.99999 ) {
  1949. this._x = Math.atan2( m32, m22 );
  1950. this._y = Math.atan2( m13, m11 );
  1951. } else {
  1952. this._x = Math.atan2( - m23, m33 );
  1953. this._y = 0;
  1954. }
  1955. } else {
  1956. THREE.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order )
  1957. }
  1958. this._order = order;
  1959. if ( update !== false ) this.onChangeCallback();
  1960. return this;
  1961. },
  1962. setFromQuaternion: function () {
  1963. var matrix;
  1964. return function ( q, order, update ) {
  1965. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1966. matrix.makeRotationFromQuaternion( q );
  1967. this.setFromRotationMatrix( matrix, order, update );
  1968. return this;
  1969. };
  1970. }(),
  1971. setFromVector3: function ( v, order ) {
  1972. return this.set( v.x, v.y, v.z, order || this._order );
  1973. },
  1974. reorder: function () {
  1975. // WARNING: this discards revolution information -bhouston
  1976. var q = new THREE.Quaternion();
  1977. return function ( newOrder ) {
  1978. q.setFromEuler( this );
  1979. this.setFromQuaternion( q, newOrder );
  1980. };
  1981. }(),
  1982. equals: function ( euler ) {
  1983. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  1984. },
  1985. fromArray: function ( array ) {
  1986. this._x = array[ 0 ];
  1987. this._y = array[ 1 ];
  1988. this._z = array[ 2 ];
  1989. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  1990. this.onChangeCallback();
  1991. return this;
  1992. },
  1993. toArray: function ( array, offset ) {
  1994. if ( array === undefined ) array = [];
  1995. if ( offset === undefined ) offset = 0;
  1996. array[ offset ] = this._x;
  1997. array[ offset + 1 ] = this._y;
  1998. array[ offset + 2 ] = this._z;
  1999. array[ offset + 3 ] = this._order;
  2000. return array;
  2001. },
  2002. toVector3: function ( optionalResult ) {
  2003. if ( optionalResult ) {
  2004. return optionalResult.set( this._x, this._y, this._z );
  2005. } else {
  2006. return new THREE.Vector3( this._x, this._y, this._z );
  2007. }
  2008. },
  2009. onChange: function ( callback ) {
  2010. this.onChangeCallback = callback;
  2011. return this;
  2012. },
  2013. onChangeCallback: function () {},
  2014. clone: function () {
  2015. return new THREE.Euler( this._x, this._y, this._z, this._order );
  2016. }
  2017. };
  2018. // File:src/math/Line3.js
  2019. /**
  2020. * @author bhouston / http://exocortex.com
  2021. */
  2022. THREE.Line3 = function ( start, end ) {
  2023. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  2024. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  2025. };
  2026. THREE.Line3.prototype = {
  2027. constructor: THREE.Line3,
  2028. set: function ( start, end ) {
  2029. this.start.copy( start );
  2030. this.end.copy( end );
  2031. return this;
  2032. },
  2033. copy: function ( line ) {
  2034. this.start.copy( line.start );
  2035. this.end.copy( line.end );
  2036. return this;
  2037. },
  2038. center: function ( optionalTarget ) {
  2039. var result = optionalTarget || new THREE.Vector3();
  2040. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  2041. },
  2042. delta: function ( optionalTarget ) {
  2043. var result = optionalTarget || new THREE.Vector3();
  2044. return result.subVectors( this.end, this.start );
  2045. },
  2046. distanceSq: function () {
  2047. return this.start.distanceToSquared( this.end );
  2048. },
  2049. distance: function () {
  2050. return this.start.distanceTo( this.end );
  2051. },
  2052. at: function ( t, optionalTarget ) {
  2053. var result = optionalTarget || new THREE.Vector3();
  2054. return this.delta( result ).multiplyScalar( t ).add( this.start );
  2055. },
  2056. closestPointToPointParameter: function () {
  2057. var startP = new THREE.Vector3();
  2058. var startEnd = new THREE.Vector3();
  2059. return function ( point, clampToLine ) {
  2060. startP.subVectors( point, this.start );
  2061. startEnd.subVectors( this.end, this.start );
  2062. var startEnd2 = startEnd.dot( startEnd );
  2063. var startEnd_startP = startEnd.dot( startP );
  2064. var t = startEnd_startP / startEnd2;
  2065. if ( clampToLine ) {
  2066. t = THREE.Math.clamp( t, 0, 1 );
  2067. }
  2068. return t;
  2069. };
  2070. }(),
  2071. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  2072. var t = this.closestPointToPointParameter( point, clampToLine );
  2073. var result = optionalTarget || new THREE.Vector3();
  2074. return this.delta( result ).multiplyScalar( t ).add( this.start );
  2075. },
  2076. applyMatrix4: function ( matrix ) {
  2077. this.start.applyMatrix4( matrix );
  2078. this.end.applyMatrix4( matrix );
  2079. return this;
  2080. },
  2081. equals: function ( line ) {
  2082. return line.start.equals( this.start ) && line.end.equals( this.end );
  2083. },
  2084. clone: function () {
  2085. return new THREE.Line3().copy( this );
  2086. }
  2087. };
  2088. // File:src/math/Box2.js
  2089. /**
  2090. * @author bhouston / http://exocortex.com
  2091. */
  2092. THREE.Box2 = function ( min, max ) {
  2093. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  2094. this.max = ( max !== undefined ) ? max : new THREE.Vector2( - Infinity, - Infinity );
  2095. };
  2096. THREE.Box2.prototype = {
  2097. constructor: THREE.Box2,
  2098. set: function ( min, max ) {
  2099. this.min.copy( min );
  2100. this.max.copy( max );
  2101. return this;
  2102. },
  2103. setFromPoints: function ( points ) {
  2104. this.makeEmpty();
  2105. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2106. this.expandByPoint( points[ i ] )
  2107. }
  2108. return this;
  2109. },
  2110. setFromCenterAndSize: function () {
  2111. var v1 = new THREE.Vector2();
  2112. return function ( center, size ) {
  2113. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2114. this.min.copy( center ).sub( halfSize );
  2115. this.max.copy( center ).add( halfSize );
  2116. return this;
  2117. };
  2118. }(),
  2119. copy: function ( box ) {
  2120. this.min.copy( box.min );
  2121. this.max.copy( box.max );
  2122. return this;
  2123. },
  2124. makeEmpty: function () {
  2125. this.min.x = this.min.y = Infinity;
  2126. this.max.x = this.max.y = - Infinity;
  2127. return this;
  2128. },
  2129. empty: function () {
  2130. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2131. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  2132. },
  2133. center: function ( optionalTarget ) {
  2134. var result = optionalTarget || new THREE.Vector2();
  2135. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2136. },
  2137. size: function ( optionalTarget ) {
  2138. var result = optionalTarget || new THREE.Vector2();
  2139. return result.subVectors( this.max, this.min );
  2140. },
  2141. expandByPoint: function ( point ) {
  2142. this.min.min( point );
  2143. this.max.max( point );
  2144. return this;
  2145. },
  2146. expandByVector: function ( vector ) {
  2147. this.min.sub( vector );
  2148. this.max.add( vector );
  2149. return this;
  2150. },
  2151. expandByScalar: function ( scalar ) {
  2152. this.min.addScalar( - scalar );
  2153. this.max.addScalar( scalar );
  2154. return this;
  2155. },
  2156. containsPoint: function ( point ) {
  2157. if ( point.x < this.min.x || point.x > this.max.x ||
  2158. point.y < this.min.y || point.y > this.max.y ) {
  2159. return false;
  2160. }
  2161. return true;
  2162. },
  2163. containsBox: function ( box ) {
  2164. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2165. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  2166. return true;
  2167. }
  2168. return false;
  2169. },
  2170. getParameter: function ( point, optionalTarget ) {
  2171. // This can potentially have a divide by zero if the box
  2172. // has a size dimension of 0.
  2173. var result = optionalTarget || new THREE.Vector2();
  2174. return result.set(
  2175. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2176. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  2177. );
  2178. },
  2179. isIntersectionBox: function ( box ) {
  2180. // using 6 splitting planes to rule out intersections.
  2181. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2182. box.max.y < this.min.y || box.min.y > this.max.y ) {
  2183. return false;
  2184. }
  2185. return true;
  2186. },
  2187. clampPoint: function ( point, optionalTarget ) {
  2188. var result = optionalTarget || new THREE.Vector2();
  2189. return result.copy( point ).clamp( this.min, this.max );
  2190. },
  2191. distanceToPoint: function () {
  2192. var v1 = new THREE.Vector2();
  2193. return function ( point ) {
  2194. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2195. return clampedPoint.sub( point ).length();
  2196. };
  2197. }(),
  2198. intersect: function ( box ) {
  2199. this.min.max( box.min );
  2200. this.max.min( box.max );
  2201. return this;
  2202. },
  2203. union: function ( box ) {
  2204. this.min.min( box.min );
  2205. this.max.max( box.max );
  2206. return this;
  2207. },
  2208. translate: function ( offset ) {
  2209. this.min.add( offset );
  2210. this.max.add( offset );
  2211. return this;
  2212. },
  2213. equals: function ( box ) {
  2214. return box.min.equals( this.min ) && box.max.equals( this.max );
  2215. },
  2216. clone: function () {
  2217. return new THREE.Box2().copy( this );
  2218. }
  2219. };
  2220. // File:src/math/Box3.js
  2221. /**
  2222. * @author bhouston / http://exocortex.com
  2223. * @author WestLangley / http://github.com/WestLangley
  2224. */
  2225. THREE.Box3 = function ( min, max ) {
  2226. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2227. this.max = ( max !== undefined ) ? max : new THREE.Vector3( - Infinity, - Infinity, - Infinity );
  2228. };
  2229. THREE.Box3.prototype = {
  2230. constructor: THREE.Box3,
  2231. set: function ( min, max ) {
  2232. this.min.copy( min );
  2233. this.max.copy( max );
  2234. return this;
  2235. },
  2236. setFromPoints: function ( points ) {
  2237. this.makeEmpty();
  2238. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2239. this.expandByPoint( points[ i ] )
  2240. }
  2241. return this;
  2242. },
  2243. setFromCenterAndSize: function () {
  2244. var v1 = new THREE.Vector3();
  2245. return function ( center, size ) {
  2246. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2247. this.min.copy( center ).sub( halfSize );
  2248. this.max.copy( center ).add( halfSize );
  2249. return this;
  2250. };
  2251. }(),
  2252. setFromObject: function () {
  2253. // Computes the world-axis-aligned bounding box of an object (including its children),
  2254. // accounting for both the object's, and childrens', world transforms
  2255. var v1 = new THREE.Vector3();
  2256. return function ( object ) {
  2257. var scope = this;
  2258. object.updateMatrixWorld( true );
  2259. this.makeEmpty();
  2260. object.traverse( function ( node ) {
  2261. var geometry = node.geometry;
  2262. if ( geometry !== undefined ) {
  2263. if ( geometry instanceof THREE.Geometry ) {
  2264. var vertices = geometry.vertices;
  2265. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  2266. v1.copy( vertices[ i ] );
  2267. v1.applyMatrix4( node.matrixWorld );
  2268. scope.expandByPoint( v1 );
  2269. }
  2270. } else if ( geometry instanceof THREE.BufferGeometry && geometry.attributes[ 'position' ] !== undefined ) {
  2271. var positions = geometry.attributes[ 'position' ].array;
  2272. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  2273. v1.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  2274. v1.applyMatrix4( node.matrixWorld );
  2275. scope.expandByPoint( v1 );
  2276. }
  2277. }
  2278. }
  2279. } );
  2280. return this;
  2281. };
  2282. }(),
  2283. copy: function ( box ) {
  2284. this.min.copy( box.min );
  2285. this.max.copy( box.max );
  2286. return this;
  2287. },
  2288. makeEmpty: function () {
  2289. this.min.x = this.min.y = this.min.z = Infinity;
  2290. this.max.x = this.max.y = this.max.z = - Infinity;
  2291. return this;
  2292. },
  2293. empty: function () {
  2294. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2295. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2296. },
  2297. center: function ( optionalTarget ) {
  2298. var result = optionalTarget || new THREE.Vector3();
  2299. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2300. },
  2301. size: function ( optionalTarget ) {
  2302. var result = optionalTarget || new THREE.Vector3();
  2303. return result.subVectors( this.max, this.min );
  2304. },
  2305. expandByPoint: function ( point ) {
  2306. this.min.min( point );
  2307. this.max.max( point );
  2308. return this;
  2309. },
  2310. expandByVector: function ( vector ) {
  2311. this.min.sub( vector );
  2312. this.max.add( vector );
  2313. return this;
  2314. },
  2315. expandByScalar: function ( scalar ) {
  2316. this.min.addScalar( - scalar );
  2317. this.max.addScalar( scalar );
  2318. return this;
  2319. },
  2320. containsPoint: function ( point ) {
  2321. if ( point.x < this.min.x || point.x > this.max.x ||
  2322. point.y < this.min.y || point.y > this.max.y ||
  2323. point.z < this.min.z || point.z > this.max.z ) {
  2324. return false;
  2325. }
  2326. return true;
  2327. },
  2328. containsBox: function ( box ) {
  2329. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2330. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2331. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2332. return true;
  2333. }
  2334. return false;
  2335. },
  2336. getParameter: function ( point, optionalTarget ) {
  2337. // This can potentially have a divide by zero if the box
  2338. // has a size dimension of 0.
  2339. var result = optionalTarget || new THREE.Vector3();
  2340. return result.set(
  2341. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2342. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2343. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2344. );
  2345. },
  2346. isIntersectionBox: function ( box ) {
  2347. // using 6 splitting planes to rule out intersections.
  2348. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2349. box.max.y < this.min.y || box.min.y > this.max.y ||
  2350. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2351. return false;
  2352. }
  2353. return true;
  2354. },
  2355. clampPoint: function ( point, optionalTarget ) {
  2356. var result = optionalTarget || new THREE.Vector3();
  2357. return result.copy( point ).clamp( this.min, this.max );
  2358. },
  2359. distanceToPoint: function () {
  2360. var v1 = new THREE.Vector3();
  2361. return function ( point ) {
  2362. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2363. return clampedPoint.sub( point ).length();
  2364. };
  2365. }(),
  2366. getBoundingSphere: function () {
  2367. var v1 = new THREE.Vector3();
  2368. return function ( optionalTarget ) {
  2369. var result = optionalTarget || new THREE.Sphere();
  2370. result.center = this.center();
  2371. result.radius = this.size( v1 ).length() * 0.5;
  2372. return result;
  2373. };
  2374. }(),
  2375. intersect: function ( box ) {
  2376. this.min.max( box.min );
  2377. this.max.min( box.max );
  2378. return this;
  2379. },
  2380. union: function ( box ) {
  2381. this.min.min( box.min );
  2382. this.max.max( box.max );
  2383. return this;
  2384. },
  2385. applyMatrix4: function () {
  2386. var points = [
  2387. new THREE.Vector3(),
  2388. new THREE.Vector3(),
  2389. new THREE.Vector3(),
  2390. new THREE.Vector3(),
  2391. new THREE.Vector3(),
  2392. new THREE.Vector3(),
  2393. new THREE.Vector3(),
  2394. new THREE.Vector3()
  2395. ];
  2396. return function ( matrix ) {
  2397. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2398. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2399. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2400. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2401. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2402. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2403. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2404. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2405. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2406. this.makeEmpty();
  2407. this.setFromPoints( points );
  2408. return this;
  2409. };
  2410. }(),
  2411. translate: function ( offset ) {
  2412. this.min.add( offset );
  2413. this.max.add( offset );
  2414. return this;
  2415. },
  2416. equals: function ( box ) {
  2417. return box.min.equals( this.min ) && box.max.equals( this.max );
  2418. },
  2419. clone: function () {
  2420. return new THREE.Box3().copy( this );
  2421. }
  2422. };
  2423. // File:src/math/Matrix3.js
  2424. /**
  2425. * @author alteredq / http://alteredqualia.com/
  2426. * @author WestLangley / http://github.com/WestLangley
  2427. * @author bhouston / http://exocortex.com
  2428. */
  2429. THREE.Matrix3 = function () {
  2430. this.elements = new Float32Array( [
  2431. 1, 0, 0,
  2432. 0, 1, 0,
  2433. 0, 0, 1
  2434. ] );
  2435. if ( arguments.length > 0 ) {
  2436. THREE.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  2437. }
  2438. };
  2439. THREE.Matrix3.prototype = {
  2440. constructor: THREE.Matrix3,
  2441. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2442. var te = this.elements;
  2443. te[ 0 ] = n11; te[ 3 ] = n12; te[ 6 ] = n13;
  2444. te[ 1 ] = n21; te[ 4 ] = n22; te[ 7 ] = n23;
  2445. te[ 2 ] = n31; te[ 5 ] = n32; te[ 8 ] = n33;
  2446. return this;
  2447. },
  2448. identity: function () {
  2449. this.set(
  2450. 1, 0, 0,
  2451. 0, 1, 0,
  2452. 0, 0, 1
  2453. );
  2454. return this;
  2455. },
  2456. copy: function ( m ) {
  2457. var me = m.elements;
  2458. this.set(
  2459. me[ 0 ], me[ 3 ], me[ 6 ],
  2460. me[ 1 ], me[ 4 ], me[ 7 ],
  2461. me[ 2 ], me[ 5 ], me[ 8 ]
  2462. );
  2463. return this;
  2464. },
  2465. multiplyVector3: function ( vector ) {
  2466. THREE.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2467. return vector.applyMatrix3( this );
  2468. },
  2469. multiplyVector3Array: function ( a ) {
  2470. THREE.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2471. return this.applyToVector3Array( a );
  2472. },
  2473. applyToVector3Array: function () {
  2474. var v1 = new THREE.Vector3();
  2475. return function ( array, offset, length ) {
  2476. if ( offset === undefined ) offset = 0;
  2477. if ( length === undefined ) length = array.length;
  2478. for ( var i = 0, j = offset, il; i < length; i += 3, j += 3 ) {
  2479. v1.x = array[ j ];
  2480. v1.y = array[ j + 1 ];
  2481. v1.z = array[ j + 2 ];
  2482. v1.applyMatrix3( this );
  2483. array[ j ] = v1.x;
  2484. array[ j + 1 ] = v1.y;
  2485. array[ j + 2 ] = v1.z;
  2486. }
  2487. return array;
  2488. };
  2489. }(),
  2490. multiplyScalar: function ( s ) {
  2491. var te = this.elements;
  2492. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  2493. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  2494. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  2495. return this;
  2496. },
  2497. determinant: function () {
  2498. var te = this.elements;
  2499. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  2500. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  2501. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  2502. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  2503. },
  2504. getInverse: function ( matrix, throwOnInvertible ) {
  2505. // input: THREE.Matrix4
  2506. // ( based on http://code.google.com/p/webgl-mjs/ )
  2507. var me = matrix.elements;
  2508. var te = this.elements;
  2509. te[ 0 ] = me[ 10 ] * me[ 5 ] - me[ 6 ] * me[ 9 ];
  2510. te[ 1 ] = - me[ 10 ] * me[ 1 ] + me[ 2 ] * me[ 9 ];
  2511. te[ 2 ] = me[ 6 ] * me[ 1 ] - me[ 2 ] * me[ 5 ];
  2512. te[ 3 ] = - me[ 10 ] * me[ 4 ] + me[ 6 ] * me[ 8 ];
  2513. te[ 4 ] = me[ 10 ] * me[ 0 ] - me[ 2 ] * me[ 8 ];
  2514. te[ 5 ] = - me[ 6 ] * me[ 0 ] + me[ 2 ] * me[ 4 ];
  2515. te[ 6 ] = me[ 9 ] * me[ 4 ] - me[ 5 ] * me[ 8 ];
  2516. te[ 7 ] = - me[ 9 ] * me[ 0 ] + me[ 1 ] * me[ 8 ];
  2517. te[ 8 ] = me[ 5 ] * me[ 0 ] - me[ 1 ] * me[ 4 ];
  2518. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2519. // no inverse
  2520. if ( det === 0 ) {
  2521. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2522. if ( throwOnInvertible || false ) {
  2523. throw new Error( msg );
  2524. } else {
  2525. THREE.warn( msg );
  2526. }
  2527. this.identity();
  2528. return this;
  2529. }
  2530. this.multiplyScalar( 1.0 / det );
  2531. return this;
  2532. },
  2533. transpose: function () {
  2534. var tmp, m = this.elements;
  2535. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  2536. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  2537. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  2538. return this;
  2539. },
  2540. flattenToArrayOffset: function ( array, offset ) {
  2541. var te = this.elements;
  2542. array[ offset ] = te[ 0 ];
  2543. array[ offset + 1 ] = te[ 1 ];
  2544. array[ offset + 2 ] = te[ 2 ];
  2545. array[ offset + 3 ] = te[ 3 ];
  2546. array[ offset + 4 ] = te[ 4 ];
  2547. array[ offset + 5 ] = te[ 5 ];
  2548. array[ offset + 6 ] = te[ 6 ];
  2549. array[ offset + 7 ] = te[ 7 ];
  2550. array[ offset + 8 ] = te[ 8 ];
  2551. return array;
  2552. },
  2553. getNormalMatrix: function ( m ) {
  2554. // input: THREE.Matrix4
  2555. this.getInverse( m ).transpose();
  2556. return this;
  2557. },
  2558. transposeIntoArray: function ( r ) {
  2559. var m = this.elements;
  2560. r[ 0 ] = m[ 0 ];
  2561. r[ 1 ] = m[ 3 ];
  2562. r[ 2 ] = m[ 6 ];
  2563. r[ 3 ] = m[ 1 ];
  2564. r[ 4 ] = m[ 4 ];
  2565. r[ 5 ] = m[ 7 ];
  2566. r[ 6 ] = m[ 2 ];
  2567. r[ 7 ] = m[ 5 ];
  2568. r[ 8 ] = m[ 8 ];
  2569. return this;
  2570. },
  2571. fromArray: function ( array ) {
  2572. this.elements.set( array );
  2573. return this;
  2574. },
  2575. toArray: function () {
  2576. var te = this.elements;
  2577. return [
  2578. te[ 0 ], te[ 1 ], te[ 2 ],
  2579. te[ 3 ], te[ 4 ], te[ 5 ],
  2580. te[ 6 ], te[ 7 ], te[ 8 ]
  2581. ];
  2582. },
  2583. clone: function () {
  2584. return new THREE.Matrix3().fromArray( this.elements );
  2585. }
  2586. };
  2587. // File:src/math/Matrix4.js
  2588. /**
  2589. * @author mrdoob / http://mrdoob.com/
  2590. * @author supereggbert / http://www.paulbrunt.co.uk/
  2591. * @author philogb / http://blog.thejit.org/
  2592. * @author jordi_ros / http://plattsoft.com
  2593. * @author D1plo1d / http://github.com/D1plo1d
  2594. * @author alteredq / http://alteredqualia.com/
  2595. * @author mikael emtinger / http://gomo.se/
  2596. * @author timknip / http://www.floorplanner.com/
  2597. * @author bhouston / http://exocortex.com
  2598. * @author WestLangley / http://github.com/WestLangley
  2599. */
  2600. THREE.Matrix4 = function () {
  2601. this.elements = new Float32Array( [
  2602. 1, 0, 0, 0,
  2603. 0, 1, 0, 0,
  2604. 0, 0, 1, 0,
  2605. 0, 0, 0, 1
  2606. ] );
  2607. if ( arguments.length > 0 ) {
  2608. THREE.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  2609. }
  2610. };
  2611. THREE.Matrix4.prototype = {
  2612. constructor: THREE.Matrix4,
  2613. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2614. var te = this.elements;
  2615. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  2616. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  2617. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  2618. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  2619. return this;
  2620. },
  2621. identity: function () {
  2622. this.set(
  2623. 1, 0, 0, 0,
  2624. 0, 1, 0, 0,
  2625. 0, 0, 1, 0,
  2626. 0, 0, 0, 1
  2627. );
  2628. return this;
  2629. },
  2630. copy: function ( m ) {
  2631. this.elements.set( m.elements );
  2632. return this;
  2633. },
  2634. extractPosition: function ( m ) {
  2635. THREE.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  2636. return this.copyPosition( m );
  2637. },
  2638. copyPosition: function ( m ) {
  2639. var te = this.elements;
  2640. var me = m.elements;
  2641. te[ 12 ] = me[ 12 ];
  2642. te[ 13 ] = me[ 13 ];
  2643. te[ 14 ] = me[ 14 ];
  2644. return this;
  2645. },
  2646. extractBasis: function ( xAxis, yAxis, zAxis ) {
  2647. var te = this.elements;
  2648. xAxis.set( te[ 0 ], te[ 1 ], te[ 2 ] );
  2649. yAxis.set( te[ 4 ], te[ 5 ], te[ 6 ] );
  2650. zAxis.set( te[ 8 ], te[ 9 ], te[ 10 ] );
  2651. return this;
  2652. },
  2653. makeBasis: function ( xAxis, yAxis, zAxis ) {
  2654. this.set(
  2655. xAxis.x, yAxis.x, zAxis.x, 0,
  2656. xAxis.y, yAxis.y, zAxis.y, 0,
  2657. xAxis.z, yAxis.z, zAxis.z, 0,
  2658. 0, 0, 0, 1
  2659. );
  2660. return this;
  2661. },
  2662. extractRotation: function () {
  2663. var v1 = new THREE.Vector3();
  2664. return function ( m ) {
  2665. var te = this.elements;
  2666. var me = m.elements;
  2667. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  2668. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  2669. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  2670. te[ 0 ] = me[ 0 ] * scaleX;
  2671. te[ 1 ] = me[ 1 ] * scaleX;
  2672. te[ 2 ] = me[ 2 ] * scaleX;
  2673. te[ 4 ] = me[ 4 ] * scaleY;
  2674. te[ 5 ] = me[ 5 ] * scaleY;
  2675. te[ 6 ] = me[ 6 ] * scaleY;
  2676. te[ 8 ] = me[ 8 ] * scaleZ;
  2677. te[ 9 ] = me[ 9 ] * scaleZ;
  2678. te[ 10 ] = me[ 10 ] * scaleZ;
  2679. return this;
  2680. };
  2681. }(),
  2682. makeRotationFromEuler: function ( euler ) {
  2683. if ( euler instanceof THREE.Euler === false ) {
  2684. THREE.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  2685. }
  2686. var te = this.elements;
  2687. var x = euler.x, y = euler.y, z = euler.z;
  2688. var a = Math.cos( x ), b = Math.sin( x );
  2689. var c = Math.cos( y ), d = Math.sin( y );
  2690. var e = Math.cos( z ), f = Math.sin( z );
  2691. if ( euler.order === 'XYZ' ) {
  2692. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2693. te[ 0 ] = c * e;
  2694. te[ 4 ] = - c * f;
  2695. te[ 8 ] = d;
  2696. te[ 1 ] = af + be * d;
  2697. te[ 5 ] = ae - bf * d;
  2698. te[ 9 ] = - b * c;
  2699. te[ 2 ] = bf - ae * d;
  2700. te[ 6 ] = be + af * d;
  2701. te[ 10 ] = a * c;
  2702. } else if ( euler.order === 'YXZ' ) {
  2703. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2704. te[ 0 ] = ce + df * b;
  2705. te[ 4 ] = de * b - cf;
  2706. te[ 8 ] = a * d;
  2707. te[ 1 ] = a * f;
  2708. te[ 5 ] = a * e;
  2709. te[ 9 ] = - b;
  2710. te[ 2 ] = cf * b - de;
  2711. te[ 6 ] = df + ce * b;
  2712. te[ 10 ] = a * c;
  2713. } else if ( euler.order === 'ZXY' ) {
  2714. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2715. te[ 0 ] = ce - df * b;
  2716. te[ 4 ] = - a * f;
  2717. te[ 8 ] = de + cf * b;
  2718. te[ 1 ] = cf + de * b;
  2719. te[ 5 ] = a * e;
  2720. te[ 9 ] = df - ce * b;
  2721. te[ 2 ] = - a * d;
  2722. te[ 6 ] = b;
  2723. te[ 10 ] = a * c;
  2724. } else if ( euler.order === 'ZYX' ) {
  2725. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2726. te[ 0 ] = c * e;
  2727. te[ 4 ] = be * d - af;
  2728. te[ 8 ] = ae * d + bf;
  2729. te[ 1 ] = c * f;
  2730. te[ 5 ] = bf * d + ae;
  2731. te[ 9 ] = af * d - be;
  2732. te[ 2 ] = - d;
  2733. te[ 6 ] = b * c;
  2734. te[ 10 ] = a * c;
  2735. } else if ( euler.order === 'YZX' ) {
  2736. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2737. te[ 0 ] = c * e;
  2738. te[ 4 ] = bd - ac * f;
  2739. te[ 8 ] = bc * f + ad;
  2740. te[ 1 ] = f;
  2741. te[ 5 ] = a * e;
  2742. te[ 9 ] = - b * e;
  2743. te[ 2 ] = - d * e;
  2744. te[ 6 ] = ad * f + bc;
  2745. te[ 10 ] = ac - bd * f;
  2746. } else if ( euler.order === 'XZY' ) {
  2747. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2748. te[ 0 ] = c * e;
  2749. te[ 4 ] = - f;
  2750. te[ 8 ] = d * e;
  2751. te[ 1 ] = ac * f + bd;
  2752. te[ 5 ] = a * e;
  2753. te[ 9 ] = ad * f - bc;
  2754. te[ 2 ] = bc * f - ad;
  2755. te[ 6 ] = b * e;
  2756. te[ 10 ] = bd * f + ac;
  2757. }
  2758. // last column
  2759. te[ 3 ] = 0;
  2760. te[ 7 ] = 0;
  2761. te[ 11 ] = 0;
  2762. // bottom row
  2763. te[ 12 ] = 0;
  2764. te[ 13 ] = 0;
  2765. te[ 14 ] = 0;
  2766. te[ 15 ] = 1;
  2767. return this;
  2768. },
  2769. setRotationFromQuaternion: function ( q ) {
  2770. THREE.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  2771. return this.makeRotationFromQuaternion( q );
  2772. },
  2773. makeRotationFromQuaternion: function ( q ) {
  2774. var te = this.elements;
  2775. var x = q.x, y = q.y, z = q.z, w = q.w;
  2776. var x2 = x + x, y2 = y + y, z2 = z + z;
  2777. var xx = x * x2, xy = x * y2, xz = x * z2;
  2778. var yy = y * y2, yz = y * z2, zz = z * z2;
  2779. var wx = w * x2, wy = w * y2, wz = w * z2;
  2780. te[ 0 ] = 1 - ( yy + zz );
  2781. te[ 4 ] = xy - wz;
  2782. te[ 8 ] = xz + wy;
  2783. te[ 1 ] = xy + wz;
  2784. te[ 5 ] = 1 - ( xx + zz );
  2785. te[ 9 ] = yz - wx;
  2786. te[ 2 ] = xz - wy;
  2787. te[ 6 ] = yz + wx;
  2788. te[ 10 ] = 1 - ( xx + yy );
  2789. // last column
  2790. te[ 3 ] = 0;
  2791. te[ 7 ] = 0;
  2792. te[ 11 ] = 0;
  2793. // bottom row
  2794. te[ 12 ] = 0;
  2795. te[ 13 ] = 0;
  2796. te[ 14 ] = 0;
  2797. te[ 15 ] = 1;
  2798. return this;
  2799. },
  2800. lookAt: function () {
  2801. var x = new THREE.Vector3();
  2802. var y = new THREE.Vector3();
  2803. var z = new THREE.Vector3();
  2804. return function ( eye, target, up ) {
  2805. var te = this.elements;
  2806. z.subVectors( eye, target ).normalize();
  2807. if ( z.length() === 0 ) {
  2808. z.z = 1;
  2809. }
  2810. x.crossVectors( up, z ).normalize();
  2811. if ( x.length() === 0 ) {
  2812. z.x += 0.0001;
  2813. x.crossVectors( up, z ).normalize();
  2814. }
  2815. y.crossVectors( z, x );
  2816. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  2817. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  2818. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  2819. return this;
  2820. };
  2821. }(),
  2822. multiply: function ( m, n ) {
  2823. if ( n !== undefined ) {
  2824. THREE.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2825. return this.multiplyMatrices( m, n );
  2826. }
  2827. return this.multiplyMatrices( this, m );
  2828. },
  2829. multiplyMatrices: function ( a, b ) {
  2830. var ae = a.elements;
  2831. var be = b.elements;
  2832. var te = this.elements;
  2833. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  2834. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  2835. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  2836. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  2837. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  2838. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  2839. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  2840. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  2841. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2842. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2843. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2844. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2845. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2846. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2847. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2848. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2849. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2850. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2851. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2852. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2853. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2854. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2855. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2856. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2857. return this;
  2858. },
  2859. multiplyToArray: function ( a, b, r ) {
  2860. var te = this.elements;
  2861. this.multiplyMatrices( a, b );
  2862. r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ];
  2863. r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ];
  2864. r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ];
  2865. r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ];
  2866. return this;
  2867. },
  2868. multiplyScalar: function ( s ) {
  2869. var te = this.elements;
  2870. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  2871. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  2872. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  2873. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  2874. return this;
  2875. },
  2876. multiplyVector3: function ( vector ) {
  2877. THREE.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2878. return vector.applyProjection( this );
  2879. },
  2880. multiplyVector4: function ( vector ) {
  2881. THREE.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2882. return vector.applyMatrix4( this );
  2883. },
  2884. multiplyVector3Array: function ( a ) {
  2885. THREE.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2886. return this.applyToVector3Array( a );
  2887. },
  2888. applyToVector3Array: function () {
  2889. var v1 = new THREE.Vector3();
  2890. return function ( array, offset, length ) {
  2891. if ( offset === undefined ) offset = 0;
  2892. if ( length === undefined ) length = array.length;
  2893. for ( var i = 0, j = offset, il; i < length; i += 3, j += 3 ) {
  2894. v1.x = array[ j ];
  2895. v1.y = array[ j + 1 ];
  2896. v1.z = array[ j + 2 ];
  2897. v1.applyMatrix4( this );
  2898. array[ j ] = v1.x;
  2899. array[ j + 1 ] = v1.y;
  2900. array[ j + 2 ] = v1.z;
  2901. }
  2902. return array;
  2903. };
  2904. }(),
  2905. rotateAxis: function ( v ) {
  2906. THREE.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2907. v.transformDirection( this );
  2908. },
  2909. crossVector: function ( vector ) {
  2910. THREE.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2911. return vector.applyMatrix4( this );
  2912. },
  2913. determinant: function () {
  2914. var te = this.elements;
  2915. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  2916. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  2917. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  2918. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  2919. //TODO: make this more efficient
  2920. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2921. return (
  2922. n41 * (
  2923. + n14 * n23 * n32
  2924. - n13 * n24 * n32
  2925. - n14 * n22 * n33
  2926. + n12 * n24 * n33
  2927. + n13 * n22 * n34
  2928. - n12 * n23 * n34
  2929. ) +
  2930. n42 * (
  2931. + n11 * n23 * n34
  2932. - n11 * n24 * n33
  2933. + n14 * n21 * n33
  2934. - n13 * n21 * n34
  2935. + n13 * n24 * n31
  2936. - n14 * n23 * n31
  2937. ) +
  2938. n43 * (
  2939. + n11 * n24 * n32
  2940. - n11 * n22 * n34
  2941. - n14 * n21 * n32
  2942. + n12 * n21 * n34
  2943. + n14 * n22 * n31
  2944. - n12 * n24 * n31
  2945. ) +
  2946. n44 * (
  2947. - n13 * n22 * n31
  2948. - n11 * n23 * n32
  2949. + n11 * n22 * n33
  2950. + n13 * n21 * n32
  2951. - n12 * n21 * n33
  2952. + n12 * n23 * n31
  2953. )
  2954. );
  2955. },
  2956. transpose: function () {
  2957. var te = this.elements;
  2958. var tmp;
  2959. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  2960. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  2961. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  2962. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  2963. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  2964. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  2965. return this;
  2966. },
  2967. flattenToArrayOffset: function ( array, offset ) {
  2968. var te = this.elements;
  2969. array[ offset ] = te[ 0 ];
  2970. array[ offset + 1 ] = te[ 1 ];
  2971. array[ offset + 2 ] = te[ 2 ];
  2972. array[ offset + 3 ] = te[ 3 ];
  2973. array[ offset + 4 ] = te[ 4 ];
  2974. array[ offset + 5 ] = te[ 5 ];
  2975. array[ offset + 6 ] = te[ 6 ];
  2976. array[ offset + 7 ] = te[ 7 ];
  2977. array[ offset + 8 ] = te[ 8 ];
  2978. array[ offset + 9 ] = te[ 9 ];
  2979. array[ offset + 10 ] = te[ 10 ];
  2980. array[ offset + 11 ] = te[ 11 ];
  2981. array[ offset + 12 ] = te[ 12 ];
  2982. array[ offset + 13 ] = te[ 13 ];
  2983. array[ offset + 14 ] = te[ 14 ];
  2984. array[ offset + 15 ] = te[ 15 ];
  2985. return array;
  2986. },
  2987. getPosition: function () {
  2988. var v1 = new THREE.Vector3();
  2989. return function () {
  2990. THREE.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  2991. var te = this.elements;
  2992. return v1.set( te[ 12 ], te[ 13 ], te[ 14 ] );
  2993. };
  2994. }(),
  2995. setPosition: function ( v ) {
  2996. var te = this.elements;
  2997. te[ 12 ] = v.x;
  2998. te[ 13 ] = v.y;
  2999. te[ 14 ] = v.z;
  3000. return this;
  3001. },
  3002. getInverse: function ( m, throwOnInvertible ) {
  3003. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3004. var te = this.elements;
  3005. var me = m.elements;
  3006. var n11 = me[ 0 ], n12 = me[ 4 ], n13 = me[ 8 ], n14 = me[ 12 ];
  3007. var n21 = me[ 1 ], n22 = me[ 5 ], n23 = me[ 9 ], n24 = me[ 13 ];
  3008. var n31 = me[ 2 ], n32 = me[ 6 ], n33 = me[ 10 ], n34 = me[ 14 ];
  3009. var n41 = me[ 3 ], n42 = me[ 7 ], n43 = me[ 11 ], n44 = me[ 15 ];
  3010. te[ 0 ] = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44;
  3011. te[ 4 ] = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44;
  3012. te[ 8 ] = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44;
  3013. te[ 12 ] = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3014. te[ 1 ] = n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44;
  3015. te[ 5 ] = n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44;
  3016. te[ 9 ] = n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44;
  3017. te[ 13 ] = n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34;
  3018. te[ 2 ] = n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44;
  3019. te[ 6 ] = n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44;
  3020. te[ 10 ] = n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44;
  3021. te[ 14 ] = n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34;
  3022. te[ 3 ] = n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43;
  3023. te[ 7 ] = n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43;
  3024. te[ 11 ] = n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43;
  3025. te[ 15 ] = n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33;
  3026. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  3027. if ( det == 0 ) {
  3028. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  3029. if ( throwOnInvertible || false ) {
  3030. throw new Error( msg );
  3031. } else {
  3032. THREE.warn( msg );
  3033. }
  3034. this.identity();
  3035. return this;
  3036. }
  3037. this.multiplyScalar( 1 / det );
  3038. return this;
  3039. },
  3040. translate: function ( v ) {
  3041. THREE.error( 'THREE.Matrix4: .translate() has been removed.' );
  3042. },
  3043. rotateX: function ( angle ) {
  3044. THREE.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  3045. },
  3046. rotateY: function ( angle ) {
  3047. THREE.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  3048. },
  3049. rotateZ: function ( angle ) {
  3050. THREE.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  3051. },
  3052. rotateByAxis: function ( axis, angle ) {
  3053. THREE.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  3054. },
  3055. scale: function ( v ) {
  3056. var te = this.elements;
  3057. var x = v.x, y = v.y, z = v.z;
  3058. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3059. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3060. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3061. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3062. return this;
  3063. },
  3064. getMaxScaleOnAxis: function () {
  3065. var te = this.elements;
  3066. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3067. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3068. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3069. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  3070. },
  3071. makeTranslation: function ( x, y, z ) {
  3072. this.set(
  3073. 1, 0, 0, x,
  3074. 0, 1, 0, y,
  3075. 0, 0, 1, z,
  3076. 0, 0, 0, 1
  3077. );
  3078. return this;
  3079. },
  3080. makeRotationX: function ( theta ) {
  3081. var c = Math.cos( theta ), s = Math.sin( theta );
  3082. this.set(
  3083. 1, 0, 0, 0,
  3084. 0, c, - s, 0,
  3085. 0, s, c, 0,
  3086. 0, 0, 0, 1
  3087. );
  3088. return this;
  3089. },
  3090. makeRotationY: function ( theta ) {
  3091. var c = Math.cos( theta ), s = Math.sin( theta );
  3092. this.set(
  3093. c, 0, s, 0,
  3094. 0, 1, 0, 0,
  3095. - s, 0, c, 0,
  3096. 0, 0, 0, 1
  3097. );
  3098. return this;
  3099. },
  3100. makeRotationZ: function ( theta ) {
  3101. var c = Math.cos( theta ), s = Math.sin( theta );
  3102. this.set(
  3103. c, - s, 0, 0,
  3104. s, c, 0, 0,
  3105. 0, 0, 1, 0,
  3106. 0, 0, 0, 1
  3107. );
  3108. return this;
  3109. },
  3110. makeRotationAxis: function ( axis, angle ) {
  3111. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3112. var c = Math.cos( angle );
  3113. var s = Math.sin( angle );
  3114. var t = 1 - c;
  3115. var x = axis.x, y = axis.y, z = axis.z;
  3116. var tx = t * x, ty = t * y;
  3117. this.set(
  3118. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3119. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3120. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3121. 0, 0, 0, 1
  3122. );
  3123. return this;
  3124. },
  3125. makeScale: function ( x, y, z ) {
  3126. this.set(
  3127. x, 0, 0, 0,
  3128. 0, y, 0, 0,
  3129. 0, 0, z, 0,
  3130. 0, 0, 0, 1
  3131. );
  3132. return this;
  3133. },
  3134. compose: function ( position, quaternion, scale ) {
  3135. this.makeRotationFromQuaternion( quaternion );
  3136. this.scale( scale );
  3137. this.setPosition( position );
  3138. return this;
  3139. },
  3140. decompose: function () {
  3141. var vector = new THREE.Vector3();
  3142. var matrix = new THREE.Matrix4();
  3143. return function ( position, quaternion, scale ) {
  3144. var te = this.elements;
  3145. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3146. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3147. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3148. // if determine is negative, we need to invert one scale
  3149. var det = this.determinant();
  3150. if ( det < 0 ) {
  3151. sx = - sx;
  3152. }
  3153. position.x = te[ 12 ];
  3154. position.y = te[ 13 ];
  3155. position.z = te[ 14 ];
  3156. // scale the rotation part
  3157. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  3158. var invSX = 1 / sx;
  3159. var invSY = 1 / sy;
  3160. var invSZ = 1 / sz;
  3161. matrix.elements[ 0 ] *= invSX;
  3162. matrix.elements[ 1 ] *= invSX;
  3163. matrix.elements[ 2 ] *= invSX;
  3164. matrix.elements[ 4 ] *= invSY;
  3165. matrix.elements[ 5 ] *= invSY;
  3166. matrix.elements[ 6 ] *= invSY;
  3167. matrix.elements[ 8 ] *= invSZ;
  3168. matrix.elements[ 9 ] *= invSZ;
  3169. matrix.elements[ 10 ] *= invSZ;
  3170. quaternion.setFromRotationMatrix( matrix );
  3171. scale.x = sx;
  3172. scale.y = sy;
  3173. scale.z = sz;
  3174. return this;
  3175. };
  3176. }(),
  3177. makeFrustum: function ( left, right, bottom, top, near, far ) {
  3178. var te = this.elements;
  3179. var x = 2 * near / ( right - left );
  3180. var y = 2 * near / ( top - bottom );
  3181. var a = ( right + left ) / ( right - left );
  3182. var b = ( top + bottom ) / ( top - bottom );
  3183. var c = - ( far + near ) / ( far - near );
  3184. var d = - 2 * far * near / ( far - near );
  3185. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3186. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3187. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3188. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3189. return this;
  3190. },
  3191. makePerspective: function ( fov, aspect, near, far ) {
  3192. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  3193. var ymin = - ymax;
  3194. var xmin = ymin * aspect;
  3195. var xmax = ymax * aspect;
  3196. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  3197. },
  3198. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  3199. var te = this.elements;
  3200. var w = right - left;
  3201. var h = top - bottom;
  3202. var p = far - near;
  3203. var x = ( right + left ) / w;
  3204. var y = ( top + bottom ) / h;
  3205. var z = ( far + near ) / p;
  3206. te[ 0 ] = 2 / w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3207. te[ 1 ] = 0; te[ 5 ] = 2 / h; te[ 9 ] = 0; te[ 13 ] = - y;
  3208. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 / p; te[ 14 ] = - z;
  3209. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3210. return this;
  3211. },
  3212. fromArray: function ( array ) {
  3213. this.elements.set( array );
  3214. return this;
  3215. },
  3216. toArray: function () {
  3217. var te = this.elements;
  3218. return [
  3219. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  3220. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  3221. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  3222. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  3223. ];
  3224. },
  3225. clone: function () {
  3226. return new THREE.Matrix4().fromArray( this.elements );
  3227. }
  3228. };
  3229. // File:src/math/Ray.js
  3230. /**
  3231. * @author bhouston / http://exocortex.com
  3232. */
  3233. THREE.Ray = function ( origin, direction ) {
  3234. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  3235. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  3236. };
  3237. THREE.Ray.prototype = {
  3238. constructor: THREE.Ray,
  3239. set: function ( origin, direction ) {
  3240. this.origin.copy( origin );
  3241. this.direction.copy( direction );
  3242. return this;
  3243. },
  3244. copy: function ( ray ) {
  3245. this.origin.copy( ray.origin );
  3246. this.direction.copy( ray.direction );
  3247. return this;
  3248. },
  3249. at: function ( t, optionalTarget ) {
  3250. var result = optionalTarget || new THREE.Vector3();
  3251. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3252. },
  3253. recast: function () {
  3254. var v1 = new THREE.Vector3();
  3255. return function ( t ) {
  3256. this.origin.copy( this.at( t, v1 ) );
  3257. return this;
  3258. };
  3259. }(),
  3260. closestPointToPoint: function ( point, optionalTarget ) {
  3261. var result = optionalTarget || new THREE.Vector3();
  3262. result.subVectors( point, this.origin );
  3263. var directionDistance = result.dot( this.direction );
  3264. if ( directionDistance < 0 ) {
  3265. return result.copy( this.origin );
  3266. }
  3267. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3268. },
  3269. distanceToPoint: function () {
  3270. var v1 = new THREE.Vector3();
  3271. return function ( point ) {
  3272. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3273. // point behind the ray
  3274. if ( directionDistance < 0 ) {
  3275. return this.origin.distanceTo( point );
  3276. }
  3277. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3278. return v1.distanceTo( point );
  3279. };
  3280. }(),
  3281. distanceSqToSegment: function () {
  3282. var segCenter = new THREE.Vector3();
  3283. var segDir = new THREE.Vector3();
  3284. var diff = new THREE.Vector3();
  3285. return function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3286. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3287. // It returns the min distance between the ray and the segment
  3288. // defined by v0 and v1
  3289. // It can also set two optional targets :
  3290. // - The closest point on the ray
  3291. // - The closest point on the segment
  3292. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3293. segDir.copy( v1 ).sub( v0 ).normalize();
  3294. diff.copy( this.origin ).sub( segCenter );
  3295. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3296. var a01 = - this.direction.dot( segDir );
  3297. var b0 = diff.dot( this.direction );
  3298. var b1 = - diff.dot( segDir );
  3299. var c = diff.lengthSq();
  3300. var det = Math.abs( 1 - a01 * a01 );
  3301. var s0, s1, sqrDist, extDet;
  3302. if ( det > 0 ) {
  3303. // The ray and segment are not parallel.
  3304. s0 = a01 * b1 - b0;
  3305. s1 = a01 * b0 - b1;
  3306. extDet = segExtent * det;
  3307. if ( s0 >= 0 ) {
  3308. if ( s1 >= - extDet ) {
  3309. if ( s1 <= extDet ) {
  3310. // region 0
  3311. // Minimum at interior points of ray and segment.
  3312. var invDet = 1 / det;
  3313. s0 *= invDet;
  3314. s1 *= invDet;
  3315. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3316. } else {
  3317. // region 1
  3318. s1 = segExtent;
  3319. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3320. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3321. }
  3322. } else {
  3323. // region 5
  3324. s1 = - segExtent;
  3325. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3326. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3327. }
  3328. } else {
  3329. if ( s1 <= - extDet ) {
  3330. // region 4
  3331. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3332. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3333. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3334. } else if ( s1 <= extDet ) {
  3335. // region 3
  3336. s0 = 0;
  3337. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3338. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3339. } else {
  3340. // region 2
  3341. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3342. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3343. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3344. }
  3345. }
  3346. } else {
  3347. // Ray and segment are parallel.
  3348. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3349. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3350. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3351. }
  3352. if ( optionalPointOnRay ) {
  3353. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  3354. }
  3355. if ( optionalPointOnSegment ) {
  3356. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  3357. }
  3358. return sqrDist;
  3359. };
  3360. }(),
  3361. isIntersectionSphere: function ( sphere ) {
  3362. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3363. },
  3364. intersectSphere: function () {
  3365. // from http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-sphere-intersection/
  3366. var v1 = new THREE.Vector3();
  3367. return function ( sphere, optionalTarget ) {
  3368. v1.subVectors( sphere.center, this.origin );
  3369. var tca = v1.dot( this.direction );
  3370. var d2 = v1.dot( v1 ) - tca * tca;
  3371. var radius2 = sphere.radius * sphere.radius;
  3372. if ( d2 > radius2 ) return null;
  3373. var thc = Math.sqrt( radius2 - d2 );
  3374. // t0 = first intersect point - entrance on front of sphere
  3375. var t0 = tca - thc;
  3376. // t1 = second intersect point - exit point on back of sphere
  3377. var t1 = tca + thc;
  3378. // test to see if both t0 and t1 are behind the ray - if so, return null
  3379. if ( t0 < 0 && t1 < 0 ) return null;
  3380. // test to see if t0 is behind the ray:
  3381. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3382. // in order to always return an intersect point that is in front of the ray.
  3383. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  3384. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3385. return this.at( t0, optionalTarget );
  3386. }
  3387. }(),
  3388. isIntersectionPlane: function ( plane ) {
  3389. // check if the ray lies on the plane first
  3390. var distToPoint = plane.distanceToPoint( this.origin );
  3391. if ( distToPoint === 0 ) {
  3392. return true;
  3393. }
  3394. var denominator = plane.normal.dot( this.direction );
  3395. if ( denominator * distToPoint < 0 ) {
  3396. return true;
  3397. }
  3398. // ray origin is behind the plane (and is pointing behind it)
  3399. return false;
  3400. },
  3401. distanceToPlane: function ( plane ) {
  3402. var denominator = plane.normal.dot( this.direction );
  3403. if ( denominator == 0 ) {
  3404. // line is coplanar, return origin
  3405. if ( plane.distanceToPoint( this.origin ) == 0 ) {
  3406. return 0;
  3407. }
  3408. // Null is preferable to undefined since undefined means.... it is undefined
  3409. return null;
  3410. }
  3411. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3412. // Return if the ray never intersects the plane
  3413. return t >= 0 ? t : null;
  3414. },
  3415. intersectPlane: function ( plane, optionalTarget ) {
  3416. var t = this.distanceToPlane( plane );
  3417. if ( t === null ) {
  3418. return null;
  3419. }
  3420. return this.at( t, optionalTarget );
  3421. },
  3422. isIntersectionBox: function () {
  3423. var v = new THREE.Vector3();
  3424. return function ( box ) {
  3425. return this.intersectBox( box, v ) !== null;
  3426. };
  3427. }(),
  3428. intersectBox: function ( box , optionalTarget ) {
  3429. // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
  3430. var tmin,tmax,tymin,tymax,tzmin,tzmax;
  3431. var invdirx = 1 / this.direction.x,
  3432. invdiry = 1 / this.direction.y,
  3433. invdirz = 1 / this.direction.z;
  3434. var origin = this.origin;
  3435. if ( invdirx >= 0 ) {
  3436. tmin = ( box.min.x - origin.x ) * invdirx;
  3437. tmax = ( box.max.x - origin.x ) * invdirx;
  3438. } else {
  3439. tmin = ( box.max.x - origin.x ) * invdirx;
  3440. tmax = ( box.min.x - origin.x ) * invdirx;
  3441. }
  3442. if ( invdiry >= 0 ) {
  3443. tymin = ( box.min.y - origin.y ) * invdiry;
  3444. tymax = ( box.max.y - origin.y ) * invdiry;
  3445. } else {
  3446. tymin = ( box.max.y - origin.y ) * invdiry;
  3447. tymax = ( box.min.y - origin.y ) * invdiry;
  3448. }
  3449. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3450. // These lines also handle the case where tmin or tmax is NaN
  3451. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3452. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3453. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3454. if ( invdirz >= 0 ) {
  3455. tzmin = ( box.min.z - origin.z ) * invdirz;
  3456. tzmax = ( box.max.z - origin.z ) * invdirz;
  3457. } else {
  3458. tzmin = ( box.max.z - origin.z ) * invdirz;
  3459. tzmax = ( box.min.z - origin.z ) * invdirz;
  3460. }
  3461. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3462. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3463. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3464. //return point closest to the ray (positive side)
  3465. if ( tmax < 0 ) return null;
  3466. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3467. },
  3468. intersectTriangle: function () {
  3469. // Compute the offset origin, edges, and normal.
  3470. var diff = new THREE.Vector3();
  3471. var edge1 = new THREE.Vector3();
  3472. var edge2 = new THREE.Vector3();
  3473. var normal = new THREE.Vector3();
  3474. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3475. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3476. edge1.subVectors( b, a );
  3477. edge2.subVectors( c, a );
  3478. normal.crossVectors( edge1, edge2 );
  3479. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3480. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3481. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3482. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3483. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3484. var DdN = this.direction.dot( normal );
  3485. var sign;
  3486. if ( DdN > 0 ) {
  3487. if ( backfaceCulling ) return null;
  3488. sign = 1;
  3489. } else if ( DdN < 0 ) {
  3490. sign = - 1;
  3491. DdN = - DdN;
  3492. } else {
  3493. return null;
  3494. }
  3495. diff.subVectors( this.origin, a );
  3496. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3497. // b1 < 0, no intersection
  3498. if ( DdQxE2 < 0 ) {
  3499. return null;
  3500. }
  3501. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3502. // b2 < 0, no intersection
  3503. if ( DdE1xQ < 0 ) {
  3504. return null;
  3505. }
  3506. // b1+b2 > 1, no intersection
  3507. if ( DdQxE2 + DdE1xQ > DdN ) {
  3508. return null;
  3509. }
  3510. // Line intersects triangle, check if ray does.
  3511. var QdN = - sign * diff.dot( normal );
  3512. // t < 0, no intersection
  3513. if ( QdN < 0 ) {
  3514. return null;
  3515. }
  3516. // Ray intersects triangle.
  3517. return this.at( QdN / DdN, optionalTarget );
  3518. };
  3519. }(),
  3520. applyMatrix4: function ( matrix4 ) {
  3521. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3522. this.origin.applyMatrix4( matrix4 );
  3523. this.direction.sub( this.origin );
  3524. this.direction.normalize();
  3525. return this;
  3526. },
  3527. equals: function ( ray ) {
  3528. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3529. },
  3530. clone: function () {
  3531. return new THREE.Ray().copy( this );
  3532. }
  3533. };
  3534. // File:src/math/Sphere.js
  3535. /**
  3536. * @author bhouston / http://exocortex.com
  3537. * @author mrdoob / http://mrdoob.com/
  3538. */
  3539. THREE.Sphere = function ( center, radius ) {
  3540. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3541. this.radius = ( radius !== undefined ) ? radius : 0;
  3542. };
  3543. THREE.Sphere.prototype = {
  3544. constructor: THREE.Sphere,
  3545. set: function ( center, radius ) {
  3546. this.center.copy( center );
  3547. this.radius = radius;
  3548. return this;
  3549. },
  3550. setFromPoints: function () {
  3551. var box = new THREE.Box3();
  3552. return function ( points, optionalCenter ) {
  3553. var center = this.center;
  3554. if ( optionalCenter !== undefined ) {
  3555. center.copy( optionalCenter );
  3556. } else {
  3557. box.setFromPoints( points ).center( center );
  3558. }
  3559. var maxRadiusSq = 0;
  3560. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3561. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3562. }
  3563. this.radius = Math.sqrt( maxRadiusSq );
  3564. return this;
  3565. };
  3566. }(),
  3567. copy: function ( sphere ) {
  3568. this.center.copy( sphere.center );
  3569. this.radius = sphere.radius;
  3570. return this;
  3571. },
  3572. empty: function () {
  3573. return ( this.radius <= 0 );
  3574. },
  3575. containsPoint: function ( point ) {
  3576. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3577. },
  3578. distanceToPoint: function ( point ) {
  3579. return ( point.distanceTo( this.center ) - this.radius );
  3580. },
  3581. intersectsSphere: function ( sphere ) {
  3582. var radiusSum = this.radius + sphere.radius;
  3583. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3584. },
  3585. clampPoint: function ( point, optionalTarget ) {
  3586. var deltaLengthSq = this.center.distanceToSquared( point );
  3587. var result = optionalTarget || new THREE.Vector3();
  3588. result.copy( point );
  3589. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3590. result.sub( this.center ).normalize();
  3591. result.multiplyScalar( this.radius ).add( this.center );
  3592. }
  3593. return result;
  3594. },
  3595. getBoundingBox: function ( optionalTarget ) {
  3596. var box = optionalTarget || new THREE.Box3();
  3597. box.set( this.center, this.center );
  3598. box.expandByScalar( this.radius );
  3599. return box;
  3600. },
  3601. applyMatrix4: function ( matrix ) {
  3602. this.center.applyMatrix4( matrix );
  3603. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3604. return this;
  3605. },
  3606. translate: function ( offset ) {
  3607. this.center.add( offset );
  3608. return this;
  3609. },
  3610. equals: function ( sphere ) {
  3611. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3612. },
  3613. clone: function () {
  3614. return new THREE.Sphere().copy( this );
  3615. }
  3616. };
  3617. // File:src/math/Frustum.js
  3618. /**
  3619. * @author mrdoob / http://mrdoob.com/
  3620. * @author alteredq / http://alteredqualia.com/
  3621. * @author bhouston / http://exocortex.com
  3622. */
  3623. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3624. this.planes = [
  3625. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3626. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3627. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3628. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3629. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3630. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3631. ];
  3632. };
  3633. THREE.Frustum.prototype = {
  3634. constructor: THREE.Frustum,
  3635. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3636. var planes = this.planes;
  3637. planes[ 0 ].copy( p0 );
  3638. planes[ 1 ].copy( p1 );
  3639. planes[ 2 ].copy( p2 );
  3640. planes[ 3 ].copy( p3 );
  3641. planes[ 4 ].copy( p4 );
  3642. planes[ 5 ].copy( p5 );
  3643. return this;
  3644. },
  3645. copy: function ( frustum ) {
  3646. var planes = this.planes;
  3647. for ( var i = 0; i < 6; i ++ ) {
  3648. planes[ i ].copy( frustum.planes[ i ] );
  3649. }
  3650. return this;
  3651. },
  3652. setFromMatrix: function ( m ) {
  3653. var planes = this.planes;
  3654. var me = m.elements;
  3655. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  3656. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  3657. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  3658. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  3659. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3660. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3661. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3662. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3663. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3664. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3665. return this;
  3666. },
  3667. intersectsObject: function () {
  3668. var sphere = new THREE.Sphere();
  3669. return function ( object ) {
  3670. var geometry = object.geometry;
  3671. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3672. sphere.copy( geometry.boundingSphere );
  3673. sphere.applyMatrix4( object.matrixWorld );
  3674. return this.intersectsSphere( sphere );
  3675. };
  3676. }(),
  3677. intersectsSphere: function ( sphere ) {
  3678. var planes = this.planes;
  3679. var center = sphere.center;
  3680. var negRadius = - sphere.radius;
  3681. for ( var i = 0; i < 6; i ++ ) {
  3682. var distance = planes[ i ].distanceToPoint( center );
  3683. if ( distance < negRadius ) {
  3684. return false;
  3685. }
  3686. }
  3687. return true;
  3688. },
  3689. intersectsBox: function () {
  3690. var p1 = new THREE.Vector3(),
  3691. p2 = new THREE.Vector3();
  3692. return function ( box ) {
  3693. var planes = this.planes;
  3694. for ( var i = 0; i < 6 ; i ++ ) {
  3695. var plane = planes[ i ];
  3696. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3697. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3698. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3699. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3700. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3701. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3702. var d1 = plane.distanceToPoint( p1 );
  3703. var d2 = plane.distanceToPoint( p2 );
  3704. // if both outside plane, no intersection
  3705. if ( d1 < 0 && d2 < 0 ) {
  3706. return false;
  3707. }
  3708. }
  3709. return true;
  3710. };
  3711. }(),
  3712. containsPoint: function ( point ) {
  3713. var planes = this.planes;
  3714. for ( var i = 0; i < 6; i ++ ) {
  3715. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3716. return false;
  3717. }
  3718. }
  3719. return true;
  3720. },
  3721. clone: function () {
  3722. return new THREE.Frustum().copy( this );
  3723. }
  3724. };
  3725. // File:src/math/Plane.js
  3726. /**
  3727. * @author bhouston / http://exocortex.com
  3728. */
  3729. THREE.Plane = function ( normal, constant ) {
  3730. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3731. this.constant = ( constant !== undefined ) ? constant : 0;
  3732. };
  3733. THREE.Plane.prototype = {
  3734. constructor: THREE.Plane,
  3735. set: function ( normal, constant ) {
  3736. this.normal.copy( normal );
  3737. this.constant = constant;
  3738. return this;
  3739. },
  3740. setComponents: function ( x, y, z, w ) {
  3741. this.normal.set( x, y, z );
  3742. this.constant = w;
  3743. return this;
  3744. },
  3745. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3746. this.normal.copy( normal );
  3747. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3748. return this;
  3749. },
  3750. setFromCoplanarPoints: function () {
  3751. var v1 = new THREE.Vector3();
  3752. var v2 = new THREE.Vector3();
  3753. return function ( a, b, c ) {
  3754. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3755. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3756. this.setFromNormalAndCoplanarPoint( normal, a );
  3757. return this;
  3758. };
  3759. }(),
  3760. copy: function ( plane ) {
  3761. this.normal.copy( plane.normal );
  3762. this.constant = plane.constant;
  3763. return this;
  3764. },
  3765. normalize: function () {
  3766. // Note: will lead to a divide by zero if the plane is invalid.
  3767. var inverseNormalLength = 1.0 / this.normal.length();
  3768. this.normal.multiplyScalar( inverseNormalLength );
  3769. this.constant *= inverseNormalLength;
  3770. return this;
  3771. },
  3772. negate: function () {
  3773. this.constant *= - 1;
  3774. this.normal.negate();
  3775. return this;
  3776. },
  3777. distanceToPoint: function ( point ) {
  3778. return this.normal.dot( point ) + this.constant;
  3779. },
  3780. distanceToSphere: function ( sphere ) {
  3781. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3782. },
  3783. projectPoint: function ( point, optionalTarget ) {
  3784. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3785. },
  3786. orthoPoint: function ( point, optionalTarget ) {
  3787. var perpendicularMagnitude = this.distanceToPoint( point );
  3788. var result = optionalTarget || new THREE.Vector3();
  3789. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3790. },
  3791. isIntersectionLine: function ( line ) {
  3792. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3793. var startSign = this.distanceToPoint( line.start );
  3794. var endSign = this.distanceToPoint( line.end );
  3795. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3796. },
  3797. intersectLine: function () {
  3798. var v1 = new THREE.Vector3();
  3799. return function ( line, optionalTarget ) {
  3800. var result = optionalTarget || new THREE.Vector3();
  3801. var direction = line.delta( v1 );
  3802. var denominator = this.normal.dot( direction );
  3803. if ( denominator == 0 ) {
  3804. // line is coplanar, return origin
  3805. if ( this.distanceToPoint( line.start ) == 0 ) {
  3806. return result.copy( line.start );
  3807. }
  3808. // Unsure if this is the correct method to handle this case.
  3809. return undefined;
  3810. }
  3811. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3812. if ( t < 0 || t > 1 ) {
  3813. return undefined;
  3814. }
  3815. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3816. };
  3817. }(),
  3818. coplanarPoint: function ( optionalTarget ) {
  3819. var result = optionalTarget || new THREE.Vector3();
  3820. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3821. },
  3822. applyMatrix4: function () {
  3823. var v1 = new THREE.Vector3();
  3824. var v2 = new THREE.Vector3();
  3825. var m1 = new THREE.Matrix3();
  3826. return function ( matrix, optionalNormalMatrix ) {
  3827. // compute new normal based on theory here:
  3828. // http://www.songho.ca/opengl/gl_normaltransform.html
  3829. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  3830. var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix );
  3831. var newCoplanarPoint = this.coplanarPoint( v2 );
  3832. newCoplanarPoint.applyMatrix4( matrix );
  3833. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3834. return this;
  3835. };
  3836. }(),
  3837. translate: function ( offset ) {
  3838. this.constant = this.constant - offset.dot( this.normal );
  3839. return this;
  3840. },
  3841. equals: function ( plane ) {
  3842. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3843. },
  3844. clone: function () {
  3845. return new THREE.Plane().copy( this );
  3846. }
  3847. };
  3848. // File:src/math/Math.js
  3849. /**
  3850. * @author alteredq / http://alteredqualia.com/
  3851. * @author mrdoob / http://mrdoob.com/
  3852. */
  3853. THREE.Math = {
  3854. generateUUID: function () {
  3855. // http://www.broofa.com/Tools/Math.uuid.htm
  3856. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  3857. var uuid = new Array( 36 );
  3858. var rnd = 0, r;
  3859. return function () {
  3860. for ( var i = 0; i < 36; i ++ ) {
  3861. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3862. uuid[ i ] = '-';
  3863. } else if ( i == 14 ) {
  3864. uuid[ i ] = '4';
  3865. } else {
  3866. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  3867. r = rnd & 0xf;
  3868. rnd = rnd >> 4;
  3869. uuid[ i ] = chars[ ( i == 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  3870. }
  3871. }
  3872. return uuid.join( '' );
  3873. };
  3874. }(),
  3875. // Clamp value to range <a, b>
  3876. clamp: function ( x, a, b ) {
  3877. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3878. },
  3879. // Clamp value to range <a, inf)
  3880. clampBottom: function ( x, a ) {
  3881. return x < a ? a : x;
  3882. },
  3883. // Linear mapping from range <a1, a2> to range <b1, b2>
  3884. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3885. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3886. },
  3887. // http://en.wikipedia.org/wiki/Smoothstep
  3888. smoothstep: function ( x, min, max ) {
  3889. if ( x <= min ) return 0;
  3890. if ( x >= max ) return 1;
  3891. x = ( x - min ) / ( max - min );
  3892. return x * x * ( 3 - 2 * x );
  3893. },
  3894. smootherstep: function ( x, min, max ) {
  3895. if ( x <= min ) return 0;
  3896. if ( x >= max ) return 1;
  3897. x = ( x - min ) / ( max - min );
  3898. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  3899. },
  3900. // Random float from <0, 1> with 16 bits of randomness
  3901. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3902. random16: function () {
  3903. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3904. },
  3905. // Random integer from <low, high> interval
  3906. randInt: function ( low, high ) {
  3907. return Math.floor( this.randFloat( low, high ) );
  3908. },
  3909. // Random float from <low, high> interval
  3910. randFloat: function ( low, high ) {
  3911. return low + Math.random() * ( high - low );
  3912. },
  3913. // Random float from <-range/2, range/2> interval
  3914. randFloatSpread: function ( range ) {
  3915. return range * ( 0.5 - Math.random() );
  3916. },
  3917. degToRad: function () {
  3918. var degreeToRadiansFactor = Math.PI / 180;
  3919. return function ( degrees ) {
  3920. return degrees * degreeToRadiansFactor;
  3921. };
  3922. }(),
  3923. radToDeg: function () {
  3924. var radianToDegreesFactor = 180 / Math.PI;
  3925. return function ( radians ) {
  3926. return radians * radianToDegreesFactor;
  3927. };
  3928. }(),
  3929. isPowerOfTwo: function ( value ) {
  3930. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  3931. },
  3932. nextPowerOfTwo: function ( value ) {
  3933. value --;
  3934. value |= value >> 1;
  3935. value |= value >> 2;
  3936. value |= value >> 4;
  3937. value |= value >> 8;
  3938. value |= value >> 16;
  3939. value ++;
  3940. return value;
  3941. }
  3942. };
  3943. // File:src/math/Spline.js
  3944. /**
  3945. * Spline from Tween.js, slightly optimized (and trashed)
  3946. * http://sole.github.com/tween.js/examples/05_spline.html
  3947. *
  3948. * @author mrdoob / http://mrdoob.com/
  3949. * @author alteredq / http://alteredqualia.com/
  3950. */
  3951. THREE.Spline = function ( points ) {
  3952. this.points = points;
  3953. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3954. point, intPoint, weight, w2, w3,
  3955. pa, pb, pc, pd;
  3956. this.initFromArray = function ( a ) {
  3957. this.points = [];
  3958. for ( var i = 0; i < a.length; i ++ ) {
  3959. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3960. }
  3961. };
  3962. this.getPoint = function ( k ) {
  3963. point = ( this.points.length - 1 ) * k;
  3964. intPoint = Math.floor( point );
  3965. weight = point - intPoint;
  3966. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3967. c[ 1 ] = intPoint;
  3968. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3969. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3970. pa = this.points[ c[ 0 ] ];
  3971. pb = this.points[ c[ 1 ] ];
  3972. pc = this.points[ c[ 2 ] ];
  3973. pd = this.points[ c[ 3 ] ];
  3974. w2 = weight * weight;
  3975. w3 = weight * w2;
  3976. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3977. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3978. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3979. return v3;
  3980. };
  3981. this.getControlPointsArray = function () {
  3982. var i, p, l = this.points.length,
  3983. coords = [];
  3984. for ( i = 0; i < l; i ++ ) {
  3985. p = this.points[ i ];
  3986. coords[ i ] = [ p.x, p.y, p.z ];
  3987. }
  3988. return coords;
  3989. };
  3990. // approximate length by summing linear segments
  3991. this.getLength = function ( nSubDivisions ) {
  3992. var i, index, nSamples, position,
  3993. point = 0, intPoint = 0, oldIntPoint = 0,
  3994. oldPosition = new THREE.Vector3(),
  3995. tmpVec = new THREE.Vector3(),
  3996. chunkLengths = [],
  3997. totalLength = 0;
  3998. // first point has 0 length
  3999. chunkLengths[ 0 ] = 0;
  4000. if ( ! nSubDivisions ) nSubDivisions = 100;
  4001. nSamples = this.points.length * nSubDivisions;
  4002. oldPosition.copy( this.points[ 0 ] );
  4003. for ( i = 1; i < nSamples; i ++ ) {
  4004. index = i / nSamples;
  4005. position = this.getPoint( index );
  4006. tmpVec.copy( position );
  4007. totalLength += tmpVec.distanceTo( oldPosition );
  4008. oldPosition.copy( position );
  4009. point = ( this.points.length - 1 ) * index;
  4010. intPoint = Math.floor( point );
  4011. if ( intPoint != oldIntPoint ) {
  4012. chunkLengths[ intPoint ] = totalLength;
  4013. oldIntPoint = intPoint;
  4014. }
  4015. }
  4016. // last point ends with total length
  4017. chunkLengths[ chunkLengths.length ] = totalLength;
  4018. return { chunks: chunkLengths, total: totalLength };
  4019. };
  4020. this.reparametrizeByArcLength = function ( samplingCoef ) {
  4021. var i, j,
  4022. index, indexCurrent, indexNext,
  4023. linearDistance, realDistance,
  4024. sampling, position,
  4025. newpoints = [],
  4026. tmpVec = new THREE.Vector3(),
  4027. sl = this.getLength();
  4028. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  4029. for ( i = 1; i < this.points.length; i ++ ) {
  4030. //tmpVec.copy( this.points[ i - 1 ] );
  4031. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  4032. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  4033. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  4034. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  4035. indexNext = i / ( this.points.length - 1 );
  4036. for ( j = 1; j < sampling - 1; j ++ ) {
  4037. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  4038. position = this.getPoint( index );
  4039. newpoints.push( tmpVec.copy( position ).clone() );
  4040. }
  4041. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  4042. }
  4043. this.points = newpoints;
  4044. };
  4045. // Catmull-Rom
  4046. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  4047. var v0 = ( p2 - p0 ) * 0.5,
  4048. v1 = ( p3 - p1 ) * 0.5;
  4049. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  4050. };
  4051. };
  4052. // File:src/math/Triangle.js
  4053. /**
  4054. * @author bhouston / http://exocortex.com
  4055. * @author mrdoob / http://mrdoob.com/
  4056. */
  4057. THREE.Triangle = function ( a, b, c ) {
  4058. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  4059. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  4060. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  4061. };
  4062. THREE.Triangle.normal = function () {
  4063. var v0 = new THREE.Vector3();
  4064. return function ( a, b, c, optionalTarget ) {
  4065. var result = optionalTarget || new THREE.Vector3();
  4066. result.subVectors( c, b );
  4067. v0.subVectors( a, b );
  4068. result.cross( v0 );
  4069. var resultLengthSq = result.lengthSq();
  4070. if ( resultLengthSq > 0 ) {
  4071. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  4072. }
  4073. return result.set( 0, 0, 0 );
  4074. };
  4075. }();
  4076. // static/instance method to calculate barycoordinates
  4077. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4078. THREE.Triangle.barycoordFromPoint = function () {
  4079. var v0 = new THREE.Vector3();
  4080. var v1 = new THREE.Vector3();
  4081. var v2 = new THREE.Vector3();
  4082. return function ( point, a, b, c, optionalTarget ) {
  4083. v0.subVectors( c, a );
  4084. v1.subVectors( b, a );
  4085. v2.subVectors( point, a );
  4086. var dot00 = v0.dot( v0 );
  4087. var dot01 = v0.dot( v1 );
  4088. var dot02 = v0.dot( v2 );
  4089. var dot11 = v1.dot( v1 );
  4090. var dot12 = v1.dot( v2 );
  4091. var denom = ( dot00 * dot11 - dot01 * dot01 );
  4092. var result = optionalTarget || new THREE.Vector3();
  4093. // colinear or singular triangle
  4094. if ( denom == 0 ) {
  4095. // arbitrary location outside of triangle?
  4096. // not sure if this is the best idea, maybe should be returning undefined
  4097. return result.set( - 2, - 1, - 1 );
  4098. }
  4099. var invDenom = 1 / denom;
  4100. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4101. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4102. // barycoordinates must always sum to 1
  4103. return result.set( 1 - u - v, v, u );
  4104. };
  4105. }();
  4106. THREE.Triangle.containsPoint = function () {
  4107. var v1 = new THREE.Vector3();
  4108. return function ( point, a, b, c ) {
  4109. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  4110. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  4111. };
  4112. }();
  4113. THREE.Triangle.prototype = {
  4114. constructor: THREE.Triangle,
  4115. set: function ( a, b, c ) {
  4116. this.a.copy( a );
  4117. this.b.copy( b );
  4118. this.c.copy( c );
  4119. return this;
  4120. },
  4121. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  4122. this.a.copy( points[ i0 ] );
  4123. this.b.copy( points[ i1 ] );
  4124. this.c.copy( points[ i2 ] );
  4125. return this;
  4126. },
  4127. copy: function ( triangle ) {
  4128. this.a.copy( triangle.a );
  4129. this.b.copy( triangle.b );
  4130. this.c.copy( triangle.c );
  4131. return this;
  4132. },
  4133. area: function () {
  4134. var v0 = new THREE.Vector3();
  4135. var v1 = new THREE.Vector3();
  4136. return function () {
  4137. v0.subVectors( this.c, this.b );
  4138. v1.subVectors( this.a, this.b );
  4139. return v0.cross( v1 ).length() * 0.5;
  4140. };
  4141. }(),
  4142. midpoint: function ( optionalTarget ) {
  4143. var result = optionalTarget || new THREE.Vector3();
  4144. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4145. },
  4146. normal: function ( optionalTarget ) {
  4147. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  4148. },
  4149. plane: function ( optionalTarget ) {
  4150. var result = optionalTarget || new THREE.Plane();
  4151. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  4152. },
  4153. barycoordFromPoint: function ( point, optionalTarget ) {
  4154. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  4155. },
  4156. containsPoint: function ( point ) {
  4157. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  4158. },
  4159. equals: function ( triangle ) {
  4160. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4161. },
  4162. clone: function () {
  4163. return new THREE.Triangle().copy( this );
  4164. }
  4165. };
  4166. // File:src/core/Clock.js
  4167. /**
  4168. * @author alteredq / http://alteredqualia.com/
  4169. */
  4170. THREE.Clock = function ( autoStart ) {
  4171. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  4172. this.startTime = 0;
  4173. this.oldTime = 0;
  4174. this.elapsedTime = 0;
  4175. this.running = false;
  4176. };
  4177. THREE.Clock.prototype = {
  4178. constructor: THREE.Clock,
  4179. start: function () {
  4180. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  4181. ? self.performance.now()
  4182. : Date.now();
  4183. this.oldTime = this.startTime;
  4184. this.running = true;
  4185. },
  4186. stop: function () {
  4187. this.getElapsedTime();
  4188. this.running = false;
  4189. },
  4190. getElapsedTime: function () {
  4191. this.getDelta();
  4192. return this.elapsedTime;
  4193. },
  4194. getDelta: function () {
  4195. var diff = 0;
  4196. if ( this.autoStart && ! this.running ) {
  4197. this.start();
  4198. }
  4199. if ( this.running ) {
  4200. var newTime = self.performance !== undefined && self.performance.now !== undefined
  4201. ? self.performance.now()
  4202. : Date.now();
  4203. diff = 0.001 * ( newTime - this.oldTime );
  4204. this.oldTime = newTime;
  4205. this.elapsedTime += diff;
  4206. }
  4207. return diff;
  4208. }
  4209. };
  4210. // File:src/core/EventDispatcher.js
  4211. /**
  4212. * https://github.com/mrdoob/eventdispatcher.js/
  4213. */
  4214. THREE.EventDispatcher = function () {}
  4215. THREE.EventDispatcher.prototype = {
  4216. constructor: THREE.EventDispatcher,
  4217. apply: function ( object ) {
  4218. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  4219. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  4220. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  4221. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  4222. },
  4223. addEventListener: function ( type, listener ) {
  4224. if ( this._listeners === undefined ) this._listeners = {};
  4225. var listeners = this._listeners;
  4226. if ( listeners[ type ] === undefined ) {
  4227. listeners[ type ] = [];
  4228. }
  4229. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4230. listeners[ type ].push( listener );
  4231. }
  4232. },
  4233. hasEventListener: function ( type, listener ) {
  4234. if ( this._listeners === undefined ) return false;
  4235. var listeners = this._listeners;
  4236. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  4237. return true;
  4238. }
  4239. return false;
  4240. },
  4241. removeEventListener: function ( type, listener ) {
  4242. if ( this._listeners === undefined ) return;
  4243. var listeners = this._listeners;
  4244. var listenerArray = listeners[ type ];
  4245. if ( listenerArray !== undefined ) {
  4246. var index = listenerArray.indexOf( listener );
  4247. if ( index !== - 1 ) {
  4248. listenerArray.splice( index, 1 );
  4249. }
  4250. }
  4251. },
  4252. dispatchEvent: function ( event ) {
  4253. if ( this._listeners === undefined ) return;
  4254. var listeners = this._listeners;
  4255. var listenerArray = listeners[ event.type ];
  4256. if ( listenerArray !== undefined ) {
  4257. event.target = this;
  4258. var array = [];
  4259. var length = listenerArray.length;
  4260. for ( var i = 0; i < length; i ++ ) {
  4261. array[ i ] = listenerArray[ i ];
  4262. }
  4263. for ( var i = 0; i < length; i ++ ) {
  4264. array[ i ].call( this, event );
  4265. }
  4266. }
  4267. }
  4268. };
  4269. // File:src/core/Raycaster.js
  4270. /**
  4271. * @author mrdoob / http://mrdoob.com/
  4272. * @author bhouston / http://exocortex.com/
  4273. * @author stephomi / http://stephaneginier.com/
  4274. */
  4275. ( function ( THREE ) {
  4276. THREE.Raycaster = function ( origin, direction, near, far ) {
  4277. this.ray = new THREE.Ray( origin, direction );
  4278. // direction is assumed to be normalized (for accurate distance calculations)
  4279. this.near = near || 0;
  4280. this.far = far || Infinity;
  4281. this.params = {
  4282. Sprite: {},
  4283. Mesh: {},
  4284. PointCloud: { threshold: 1 },
  4285. LOD: {},
  4286. Line: {}
  4287. };
  4288. };
  4289. var descSort = function ( a, b ) {
  4290. return a.distance - b.distance;
  4291. };
  4292. var intersectObject = function ( object, raycaster, intersects, recursive ) {
  4293. object.raycast( raycaster, intersects );
  4294. if ( recursive === true ) {
  4295. var children = object.children;
  4296. for ( var i = 0, l = children.length; i < l; i ++ ) {
  4297. intersectObject( children[ i ], raycaster, intersects, true );
  4298. }
  4299. }
  4300. };
  4301. //
  4302. THREE.Raycaster.prototype = {
  4303. constructor: THREE.Raycaster,
  4304. precision: 0.0001,
  4305. linePrecision: 1,
  4306. set: function ( origin, direction ) {
  4307. // direction is assumed to be normalized (for accurate distance calculations)
  4308. this.ray.set( origin, direction );
  4309. },
  4310. setFromCamera: function ( coords, camera ) {
  4311. // camera is assumed _not_ to be a child of a transformed object
  4312. if ( camera instanceof THREE.PerspectiveCamera ) {
  4313. this.ray.origin.copy( camera.position );
  4314. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( camera.position ).normalize();
  4315. } else if ( camera instanceof THREE.OrthographicCamera ) {
  4316. this.ray.origin.set( coords.x, coords.y, - 1 ).unproject( camera );
  4317. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  4318. } else {
  4319. THREE.error( 'THREE.Raycaster: Unsupported camera type.' );
  4320. }
  4321. },
  4322. intersectObject: function ( object, recursive ) {
  4323. var intersects = [];
  4324. intersectObject( object, this, intersects, recursive );
  4325. intersects.sort( descSort );
  4326. return intersects;
  4327. },
  4328. intersectObjects: function ( objects, recursive ) {
  4329. var intersects = [];
  4330. if ( objects instanceof Array === false ) {
  4331. THREE.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  4332. return intersects;
  4333. }
  4334. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4335. intersectObject( objects[ i ], this, intersects, recursive );
  4336. }
  4337. intersects.sort( descSort );
  4338. return intersects;
  4339. }
  4340. };
  4341. }( THREE ) );
  4342. // File:src/core/Object3D.js
  4343. /**
  4344. * @author mrdoob / http://mrdoob.com/
  4345. * @author mikael emtinger / http://gomo.se/
  4346. * @author alteredq / http://alteredqualia.com/
  4347. * @author WestLangley / http://github.com/WestLangley
  4348. */
  4349. THREE.Object3D = function () {
  4350. Object.defineProperty( this, 'id', { value: THREE.Object3DIdCount ++ } );
  4351. this.uuid = THREE.Math.generateUUID();
  4352. this.name = '';
  4353. this.type = 'Object3D';
  4354. this.parent = undefined;
  4355. this.children = [];
  4356. this.up = THREE.Object3D.DefaultUp.clone();
  4357. var scope = this;
  4358. var position = new THREE.Vector3();
  4359. var rotation = new THREE.Euler();
  4360. var quaternion = new THREE.Quaternion();
  4361. var scale = new THREE.Vector3( 1, 1, 1 );
  4362. var onRotationChange = function () {
  4363. quaternion.setFromEuler( rotation, false );
  4364. };
  4365. var onQuaternionChange = function () {
  4366. rotation.setFromQuaternion( quaternion, undefined, false );
  4367. };
  4368. rotation.onChange( onRotationChange );
  4369. quaternion.onChange( onQuaternionChange );
  4370. Object.defineProperties( this, {
  4371. position: {
  4372. enumerable: true,
  4373. value: position
  4374. },
  4375. rotation: {
  4376. enumerable: true,
  4377. value: rotation
  4378. },
  4379. quaternion: {
  4380. enumerable: true,
  4381. value: quaternion
  4382. },
  4383. scale: {
  4384. enumerable: true,
  4385. value: scale
  4386. },
  4387. } );
  4388. this.rotationAutoUpdate = true;
  4389. this.matrix = new THREE.Matrix4();
  4390. this.matrixWorld = new THREE.Matrix4();
  4391. this.matrixAutoUpdate = true;
  4392. this.matrixWorldNeedsUpdate = false;
  4393. this.visible = true;
  4394. this.castShadow = false;
  4395. this.receiveShadow = false;
  4396. this.frustumCulled = true;
  4397. this.userData = {};
  4398. };
  4399. THREE.Object3D.DefaultUp = new THREE.Vector3( 0, 1, 0 );
  4400. THREE.Object3D.prototype = {
  4401. constructor: THREE.Object3D,
  4402. get eulerOrder () {
  4403. THREE.warn( 'THREE.Object3D: .eulerOrder has been moved to .rotation.order.' );
  4404. return this.rotation.order;
  4405. },
  4406. set eulerOrder ( value ) {
  4407. THREE.warn( 'THREE.Object3D: .eulerOrder has been moved to .rotation.order.' );
  4408. this.rotation.order = value;
  4409. },
  4410. get useQuaternion () {
  4411. THREE.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  4412. },
  4413. set useQuaternion ( value ) {
  4414. THREE.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  4415. },
  4416. applyMatrix: function ( matrix ) {
  4417. this.matrix.multiplyMatrices( matrix, this.matrix );
  4418. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4419. },
  4420. setRotationFromAxisAngle: function ( axis, angle ) {
  4421. // assumes axis is normalized
  4422. this.quaternion.setFromAxisAngle( axis, angle );
  4423. },
  4424. setRotationFromEuler: function ( euler ) {
  4425. this.quaternion.setFromEuler( euler, true );
  4426. },
  4427. setRotationFromMatrix: function ( m ) {
  4428. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4429. this.quaternion.setFromRotationMatrix( m );
  4430. },
  4431. setRotationFromQuaternion: function ( q ) {
  4432. // assumes q is normalized
  4433. this.quaternion.copy( q );
  4434. },
  4435. rotateOnAxis: function () {
  4436. // rotate object on axis in object space
  4437. // axis is assumed to be normalized
  4438. var q1 = new THREE.Quaternion();
  4439. return function ( axis, angle ) {
  4440. q1.setFromAxisAngle( axis, angle );
  4441. this.quaternion.multiply( q1 );
  4442. return this;
  4443. }
  4444. }(),
  4445. rotateX: function () {
  4446. var v1 = new THREE.Vector3( 1, 0, 0 );
  4447. return function ( angle ) {
  4448. return this.rotateOnAxis( v1, angle );
  4449. };
  4450. }(),
  4451. rotateY: function () {
  4452. var v1 = new THREE.Vector3( 0, 1, 0 );
  4453. return function ( angle ) {
  4454. return this.rotateOnAxis( v1, angle );
  4455. };
  4456. }(),
  4457. rotateZ: function () {
  4458. var v1 = new THREE.Vector3( 0, 0, 1 );
  4459. return function ( angle ) {
  4460. return this.rotateOnAxis( v1, angle );
  4461. };
  4462. }(),
  4463. translateOnAxis: function () {
  4464. // translate object by distance along axis in object space
  4465. // axis is assumed to be normalized
  4466. var v1 = new THREE.Vector3();
  4467. return function ( axis, distance ) {
  4468. v1.copy( axis ).applyQuaternion( this.quaternion );
  4469. this.position.add( v1.multiplyScalar( distance ) );
  4470. return this;
  4471. }
  4472. }(),
  4473. translate: function ( distance, axis ) {
  4474. THREE.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  4475. return this.translateOnAxis( axis, distance );
  4476. },
  4477. translateX: function () {
  4478. var v1 = new THREE.Vector3( 1, 0, 0 );
  4479. return function ( distance ) {
  4480. return this.translateOnAxis( v1, distance );
  4481. };
  4482. }(),
  4483. translateY: function () {
  4484. var v1 = new THREE.Vector3( 0, 1, 0 );
  4485. return function ( distance ) {
  4486. return this.translateOnAxis( v1, distance );
  4487. };
  4488. }(),
  4489. translateZ: function () {
  4490. var v1 = new THREE.Vector3( 0, 0, 1 );
  4491. return function ( distance ) {
  4492. return this.translateOnAxis( v1, distance );
  4493. };
  4494. }(),
  4495. localToWorld: function ( vector ) {
  4496. return vector.applyMatrix4( this.matrixWorld );
  4497. },
  4498. worldToLocal: function () {
  4499. var m1 = new THREE.Matrix4();
  4500. return function ( vector ) {
  4501. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4502. };
  4503. }(),
  4504. lookAt: function () {
  4505. // This routine does not support objects with rotated and/or translated parent(s)
  4506. var m1 = new THREE.Matrix4();
  4507. return function ( vector ) {
  4508. m1.lookAt( vector, this.position, this.up );
  4509. this.quaternion.setFromRotationMatrix( m1 );
  4510. };
  4511. }(),
  4512. add: function ( object ) {
  4513. if ( arguments.length > 1 ) {
  4514. for ( var i = 0; i < arguments.length; i++ ) {
  4515. this.add( arguments[ i ] );
  4516. }
  4517. return this;
  4518. };
  4519. if ( object === this ) {
  4520. THREE.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  4521. return this;
  4522. }
  4523. if ( object instanceof THREE.Object3D ) {
  4524. if ( object.parent !== undefined ) {
  4525. object.parent.remove( object );
  4526. }
  4527. object.parent = this;
  4528. object.dispatchEvent( { type: 'added' } );
  4529. this.children.push( object );
  4530. } else {
  4531. THREE.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  4532. }
  4533. return this;
  4534. },
  4535. remove: function ( object ) {
  4536. if ( arguments.length > 1 ) {
  4537. for ( var i = 0; i < arguments.length; i++ ) {
  4538. this.remove( arguments[ i ] );
  4539. }
  4540. };
  4541. var index = this.children.indexOf( object );
  4542. if ( index !== - 1 ) {
  4543. object.parent = undefined;
  4544. object.dispatchEvent( { type: 'removed' } );
  4545. this.children.splice( index, 1 );
  4546. }
  4547. },
  4548. getChildByName: function ( name ) {
  4549. THREE.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  4550. return this.getObjectByName( name );
  4551. },
  4552. getObjectById: function ( id ) {
  4553. return this.getObjectByProperty( 'id', id );
  4554. },
  4555. getObjectByName: function ( name ) {
  4556. return this.getObjectByProperty( 'name', name );
  4557. },
  4558. getObjectByProperty: function ( name, value ) {
  4559. if ( this[ name ] === value ) return this;
  4560. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4561. var child = this.children[ i ];
  4562. var object = child.getObjectByProperty( name, value );
  4563. if ( object !== undefined ) {
  4564. return object;
  4565. }
  4566. }
  4567. return undefined;
  4568. },
  4569. getWorldPosition: function ( optionalTarget ) {
  4570. var result = optionalTarget || new THREE.Vector3();
  4571. this.updateMatrixWorld( true );
  4572. return result.setFromMatrixPosition( this.matrixWorld );
  4573. },
  4574. getWorldQuaternion: function () {
  4575. var position = new THREE.Vector3();
  4576. var scale = new THREE.Vector3();
  4577. return function ( optionalTarget ) {
  4578. var result = optionalTarget || new THREE.Quaternion();
  4579. this.updateMatrixWorld( true );
  4580. this.matrixWorld.decompose( position, result, scale );
  4581. return result;
  4582. }
  4583. }(),
  4584. getWorldRotation: function () {
  4585. var quaternion = new THREE.Quaternion();
  4586. return function ( optionalTarget ) {
  4587. var result = optionalTarget || new THREE.Euler();
  4588. this.getWorldQuaternion( quaternion );
  4589. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  4590. }
  4591. }(),
  4592. getWorldScale: function () {
  4593. var position = new THREE.Vector3();
  4594. var quaternion = new THREE.Quaternion();
  4595. return function ( optionalTarget ) {
  4596. var result = optionalTarget || new THREE.Vector3();
  4597. this.updateMatrixWorld( true );
  4598. this.matrixWorld.decompose( position, quaternion, result );
  4599. return result;
  4600. }
  4601. }(),
  4602. getWorldDirection: function () {
  4603. var quaternion = new THREE.Quaternion();
  4604. return function ( optionalTarget ) {
  4605. var result = optionalTarget || new THREE.Vector3();
  4606. this.getWorldQuaternion( quaternion );
  4607. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  4608. }
  4609. }(),
  4610. raycast: function () {},
  4611. traverse: function ( callback ) {
  4612. callback( this );
  4613. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4614. this.children[ i ].traverse( callback );
  4615. }
  4616. },
  4617. traverseVisible: function ( callback ) {
  4618. if ( this.visible === false ) return;
  4619. callback( this );
  4620. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4621. this.children[ i ].traverseVisible( callback );
  4622. }
  4623. },
  4624. traverseAncestors: function ( callback ) {
  4625. if ( this.parent ) {
  4626. callback( this.parent );
  4627. this.parent.traverseAncestors( callback );
  4628. }
  4629. },
  4630. updateMatrix: function () {
  4631. this.matrix.compose( this.position, this.quaternion, this.scale );
  4632. this.matrixWorldNeedsUpdate = true;
  4633. },
  4634. updateMatrixWorld: function ( force ) {
  4635. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4636. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4637. if ( this.parent === undefined ) {
  4638. this.matrixWorld.copy( this.matrix );
  4639. } else {
  4640. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4641. }
  4642. this.matrixWorldNeedsUpdate = false;
  4643. force = true;
  4644. }
  4645. // update children
  4646. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4647. this.children[ i ].updateMatrixWorld( force );
  4648. }
  4649. },
  4650. toJSON: function () {
  4651. var output = {
  4652. metadata: {
  4653. version: 4.3,
  4654. type: 'Object',
  4655. generator: 'ObjectExporter'
  4656. }
  4657. };
  4658. //
  4659. var geometries = {};
  4660. var parseGeometry = function ( geometry ) {
  4661. if ( output.geometries === undefined ) {
  4662. output.geometries = [];
  4663. }
  4664. if ( geometries[ geometry.uuid ] === undefined ) {
  4665. var json = geometry.toJSON();
  4666. delete json.metadata;
  4667. geometries[ geometry.uuid ] = json;
  4668. output.geometries.push( json );
  4669. }
  4670. return geometry.uuid;
  4671. };
  4672. //
  4673. var materials = {};
  4674. var parseMaterial = function ( material ) {
  4675. if ( output.materials === undefined ) {
  4676. output.materials = [];
  4677. }
  4678. if ( materials[ material.uuid ] === undefined ) {
  4679. var json = material.toJSON();
  4680. delete json.metadata;
  4681. materials[ material.uuid ] = json;
  4682. output.materials.push( json );
  4683. }
  4684. return material.uuid;
  4685. };
  4686. //
  4687. var parseObject = function ( object ) {
  4688. var data = {};
  4689. data.uuid = object.uuid;
  4690. data.type = object.type;
  4691. if ( object.name !== '' ) data.name = object.name;
  4692. if ( JSON.stringify( object.userData ) !== '{}' ) data.userData = object.userData;
  4693. if ( object.visible !== true ) data.visible = object.visible;
  4694. if ( object instanceof THREE.PerspectiveCamera ) {
  4695. data.fov = object.fov;
  4696. data.aspect = object.aspect;
  4697. data.near = object.near;
  4698. data.far = object.far;
  4699. } else if ( object instanceof THREE.OrthographicCamera ) {
  4700. data.left = object.left;
  4701. data.right = object.right;
  4702. data.top = object.top;
  4703. data.bottom = object.bottom;
  4704. data.near = object.near;
  4705. data.far = object.far;
  4706. } else if ( object instanceof THREE.AmbientLight ) {
  4707. data.color = object.color.getHex();
  4708. } else if ( object instanceof THREE.DirectionalLight ) {
  4709. data.color = object.color.getHex();
  4710. data.intensity = object.intensity;
  4711. } else if ( object instanceof THREE.PointLight ) {
  4712. data.color = object.color.getHex();
  4713. data.intensity = object.intensity;
  4714. data.distance = object.distance;
  4715. data.decay = object.decay;
  4716. } else if ( object instanceof THREE.SpotLight ) {
  4717. data.color = object.color.getHex();
  4718. data.intensity = object.intensity;
  4719. data.distance = object.distance;
  4720. data.angle = object.angle;
  4721. data.exponent = object.exponent;
  4722. data.decay = object.decay;
  4723. } else if ( object instanceof THREE.HemisphereLight ) {
  4724. data.color = object.color.getHex();
  4725. data.groundColor = object.groundColor.getHex();
  4726. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.PointCloud ) {
  4727. data.geometry = parseGeometry( object.geometry );
  4728. data.material = parseMaterial( object.material );
  4729. } else if ( object instanceof THREE.Sprite ) {
  4730. data.material = parseMaterial( object.material );
  4731. }
  4732. data.matrix = object.matrix.toArray();
  4733. if ( object.children.length > 0 ) {
  4734. data.children = [];
  4735. for ( var i = 0; i < object.children.length; i ++ ) {
  4736. data.children.push( parseObject( object.children[ i ] ) );
  4737. }
  4738. }
  4739. return data;
  4740. }
  4741. output.object = parseObject( this );
  4742. return output;
  4743. },
  4744. clone: function ( object, recursive ) {
  4745. if ( object === undefined ) object = new THREE.Object3D();
  4746. if ( recursive === undefined ) recursive = true;
  4747. object.name = this.name;
  4748. object.up.copy( this.up );
  4749. object.position.copy( this.position );
  4750. object.quaternion.copy( this.quaternion );
  4751. object.scale.copy( this.scale );
  4752. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4753. object.matrix.copy( this.matrix );
  4754. object.matrixWorld.copy( this.matrixWorld );
  4755. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4756. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4757. object.visible = this.visible;
  4758. object.castShadow = this.castShadow;
  4759. object.receiveShadow = this.receiveShadow;
  4760. object.frustumCulled = this.frustumCulled;
  4761. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4762. if ( recursive === true ) {
  4763. for ( var i = 0; i < this.children.length; i ++ ) {
  4764. var child = this.children[ i ];
  4765. object.add( child.clone() );
  4766. }
  4767. }
  4768. return object;
  4769. }
  4770. };
  4771. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  4772. THREE.Object3DIdCount = 0;
  4773. // File:src/core/Face3.js
  4774. /**
  4775. * @author mrdoob / http://mrdoob.com/
  4776. * @author alteredq / http://alteredqualia.com/
  4777. */
  4778. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4779. this.a = a;
  4780. this.b = b;
  4781. this.c = c;
  4782. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4783. this.vertexNormals = normal instanceof Array ? normal : [];
  4784. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4785. this.vertexColors = color instanceof Array ? color : [];
  4786. this.vertexTangents = [];
  4787. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4788. };
  4789. THREE.Face3.prototype = {
  4790. constructor: THREE.Face3,
  4791. clone: function () {
  4792. var face = new THREE.Face3( this.a, this.b, this.c );
  4793. face.normal.copy( this.normal );
  4794. face.color.copy( this.color );
  4795. face.materialIndex = this.materialIndex;
  4796. for ( var i = 0, il = this.vertexNormals.length; i < il; i ++ ) {
  4797. face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4798. }
  4799. for ( var i = 0, il = this.vertexColors.length; i < il; i ++ ) {
  4800. face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4801. }
  4802. for ( var i = 0, il = this.vertexTangents.length; i < il; i ++ ) {
  4803. face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4804. }
  4805. return face;
  4806. }
  4807. };
  4808. // File:src/core/Face4.js
  4809. /**
  4810. * @author mrdoob / http://mrdoob.com/
  4811. */
  4812. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4813. THREE.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' )
  4814. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  4815. };
  4816. // File:src/core/BufferAttribute.js
  4817. /**
  4818. * @author mrdoob / http://mrdoob.com/
  4819. */
  4820. THREE.BufferAttribute = function ( array, itemSize ) {
  4821. this.array = array;
  4822. this.itemSize = itemSize;
  4823. this.needsUpdate = false;
  4824. };
  4825. THREE.BufferAttribute.prototype = {
  4826. constructor: THREE.BufferAttribute,
  4827. get length () {
  4828. return this.array.length;
  4829. },
  4830. copyAt: function ( index1, attribute, index2 ) {
  4831. index1 *= this.itemSize;
  4832. index2 *= attribute.itemSize;
  4833. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  4834. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  4835. }
  4836. return this;
  4837. },
  4838. set: function ( value, offset ) {
  4839. if ( offset === undefined ) offset = 0;
  4840. this.array.set( value, offset );
  4841. return this;
  4842. },
  4843. setX: function ( index, x ) {
  4844. this.array[ index * this.itemSize ] = x;
  4845. return this;
  4846. },
  4847. setY: function ( index, y ) {
  4848. this.array[ index * this.itemSize + 1 ] = y;
  4849. return this;
  4850. },
  4851. setZ: function ( index, z ) {
  4852. this.array[ index * this.itemSize + 2 ] = z;
  4853. return this;
  4854. },
  4855. setXY: function ( index, x, y ) {
  4856. index *= this.itemSize;
  4857. this.array[ index ] = x;
  4858. this.array[ index + 1 ] = y;
  4859. return this;
  4860. },
  4861. setXYZ: function ( index, x, y, z ) {
  4862. index *= this.itemSize;
  4863. this.array[ index ] = x;
  4864. this.array[ index + 1 ] = y;
  4865. this.array[ index + 2 ] = z;
  4866. return this;
  4867. },
  4868. setXYZW: function ( index, x, y, z, w ) {
  4869. index *= this.itemSize;
  4870. this.array[ index ] = x;
  4871. this.array[ index + 1 ] = y;
  4872. this.array[ index + 2 ] = z;
  4873. this.array[ index + 3 ] = w;
  4874. return this;
  4875. },
  4876. clone: function () {
  4877. return new THREE.BufferAttribute( new this.array.constructor( this.array ), this.itemSize );
  4878. }
  4879. };
  4880. //
  4881. THREE.Int8Attribute = function ( data, itemSize ) {
  4882. THREE.warn( 'THREE.Int8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  4883. return new THREE.BufferAttribute( data, itemSize );
  4884. };
  4885. THREE.Uint8Attribute = function ( data, itemSize ) {
  4886. THREE.warn( 'THREE.Uint8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  4887. return new THREE.BufferAttribute( data, itemSize );
  4888. };
  4889. THREE.Uint8ClampedAttribute = function ( data, itemSize ) {
  4890. THREE.warn( 'THREE.Uint8ClampedAttribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  4891. return new THREE.BufferAttribute( data, itemSize );
  4892. };
  4893. THREE.Int16Attribute = function ( data, itemSize ) {
  4894. THREE.warn( 'THREE.Int16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  4895. return new THREE.BufferAttribute( data, itemSize );
  4896. };
  4897. THREE.Uint16Attribute = function ( data, itemSize ) {
  4898. THREE.warn( 'THREE.Uint16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  4899. return new THREE.BufferAttribute( data, itemSize );
  4900. };
  4901. THREE.Int32Attribute = function ( data, itemSize ) {
  4902. THREE.warn( 'THREE.Int32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  4903. return new THREE.BufferAttribute( data, itemSize );
  4904. };
  4905. THREE.Uint32Attribute = function ( data, itemSize ) {
  4906. THREE.warn( 'THREE.Uint32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  4907. return new THREE.BufferAttribute( data, itemSize );
  4908. };
  4909. THREE.Float32Attribute = function ( data, itemSize ) {
  4910. THREE.warn( 'THREE.Float32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  4911. return new THREE.BufferAttribute( data, itemSize );
  4912. };
  4913. THREE.Float64Attribute = function ( data, itemSize ) {
  4914. THREE.warn( 'THREE.Float64Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
  4915. return new THREE.BufferAttribute( data, itemSize );
  4916. };
  4917. // File:src/core/DynamicBufferAttribute.js
  4918. /**
  4919. * @author benaadams / https://twitter.com/ben_a_adams
  4920. * @author mrdoob / http://mrdoob.com/
  4921. */
  4922. THREE.DynamicBufferAttribute = function ( array, itemSize ) {
  4923. THREE.BufferAttribute.call( this, array, itemSize );
  4924. this.updateRange = { offset: 0, count: -1 };
  4925. };
  4926. THREE.DynamicBufferAttribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  4927. THREE.DynamicBufferAttribute.prototype.constructor = THREE.DynamicBufferAttribute;
  4928. THREE.DynamicBufferAttribute.prototype.clone = function () {
  4929. return new THREE.DynamicBufferAttribute( new this.array.constructor( this.array ), this.itemSize );
  4930. };
  4931. // File:src/core/BufferGeometry.js
  4932. /**
  4933. * @author alteredq / http://alteredqualia.com/
  4934. * @author mrdoob / http://mrdoob.com/
  4935. */
  4936. THREE.BufferGeometry = function () {
  4937. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  4938. this.uuid = THREE.Math.generateUUID();
  4939. this.name = '';
  4940. this.type = 'BufferGeometry';
  4941. this.attributes = {};
  4942. this.attributesKeys = [];
  4943. this.drawcalls = [];
  4944. this.offsets = this.drawcalls; // backwards compatibility
  4945. this.boundingBox = null;
  4946. this.boundingSphere = null;
  4947. };
  4948. THREE.BufferGeometry.prototype = {
  4949. constructor: THREE.BufferGeometry,
  4950. addAttribute: function ( name, attribute ) {
  4951. if ( attribute instanceof THREE.BufferAttribute === false ) {
  4952. THREE.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  4953. this.attributes[ name ] = { array: arguments[ 1 ], itemSize: arguments[ 2 ] };
  4954. return;
  4955. }
  4956. this.attributes[ name ] = attribute;
  4957. this.attributesKeys = Object.keys( this.attributes );
  4958. },
  4959. getAttribute: function ( name ) {
  4960. return this.attributes[ name ];
  4961. },
  4962. addDrawCall: function ( start, count, indexOffset ) {
  4963. this.drawcalls.push( {
  4964. start: start,
  4965. count: count,
  4966. index: indexOffset !== undefined ? indexOffset : 0
  4967. } );
  4968. },
  4969. applyMatrix: function ( matrix ) {
  4970. var position = this.attributes.position;
  4971. if ( position !== undefined ) {
  4972. matrix.applyToVector3Array( position.array );
  4973. position.needsUpdate = true;
  4974. }
  4975. var normal = this.attributes.normal;
  4976. if ( normal !== undefined ) {
  4977. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  4978. normalMatrix.applyToVector3Array( normal.array );
  4979. normal.needsUpdate = true;
  4980. }
  4981. },
  4982. center: function () {
  4983. // TODO
  4984. },
  4985. fromGeometry: function ( geometry, settings ) {
  4986. settings = settings || { 'vertexColors': THREE.NoColors };
  4987. var vertices = geometry.vertices;
  4988. var faces = geometry.faces;
  4989. var faceVertexUvs = geometry.faceVertexUvs;
  4990. var vertexColors = settings.vertexColors;
  4991. var hasFaceVertexUv = faceVertexUvs[ 0 ].length > 0;
  4992. var hasFaceVertexNormals = faces[ 0 ].vertexNormals.length == 3;
  4993. var positions = new Float32Array( faces.length * 3 * 3 );
  4994. this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  4995. var normals = new Float32Array( faces.length * 3 * 3 );
  4996. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  4997. if ( vertexColors !== THREE.NoColors ) {
  4998. var colors = new Float32Array( faces.length * 3 * 3 );
  4999. this.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
  5000. }
  5001. if ( hasFaceVertexUv === true ) {
  5002. var uvs = new Float32Array( faces.length * 3 * 2 );
  5003. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  5004. }
  5005. for ( var i = 0, i2 = 0, i3 = 0; i < faces.length; i ++, i2 += 6, i3 += 9 ) {
  5006. var face = faces[ i ];
  5007. var a = vertices[ face.a ];
  5008. var b = vertices[ face.b ];
  5009. var c = vertices[ face.c ];
  5010. positions[ i3 ] = a.x;
  5011. positions[ i3 + 1 ] = a.y;
  5012. positions[ i3 + 2 ] = a.z;
  5013. positions[ i3 + 3 ] = b.x;
  5014. positions[ i3 + 4 ] = b.y;
  5015. positions[ i3 + 5 ] = b.z;
  5016. positions[ i3 + 6 ] = c.x;
  5017. positions[ i3 + 7 ] = c.y;
  5018. positions[ i3 + 8 ] = c.z;
  5019. if ( hasFaceVertexNormals === true ) {
  5020. var na = face.vertexNormals[ 0 ];
  5021. var nb = face.vertexNormals[ 1 ];
  5022. var nc = face.vertexNormals[ 2 ];
  5023. normals[ i3 ] = na.x;
  5024. normals[ i3 + 1 ] = na.y;
  5025. normals[ i3 + 2 ] = na.z;
  5026. normals[ i3 + 3 ] = nb.x;
  5027. normals[ i3 + 4 ] = nb.y;
  5028. normals[ i3 + 5 ] = nb.z;
  5029. normals[ i3 + 6 ] = nc.x;
  5030. normals[ i3 + 7 ] = nc.y;
  5031. normals[ i3 + 8 ] = nc.z;
  5032. } else {
  5033. var n = face.normal;
  5034. normals[ i3 ] = n.x;
  5035. normals[ i3 + 1 ] = n.y;
  5036. normals[ i3 + 2 ] = n.z;
  5037. normals[ i3 + 3 ] = n.x;
  5038. normals[ i3 + 4 ] = n.y;
  5039. normals[ i3 + 5 ] = n.z;
  5040. normals[ i3 + 6 ] = n.x;
  5041. normals[ i3 + 7 ] = n.y;
  5042. normals[ i3 + 8 ] = n.z;
  5043. }
  5044. if ( vertexColors === THREE.FaceColors ) {
  5045. var fc = face.color;
  5046. colors[ i3 ] = fc.r;
  5047. colors[ i3 + 1 ] = fc.g;
  5048. colors[ i3 + 2 ] = fc.b;
  5049. colors[ i3 + 3 ] = fc.r;
  5050. colors[ i3 + 4 ] = fc.g;
  5051. colors[ i3 + 5 ] = fc.b;
  5052. colors[ i3 + 6 ] = fc.r;
  5053. colors[ i3 + 7 ] = fc.g;
  5054. colors[ i3 + 8 ] = fc.b;
  5055. } else if ( vertexColors === THREE.VertexColors ) {
  5056. var vca = face.vertexColors[ 0 ];
  5057. var vcb = face.vertexColors[ 1 ];
  5058. var vcc = face.vertexColors[ 2 ];
  5059. colors[ i3 ] = vca.r;
  5060. colors[ i3 + 1 ] = vca.g;
  5061. colors[ i3 + 2 ] = vca.b;
  5062. colors[ i3 + 3 ] = vcb.r;
  5063. colors[ i3 + 4 ] = vcb.g;
  5064. colors[ i3 + 5 ] = vcb.b;
  5065. colors[ i3 + 6 ] = vcc.r;
  5066. colors[ i3 + 7 ] = vcc.g;
  5067. colors[ i3 + 8 ] = vcc.b;
  5068. }
  5069. if ( hasFaceVertexUv === true ) {
  5070. var uva = faceVertexUvs[ 0 ][ i ][ 0 ];
  5071. var uvb = faceVertexUvs[ 0 ][ i ][ 1 ];
  5072. var uvc = faceVertexUvs[ 0 ][ i ][ 2 ];
  5073. uvs[ i2 ] = uva.x;
  5074. uvs[ i2 + 1 ] = uva.y;
  5075. uvs[ i2 + 2 ] = uvb.x;
  5076. uvs[ i2 + 3 ] = uvb.y;
  5077. uvs[ i2 + 4 ] = uvc.x;
  5078. uvs[ i2 + 5 ] = uvc.y;
  5079. }
  5080. }
  5081. this.computeBoundingSphere()
  5082. return this;
  5083. },
  5084. computeBoundingBox: function () {
  5085. var vector = new THREE.Vector3();
  5086. return function () {
  5087. if ( this.boundingBox === null ) {
  5088. this.boundingBox = new THREE.Box3();
  5089. }
  5090. var positions = this.attributes.position.array;
  5091. if ( positions ) {
  5092. var bb = this.boundingBox;
  5093. bb.makeEmpty();
  5094. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5095. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5096. bb.expandByPoint( vector );
  5097. }
  5098. }
  5099. if ( positions === undefined || positions.length === 0 ) {
  5100. this.boundingBox.min.set( 0, 0, 0 );
  5101. this.boundingBox.max.set( 0, 0, 0 );
  5102. }
  5103. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  5104. THREE.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.' );
  5105. }
  5106. }
  5107. }(),
  5108. computeBoundingSphere: function () {
  5109. var box = new THREE.Box3();
  5110. var vector = new THREE.Vector3();
  5111. return function () {
  5112. if ( this.boundingSphere === null ) {
  5113. this.boundingSphere = new THREE.Sphere();
  5114. }
  5115. var positions = this.attributes.position.array;
  5116. if ( positions ) {
  5117. box.makeEmpty();
  5118. var center = this.boundingSphere.center;
  5119. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5120. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5121. box.expandByPoint( vector );
  5122. }
  5123. box.center( center );
  5124. // hoping to find a boundingSphere with a radius smaller than the
  5125. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  5126. var maxRadiusSq = 0;
  5127. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5128. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5129. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  5130. }
  5131. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5132. if ( isNaN( this.boundingSphere.radius ) ) {
  5133. THREE.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.' );
  5134. }
  5135. }
  5136. }
  5137. }(),
  5138. computeFaceNormals: function () {
  5139. // backwards compatibility
  5140. },
  5141. computeVertexNormals: function () {
  5142. var attributes = this.attributes;
  5143. if ( attributes.position ) {
  5144. var positions = attributes.position.array;
  5145. if ( attributes.normal === undefined ) {
  5146. this.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( positions.length ), 3 ) );
  5147. } else {
  5148. // reset existing normals to zero
  5149. var normals = attributes.normal.array;
  5150. for ( var i = 0, il = normals.length; i < il; i ++ ) {
  5151. normals[ i ] = 0;
  5152. }
  5153. }
  5154. var normals = attributes.normal.array;
  5155. var vA, vB, vC,
  5156. pA = new THREE.Vector3(),
  5157. pB = new THREE.Vector3(),
  5158. pC = new THREE.Vector3(),
  5159. cb = new THREE.Vector3(),
  5160. ab = new THREE.Vector3();
  5161. // indexed elements
  5162. if ( attributes.index ) {
  5163. var indices = attributes.index.array;
  5164. var offsets = ( this.offsets.length > 0 ? this.offsets : [ { start: 0, count: indices.length, index: 0 } ] );
  5165. for ( var j = 0, jl = offsets.length; j < jl; ++ j ) {
  5166. var start = offsets[ j ].start;
  5167. var count = offsets[ j ].count;
  5168. var index = offsets[ j ].index;
  5169. for ( var i = start, il = start + count; i < il; i += 3 ) {
  5170. vA = ( index + indices[ i ] ) * 3;
  5171. vB = ( index + indices[ i + 1 ] ) * 3;
  5172. vC = ( index + indices[ i + 2 ] ) * 3;
  5173. pA.fromArray( positions, vA );
  5174. pB.fromArray( positions, vB );
  5175. pC.fromArray( positions, vC );
  5176. cb.subVectors( pC, pB );
  5177. ab.subVectors( pA, pB );
  5178. cb.cross( ab );
  5179. normals[ vA ] += cb.x;
  5180. normals[ vA + 1 ] += cb.y;
  5181. normals[ vA + 2 ] += cb.z;
  5182. normals[ vB ] += cb.x;
  5183. normals[ vB + 1 ] += cb.y;
  5184. normals[ vB + 2 ] += cb.z;
  5185. normals[ vC ] += cb.x;
  5186. normals[ vC + 1 ] += cb.y;
  5187. normals[ vC + 2 ] += cb.z;
  5188. }
  5189. }
  5190. } else {
  5191. // non-indexed elements (unconnected triangle soup)
  5192. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  5193. pA.fromArray( positions, i );
  5194. pB.fromArray( positions, i + 3 );
  5195. pC.fromArray( positions, i + 6 );
  5196. cb.subVectors( pC, pB );
  5197. ab.subVectors( pA, pB );
  5198. cb.cross( ab );
  5199. normals[ i ] = cb.x;
  5200. normals[ i + 1 ] = cb.y;
  5201. normals[ i + 2 ] = cb.z;
  5202. normals[ i + 3 ] = cb.x;
  5203. normals[ i + 4 ] = cb.y;
  5204. normals[ i + 5 ] = cb.z;
  5205. normals[ i + 6 ] = cb.x;
  5206. normals[ i + 7 ] = cb.y;
  5207. normals[ i + 8 ] = cb.z;
  5208. }
  5209. }
  5210. this.normalizeNormals();
  5211. attributes.normal.needsUpdate = true;
  5212. }
  5213. },
  5214. computeTangents: function () {
  5215. // based on http://www.terathon.com/code/tangent.html
  5216. // (per vertex tangents)
  5217. if ( this.attributes.index === undefined ||
  5218. this.attributes.position === undefined ||
  5219. this.attributes.normal === undefined ||
  5220. this.attributes.uv === undefined ) {
  5221. THREE.warn( 'THREE.BufferGeometry: Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()' );
  5222. return;
  5223. }
  5224. var indices = this.attributes.index.array;
  5225. var positions = this.attributes.position.array;
  5226. var normals = this.attributes.normal.array;
  5227. var uvs = this.attributes.uv.array;
  5228. var nVertices = positions.length / 3;
  5229. if ( this.attributes.tangent === undefined ) {
  5230. this.addAttribute( 'tangent', new THREE.BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  5231. }
  5232. var tangents = this.attributes.tangent.array;
  5233. var tan1 = [], tan2 = [];
  5234. for ( var k = 0; k < nVertices; k ++ ) {
  5235. tan1[ k ] = new THREE.Vector3();
  5236. tan2[ k ] = new THREE.Vector3();
  5237. }
  5238. var vA = new THREE.Vector3(),
  5239. vB = new THREE.Vector3(),
  5240. vC = new THREE.Vector3(),
  5241. uvA = new THREE.Vector2(),
  5242. uvB = new THREE.Vector2(),
  5243. uvC = new THREE.Vector2(),
  5244. x1, x2, y1, y2, z1, z2,
  5245. s1, s2, t1, t2, r;
  5246. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5247. function handleTriangle( a, b, c ) {
  5248. vA.fromArray( positions, a * 3 );
  5249. vB.fromArray( positions, b * 3 );
  5250. vC.fromArray( positions, c * 3 );
  5251. uvA.fromArray( uvs, a * 2 );
  5252. uvB.fromArray( uvs, b * 2 );
  5253. uvC.fromArray( uvs, c * 2 );
  5254. x1 = vB.x - vA.x;
  5255. x2 = vC.x - vA.x;
  5256. y1 = vB.y - vA.y;
  5257. y2 = vC.y - vA.y;
  5258. z1 = vB.z - vA.z;
  5259. z2 = vC.z - vA.z;
  5260. s1 = uvB.x - uvA.x;
  5261. s2 = uvC.x - uvA.x;
  5262. t1 = uvB.y - uvA.y;
  5263. t2 = uvC.y - uvA.y;
  5264. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5265. sdir.set(
  5266. ( t2 * x1 - t1 * x2 ) * r,
  5267. ( t2 * y1 - t1 * y2 ) * r,
  5268. ( t2 * z1 - t1 * z2 ) * r
  5269. );
  5270. tdir.set(
  5271. ( s1 * x2 - s2 * x1 ) * r,
  5272. ( s1 * y2 - s2 * y1 ) * r,
  5273. ( s1 * z2 - s2 * z1 ) * r
  5274. );
  5275. tan1[ a ].add( sdir );
  5276. tan1[ b ].add( sdir );
  5277. tan1[ c ].add( sdir );
  5278. tan2[ a ].add( tdir );
  5279. tan2[ b ].add( tdir );
  5280. tan2[ c ].add( tdir );
  5281. }
  5282. var i, il;
  5283. var j, jl;
  5284. var iA, iB, iC;
  5285. if ( this.drawcalls.length === 0 ) {
  5286. this.addDrawCall( 0, indices.length, 0 );
  5287. }
  5288. var drawcalls = this.drawcalls;
  5289. for ( j = 0, jl = drawcalls.length; j < jl; ++ j ) {
  5290. var start = drawcalls[ j ].start;
  5291. var count = drawcalls[ j ].count;
  5292. var index = drawcalls[ j ].index;
  5293. for ( i = start, il = start + count; i < il; i += 3 ) {
  5294. iA = index + indices[ i ];
  5295. iB = index + indices[ i + 1 ];
  5296. iC = index + indices[ i + 2 ];
  5297. handleTriangle( iA, iB, iC );
  5298. }
  5299. }
  5300. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5301. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5302. var w, t, test;
  5303. function handleVertex( v ) {
  5304. n.fromArray( normals, v * 3 );
  5305. n2.copy( n );
  5306. t = tan1[ v ];
  5307. // Gram-Schmidt orthogonalize
  5308. tmp.copy( t );
  5309. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5310. // Calculate handedness
  5311. tmp2.crossVectors( n2, t );
  5312. test = tmp2.dot( tan2[ v ] );
  5313. w = ( test < 0.0 ) ? - 1.0 : 1.0;
  5314. tangents[ v * 4 ] = tmp.x;
  5315. tangents[ v * 4 + 1 ] = tmp.y;
  5316. tangents[ v * 4 + 2 ] = tmp.z;
  5317. tangents[ v * 4 + 3 ] = w;
  5318. }
  5319. for ( j = 0, jl = drawcalls.length; j < jl; ++ j ) {
  5320. var start = drawcalls[ j ].start;
  5321. var count = drawcalls[ j ].count;
  5322. var index = drawcalls[ j ].index;
  5323. for ( i = start, il = start + count; i < il; i += 3 ) {
  5324. iA = index + indices[ i ];
  5325. iB = index + indices[ i + 1 ];
  5326. iC = index + indices[ i + 2 ];
  5327. handleVertex( iA );
  5328. handleVertex( iB );
  5329. handleVertex( iC );
  5330. }
  5331. }
  5332. },
  5333. /*
  5334. computeOffsets
  5335. Compute the draw offset for large models by chunking the index buffer into chunks of 65k addressable vertices.
  5336. This method will effectively rewrite the index buffer and remap all attributes to match the new indices.
  5337. WARNING: This method will also expand the vertex count to prevent sprawled triangles across draw offsets.
  5338. indexBufferSize - Defaults to 65535, but allows for larger or smaller chunks.
  5339. */
  5340. computeOffsets: function ( indexBufferSize ) {
  5341. var size = indexBufferSize;
  5342. if ( indexBufferSize === undefined )
  5343. size = 65535; //WebGL limits type of index buffer values to 16-bit.
  5344. var s = Date.now();
  5345. var indices = this.attributes.index.array;
  5346. var vertices = this.attributes.position.array;
  5347. var verticesCount = ( vertices.length / 3 );
  5348. var facesCount = ( indices.length / 3 );
  5349. /*
  5350. console.log("Computing buffers in offsets of "+size+" -> indices:"+indices.length+" vertices:"+vertices.length);
  5351. console.log("Faces to process: "+(indices.length/3));
  5352. console.log("Reordering "+verticesCount+" vertices.");
  5353. */
  5354. var sortedIndices = new Uint16Array( indices.length ); //16-bit buffers
  5355. var indexPtr = 0;
  5356. var vertexPtr = 0;
  5357. var offsets = [ { start:0, count:0, index:0 } ];
  5358. var offset = offsets[ 0 ];
  5359. var duplicatedVertices = 0;
  5360. var newVerticeMaps = 0;
  5361. var faceVertices = new Int32Array( 6 );
  5362. var vertexMap = new Int32Array( vertices.length );
  5363. var revVertexMap = new Int32Array( vertices.length );
  5364. for ( var j = 0; j < vertices.length; j ++ ) { vertexMap[ j ] = - 1; revVertexMap[ j ] = - 1; }
  5365. /*
  5366. Traverse every face and reorder vertices in the proper offsets of 65k.
  5367. We can have more than 65k entries in the index buffer per offset, but only reference 65k values.
  5368. */
  5369. for ( var findex = 0; findex < facesCount; findex ++ ) {
  5370. newVerticeMaps = 0;
  5371. for ( var vo = 0; vo < 3; vo ++ ) {
  5372. var vid = indices[ findex * 3 + vo ];
  5373. if ( vertexMap[ vid ] == - 1 ) {
  5374. //Unmapped vertice
  5375. faceVertices[ vo * 2 ] = vid;
  5376. faceVertices[ vo * 2 + 1 ] = - 1;
  5377. newVerticeMaps ++;
  5378. } else if ( vertexMap[ vid ] < offset.index ) {
  5379. //Reused vertices from previous block (duplicate)
  5380. faceVertices[ vo * 2 ] = vid;
  5381. faceVertices[ vo * 2 + 1 ] = - 1;
  5382. duplicatedVertices ++;
  5383. } else {
  5384. //Reused vertice in the current block
  5385. faceVertices[ vo * 2 ] = vid;
  5386. faceVertices[ vo * 2 + 1 ] = vertexMap[ vid ];
  5387. }
  5388. }
  5389. var faceMax = vertexPtr + newVerticeMaps;
  5390. if ( faceMax > ( offset.index + size ) ) {
  5391. var new_offset = { start:indexPtr, count:0, index:vertexPtr };
  5392. offsets.push( new_offset );
  5393. offset = new_offset;
  5394. //Re-evaluate reused vertices in light of new offset.
  5395. for ( var v = 0; v < 6; v += 2 ) {
  5396. var new_vid = faceVertices[ v + 1 ];
  5397. if ( new_vid > - 1 && new_vid < offset.index )
  5398. faceVertices[ v + 1 ] = - 1;
  5399. }
  5400. }
  5401. //Reindex the face.
  5402. for ( var v = 0; v < 6; v += 2 ) {
  5403. var vid = faceVertices[ v ];
  5404. var new_vid = faceVertices[ v + 1 ];
  5405. if ( new_vid === - 1 )
  5406. new_vid = vertexPtr ++;
  5407. vertexMap[ vid ] = new_vid;
  5408. revVertexMap[ new_vid ] = vid;
  5409. sortedIndices[ indexPtr ++ ] = new_vid - offset.index; //XXX overflows at 16bit
  5410. offset.count ++;
  5411. }
  5412. }
  5413. /* Move all attribute values to map to the new computed indices , also expand the vertice stack to match our new vertexPtr. */
  5414. this.reorderBuffers( sortedIndices, revVertexMap, vertexPtr );
  5415. this.offsets = offsets;
  5416. /*
  5417. var orderTime = Date.now();
  5418. console.log("Reorder time: "+(orderTime-s)+"ms");
  5419. console.log("Duplicated "+duplicatedVertices+" vertices.");
  5420. console.log("Compute Buffers time: "+(Date.now()-s)+"ms");
  5421. console.log("Draw offsets: "+offsets.length);
  5422. */
  5423. return offsets;
  5424. },
  5425. merge: function ( geometry, offset ) {
  5426. if ( geometry instanceof THREE.BufferGeometry === false ) {
  5427. THREE.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  5428. return;
  5429. }
  5430. if ( offset === undefined ) offset = 0;
  5431. var attributes = this.attributes;
  5432. for ( var key in attributes ) {
  5433. if ( geometry.attributes[ key ] === undefined ) continue;
  5434. var attribute1 = attributes[ key ];
  5435. var attributeArray1 = attribute1.array;
  5436. var attribute2 = geometry.attributes[ key ];
  5437. var attributeArray2 = attribute2.array;
  5438. var attributeSize = attribute2.itemSize;
  5439. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  5440. attributeArray1[ j ] = attributeArray2[ i ];
  5441. }
  5442. }
  5443. return this;
  5444. },
  5445. normalizeNormals: function () {
  5446. var normals = this.attributes.normal.array;
  5447. var x, y, z, n;
  5448. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5449. x = normals[ i ];
  5450. y = normals[ i + 1 ];
  5451. z = normals[ i + 2 ];
  5452. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5453. normals[ i ] *= n;
  5454. normals[ i + 1 ] *= n;
  5455. normals[ i + 2 ] *= n;
  5456. }
  5457. },
  5458. /*
  5459. reoderBuffers:
  5460. Reorder attributes based on a new indexBuffer and indexMap.
  5461. indexBuffer - Uint16Array of the new ordered indices.
  5462. indexMap - Int32Array where the position is the new vertex ID and the value the old vertex ID for each vertex.
  5463. vertexCount - Amount of total vertices considered in this reordering (in case you want to grow the vertice stack).
  5464. */
  5465. reorderBuffers: function ( indexBuffer, indexMap, vertexCount ) {
  5466. /* Create a copy of all attributes for reordering. */
  5467. var sortedAttributes = {};
  5468. for ( var attr in this.attributes ) {
  5469. if ( attr == 'index' )
  5470. continue;
  5471. var sourceArray = this.attributes[ attr ].array;
  5472. sortedAttributes[ attr ] = new sourceArray.constructor( this.attributes[ attr ].itemSize * vertexCount );
  5473. }
  5474. /* Move attribute positions based on the new index map */
  5475. for ( var new_vid = 0; new_vid < vertexCount; new_vid ++ ) {
  5476. var vid = indexMap[ new_vid ];
  5477. for ( var attr in this.attributes ) {
  5478. if ( attr == 'index' )
  5479. continue;
  5480. var attrArray = this.attributes[ attr ].array;
  5481. var attrSize = this.attributes[ attr ].itemSize;
  5482. var sortedAttr = sortedAttributes[ attr ];
  5483. for ( var k = 0; k < attrSize; k ++ )
  5484. sortedAttr[ new_vid * attrSize + k ] = attrArray[ vid * attrSize + k ];
  5485. }
  5486. }
  5487. /* Carry the new sorted buffers locally */
  5488. this.attributes[ 'index' ].array = indexBuffer;
  5489. for ( var attr in this.attributes ) {
  5490. if ( attr == 'index' )
  5491. continue;
  5492. this.attributes[ attr ].array = sortedAttributes[ attr ];
  5493. this.attributes[ attr ].numItems = this.attributes[ attr ].itemSize * vertexCount;
  5494. }
  5495. },
  5496. toJSON: function () {
  5497. var output = {
  5498. metadata: {
  5499. version: 4.0,
  5500. type: 'BufferGeometry',
  5501. generator: 'BufferGeometryExporter'
  5502. },
  5503. uuid: this.uuid,
  5504. type: this.type,
  5505. data: {
  5506. attributes: {}
  5507. }
  5508. };
  5509. var attributes = this.attributes;
  5510. var offsets = this.offsets;
  5511. var boundingSphere = this.boundingSphere;
  5512. for ( var key in attributes ) {
  5513. var attribute = attributes[ key ];
  5514. var array = [], typeArray = attribute.array;
  5515. for ( var i = 0, l = typeArray.length; i < l; i ++ ) {
  5516. array[ i ] = typeArray[ i ];
  5517. }
  5518. output.data.attributes[ key ] = {
  5519. itemSize: attribute.itemSize,
  5520. type: attribute.array.constructor.name,
  5521. array: array
  5522. }
  5523. }
  5524. if ( offsets.length > 0 ) {
  5525. output.data.offsets = JSON.parse( JSON.stringify( offsets ) );
  5526. }
  5527. if ( boundingSphere !== null ) {
  5528. output.data.boundingSphere = {
  5529. center: boundingSphere.center.toArray(),
  5530. radius: boundingSphere.radius
  5531. }
  5532. }
  5533. return output;
  5534. },
  5535. clone: function () {
  5536. var geometry = new THREE.BufferGeometry();
  5537. for ( var attr in this.attributes ) {
  5538. var sourceAttr = this.attributes[ attr ];
  5539. geometry.addAttribute( attr, sourceAttr.clone() );
  5540. }
  5541. for ( var i = 0, il = this.offsets.length; i < il; i ++ ) {
  5542. var offset = this.offsets[ i ];
  5543. geometry.offsets.push( {
  5544. start: offset.start,
  5545. index: offset.index,
  5546. count: offset.count
  5547. } );
  5548. }
  5549. return geometry;
  5550. },
  5551. dispose: function () {
  5552. this.dispatchEvent( { type: 'dispose' } );
  5553. }
  5554. };
  5555. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  5556. // File:src/core/Geometry.js
  5557. /**
  5558. * @author mrdoob / http://mrdoob.com/
  5559. * @author kile / http://kile.stravaganza.org/
  5560. * @author alteredq / http://alteredqualia.com/
  5561. * @author mikael emtinger / http://gomo.se/
  5562. * @author zz85 / http://www.lab4games.net/zz85/blog
  5563. * @author bhouston / http://exocortex.com
  5564. */
  5565. THREE.Geometry = function () {
  5566. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  5567. this.uuid = THREE.Math.generateUUID();
  5568. this.name = '';
  5569. this.type = 'Geometry';
  5570. this.vertices = [];
  5571. this.colors = []; // one-to-one vertex colors, used in Points and Line
  5572. this.faces = [];
  5573. this.faceVertexUvs = [ [] ];
  5574. this.morphTargets = [];
  5575. this.morphColors = [];
  5576. this.morphNormals = [];
  5577. this.skinWeights = [];
  5578. this.skinIndices = [];
  5579. this.lineDistances = [];
  5580. this.boundingBox = null;
  5581. this.boundingSphere = null;
  5582. this.hasTangents = false;
  5583. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  5584. // update flags
  5585. this.verticesNeedUpdate = false;
  5586. this.elementsNeedUpdate = false;
  5587. this.uvsNeedUpdate = false;
  5588. this.normalsNeedUpdate = false;
  5589. this.tangentsNeedUpdate = false;
  5590. this.colorsNeedUpdate = false;
  5591. this.lineDistancesNeedUpdate = false;
  5592. this.groupsNeedUpdate = false;
  5593. };
  5594. THREE.Geometry.prototype = {
  5595. constructor: THREE.Geometry,
  5596. applyMatrix: function ( matrix ) {
  5597. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5598. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  5599. var vertex = this.vertices[ i ];
  5600. vertex.applyMatrix4( matrix );
  5601. }
  5602. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  5603. var face = this.faces[ i ];
  5604. face.normal.applyMatrix3( normalMatrix ).normalize();
  5605. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  5606. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  5607. }
  5608. }
  5609. if ( this.boundingBox instanceof THREE.Box3 ) {
  5610. this.computeBoundingBox();
  5611. }
  5612. if ( this.boundingSphere instanceof THREE.Sphere ) {
  5613. this.computeBoundingSphere();
  5614. }
  5615. },
  5616. fromBufferGeometry: function ( geometry ) {
  5617. var scope = this;
  5618. var attributes = geometry.attributes;
  5619. var vertices = attributes.position.array;
  5620. var indices = attributes.index !== undefined ? attributes.index.array : undefined;
  5621. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  5622. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  5623. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  5624. var tempNormals = [];
  5625. var tempUVs = [];
  5626. for ( var i = 0, j = 0; i < vertices.length; i += 3, j += 2 ) {
  5627. scope.vertices.push( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  5628. if ( normals !== undefined ) {
  5629. tempNormals.push( new THREE.Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  5630. }
  5631. if ( colors !== undefined ) {
  5632. scope.colors.push( new THREE.Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  5633. }
  5634. if ( uvs !== undefined ) {
  5635. tempUVs.push( new THREE.Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  5636. }
  5637. }
  5638. var addFace = function ( a, b, c ) {
  5639. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  5640. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  5641. scope.faces.push( new THREE.Face3( a, b, c, vertexNormals, vertexColors ) );
  5642. if ( uvs !== undefined ) {
  5643. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  5644. }
  5645. };
  5646. if ( indices !== undefined ) {
  5647. for ( var i = 0; i < indices.length; i += 3 ) {
  5648. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  5649. }
  5650. } else {
  5651. for ( var i = 0; i < vertices.length / 3; i += 3 ) {
  5652. addFace( i, i + 1, i + 2 );
  5653. }
  5654. }
  5655. this.computeFaceNormals();
  5656. if ( geometry.boundingBox !== null ) {
  5657. this.boundingBox = geometry.boundingBox.clone();
  5658. }
  5659. if ( geometry.boundingSphere !== null ) {
  5660. this.boundingSphere = geometry.boundingSphere.clone();
  5661. }
  5662. return this;
  5663. },
  5664. center: function () {
  5665. this.computeBoundingBox();
  5666. var offset = new THREE.Vector3();
  5667. offset.addVectors( this.boundingBox.min, this.boundingBox.max );
  5668. offset.multiplyScalar( - 0.5 );
  5669. this.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  5670. this.computeBoundingBox();
  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, vD;
  5697. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  5698. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  5699. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5700. face = this.faces[ f ];
  5701. vA = this.vertices[ face.a ];
  5702. vB = this.vertices[ face.b ];
  5703. vC = this.vertices[ face.c ];
  5704. cb.subVectors( vC, vB );
  5705. ab.subVectors( vA, vB );
  5706. cb.cross( ab );
  5707. vertices[ face.a ].add( cb );
  5708. vertices[ face.b ].add( cb );
  5709. vertices[ face.c ].add( cb );
  5710. }
  5711. } else {
  5712. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5713. face = this.faces[ f ];
  5714. vertices[ face.a ].add( face.normal );
  5715. vertices[ face.b ].add( face.normal );
  5716. vertices[ face.c ].add( face.normal );
  5717. }
  5718. }
  5719. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5720. vertices[ v ].normalize();
  5721. }
  5722. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5723. face = this.faces[ f ];
  5724. face.vertexNormals[ 0 ] = vertices[ face.a ].clone();
  5725. face.vertexNormals[ 1 ] = vertices[ face.b ].clone();
  5726. face.vertexNormals[ 2 ] = vertices[ face.c ].clone();
  5727. }
  5728. },
  5729. computeMorphNormals: function () {
  5730. var i, il, f, fl, face;
  5731. // save original normals
  5732. // - create temp variables on first access
  5733. // otherwise just copy (for faster repeated calls)
  5734. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5735. face = this.faces[ f ];
  5736. if ( ! face.__originalFaceNormal ) {
  5737. face.__originalFaceNormal = face.normal.clone();
  5738. } else {
  5739. face.__originalFaceNormal.copy( face.normal );
  5740. }
  5741. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  5742. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  5743. if ( ! face.__originalVertexNormals[ i ] ) {
  5744. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  5745. } else {
  5746. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  5747. }
  5748. }
  5749. }
  5750. // use temp geometry to compute face and vertex normals for each morph
  5751. var tmpGeo = new THREE.Geometry();
  5752. tmpGeo.faces = this.faces;
  5753. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  5754. // create on first access
  5755. if ( ! this.morphNormals[ i ] ) {
  5756. this.morphNormals[ i ] = {};
  5757. this.morphNormals[ i ].faceNormals = [];
  5758. this.morphNormals[ i ].vertexNormals = [];
  5759. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  5760. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  5761. var faceNormal, vertexNormals;
  5762. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5763. faceNormal = new THREE.Vector3();
  5764. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  5765. dstNormalsFace.push( faceNormal );
  5766. dstNormalsVertex.push( vertexNormals );
  5767. }
  5768. }
  5769. var morphNormals = this.morphNormals[ i ];
  5770. // set vertices to morph target
  5771. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  5772. // compute morph normals
  5773. tmpGeo.computeFaceNormals();
  5774. tmpGeo.computeVertexNormals();
  5775. // store morph normals
  5776. var faceNormal, vertexNormals;
  5777. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5778. face = this.faces[ f ];
  5779. faceNormal = morphNormals.faceNormals[ f ];
  5780. vertexNormals = morphNormals.vertexNormals[ f ];
  5781. faceNormal.copy( face.normal );
  5782. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  5783. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  5784. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  5785. }
  5786. }
  5787. // restore original normals
  5788. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5789. face = this.faces[ f ];
  5790. face.normal = face.__originalFaceNormal;
  5791. face.vertexNormals = face.__originalVertexNormals;
  5792. }
  5793. },
  5794. computeTangents: function () {
  5795. // based on http://www.terathon.com/code/tangent.html
  5796. // tangents go to vertices
  5797. var f, fl, v, vl, i, il, vertexIndex,
  5798. face, uv, vA, vB, vC, uvA, uvB, uvC,
  5799. x1, x2, y1, y2, z1, z2,
  5800. s1, s2, t1, t2, r, t, test,
  5801. tan1 = [], tan2 = [],
  5802. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  5803. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  5804. n = new THREE.Vector3(), w;
  5805. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5806. tan1[ v ] = new THREE.Vector3();
  5807. tan2[ v ] = new THREE.Vector3();
  5808. }
  5809. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  5810. vA = context.vertices[ a ];
  5811. vB = context.vertices[ b ];
  5812. vC = context.vertices[ c ];
  5813. uvA = uv[ ua ];
  5814. uvB = uv[ ub ];
  5815. uvC = uv[ uc ];
  5816. x1 = vB.x - vA.x;
  5817. x2 = vC.x - vA.x;
  5818. y1 = vB.y - vA.y;
  5819. y2 = vC.y - vA.y;
  5820. z1 = vB.z - vA.z;
  5821. z2 = vC.z - vA.z;
  5822. s1 = uvB.x - uvA.x;
  5823. s2 = uvC.x - uvA.x;
  5824. t1 = uvB.y - uvA.y;
  5825. t2 = uvC.y - uvA.y;
  5826. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5827. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  5828. ( t2 * y1 - t1 * y2 ) * r,
  5829. ( t2 * z1 - t1 * z2 ) * r );
  5830. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  5831. ( s1 * y2 - s2 * y1 ) * r,
  5832. ( s1 * z2 - s2 * z1 ) * r );
  5833. tan1[ a ].add( sdir );
  5834. tan1[ b ].add( sdir );
  5835. tan1[ c ].add( sdir );
  5836. tan2[ a ].add( tdir );
  5837. tan2[ b ].add( tdir );
  5838. tan2[ c ].add( tdir );
  5839. }
  5840. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5841. face = this.faces[ f ];
  5842. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  5843. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  5844. }
  5845. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  5846. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5847. face = this.faces[ f ];
  5848. for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i ++ ) {
  5849. n.copy( face.vertexNormals[ i ] );
  5850. vertexIndex = face[ faceIndex[ i ] ];
  5851. t = tan1[ vertexIndex ];
  5852. // Gram-Schmidt orthogonalize
  5853. tmp.copy( t );
  5854. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5855. // Calculate handedness
  5856. tmp2.crossVectors( face.vertexNormals[ i ], t );
  5857. test = tmp2.dot( tan2[ vertexIndex ] );
  5858. w = ( test < 0.0 ) ? - 1.0 : 1.0;
  5859. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  5860. }
  5861. }
  5862. this.hasTangents = true;
  5863. },
  5864. computeLineDistances: function () {
  5865. var d = 0;
  5866. var vertices = this.vertices;
  5867. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5868. if ( i > 0 ) {
  5869. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  5870. }
  5871. this.lineDistances[ i ] = d;
  5872. }
  5873. },
  5874. computeBoundingBox: function () {
  5875. if ( this.boundingBox === null ) {
  5876. this.boundingBox = new THREE.Box3();
  5877. }
  5878. this.boundingBox.setFromPoints( this.vertices );
  5879. },
  5880. computeBoundingSphere: function () {
  5881. if ( this.boundingSphere === null ) {
  5882. this.boundingSphere = new THREE.Sphere();
  5883. }
  5884. this.boundingSphere.setFromPoints( this.vertices );
  5885. },
  5886. merge: function ( geometry, matrix, materialIndexOffset ) {
  5887. if ( geometry instanceof THREE.Geometry === false ) {
  5888. THREE.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  5889. return;
  5890. }
  5891. var normalMatrix,
  5892. vertexOffset = this.vertices.length,
  5893. vertices1 = this.vertices,
  5894. vertices2 = geometry.vertices,
  5895. faces1 = this.faces,
  5896. faces2 = geometry.faces,
  5897. uvs1 = this.faceVertexUvs[ 0 ],
  5898. uvs2 = geometry.faceVertexUvs[ 0 ];
  5899. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  5900. if ( matrix !== undefined ) {
  5901. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5902. }
  5903. // vertices
  5904. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  5905. var vertex = vertices2[ i ];
  5906. var vertexCopy = vertex.clone();
  5907. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  5908. vertices1.push( vertexCopy );
  5909. }
  5910. // faces
  5911. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  5912. var face = faces2[ i ], faceCopy, normal, color,
  5913. faceVertexNormals = face.vertexNormals,
  5914. faceVertexColors = face.vertexColors;
  5915. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  5916. faceCopy.normal.copy( face.normal );
  5917. if ( normalMatrix !== undefined ) {
  5918. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  5919. }
  5920. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  5921. normal = faceVertexNormals[ j ].clone();
  5922. if ( normalMatrix !== undefined ) {
  5923. normal.applyMatrix3( normalMatrix ).normalize();
  5924. }
  5925. faceCopy.vertexNormals.push( normal );
  5926. }
  5927. faceCopy.color.copy( face.color );
  5928. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  5929. color = faceVertexColors[ j ];
  5930. faceCopy.vertexColors.push( color.clone() );
  5931. }
  5932. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  5933. faces1.push( faceCopy );
  5934. }
  5935. // uvs
  5936. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  5937. var uv = uvs2[ i ], uvCopy = [];
  5938. if ( uv === undefined ) {
  5939. continue;
  5940. }
  5941. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  5942. uvCopy.push( uv[ j ].clone() );
  5943. }
  5944. uvs1.push( uvCopy );
  5945. }
  5946. },
  5947. mergeMesh: function ( mesh ) {
  5948. if ( mesh instanceof THREE.Mesh === false ) {
  5949. THREE.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  5950. return;
  5951. }
  5952. mesh.matrixAutoUpdate && mesh.updateMatrix();
  5953. this.merge( mesh.geometry, mesh.matrix );
  5954. },
  5955. /*
  5956. * Checks for duplicate vertices with hashmap.
  5957. * Duplicated vertices are removed
  5958. * and faces' vertices are updated.
  5959. */
  5960. mergeVertices: function () {
  5961. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  5962. var unique = [], changes = [];
  5963. var v, key;
  5964. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  5965. var precision = Math.pow( 10, precisionPoints );
  5966. var i,il, face;
  5967. var indices, k, j, jl, u;
  5968. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  5969. v = this.vertices[ i ];
  5970. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  5971. if ( verticesMap[ key ] === undefined ) {
  5972. verticesMap[ key ] = i;
  5973. unique.push( this.vertices[ i ] );
  5974. changes[ i ] = unique.length - 1;
  5975. } else {
  5976. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  5977. changes[ i ] = changes[ verticesMap[ key ] ];
  5978. }
  5979. };
  5980. // if faces are completely degenerate after merging vertices, we
  5981. // have to remove them from the geometry.
  5982. var faceIndicesToRemove = [];
  5983. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  5984. face = this.faces[ i ];
  5985. face.a = changes[ face.a ];
  5986. face.b = changes[ face.b ];
  5987. face.c = changes[ face.c ];
  5988. indices = [ face.a, face.b, face.c ];
  5989. var dupIndex = - 1;
  5990. // if any duplicate vertices are found in a Face3
  5991. // we have to remove the face as nothing can be saved
  5992. for ( var n = 0; n < 3; n ++ ) {
  5993. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  5994. dupIndex = n;
  5995. faceIndicesToRemove.push( i );
  5996. break;
  5997. }
  5998. }
  5999. }
  6000. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  6001. var idx = faceIndicesToRemove[ i ];
  6002. this.faces.splice( idx, 1 );
  6003. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  6004. this.faceVertexUvs[ j ].splice( idx, 1 );
  6005. }
  6006. }
  6007. // Use unique set of vertices
  6008. var diff = this.vertices.length - unique.length;
  6009. this.vertices = unique;
  6010. return diff;
  6011. },
  6012. toJSON: function () {
  6013. var output = {
  6014. metadata: {
  6015. version: 4.0,
  6016. type: 'BufferGeometry',
  6017. generator: 'BufferGeometryExporter'
  6018. },
  6019. uuid: this.uuid,
  6020. type: this.type
  6021. };
  6022. if ( this.name !== "" ) output.name = this.name;
  6023. if ( this.parameters !== undefined ) {
  6024. var parameters = this.parameters;
  6025. for ( var key in parameters ) {
  6026. if ( parameters[ key ] !== undefined ) output[ key ] = parameters[ key ];
  6027. }
  6028. return output;
  6029. }
  6030. var vertices = [];
  6031. for ( var i = 0; i < this.vertices.length; i ++ ) {
  6032. var vertex = this.vertices[ i ];
  6033. vertices.push( vertex.x, vertex.y, vertex.z );
  6034. }
  6035. var faces = [];
  6036. var normals = [];
  6037. var normalsHash = {};
  6038. var colors = [];
  6039. var colorsHash = {};
  6040. var uvs = [];
  6041. var uvsHash = {};
  6042. for ( var i = 0; i < this.faces.length; i ++ ) {
  6043. var face = this.faces[ i ];
  6044. var hasMaterial = false; // face.materialIndex !== undefined;
  6045. var hasFaceUv = false; // deprecated
  6046. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  6047. var hasFaceNormal = face.normal.length() > 0;
  6048. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  6049. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  6050. var hasFaceVertexColor = face.vertexColors.length > 0;
  6051. var faceType = 0;
  6052. faceType = setBit( faceType, 0, 0 );
  6053. faceType = setBit( faceType, 1, hasMaterial );
  6054. faceType = setBit( faceType, 2, hasFaceUv );
  6055. faceType = setBit( faceType, 3, hasFaceVertexUv );
  6056. faceType = setBit( faceType, 4, hasFaceNormal );
  6057. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  6058. faceType = setBit( faceType, 6, hasFaceColor );
  6059. faceType = setBit( faceType, 7, hasFaceVertexColor );
  6060. faces.push( faceType );
  6061. faces.push( face.a, face.b, face.c );
  6062. /*
  6063. if ( hasMaterial ) {
  6064. faces.push( face.materialIndex );
  6065. }
  6066. */
  6067. if ( hasFaceVertexUv ) {
  6068. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  6069. faces.push(
  6070. getUvIndex( faceVertexUvs[ 0 ] ),
  6071. getUvIndex( faceVertexUvs[ 1 ] ),
  6072. getUvIndex( faceVertexUvs[ 2 ] )
  6073. );
  6074. }
  6075. if ( hasFaceNormal ) {
  6076. faces.push( getNormalIndex( face.normal ) );
  6077. }
  6078. if ( hasFaceVertexNormal ) {
  6079. var vertexNormals = face.vertexNormals;
  6080. faces.push(
  6081. getNormalIndex( vertexNormals[ 0 ] ),
  6082. getNormalIndex( vertexNormals[ 1 ] ),
  6083. getNormalIndex( vertexNormals[ 2 ] )
  6084. );
  6085. }
  6086. if ( hasFaceColor ) {
  6087. faces.push( getColorIndex( face.color ) );
  6088. }
  6089. if ( hasFaceVertexColor ) {
  6090. var vertexColors = face.vertexColors;
  6091. faces.push(
  6092. getColorIndex( vertexColors[ 0 ] ),
  6093. getColorIndex( vertexColors[ 1 ] ),
  6094. getColorIndex( vertexColors[ 2 ] )
  6095. );
  6096. }
  6097. }
  6098. function setBit( value, position, enabled ) {
  6099. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position) );
  6100. }
  6101. function getNormalIndex( normal ) {
  6102. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  6103. if ( normalsHash[ hash ] !== undefined ) {
  6104. return normalsHash[ hash ];
  6105. }
  6106. normalsHash[ hash ] = normals.length / 3;
  6107. normals.push( normal.x, normal.y, normal.z );
  6108. return normalsHash[ hash ];
  6109. }
  6110. function getColorIndex( color ) {
  6111. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  6112. if ( colorsHash[ hash ] !== undefined ) {
  6113. return colorsHash[ hash ];
  6114. }
  6115. colorsHash[ hash ] = colors.length;
  6116. colors.push( color.getHex() );
  6117. return colorsHash[ hash ];
  6118. }
  6119. function getUvIndex( uv ) {
  6120. var hash = uv.x.toString() + uv.y.toString();
  6121. if ( uvsHash[ hash ] !== undefined ) {
  6122. return uvsHash[ hash ];
  6123. }
  6124. uvsHash[ hash ] = uvs.length / 2;
  6125. uvs.push( uv.x, uv.y );
  6126. return uvsHash[ hash ];
  6127. }
  6128. output.data = {};
  6129. output.data.vertices = vertices;
  6130. output.data.normals = normals;
  6131. if ( colors.length > 0 ) output.data.colors = colors;
  6132. if ( uvs.length > 0 ) output.data.uvs = [ uvs ]; // temporal backward compatibility
  6133. output.data.faces = faces;
  6134. //
  6135. return output;
  6136. },
  6137. clone: function () {
  6138. var geometry = new THREE.Geometry();
  6139. var vertices = this.vertices;
  6140. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6141. geometry.vertices.push( vertices[ i ].clone() );
  6142. }
  6143. var faces = this.faces;
  6144. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  6145. geometry.faces.push( faces[ i ].clone() );
  6146. }
  6147. for ( var i = 0, il = this.faceVertexUvs.length; i < il; i ++ ) {
  6148. var faceVertexUvs = this.faceVertexUvs[ i ];
  6149. if ( geometry.faceVertexUvs[ i ] === undefined ) {
  6150. geometry.faceVertexUvs[ i ] = [];
  6151. }
  6152. for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  6153. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  6154. for ( var k = 0, kl = uvs.length; k < kl; k ++ ) {
  6155. var uv = uvs[ k ];
  6156. uvsCopy.push( uv.clone() );
  6157. }
  6158. geometry.faceVertexUvs[ i ].push( uvsCopy );
  6159. }
  6160. }
  6161. return geometry;
  6162. },
  6163. dispose: function () {
  6164. this.dispatchEvent( { type: 'dispose' } );
  6165. }
  6166. };
  6167. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  6168. THREE.GeometryIdCount = 0;
  6169. // File:src/cameras/Camera.js
  6170. /**
  6171. * @author mrdoob / http://mrdoob.com/
  6172. * @author mikael emtinger / http://gomo.se/
  6173. * @author WestLangley / http://github.com/WestLangley
  6174. */
  6175. THREE.Camera = function () {
  6176. THREE.Object3D.call( this );
  6177. this.type = 'Camera';
  6178. this.matrixWorldInverse = new THREE.Matrix4();
  6179. this.projectionMatrix = new THREE.Matrix4();
  6180. };
  6181. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  6182. THREE.Camera.prototype.constructor = THREE.Camera;
  6183. THREE.Camera.prototype.getWorldDirection = function () {
  6184. var quaternion = new THREE.Quaternion();
  6185. return function ( optionalTarget ) {
  6186. var result = optionalTarget || new THREE.Vector3();
  6187. this.getWorldQuaternion( quaternion );
  6188. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  6189. }
  6190. }();
  6191. THREE.Camera.prototype.lookAt = function () {
  6192. // This routine does not support cameras with rotated and/or translated parent(s)
  6193. var m1 = new THREE.Matrix4();
  6194. return function ( vector ) {
  6195. m1.lookAt( this.position, vector, this.up );
  6196. this.quaternion.setFromRotationMatrix( m1 );
  6197. };
  6198. }();
  6199. THREE.Camera.prototype.clone = function ( camera ) {
  6200. if ( camera === undefined ) camera = new THREE.Camera();
  6201. THREE.Object3D.prototype.clone.call( this, camera );
  6202. camera.matrixWorldInverse.copy( this.matrixWorldInverse );
  6203. camera.projectionMatrix.copy( this.projectionMatrix );
  6204. return camera;
  6205. };
  6206. // File:src/cameras/CubeCamera.js
  6207. /**
  6208. * Camera for rendering cube maps
  6209. * - renders scene into axis-aligned cube
  6210. *
  6211. * @author alteredq / http://alteredqualia.com/
  6212. */
  6213. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  6214. THREE.Object3D.call( this );
  6215. this.type = 'CubeCamera';
  6216. var fov = 90, aspect = 1;
  6217. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6218. cameraPX.up.set( 0, - 1, 0 );
  6219. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  6220. this.add( cameraPX );
  6221. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6222. cameraNX.up.set( 0, - 1, 0 );
  6223. cameraNX.lookAt( new THREE.Vector3( - 1, 0, 0 ) );
  6224. this.add( cameraNX );
  6225. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6226. cameraPY.up.set( 0, 0, 1 );
  6227. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  6228. this.add( cameraPY );
  6229. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6230. cameraNY.up.set( 0, 0, - 1 );
  6231. cameraNY.lookAt( new THREE.Vector3( 0, - 1, 0 ) );
  6232. this.add( cameraNY );
  6233. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6234. cameraPZ.up.set( 0, - 1, 0 );
  6235. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  6236. this.add( cameraPZ );
  6237. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6238. cameraNZ.up.set( 0, - 1, 0 );
  6239. cameraNZ.lookAt( new THREE.Vector3( 0, 0, - 1 ) );
  6240. this.add( cameraNZ );
  6241. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  6242. this.updateCubeMap = function ( renderer, scene ) {
  6243. var renderTarget = this.renderTarget;
  6244. var generateMipmaps = renderTarget.generateMipmaps;
  6245. renderTarget.generateMipmaps = false;
  6246. renderTarget.activeCubeFace = 0;
  6247. renderer.render( scene, cameraPX, renderTarget );
  6248. renderTarget.activeCubeFace = 1;
  6249. renderer.render( scene, cameraNX, renderTarget );
  6250. renderTarget.activeCubeFace = 2;
  6251. renderer.render( scene, cameraPY, renderTarget );
  6252. renderTarget.activeCubeFace = 3;
  6253. renderer.render( scene, cameraNY, renderTarget );
  6254. renderTarget.activeCubeFace = 4;
  6255. renderer.render( scene, cameraPZ, renderTarget );
  6256. renderTarget.generateMipmaps = generateMipmaps;
  6257. renderTarget.activeCubeFace = 5;
  6258. renderer.render( scene, cameraNZ, renderTarget );
  6259. };
  6260. };
  6261. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  6262. THREE.CubeCamera.prototype.constructor = THREE.CubeCamera;
  6263. // File:src/cameras/OrthographicCamera.js
  6264. /**
  6265. * @author alteredq / http://alteredqualia.com/
  6266. */
  6267. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  6268. THREE.Camera.call( this );
  6269. this.type = 'OrthographicCamera';
  6270. this.zoom = 1;
  6271. this.left = left;
  6272. this.right = right;
  6273. this.top = top;
  6274. this.bottom = bottom;
  6275. this.near = ( near !== undefined ) ? near : 0.1;
  6276. this.far = ( far !== undefined ) ? far : 2000;
  6277. this.updateProjectionMatrix();
  6278. };
  6279. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  6280. THREE.OrthographicCamera.prototype.constructor = THREE.OrthographicCamera;
  6281. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  6282. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  6283. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  6284. var cx = ( this.right + this.left ) / 2;
  6285. var cy = ( this.top + this.bottom ) / 2;
  6286. this.projectionMatrix.makeOrthographic( cx - dx, cx + dx, cy + dy, cy - dy, this.near, this.far );
  6287. };
  6288. THREE.OrthographicCamera.prototype.clone = function () {
  6289. var camera = new THREE.OrthographicCamera();
  6290. THREE.Camera.prototype.clone.call( this, camera );
  6291. camera.zoom = this.zoom;
  6292. camera.left = this.left;
  6293. camera.right = this.right;
  6294. camera.top = this.top;
  6295. camera.bottom = this.bottom;
  6296. camera.near = this.near;
  6297. camera.far = this.far;
  6298. camera.projectionMatrix.copy( this.projectionMatrix );
  6299. return camera;
  6300. };
  6301. // File:src/cameras/PerspectiveCamera.js
  6302. /**
  6303. * @author mrdoob / http://mrdoob.com/
  6304. * @author greggman / http://games.greggman.com/
  6305. * @author zz85 / http://www.lab4games.net/zz85/blog
  6306. */
  6307. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  6308. THREE.Camera.call( this );
  6309. this.type = 'PerspectiveCamera';
  6310. this.zoom = 1;
  6311. this.fov = fov !== undefined ? fov : 50;
  6312. this.aspect = aspect !== undefined ? aspect : 1;
  6313. this.near = near !== undefined ? near : 0.1;
  6314. this.far = far !== undefined ? far : 2000;
  6315. this.updateProjectionMatrix();
  6316. };
  6317. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  6318. THREE.PerspectiveCamera.prototype.constructor = THREE.PerspectiveCamera;
  6319. /**
  6320. * Uses Focal Length (in mm) to estimate and set FOV
  6321. * 35mm (fullframe) camera is used if frame size is not specified;
  6322. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  6323. */
  6324. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  6325. if ( frameHeight === undefined ) frameHeight = 24;
  6326. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  6327. this.updateProjectionMatrix();
  6328. }
  6329. /**
  6330. * Sets an offset in a larger frustum. This is useful for multi-window or
  6331. * multi-monitor/multi-machine setups.
  6332. *
  6333. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6334. * the monitors are in grid like this
  6335. *
  6336. * +---+---+---+
  6337. * | A | B | C |
  6338. * +---+---+---+
  6339. * | D | E | F |
  6340. * +---+---+---+
  6341. *
  6342. * then for each monitor you would call it like this
  6343. *
  6344. * var w = 1920;
  6345. * var h = 1080;
  6346. * var fullWidth = w * 3;
  6347. * var fullHeight = h * 2;
  6348. *
  6349. * --A--
  6350. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6351. * --B--
  6352. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6353. * --C--
  6354. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6355. * --D--
  6356. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6357. * --E--
  6358. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  6359. * --F--
  6360. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  6361. *
  6362. * Note there is no reason monitors have to be the same size or in a grid.
  6363. */
  6364. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  6365. this.fullWidth = fullWidth;
  6366. this.fullHeight = fullHeight;
  6367. this.x = x;
  6368. this.y = y;
  6369. this.width = width;
  6370. this.height = height;
  6371. this.updateProjectionMatrix();
  6372. };
  6373. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  6374. var fov = THREE.Math.radToDeg( 2 * Math.atan( Math.tan( THREE.Math.degToRad( this.fov ) * 0.5 ) / this.zoom ) );
  6375. if ( this.fullWidth ) {
  6376. var aspect = this.fullWidth / this.fullHeight;
  6377. var top = Math.tan( THREE.Math.degToRad( fov * 0.5 ) ) * this.near;
  6378. var bottom = - top;
  6379. var left = aspect * bottom;
  6380. var right = aspect * top;
  6381. var width = Math.abs( right - left );
  6382. var height = Math.abs( top - bottom );
  6383. this.projectionMatrix.makeFrustum(
  6384. left + this.x * width / this.fullWidth,
  6385. left + ( this.x + this.width ) * width / this.fullWidth,
  6386. top - ( this.y + this.height ) * height / this.fullHeight,
  6387. top - this.y * height / this.fullHeight,
  6388. this.near,
  6389. this.far
  6390. );
  6391. } else {
  6392. this.projectionMatrix.makePerspective( fov, this.aspect, this.near, this.far );
  6393. }
  6394. };
  6395. THREE.PerspectiveCamera.prototype.clone = function () {
  6396. var camera = new THREE.PerspectiveCamera();
  6397. THREE.Camera.prototype.clone.call( this, camera );
  6398. camera.zoom = this.zoom;
  6399. camera.fov = this.fov;
  6400. camera.aspect = this.aspect;
  6401. camera.near = this.near;
  6402. camera.far = this.far;
  6403. camera.projectionMatrix.copy( this.projectionMatrix );
  6404. return camera;
  6405. };
  6406. // File:src/lights/Light.js
  6407. /**
  6408. * @author mrdoob / http://mrdoob.com/
  6409. * @author alteredq / http://alteredqualia.com/
  6410. */
  6411. THREE.Light = function ( color ) {
  6412. THREE.Object3D.call( this );
  6413. this.type = 'Light';
  6414. this.color = new THREE.Color( color );
  6415. };
  6416. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  6417. THREE.Light.prototype.constructor = THREE.Light;
  6418. THREE.Light.prototype.clone = function ( light ) {
  6419. if ( light === undefined ) light = new THREE.Light();
  6420. THREE.Object3D.prototype.clone.call( this, light );
  6421. light.color.copy( this.color );
  6422. return light;
  6423. };
  6424. // File:src/lights/AmbientLight.js
  6425. /**
  6426. * @author mrdoob / http://mrdoob.com/
  6427. */
  6428. THREE.AmbientLight = function ( color ) {
  6429. THREE.Light.call( this, color );
  6430. this.type = 'AmbientLight';
  6431. };
  6432. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  6433. THREE.AmbientLight.prototype.constructor = THREE.AmbientLight;
  6434. THREE.AmbientLight.prototype.clone = function () {
  6435. var light = new THREE.AmbientLight();
  6436. THREE.Light.prototype.clone.call( this, light );
  6437. return light;
  6438. };
  6439. // File:src/lights/AreaLight.js
  6440. /**
  6441. * @author MPanknin / http://www.redplant.de/
  6442. * @author alteredq / http://alteredqualia.com/
  6443. */
  6444. THREE.AreaLight = function ( color, intensity ) {
  6445. THREE.Light.call( this, color );
  6446. this.type = 'AreaLight';
  6447. this.normal = new THREE.Vector3( 0, - 1, 0 );
  6448. this.right = new THREE.Vector3( 1, 0, 0 );
  6449. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6450. this.width = 1.0;
  6451. this.height = 1.0;
  6452. this.constantAttenuation = 1.5;
  6453. this.linearAttenuation = 0.5;
  6454. this.quadraticAttenuation = 0.1;
  6455. };
  6456. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  6457. THREE.AreaLight.prototype.constructor = THREE.AreaLight;
  6458. // File:src/lights/DirectionalLight.js
  6459. /**
  6460. * @author mrdoob / http://mrdoob.com/
  6461. * @author alteredq / http://alteredqualia.com/
  6462. */
  6463. THREE.DirectionalLight = function ( color, intensity ) {
  6464. THREE.Light.call( this, color );
  6465. this.type = 'DirectionalLight';
  6466. this.position.set( 0, 1, 0 );
  6467. this.target = new THREE.Object3D();
  6468. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6469. this.castShadow = false;
  6470. this.onlyShadow = false;
  6471. //
  6472. this.shadowCameraNear = 50;
  6473. this.shadowCameraFar = 5000;
  6474. this.shadowCameraLeft = - 500;
  6475. this.shadowCameraRight = 500;
  6476. this.shadowCameraTop = 500;
  6477. this.shadowCameraBottom = - 500;
  6478. this.shadowCameraVisible = false;
  6479. this.shadowBias = 0;
  6480. this.shadowDarkness = 0.5;
  6481. this.shadowMapWidth = 512;
  6482. this.shadowMapHeight = 512;
  6483. //
  6484. this.shadowCascade = false;
  6485. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, - 1000 );
  6486. this.shadowCascadeCount = 2;
  6487. this.shadowCascadeBias = [ 0, 0, 0 ];
  6488. this.shadowCascadeWidth = [ 512, 512, 512 ];
  6489. this.shadowCascadeHeight = [ 512, 512, 512 ];
  6490. this.shadowCascadeNearZ = [ - 1.000, 0.990, 0.998 ];
  6491. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  6492. this.shadowCascadeArray = [];
  6493. //
  6494. this.shadowMap = null;
  6495. this.shadowMapSize = null;
  6496. this.shadowCamera = null;
  6497. this.shadowMatrix = null;
  6498. };
  6499. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  6500. THREE.DirectionalLight.prototype.constructor = THREE.DirectionalLight;
  6501. THREE.DirectionalLight.prototype.clone = function () {
  6502. var light = new THREE.DirectionalLight();
  6503. THREE.Light.prototype.clone.call( this, light );
  6504. light.target = this.target.clone();
  6505. light.intensity = this.intensity;
  6506. light.castShadow = this.castShadow;
  6507. light.onlyShadow = this.onlyShadow;
  6508. //
  6509. light.shadowCameraNear = this.shadowCameraNear;
  6510. light.shadowCameraFar = this.shadowCameraFar;
  6511. light.shadowCameraLeft = this.shadowCameraLeft;
  6512. light.shadowCameraRight = this.shadowCameraRight;
  6513. light.shadowCameraTop = this.shadowCameraTop;
  6514. light.shadowCameraBottom = this.shadowCameraBottom;
  6515. light.shadowCameraVisible = this.shadowCameraVisible;
  6516. light.shadowBias = this.shadowBias;
  6517. light.shadowDarkness = this.shadowDarkness;
  6518. light.shadowMapWidth = this.shadowMapWidth;
  6519. light.shadowMapHeight = this.shadowMapHeight;
  6520. //
  6521. light.shadowCascade = this.shadowCascade;
  6522. light.shadowCascadeOffset.copy( this.shadowCascadeOffset );
  6523. light.shadowCascadeCount = this.shadowCascadeCount;
  6524. light.shadowCascadeBias = this.shadowCascadeBias.slice( 0 );
  6525. light.shadowCascadeWidth = this.shadowCascadeWidth.slice( 0 );
  6526. light.shadowCascadeHeight = this.shadowCascadeHeight.slice( 0 );
  6527. light.shadowCascadeNearZ = this.shadowCascadeNearZ.slice( 0 );
  6528. light.shadowCascadeFarZ = this.shadowCascadeFarZ.slice( 0 );
  6529. return light;
  6530. };
  6531. // File:src/lights/HemisphereLight.js
  6532. /**
  6533. * @author alteredq / http://alteredqualia.com/
  6534. */
  6535. THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
  6536. THREE.Light.call( this, skyColor );
  6537. this.type = 'HemisphereLight';
  6538. this.position.set( 0, 100, 0 );
  6539. this.groundColor = new THREE.Color( groundColor );
  6540. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6541. };
  6542. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  6543. THREE.HemisphereLight.prototype.constructor = THREE.HemisphereLight;
  6544. THREE.HemisphereLight.prototype.clone = function () {
  6545. var light = new THREE.HemisphereLight();
  6546. THREE.Light.prototype.clone.call( this, light );
  6547. light.groundColor.copy( this.groundColor );
  6548. light.intensity = this.intensity;
  6549. return light;
  6550. };
  6551. // File:src/lights/PointLight.js
  6552. /**
  6553. * @author mrdoob / http://mrdoob.com/
  6554. */
  6555. THREE.PointLight = function ( color, intensity, distance, decay ) {
  6556. THREE.Light.call( this, color );
  6557. this.type = 'PointLight';
  6558. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6559. this.distance = ( distance !== undefined ) ? distance : 0;
  6560. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  6561. };
  6562. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  6563. THREE.PointLight.prototype.constructor = THREE.PointLight;
  6564. THREE.PointLight.prototype.clone = function () {
  6565. var light = new THREE.PointLight();
  6566. THREE.Light.prototype.clone.call( this, light );
  6567. light.intensity = this.intensity;
  6568. light.distance = this.distance;
  6569. light.decay = this.decay;
  6570. return light;
  6571. };
  6572. // File:src/lights/SpotLight.js
  6573. /**
  6574. * @author alteredq / http://alteredqualia.com/
  6575. */
  6576. THREE.SpotLight = function ( color, intensity, distance, angle, exponent, decay ) {
  6577. THREE.Light.call( this, color );
  6578. this.type = 'SpotLight';
  6579. this.position.set( 0, 1, 0 );
  6580. this.target = new THREE.Object3D();
  6581. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6582. this.distance = ( distance !== undefined ) ? distance : 0;
  6583. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  6584. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  6585. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  6586. this.castShadow = false;
  6587. this.onlyShadow = false;
  6588. //
  6589. this.shadowCameraNear = 50;
  6590. this.shadowCameraFar = 5000;
  6591. this.shadowCameraFov = 50;
  6592. this.shadowCameraVisible = false;
  6593. this.shadowBias = 0;
  6594. this.shadowDarkness = 0.5;
  6595. this.shadowMapWidth = 512;
  6596. this.shadowMapHeight = 512;
  6597. //
  6598. this.shadowMap = null;
  6599. this.shadowMapSize = null;
  6600. this.shadowCamera = null;
  6601. this.shadowMatrix = null;
  6602. };
  6603. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  6604. THREE.SpotLight.prototype.constructor = THREE.SpotLight;
  6605. THREE.SpotLight.prototype.clone = function () {
  6606. var light = new THREE.SpotLight();
  6607. THREE.Light.prototype.clone.call( this, light );
  6608. light.target = this.target.clone();
  6609. light.intensity = this.intensity;
  6610. light.distance = this.distance;
  6611. light.angle = this.angle;
  6612. light.exponent = this.exponent;
  6613. light.decay = this.decay;
  6614. light.castShadow = this.castShadow;
  6615. light.onlyShadow = this.onlyShadow;
  6616. //
  6617. light.shadowCameraNear = this.shadowCameraNear;
  6618. light.shadowCameraFar = this.shadowCameraFar;
  6619. light.shadowCameraFov = this.shadowCameraFov;
  6620. light.shadowCameraVisible = this.shadowCameraVisible;
  6621. light.shadowBias = this.shadowBias;
  6622. light.shadowDarkness = this.shadowDarkness;
  6623. light.shadowMapWidth = this.shadowMapWidth;
  6624. light.shadowMapHeight = this.shadowMapHeight;
  6625. return light;
  6626. };
  6627. // File:src/loaders/Cache.js
  6628. /**
  6629. * @author mrdoob / http://mrdoob.com/
  6630. */
  6631. THREE.Cache = function () {
  6632. this.files = {};
  6633. };
  6634. THREE.Cache.prototype = {
  6635. constructor: THREE.Cache,
  6636. add: function ( key, file ) {
  6637. // console.log( 'THREE.Cache', 'Adding key:', key );
  6638. this.files[ key ] = file;
  6639. },
  6640. get: function ( key ) {
  6641. // console.log( 'THREE.Cache', 'Checking key:', key );
  6642. return this.files[ key ];
  6643. },
  6644. remove: function ( key ) {
  6645. delete this.files[ key ];
  6646. },
  6647. clear: function () {
  6648. this.files = {}
  6649. }
  6650. };
  6651. // File:src/loaders/Loader.js
  6652. /**
  6653. * @author alteredq / http://alteredqualia.com/
  6654. */
  6655. THREE.Loader = function ( showStatus ) {
  6656. this.showStatus = showStatus;
  6657. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  6658. this.imageLoader = new THREE.ImageLoader();
  6659. this.onLoadStart = function () {};
  6660. this.onLoadProgress = function () {};
  6661. this.onLoadComplete = function () {};
  6662. };
  6663. THREE.Loader.prototype = {
  6664. constructor: THREE.Loader,
  6665. crossOrigin: undefined,
  6666. addStatusElement: function () {
  6667. var e = document.createElement( 'div' );
  6668. e.style.position = 'absolute';
  6669. e.style.right = '0px';
  6670. e.style.top = '0px';
  6671. e.style.fontSize = '0.8em';
  6672. e.style.textAlign = 'left';
  6673. e.style.background = 'rgba(0,0,0,0.25)';
  6674. e.style.color = '#fff';
  6675. e.style.width = '120px';
  6676. e.style.padding = '0.5em 0.5em 0.5em 0.5em';
  6677. e.style.zIndex = 1000;
  6678. e.innerHTML = 'Loading ...';
  6679. return e;
  6680. },
  6681. updateProgress: function ( progress ) {
  6682. var message = 'Loaded ';
  6683. if ( progress.total ) {
  6684. message += ( 100 * progress.loaded / progress.total ).toFixed( 0 ) + '%';
  6685. } else {
  6686. message += ( progress.loaded / 1024 ).toFixed( 2 ) + ' KB';
  6687. }
  6688. this.statusDomElement.innerHTML = message;
  6689. },
  6690. extractUrlBase: function ( url ) {
  6691. var parts = url.split( '/' );
  6692. if ( parts.length === 1 ) return './';
  6693. parts.pop();
  6694. return parts.join( '/' ) + '/';
  6695. },
  6696. initMaterials: function ( materials, texturePath ) {
  6697. var array = [];
  6698. for ( var i = 0; i < materials.length; ++ i ) {
  6699. array[ i ] = this.createMaterial( materials[ i ], texturePath );
  6700. }
  6701. return array;
  6702. },
  6703. needsTangents: function ( materials ) {
  6704. for ( var i = 0, il = materials.length; i < il; i ++ ) {
  6705. var m = materials[ i ];
  6706. if ( m instanceof THREE.ShaderMaterial ) return true;
  6707. }
  6708. return false;
  6709. },
  6710. createMaterial: function ( m, texturePath ) {
  6711. var scope = this;
  6712. function nearest_pow2( n ) {
  6713. var l = Math.log( n ) / Math.LN2;
  6714. return Math.pow( 2, Math.round( l ) );
  6715. }
  6716. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  6717. var fullPath = texturePath + sourceFile;
  6718. var texture;
  6719. var loader = THREE.Loader.Handlers.get( fullPath );
  6720. if ( loader !== null ) {
  6721. texture = loader.load( fullPath );
  6722. } else {
  6723. texture = new THREE.Texture();
  6724. loader = scope.imageLoader;
  6725. loader.crossOrigin = scope.crossOrigin;
  6726. loader.load( fullPath, function ( image ) {
  6727. if ( THREE.Math.isPowerOfTwo( image.width ) === false ||
  6728. THREE.Math.isPowerOfTwo( image.height ) === false ) {
  6729. var width = nearest_pow2( image.width );
  6730. var height = nearest_pow2( image.height );
  6731. var canvas = document.createElement( 'canvas' );
  6732. canvas.width = width;
  6733. canvas.height = height;
  6734. var context = canvas.getContext( '2d' );
  6735. context.drawImage( image, 0, 0, width, height );
  6736. texture.image = canvas;
  6737. } else {
  6738. texture.image = image;
  6739. }
  6740. texture.needsUpdate = true;
  6741. } );
  6742. }
  6743. texture.sourceFile = sourceFile;
  6744. if ( repeat ) {
  6745. texture.repeat.set( repeat[ 0 ], repeat[ 1 ] );
  6746. if ( repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  6747. if ( repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  6748. }
  6749. if ( offset ) {
  6750. texture.offset.set( offset[ 0 ], offset[ 1 ] );
  6751. }
  6752. if ( wrap ) {
  6753. var wrapMap = {
  6754. 'repeat': THREE.RepeatWrapping,
  6755. 'mirror': THREE.MirroredRepeatWrapping
  6756. }
  6757. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ wrap[ 0 ] ];
  6758. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ wrap[ 1 ] ];
  6759. }
  6760. if ( anisotropy ) {
  6761. texture.anisotropy = anisotropy;
  6762. }
  6763. where[ name ] = texture;
  6764. }
  6765. function rgb2hex( rgb ) {
  6766. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  6767. }
  6768. // defaults
  6769. var mtype = 'MeshLambertMaterial';
  6770. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  6771. // parameters from model file
  6772. if ( m.shading ) {
  6773. var shading = m.shading.toLowerCase();
  6774. if ( shading === 'phong' ) mtype = 'MeshPhongMaterial';
  6775. else if ( shading === 'basic' ) mtype = 'MeshBasicMaterial';
  6776. }
  6777. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  6778. mpars.blending = THREE[ m.blending ];
  6779. }
  6780. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  6781. mpars.transparent = m.transparent;
  6782. }
  6783. if ( m.depthTest !== undefined ) {
  6784. mpars.depthTest = m.depthTest;
  6785. }
  6786. if ( m.depthWrite !== undefined ) {
  6787. mpars.depthWrite = m.depthWrite;
  6788. }
  6789. if ( m.visible !== undefined ) {
  6790. mpars.visible = m.visible;
  6791. }
  6792. if ( m.flipSided !== undefined ) {
  6793. mpars.side = THREE.BackSide;
  6794. }
  6795. if ( m.doubleSided !== undefined ) {
  6796. mpars.side = THREE.DoubleSide;
  6797. }
  6798. if ( m.wireframe !== undefined ) {
  6799. mpars.wireframe = m.wireframe;
  6800. }
  6801. if ( m.vertexColors !== undefined ) {
  6802. if ( m.vertexColors === 'face' ) {
  6803. mpars.vertexColors = THREE.FaceColors;
  6804. } else if ( m.vertexColors ) {
  6805. mpars.vertexColors = THREE.VertexColors;
  6806. }
  6807. }
  6808. // colors
  6809. if ( m.colorDiffuse ) {
  6810. mpars.color = rgb2hex( m.colorDiffuse );
  6811. } else if ( m.DbgColor ) {
  6812. mpars.color = m.DbgColor;
  6813. }
  6814. if ( m.colorSpecular ) {
  6815. mpars.specular = rgb2hex( m.colorSpecular );
  6816. }
  6817. if ( m.colorEmissive ) {
  6818. mpars.emissive = rgb2hex( m.colorEmissive );
  6819. }
  6820. // modifiers
  6821. if ( m.transparency ) {
  6822. console.warn( 'THREE.Loader: transparency has been renamed to opacity' );
  6823. mpars.opacity = m.transparency;
  6824. }
  6825. if ( m.opacity ) {
  6826. mpars.opacity = m.opacity;
  6827. }
  6828. if ( m.specularCoef ) {
  6829. mpars.shininess = m.specularCoef;
  6830. }
  6831. // textures
  6832. if ( m.mapDiffuse && texturePath ) {
  6833. create_texture( mpars, 'map', m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  6834. }
  6835. if ( m.mapLight && texturePath ) {
  6836. create_texture( mpars, 'lightMap', m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  6837. }
  6838. if ( m.mapBump && texturePath ) {
  6839. create_texture( mpars, 'bumpMap', m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  6840. }
  6841. if ( m.mapNormal && texturePath ) {
  6842. create_texture( mpars, 'normalMap', m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  6843. }
  6844. if ( m.mapSpecular && texturePath ) {
  6845. create_texture( mpars, 'specularMap', m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  6846. }
  6847. if ( m.mapAlpha && texturePath ) {
  6848. create_texture( mpars, 'alphaMap', m.mapAlpha, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  6849. }
  6850. //
  6851. if ( m.mapBumpScale ) {
  6852. mpars.bumpScale = m.mapBumpScale;
  6853. }
  6854. if ( m.mapNormalFactor ) {
  6855. mpars.normalScale = new THREE.Vector2( m.mapNormalFactor, m.mapNormalFactor );
  6856. }
  6857. var material = new THREE[ mtype ]( mpars );
  6858. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6859. return material;
  6860. }
  6861. };
  6862. THREE.Loader.Handlers = {
  6863. handlers: [],
  6864. add: function ( regex, loader ) {
  6865. this.handlers.push( regex, loader );
  6866. },
  6867. get: function ( file ) {
  6868. for ( var i = 0, l = this.handlers.length; i < l; i += 2 ) {
  6869. var regex = this.handlers[ i ];
  6870. var loader = this.handlers[ i + 1 ];
  6871. if ( regex.test( file ) ) {
  6872. return loader;
  6873. }
  6874. }
  6875. return null;
  6876. }
  6877. };
  6878. // File:src/loaders/XHRLoader.js
  6879. /**
  6880. * @author mrdoob / http://mrdoob.com/
  6881. */
  6882. THREE.XHRLoader = function ( manager ) {
  6883. this.cache = new THREE.Cache();
  6884. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6885. };
  6886. THREE.XHRLoader.prototype = {
  6887. constructor: THREE.XHRLoader,
  6888. load: function ( url, onLoad, onProgress, onError ) {
  6889. var scope = this;
  6890. var cached = scope.cache.get( url );
  6891. if ( cached !== undefined ) {
  6892. if ( onLoad ) onLoad( cached );
  6893. return;
  6894. }
  6895. var request = new XMLHttpRequest();
  6896. request.open( 'GET', url, true );
  6897. request.addEventListener( 'load', function ( event ) {
  6898. scope.cache.add( url, this.response );
  6899. if ( onLoad ) onLoad( this.response );
  6900. scope.manager.itemEnd( url );
  6901. }, false );
  6902. if ( onProgress !== undefined ) {
  6903. request.addEventListener( 'progress', function ( event ) {
  6904. onProgress( event );
  6905. }, false );
  6906. }
  6907. if ( onError !== undefined ) {
  6908. request.addEventListener( 'error', function ( event ) {
  6909. onError( event );
  6910. }, false );
  6911. }
  6912. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  6913. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  6914. request.send( null );
  6915. scope.manager.itemStart( url );
  6916. },
  6917. setResponseType: function ( value ) {
  6918. this.responseType = value;
  6919. },
  6920. setCrossOrigin: function ( value ) {
  6921. this.crossOrigin = value;
  6922. }
  6923. };
  6924. // File:src/loaders/ImageLoader.js
  6925. /**
  6926. * @author mrdoob / http://mrdoob.com/
  6927. */
  6928. THREE.ImageLoader = function ( manager ) {
  6929. this.cache = new THREE.Cache();
  6930. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6931. };
  6932. THREE.ImageLoader.prototype = {
  6933. constructor: THREE.ImageLoader,
  6934. load: function ( url, onLoad, onProgress, onError ) {
  6935. var scope = this;
  6936. var cached = scope.cache.get( url );
  6937. if ( cached !== undefined ) {
  6938. onLoad( cached );
  6939. return;
  6940. }
  6941. var image = document.createElement( 'img' );
  6942. if ( onLoad !== undefined ) {
  6943. image.addEventListener( 'load', function ( event ) {
  6944. scope.cache.add( url, this );
  6945. onLoad( this );
  6946. scope.manager.itemEnd( url );
  6947. }, false );
  6948. }
  6949. if ( onProgress !== undefined ) {
  6950. image.addEventListener( 'progress', function ( event ) {
  6951. onProgress( event );
  6952. }, false );
  6953. }
  6954. if ( onError !== undefined ) {
  6955. image.addEventListener( 'error', function ( event ) {
  6956. onError( event );
  6957. }, false );
  6958. }
  6959. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  6960. image.src = url;
  6961. scope.manager.itemStart( url );
  6962. return image;
  6963. },
  6964. setCrossOrigin: function ( value ) {
  6965. this.crossOrigin = value;
  6966. }
  6967. }
  6968. // File:src/loaders/JSONLoader.js
  6969. /**
  6970. * @author mrdoob / http://mrdoob.com/
  6971. * @author alteredq / http://alteredqualia.com/
  6972. */
  6973. THREE.JSONLoader = function ( showStatus ) {
  6974. THREE.Loader.call( this, showStatus );
  6975. this.withCredentials = false;
  6976. };
  6977. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  6978. THREE.JSONLoader.prototype.constructor = THREE.JSONLoader;
  6979. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  6980. var scope = this;
  6981. // todo: unify load API to for easier SceneLoader use
  6982. texturePath = texturePath && ( typeof texturePath === 'string' ) ? texturePath : this.extractUrlBase( url );
  6983. this.onLoadStart();
  6984. this.loadAjaxJSON( this, url, callback, texturePath );
  6985. };
  6986. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  6987. var xhr = new XMLHttpRequest();
  6988. var length = 0;
  6989. xhr.onreadystatechange = function () {
  6990. if ( xhr.readyState === xhr.DONE ) {
  6991. if ( xhr.status === 200 || xhr.status === 0 ) {
  6992. if ( xhr.responseText ) {
  6993. var json = JSON.parse( xhr.responseText );
  6994. if ( json.metadata !== undefined && json.metadata.version >= 4 ) {
  6995. console.error( 'THREE.JSONLoader: "' + url + '" should be loaded with THREE.ObjectLoader instead.' );
  6996. return;
  6997. }
  6998. if ( json.metadata !== undefined && json.metadata.type === 'scene' ) {
  6999. THREE.error( 'THREE.JSONLoader: "' + url + '" seems to be a Scene. Use THREE.SceneLoader instead.' );
  7000. return;
  7001. }
  7002. var result = context.parse( json, texturePath );
  7003. callback( result.geometry, result.materials );
  7004. } else {
  7005. THREE.error( 'THREE.JSONLoader: "' + url + '" seems to be unreachable or the file is empty.' );
  7006. }
  7007. // in context of more complex asset initialization
  7008. // do not block on single failed file
  7009. // maybe should go even one more level up
  7010. context.onLoadComplete();
  7011. } else {
  7012. THREE.error( 'THREE.JSONLoader: Couldn\'t load "' + url + '" (' + xhr.status + ')' );
  7013. }
  7014. } else if ( xhr.readyState === xhr.LOADING ) {
  7015. if ( callbackProgress ) {
  7016. if ( length === 0 ) {
  7017. length = xhr.getResponseHeader( 'Content-Length' );
  7018. }
  7019. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  7020. }
  7021. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  7022. if ( callbackProgress !== undefined ) {
  7023. length = xhr.getResponseHeader( 'Content-Length' );
  7024. }
  7025. }
  7026. };
  7027. xhr.open( 'GET', url, true );
  7028. xhr.withCredentials = this.withCredentials;
  7029. xhr.send( null );
  7030. };
  7031. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  7032. var scope = this,
  7033. geometry = new THREE.Geometry(),
  7034. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  7035. parseModel( scale );
  7036. parseSkin();
  7037. parseMorphing( scale );
  7038. geometry.computeFaceNormals();
  7039. geometry.computeBoundingSphere();
  7040. function parseModel( scale ) {
  7041. function isBitSet( value, position ) {
  7042. return value & ( 1 << position );
  7043. }
  7044. var i, j, fi,
  7045. offset, zLength,
  7046. colorIndex, normalIndex, uvIndex, materialIndex,
  7047. type,
  7048. isQuad,
  7049. hasMaterial,
  7050. hasFaceVertexUv,
  7051. hasFaceNormal, hasFaceVertexNormal,
  7052. hasFaceColor, hasFaceVertexColor,
  7053. vertex, face, faceA, faceB, color, hex, normal,
  7054. uvLayer, uv, u, v,
  7055. faces = json.faces,
  7056. vertices = json.vertices,
  7057. normals = json.normals,
  7058. colors = json.colors,
  7059. nUvLayers = 0;
  7060. if ( json.uvs !== undefined ) {
  7061. // disregard empty arrays
  7062. for ( i = 0; i < json.uvs.length; i ++ ) {
  7063. if ( json.uvs[ i ].length ) nUvLayers ++;
  7064. }
  7065. for ( i = 0; i < nUvLayers; i ++ ) {
  7066. geometry.faceVertexUvs[ i ] = [];
  7067. }
  7068. }
  7069. offset = 0;
  7070. zLength = vertices.length;
  7071. while ( offset < zLength ) {
  7072. vertex = new THREE.Vector3();
  7073. vertex.x = vertices[ offset ++ ] * scale;
  7074. vertex.y = vertices[ offset ++ ] * scale;
  7075. vertex.z = vertices[ offset ++ ] * scale;
  7076. geometry.vertices.push( vertex );
  7077. }
  7078. offset = 0;
  7079. zLength = faces.length;
  7080. while ( offset < zLength ) {
  7081. type = faces[ offset ++ ];
  7082. isQuad = isBitSet( type, 0 );
  7083. hasMaterial = isBitSet( type, 1 );
  7084. hasFaceVertexUv = isBitSet( type, 3 );
  7085. hasFaceNormal = isBitSet( type, 4 );
  7086. hasFaceVertexNormal = isBitSet( type, 5 );
  7087. hasFaceColor = isBitSet( type, 6 );
  7088. hasFaceVertexColor = isBitSet( type, 7 );
  7089. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  7090. if ( isQuad ) {
  7091. faceA = new THREE.Face3();
  7092. faceA.a = faces[ offset ];
  7093. faceA.b = faces[ offset + 1 ];
  7094. faceA.c = faces[ offset + 3 ];
  7095. faceB = new THREE.Face3();
  7096. faceB.a = faces[ offset + 1 ];
  7097. faceB.b = faces[ offset + 2 ];
  7098. faceB.c = faces[ offset + 3 ];
  7099. offset += 4;
  7100. if ( hasMaterial ) {
  7101. materialIndex = faces[ offset ++ ];
  7102. faceA.materialIndex = materialIndex;
  7103. faceB.materialIndex = materialIndex;
  7104. }
  7105. // to get face <=> uv index correspondence
  7106. fi = geometry.faces.length;
  7107. if ( hasFaceVertexUv ) {
  7108. for ( i = 0; i < nUvLayers; i ++ ) {
  7109. uvLayer = json.uvs[ i ];
  7110. geometry.faceVertexUvs[ i ][ fi ] = [];
  7111. geometry.faceVertexUvs[ i ][ fi + 1 ] = []
  7112. for ( j = 0; j < 4; j ++ ) {
  7113. uvIndex = faces[ offset ++ ];
  7114. u = uvLayer[ uvIndex * 2 ];
  7115. v = uvLayer[ uvIndex * 2 + 1 ];
  7116. uv = new THREE.Vector2( u, v );
  7117. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7118. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  7119. }
  7120. }
  7121. }
  7122. if ( hasFaceNormal ) {
  7123. normalIndex = faces[ offset ++ ] * 3;
  7124. faceA.normal.set(
  7125. normals[ normalIndex ++ ],
  7126. normals[ normalIndex ++ ],
  7127. normals[ normalIndex ]
  7128. );
  7129. faceB.normal.copy( faceA.normal );
  7130. }
  7131. if ( hasFaceVertexNormal ) {
  7132. for ( i = 0; i < 4; i ++ ) {
  7133. normalIndex = faces[ offset ++ ] * 3;
  7134. normal = new THREE.Vector3(
  7135. normals[ normalIndex ++ ],
  7136. normals[ normalIndex ++ ],
  7137. normals[ normalIndex ]
  7138. );
  7139. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  7140. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  7141. }
  7142. }
  7143. if ( hasFaceColor ) {
  7144. colorIndex = faces[ offset ++ ];
  7145. hex = colors[ colorIndex ];
  7146. faceA.color.setHex( hex );
  7147. faceB.color.setHex( hex );
  7148. }
  7149. if ( hasFaceVertexColor ) {
  7150. for ( i = 0; i < 4; i ++ ) {
  7151. colorIndex = faces[ offset ++ ];
  7152. hex = colors[ colorIndex ];
  7153. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  7154. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  7155. }
  7156. }
  7157. geometry.faces.push( faceA );
  7158. geometry.faces.push( faceB );
  7159. } else {
  7160. face = new THREE.Face3();
  7161. face.a = faces[ offset ++ ];
  7162. face.b = faces[ offset ++ ];
  7163. face.c = faces[ offset ++ ];
  7164. if ( hasMaterial ) {
  7165. materialIndex = faces[ offset ++ ];
  7166. face.materialIndex = materialIndex;
  7167. }
  7168. // to get face <=> uv index correspondence
  7169. fi = geometry.faces.length;
  7170. if ( hasFaceVertexUv ) {
  7171. for ( i = 0; i < nUvLayers; i ++ ) {
  7172. uvLayer = json.uvs[ i ];
  7173. geometry.faceVertexUvs[ i ][ fi ] = [];
  7174. for ( j = 0; j < 3; j ++ ) {
  7175. uvIndex = faces[ offset ++ ];
  7176. u = uvLayer[ uvIndex * 2 ];
  7177. v = uvLayer[ uvIndex * 2 + 1 ];
  7178. uv = new THREE.Vector2( u, v );
  7179. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7180. }
  7181. }
  7182. }
  7183. if ( hasFaceNormal ) {
  7184. normalIndex = faces[ offset ++ ] * 3;
  7185. face.normal.set(
  7186. normals[ normalIndex ++ ],
  7187. normals[ normalIndex ++ ],
  7188. normals[ normalIndex ]
  7189. );
  7190. }
  7191. if ( hasFaceVertexNormal ) {
  7192. for ( i = 0; i < 3; i ++ ) {
  7193. normalIndex = faces[ offset ++ ] * 3;
  7194. normal = new THREE.Vector3(
  7195. normals[ normalIndex ++ ],
  7196. normals[ normalIndex ++ ],
  7197. normals[ normalIndex ]
  7198. );
  7199. face.vertexNormals.push( normal );
  7200. }
  7201. }
  7202. if ( hasFaceColor ) {
  7203. colorIndex = faces[ offset ++ ];
  7204. face.color.setHex( colors[ colorIndex ] );
  7205. }
  7206. if ( hasFaceVertexColor ) {
  7207. for ( i = 0; i < 3; i ++ ) {
  7208. colorIndex = faces[ offset ++ ];
  7209. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  7210. }
  7211. }
  7212. geometry.faces.push( face );
  7213. }
  7214. }
  7215. };
  7216. function parseSkin() {
  7217. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  7218. if ( json.skinWeights ) {
  7219. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  7220. var x = json.skinWeights[ i ];
  7221. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  7222. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  7223. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  7224. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  7225. }
  7226. }
  7227. if ( json.skinIndices ) {
  7228. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  7229. var a = json.skinIndices[ i ];
  7230. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  7231. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  7232. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  7233. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  7234. }
  7235. }
  7236. geometry.bones = json.bones;
  7237. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  7238. THREE.warn( 'THREE.JSONLoader: When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  7239. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  7240. }
  7241. // could change this to json.animations[0] or remove completely
  7242. geometry.animation = json.animation;
  7243. geometry.animations = json.animations;
  7244. };
  7245. function parseMorphing( scale ) {
  7246. if ( json.morphTargets !== undefined ) {
  7247. var i, l, v, vl, dstVertices, srcVertices;
  7248. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  7249. geometry.morphTargets[ i ] = {};
  7250. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  7251. geometry.morphTargets[ i ].vertices = [];
  7252. dstVertices = geometry.morphTargets[ i ].vertices;
  7253. srcVertices = json.morphTargets [ i ].vertices;
  7254. for ( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  7255. var vertex = new THREE.Vector3();
  7256. vertex.x = srcVertices[ v ] * scale;
  7257. vertex.y = srcVertices[ v + 1 ] * scale;
  7258. vertex.z = srcVertices[ v + 2 ] * scale;
  7259. dstVertices.push( vertex );
  7260. }
  7261. }
  7262. }
  7263. if ( json.morphColors !== undefined ) {
  7264. var i, l, c, cl, dstColors, srcColors, color;
  7265. for ( i = 0, l = json.morphColors.length; i < l; i ++ ) {
  7266. geometry.morphColors[ i ] = {};
  7267. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  7268. geometry.morphColors[ i ].colors = [];
  7269. dstColors = geometry.morphColors[ i ].colors;
  7270. srcColors = json.morphColors [ i ].colors;
  7271. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  7272. color = new THREE.Color( 0xffaa00 );
  7273. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  7274. dstColors.push( color );
  7275. }
  7276. }
  7277. }
  7278. };
  7279. if ( json.materials === undefined || json.materials.length === 0 ) {
  7280. return { geometry: geometry };
  7281. } else {
  7282. var materials = this.initMaterials( json.materials, texturePath );
  7283. if ( this.needsTangents( materials ) ) {
  7284. geometry.computeTangents();
  7285. }
  7286. return { geometry: geometry, materials: materials };
  7287. }
  7288. };
  7289. // File:src/loaders/LoadingManager.js
  7290. /**
  7291. * @author mrdoob / http://mrdoob.com/
  7292. */
  7293. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  7294. var scope = this;
  7295. var loaded = 0, total = 0;
  7296. this.onLoad = onLoad;
  7297. this.onProgress = onProgress;
  7298. this.onError = onError;
  7299. this.itemStart = function ( url ) {
  7300. total ++;
  7301. };
  7302. this.itemEnd = function ( url ) {
  7303. loaded ++;
  7304. if ( scope.onProgress !== undefined ) {
  7305. scope.onProgress( url, loaded, total );
  7306. }
  7307. if ( loaded === total && scope.onLoad !== undefined ) {
  7308. scope.onLoad();
  7309. }
  7310. };
  7311. };
  7312. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  7313. // File:src/loaders/BufferGeometryLoader.js
  7314. /**
  7315. * @author mrdoob / http://mrdoob.com/
  7316. */
  7317. THREE.BufferGeometryLoader = function ( manager ) {
  7318. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7319. };
  7320. THREE.BufferGeometryLoader.prototype = {
  7321. constructor: THREE.BufferGeometryLoader,
  7322. load: function ( url, onLoad, onProgress, onError ) {
  7323. var scope = this;
  7324. var loader = new THREE.XHRLoader( scope.manager );
  7325. loader.setCrossOrigin( this.crossOrigin );
  7326. loader.load( url, function ( text ) {
  7327. onLoad( scope.parse( JSON.parse( text ) ) );
  7328. }, onProgress, onError );
  7329. },
  7330. setCrossOrigin: function ( value ) {
  7331. this.crossOrigin = value;
  7332. },
  7333. parse: function ( json ) {
  7334. var geometry = new THREE.BufferGeometry();
  7335. var attributes = json.attributes;
  7336. for ( var key in attributes ) {
  7337. var attribute = attributes[ key ];
  7338. var typedArray = new self[ attribute.type ]( attribute.array );
  7339. geometry.addAttribute( key, new THREE.BufferAttribute( typedArray, attribute.itemSize ) );
  7340. }
  7341. var offsets = json.offsets;
  7342. if ( offsets !== undefined ) {
  7343. geometry.offsets = JSON.parse( JSON.stringify( offsets ) );
  7344. }
  7345. var boundingSphere = json.boundingSphere;
  7346. if ( boundingSphere !== undefined ) {
  7347. var center = new THREE.Vector3();
  7348. if ( boundingSphere.center !== undefined ) {
  7349. center.fromArray( boundingSphere.center );
  7350. }
  7351. geometry.boundingSphere = new THREE.Sphere( center, boundingSphere.radius );
  7352. }
  7353. return geometry;
  7354. }
  7355. };
  7356. // File:src/loaders/MaterialLoader.js
  7357. /**
  7358. * @author mrdoob / http://mrdoob.com/
  7359. */
  7360. THREE.MaterialLoader = function ( manager ) {
  7361. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7362. };
  7363. THREE.MaterialLoader.prototype = {
  7364. constructor: THREE.MaterialLoader,
  7365. load: function ( url, onLoad, onProgress, onError ) {
  7366. var scope = this;
  7367. var loader = new THREE.XHRLoader( scope.manager );
  7368. loader.setCrossOrigin( this.crossOrigin );
  7369. loader.load( url, function ( text ) {
  7370. onLoad( scope.parse( JSON.parse( text ) ) );
  7371. }, onProgress, onError );
  7372. },
  7373. setCrossOrigin: function ( value ) {
  7374. this.crossOrigin = value;
  7375. },
  7376. parse: function ( json ) {
  7377. var material = new THREE[ json.type ];
  7378. if ( json.color !== undefined ) material.color.setHex( json.color );
  7379. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  7380. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  7381. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  7382. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  7383. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  7384. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  7385. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  7386. if ( json.shading !== undefined ) material.shading = json.shading;
  7387. if ( json.blending !== undefined ) material.blending = json.blending;
  7388. if ( json.side !== undefined ) material.side = json.side;
  7389. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  7390. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  7391. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  7392. // for PointCloudMaterial
  7393. if ( json.size !== undefined ) material.size = json.size;
  7394. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  7395. if ( json.materials !== undefined ) {
  7396. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  7397. material.materials.push( this.parse( json.materials[ i ] ) );
  7398. }
  7399. }
  7400. return material;
  7401. }
  7402. };
  7403. // File:src/loaders/ObjectLoader.js
  7404. /**
  7405. * @author mrdoob / http://mrdoob.com/
  7406. */
  7407. THREE.ObjectLoader = function ( manager ) {
  7408. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7409. };
  7410. THREE.ObjectLoader.prototype = {
  7411. constructor: THREE.ObjectLoader,
  7412. load: function ( url, onLoad, onProgress, onError ) {
  7413. if ( this.texturePath === undefined ) {
  7414. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  7415. }
  7416. var scope = this;
  7417. var loader = new THREE.XHRLoader( scope.manager );
  7418. loader.setCrossOrigin( this.crossOrigin );
  7419. loader.load( url, function ( text ) {
  7420. scope.parse( JSON.parse( text ), onLoad );
  7421. }, onProgress, onError );
  7422. },
  7423. setTexturePath: function ( value ) {
  7424. this.texturePath = value;
  7425. },
  7426. setCrossOrigin: function ( value ) {
  7427. this.crossOrigin = value;
  7428. },
  7429. parse: function ( json, onLoad ) {
  7430. var geometries = this.parseGeometries( json.geometries );
  7431. var images = this.parseImages( json.images, onLoad );
  7432. var textures = this.parseTextures( json.textures, images );
  7433. var materials = this.parseMaterials( json.materials, textures );
  7434. return this.parseObject( json.object, geometries, materials );
  7435. },
  7436. parseGeometries: function ( json ) {
  7437. var geometries = {};
  7438. if ( json !== undefined ) {
  7439. var geometryLoader = new THREE.JSONLoader();
  7440. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  7441. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7442. var geometry;
  7443. var data = json[ i ];
  7444. switch ( data.type ) {
  7445. case 'PlaneGeometry':
  7446. geometry = new THREE.PlaneGeometry(
  7447. data.width,
  7448. data.height,
  7449. data.widthSegments,
  7450. data.heightSegments
  7451. );
  7452. break;
  7453. case 'BoxGeometry':
  7454. case 'CubeGeometry': // backwards compatible
  7455. geometry = new THREE.BoxGeometry(
  7456. data.width,
  7457. data.height,
  7458. data.depth,
  7459. data.widthSegments,
  7460. data.heightSegments,
  7461. data.depthSegments
  7462. );
  7463. break;
  7464. case 'CircleGeometry':
  7465. geometry = new THREE.CircleGeometry(
  7466. data.radius,
  7467. data.segments
  7468. );
  7469. break;
  7470. case 'CylinderGeometry':
  7471. geometry = new THREE.CylinderGeometry(
  7472. data.radiusTop,
  7473. data.radiusBottom,
  7474. data.height,
  7475. data.radialSegments,
  7476. data.heightSegments,
  7477. data.openEnded
  7478. );
  7479. break;
  7480. case 'SphereGeometry':
  7481. geometry = new THREE.SphereGeometry(
  7482. data.radius,
  7483. data.widthSegments,
  7484. data.heightSegments,
  7485. data.phiStart,
  7486. data.phiLength,
  7487. data.thetaStart,
  7488. data.thetaLength
  7489. );
  7490. break;
  7491. case 'IcosahedronGeometry':
  7492. geometry = new THREE.IcosahedronGeometry(
  7493. data.radius,
  7494. data.detail
  7495. );
  7496. break;
  7497. case 'TorusGeometry':
  7498. geometry = new THREE.TorusGeometry(
  7499. data.radius,
  7500. data.tube,
  7501. data.radialSegments,
  7502. data.tubularSegments,
  7503. data.arc
  7504. );
  7505. break;
  7506. case 'TorusKnotGeometry':
  7507. geometry = new THREE.TorusKnotGeometry(
  7508. data.radius,
  7509. data.tube,
  7510. data.radialSegments,
  7511. data.tubularSegments,
  7512. data.p,
  7513. data.q,
  7514. data.heightScale
  7515. );
  7516. break;
  7517. case 'BufferGeometry':
  7518. geometry = bufferGeometryLoader.parse( data.data );
  7519. break;
  7520. case 'Geometry':
  7521. geometry = geometryLoader.parse( data.data ).geometry;
  7522. break;
  7523. }
  7524. geometry.uuid = data.uuid;
  7525. if ( data.name !== undefined ) geometry.name = data.name;
  7526. geometries[ data.uuid ] = geometry;
  7527. }
  7528. }
  7529. return geometries;
  7530. },
  7531. parseMaterials: function ( json, textures ) {
  7532. var materials = {};
  7533. if ( json !== undefined ) {
  7534. var getTexture = function ( name ) {
  7535. if ( textures[ name ] === undefined ) {
  7536. THREE.warn( 'THREE.ObjectLoader: Undefined texture', name );
  7537. }
  7538. return textures[ name ];
  7539. };
  7540. var loader = new THREE.MaterialLoader();
  7541. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7542. var data = json[ i ];
  7543. var material = loader.parse( data );
  7544. material.uuid = data.uuid;
  7545. if ( data.name !== undefined ) material.name = data.name;
  7546. if ( data.map !== undefined ) {
  7547. material.map = getTexture( data.map );
  7548. }
  7549. if ( data.bumpMap !== undefined ) {
  7550. material.bumpMap = getTexture( data.bumpMap );
  7551. }
  7552. if ( data.alphaMap !== undefined ) {
  7553. material.alphaMap = getTexture( data.alphaMap );
  7554. }
  7555. if ( data.envMap !== undefined ) {
  7556. material.envMap = getTexture( data.envMap );
  7557. }
  7558. if ( data.normalMap !== undefined ) {
  7559. material.normalMap = getTexture( data.normalMap );
  7560. }
  7561. if ( data.lightMap !== undefined ) {
  7562. material.lightMap = getTexture( data.lightMap );
  7563. }
  7564. if ( data.specularMap !== undefined ) {
  7565. material.specularMap = getTexture( data.specularMap );
  7566. }
  7567. materials[ data.uuid ] = material;
  7568. }
  7569. }
  7570. return materials;
  7571. },
  7572. parseImages: function ( json, onLoad ) {
  7573. var scope = this;
  7574. var images = {};
  7575. if ( json !== undefined && json.length > 0 ) {
  7576. var manager = new THREE.LoadingManager( onLoad );
  7577. var loader = new THREE.ImageLoader( manager );
  7578. loader.setCrossOrigin( this.crossOrigin );
  7579. var loadImage = function ( data ) {
  7580. var url = scope.texturePath + data.url;
  7581. scope.manager.itemStart( url );
  7582. loader.load( url, function ( image ) {
  7583. scope.manager.itemEnd( url );
  7584. images[ data.uuid ] = image;
  7585. } );
  7586. };
  7587. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7588. loadImage( json[ i ] );
  7589. }
  7590. } else {
  7591. if ( onLoad !== undefined ) onLoad();
  7592. }
  7593. return images;
  7594. },
  7595. parseTextures: function ( json, images ) {
  7596. var textures = {};
  7597. if ( json !== undefined ) {
  7598. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7599. var data = json[ i ];
  7600. if ( data.image === undefined ) {
  7601. THREE.warn( 'THREE.ObjectLoader: No "image" speficied for', data.uuid );
  7602. }
  7603. if ( images[ data.image ] === undefined ) {
  7604. THREE.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  7605. }
  7606. var texture = new THREE.Texture( images[ data.image ] );
  7607. texture.needsUpdate = true;
  7608. texture.uuid = data.uuid;
  7609. if ( data.name !== undefined ) texture.name = data.name;
  7610. if ( data.repeat !== undefined ) texture.repeat = new THREE.Vector2( data.repeat[ 0 ], data.repeat[ 1 ] );
  7611. if ( data.minFilter !== undefined ) texture.minFilter = THREE[ data.minFilter ];
  7612. if ( data.magFilter !== undefined ) texture.magFilter = THREE[ data.magFilter ];
  7613. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  7614. if ( data.wrap instanceof Array ) {
  7615. texture.wrapS = THREE[ data.wrap[ 0 ] ];
  7616. texture.wrapT = THREE[ data.wrap[ 1 ] ];
  7617. }
  7618. textures[ data.uuid ] = texture;
  7619. }
  7620. }
  7621. return textures;
  7622. },
  7623. parseObject: function () {
  7624. var matrix = new THREE.Matrix4();
  7625. return function ( data, geometries, materials ) {
  7626. var object;
  7627. var getGeometry = function ( name ) {
  7628. if ( geometries[ name ] === undefined ) {
  7629. THREE.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  7630. }
  7631. return geometries[ name ];
  7632. };
  7633. var getMaterial = function ( name ) {
  7634. if ( materials[ name ] === undefined ) {
  7635. THREE.warn( 'THREE.ObjectLoader: Undefined material', name );
  7636. }
  7637. return materials[ name ];
  7638. };
  7639. switch ( data.type ) {
  7640. case 'Scene':
  7641. object = new THREE.Scene();
  7642. break;
  7643. case 'PerspectiveCamera':
  7644. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  7645. break;
  7646. case 'OrthographicCamera':
  7647. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  7648. break;
  7649. case 'AmbientLight':
  7650. object = new THREE.AmbientLight( data.color );
  7651. break;
  7652. case 'DirectionalLight':
  7653. object = new THREE.DirectionalLight( data.color, data.intensity );
  7654. break;
  7655. case 'PointLight':
  7656. object = new THREE.PointLight( data.color, data.intensity, data.distance, data.decay );
  7657. break;
  7658. case 'SpotLight':
  7659. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent, data.decay );
  7660. break;
  7661. case 'HemisphereLight':
  7662. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  7663. break;
  7664. case 'Mesh':
  7665. object = new THREE.Mesh( getGeometry( data.geometry ), getMaterial( data.material ) );
  7666. break;
  7667. case 'Line':
  7668. object = new THREE.Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  7669. break;
  7670. case 'PointCloud':
  7671. object = new THREE.PointCloud( getGeometry( data.geometry ), getMaterial( data.material ) );
  7672. break;
  7673. case 'Sprite':
  7674. object = new THREE.Sprite( getMaterial( data.material ) );
  7675. break;
  7676. case 'Group':
  7677. object = new THREE.Group();
  7678. break;
  7679. default:
  7680. object = new THREE.Object3D();
  7681. }
  7682. object.uuid = data.uuid;
  7683. if ( data.name !== undefined ) object.name = data.name;
  7684. if ( data.matrix !== undefined ) {
  7685. matrix.fromArray( data.matrix );
  7686. matrix.decompose( object.position, object.quaternion, object.scale );
  7687. } else {
  7688. if ( data.position !== undefined ) object.position.fromArray( data.position );
  7689. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  7690. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  7691. }
  7692. if ( data.visible !== undefined ) object.visible = data.visible;
  7693. if ( data.userData !== undefined ) object.userData = data.userData;
  7694. if ( data.children !== undefined ) {
  7695. for ( var child in data.children ) {
  7696. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  7697. }
  7698. }
  7699. return object;
  7700. }
  7701. }()
  7702. };
  7703. // File:src/loaders/TextureLoader.js
  7704. /**
  7705. * @author mrdoob / http://mrdoob.com/
  7706. */
  7707. THREE.TextureLoader = function ( manager ) {
  7708. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7709. };
  7710. THREE.TextureLoader.prototype = {
  7711. constructor: THREE.TextureLoader,
  7712. load: function ( url, onLoad, onProgress, onError ) {
  7713. var scope = this;
  7714. var loader = new THREE.ImageLoader( scope.manager );
  7715. loader.setCrossOrigin( this.crossOrigin );
  7716. loader.load( url, function ( image ) {
  7717. var texture = new THREE.Texture( image );
  7718. texture.needsUpdate = true;
  7719. if ( onLoad !== undefined ) {
  7720. onLoad( texture );
  7721. }
  7722. }, onProgress, onError );
  7723. },
  7724. setCrossOrigin: function ( value ) {
  7725. this.crossOrigin = value;
  7726. }
  7727. };
  7728. // File:src/loaders/BinaryTextureLoader.js
  7729. /**
  7730. * @author Nikos M. / https://github.com/foo123/
  7731. *
  7732. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  7733. */
  7734. THREE.DataTextureLoader = THREE.BinaryTextureLoader = function () {
  7735. // override in sub classes
  7736. this._parser = null;
  7737. };
  7738. THREE.BinaryTextureLoader.prototype = {
  7739. constructor: THREE.BinaryTextureLoader,
  7740. load: function ( url, onLoad, onProgress, onError ) {
  7741. var scope = this;
  7742. var texture = new THREE.DataTexture( );
  7743. var loader = new THREE.XHRLoader();
  7744. loader.setResponseType( 'arraybuffer' );
  7745. loader.load( url, function ( buffer ) {
  7746. var texData = scope._parser( buffer );
  7747. if ( !texData ) return;
  7748. if ( undefined !== texData.image ) {
  7749. texture.image = texData.image;
  7750. } else if ( undefined !== texData.data ){
  7751. texture.image.width = texData.width;
  7752. texture.image.height = texData.height;
  7753. texture.image.data = texData.data;
  7754. }
  7755. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : THREE.ClampToEdgeWrapping;
  7756. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : THREE.ClampToEdgeWrapping;
  7757. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : THREE.LinearFilter;
  7758. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : THREE.LinearMipMapLinearFilter;
  7759. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  7760. if ( undefined !== texData.format ) {
  7761. texture.format = texData.format;
  7762. }
  7763. if ( undefined !== texData.type ) {
  7764. texture.type = texData.type;
  7765. }
  7766. if ( undefined !== texData.mipmaps ) {
  7767. texture.mipmaps = texData.mipmaps;
  7768. }
  7769. if ( 1 === texData.mipmapCount ) {
  7770. texture.minFilter = THREE.LinearFilter;
  7771. }
  7772. texture.needsUpdate = true;
  7773. if ( onLoad ) onLoad( texture, texData );
  7774. }, onProgress, onError );
  7775. return texture;
  7776. }
  7777. };
  7778. // File:src/loaders/CompressedTextureLoader.js
  7779. /**
  7780. * @author mrdoob / http://mrdoob.com/
  7781. *
  7782. * Abstract Base class to block based textures loader (dds, pvr, ...)
  7783. */
  7784. THREE.CompressedTextureLoader = function () {
  7785. // override in sub classes
  7786. this._parser = null;
  7787. };
  7788. THREE.CompressedTextureLoader.prototype = {
  7789. constructor: THREE.CompressedTextureLoader,
  7790. load: function ( url, onLoad, onError ) {
  7791. var scope = this;
  7792. var images = [];
  7793. var texture = new THREE.CompressedTexture();
  7794. texture.image = images;
  7795. var loader = new THREE.XHRLoader();
  7796. loader.setResponseType( 'arraybuffer' );
  7797. if ( url instanceof Array ) {
  7798. var loaded = 0;
  7799. var loadTexture = function ( i ) {
  7800. loader.load( url[ i ], function ( buffer ) {
  7801. var texDatas = scope._parser( buffer, true );
  7802. images[ i ] = {
  7803. width: texDatas.width,
  7804. height: texDatas.height,
  7805. format: texDatas.format,
  7806. mipmaps: texDatas.mipmaps
  7807. };
  7808. loaded += 1;
  7809. if ( loaded === 6 ) {
  7810. if (texDatas.mipmapCount == 1)
  7811. texture.minFilter = THREE.LinearFilter;
  7812. texture.format = texDatas.format;
  7813. texture.needsUpdate = true;
  7814. if ( onLoad ) onLoad( texture );
  7815. }
  7816. } );
  7817. };
  7818. for ( var i = 0, il = url.length; i < il; ++ i ) {
  7819. loadTexture( i );
  7820. }
  7821. } else {
  7822. // compressed cubemap texture stored in a single DDS file
  7823. loader.load( url, function ( buffer ) {
  7824. var texDatas = scope._parser( buffer, true );
  7825. if ( texDatas.isCubemap ) {
  7826. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  7827. for ( var f = 0; f < faces; f ++ ) {
  7828. images[ f ] = { mipmaps : [] };
  7829. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  7830. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  7831. images[ f ].format = texDatas.format;
  7832. images[ f ].width = texDatas.width;
  7833. images[ f ].height = texDatas.height;
  7834. }
  7835. }
  7836. } else {
  7837. texture.image.width = texDatas.width;
  7838. texture.image.height = texDatas.height;
  7839. texture.mipmaps = texDatas.mipmaps;
  7840. }
  7841. if ( texDatas.mipmapCount === 1 ) {
  7842. texture.minFilter = THREE.LinearFilter;
  7843. }
  7844. texture.format = texDatas.format;
  7845. texture.needsUpdate = true;
  7846. if ( onLoad ) onLoad( texture );
  7847. } );
  7848. }
  7849. return texture;
  7850. }
  7851. };
  7852. // File:src/materials/Material.js
  7853. /**
  7854. * @author mrdoob / http://mrdoob.com/
  7855. * @author alteredq / http://alteredqualia.com/
  7856. */
  7857. THREE.Material = function () {
  7858. Object.defineProperty( this, 'id', { value: THREE.MaterialIdCount ++ } );
  7859. this.uuid = THREE.Math.generateUUID();
  7860. this.name = '';
  7861. this.type = 'Material';
  7862. this.side = THREE.FrontSide;
  7863. this.opacity = 1;
  7864. this.transparent = false;
  7865. this.blending = THREE.NormalBlending;
  7866. this.blendSrc = THREE.SrcAlphaFactor;
  7867. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  7868. this.blendEquation = THREE.AddEquation;
  7869. this.blendSrcAlpha = null;
  7870. this.blendDstAlpha = null;
  7871. this.blendEquationAlpha = null;
  7872. this.depthTest = true;
  7873. this.depthWrite = true;
  7874. this.polygonOffset = false;
  7875. this.polygonOffsetFactor = 0;
  7876. this.polygonOffsetUnits = 0;
  7877. this.alphaTest = 0;
  7878. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  7879. this.visible = true;
  7880. this._needsUpdate = true;
  7881. };
  7882. THREE.Material.prototype = {
  7883. constructor: THREE.Material,
  7884. get needsUpdate () {
  7885. return this._needsUpdate;
  7886. },
  7887. set needsUpdate ( value ) {
  7888. if ( value === true ) this.update();
  7889. this._needsUpdate = value;
  7890. },
  7891. setValues: function ( values ) {
  7892. if ( values === undefined ) return;
  7893. for ( var key in values ) {
  7894. var newValue = values[ key ];
  7895. if ( newValue === undefined ) {
  7896. THREE.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  7897. continue;
  7898. }
  7899. if ( key in this ) {
  7900. var currentValue = this[ key ];
  7901. if ( currentValue instanceof THREE.Color ) {
  7902. currentValue.set( newValue );
  7903. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  7904. currentValue.copy( newValue );
  7905. } else if ( key == 'overdraw' ) {
  7906. // ensure overdraw is backwards-compatable with legacy boolean type
  7907. this[ key ] = Number( newValue );
  7908. } else {
  7909. this[ key ] = newValue;
  7910. }
  7911. }
  7912. }
  7913. },
  7914. toJSON: function () {
  7915. var output = {
  7916. metadata: {
  7917. version: 4.2,
  7918. type: 'material',
  7919. generator: 'MaterialExporter'
  7920. },
  7921. uuid: this.uuid,
  7922. type: this.type
  7923. };
  7924. if ( this.name !== "" ) output.name = this.name;
  7925. if ( this instanceof THREE.MeshBasicMaterial ) {
  7926. output.color = this.color.getHex();
  7927. if ( this.vertexColors !== THREE.NoColors ) output.vertexColors = this.vertexColors;
  7928. if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending;
  7929. if ( this.side !== THREE.FrontSide ) output.side = this.side;
  7930. } else if ( this instanceof THREE.MeshLambertMaterial ) {
  7931. output.color = this.color.getHex();
  7932. output.emissive = this.emissive.getHex();
  7933. if ( this.vertexColors !== THREE.NoColors ) output.vertexColors = this.vertexColors;
  7934. if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending;
  7935. if ( this.side !== THREE.FrontSide ) output.side = this.side;
  7936. } else if ( this instanceof THREE.MeshPhongMaterial ) {
  7937. output.color = this.color.getHex();
  7938. output.emissive = this.emissive.getHex();
  7939. output.specular = this.specular.getHex();
  7940. output.shininess = this.shininess;
  7941. if ( this.vertexColors !== THREE.NoColors ) output.vertexColors = this.vertexColors;
  7942. if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending;
  7943. if ( this.side !== THREE.FrontSide ) output.side = this.side;
  7944. } else if ( this instanceof THREE.MeshNormalMaterial ) {
  7945. if ( this.shading !== THREE.FlatShading ) output.shading = this.shading;
  7946. if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending;
  7947. if ( this.side !== THREE.FrontSide ) output.side = this.side;
  7948. } else if ( this instanceof THREE.MeshDepthMaterial ) {
  7949. if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending;
  7950. if ( this.side !== THREE.FrontSide ) output.side = this.side;
  7951. } else if ( this instanceof THREE.PointCloudMaterial ) {
  7952. output.size = this.size;
  7953. output.sizeAttenuation = this.sizeAttenuation;
  7954. output.color = this.color.getHex();
  7955. if ( this.vertexColors !== THREE.NoColors ) output.vertexColors = this.vertexColors;
  7956. if ( this.blending !== THREE.NormalBlending ) output.blending = this.blending;
  7957. } else if ( this instanceof THREE.ShaderMaterial ) {
  7958. output.uniforms = this.uniforms;
  7959. output.vertexShader = this.vertexShader;
  7960. output.fragmentShader = this.fragmentShader;
  7961. } else if ( this instanceof THREE.SpriteMaterial ) {
  7962. output.color = this.color.getHex();
  7963. }
  7964. if ( this.opacity < 1 ) output.opacity = this.opacity;
  7965. if ( this.transparent !== false ) output.transparent = this.transparent;
  7966. if ( this.wireframe !== false ) output.wireframe = this.wireframe;
  7967. return output;
  7968. },
  7969. clone: function ( material ) {
  7970. if ( material === undefined ) material = new THREE.Material();
  7971. material.name = this.name;
  7972. material.side = this.side;
  7973. material.opacity = this.opacity;
  7974. material.transparent = this.transparent;
  7975. material.blending = this.blending;
  7976. material.blendSrc = this.blendSrc;
  7977. material.blendDst = this.blendDst;
  7978. material.blendEquation = this.blendEquation;
  7979. material.blendSrcAlpha = this.blendSrcAlpha;
  7980. material.blendDstAlpha = this.blendDstAlpha;
  7981. material.blendEquationAlpha = this.blendEquationAlpha;
  7982. material.depthTest = this.depthTest;
  7983. material.depthWrite = this.depthWrite;
  7984. material.polygonOffset = this.polygonOffset;
  7985. material.polygonOffsetFactor = this.polygonOffsetFactor;
  7986. material.polygonOffsetUnits = this.polygonOffsetUnits;
  7987. material.alphaTest = this.alphaTest;
  7988. material.overdraw = this.overdraw;
  7989. material.visible = this.visible;
  7990. return material;
  7991. },
  7992. update: function () {
  7993. this.dispatchEvent( { type: 'update' } );
  7994. },
  7995. dispose: function () {
  7996. this.dispatchEvent( { type: 'dispose' } );
  7997. }
  7998. };
  7999. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  8000. THREE.MaterialIdCount = 0;
  8001. // File:src/materials/LineBasicMaterial.js
  8002. /**
  8003. * @author mrdoob / http://mrdoob.com/
  8004. * @author alteredq / http://alteredqualia.com/
  8005. *
  8006. * parameters = {
  8007. * color: <hex>,
  8008. * opacity: <float>,
  8009. *
  8010. * blending: THREE.NormalBlending,
  8011. * depthTest: <bool>,
  8012. * depthWrite: <bool>,
  8013. *
  8014. * linewidth: <float>,
  8015. * linecap: "round",
  8016. * linejoin: "round",
  8017. *
  8018. * vertexColors: <bool>
  8019. *
  8020. * fog: <bool>
  8021. * }
  8022. */
  8023. THREE.LineBasicMaterial = function ( parameters ) {
  8024. THREE.Material.call( this );
  8025. this.type = 'LineBasicMaterial';
  8026. this.color = new THREE.Color( 0xffffff );
  8027. this.linewidth = 1;
  8028. this.linecap = 'round';
  8029. this.linejoin = 'round';
  8030. this.vertexColors = THREE.NoColors;
  8031. this.fog = true;
  8032. this.setValues( parameters );
  8033. };
  8034. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8035. THREE.LineBasicMaterial.prototype.constructor = THREE.LineBasicMaterial;
  8036. THREE.LineBasicMaterial.prototype.clone = function () {
  8037. var material = new THREE.LineBasicMaterial();
  8038. THREE.Material.prototype.clone.call( this, material );
  8039. material.color.copy( this.color );
  8040. material.linewidth = this.linewidth;
  8041. material.linecap = this.linecap;
  8042. material.linejoin = this.linejoin;
  8043. material.vertexColors = this.vertexColors;
  8044. material.fog = this.fog;
  8045. return material;
  8046. };
  8047. // File:src/materials/LineDashedMaterial.js
  8048. /**
  8049. * @author alteredq / http://alteredqualia.com/
  8050. *
  8051. * parameters = {
  8052. * color: <hex>,
  8053. * opacity: <float>,
  8054. *
  8055. * blending: THREE.NormalBlending,
  8056. * depthTest: <bool>,
  8057. * depthWrite: <bool>,
  8058. *
  8059. * linewidth: <float>,
  8060. *
  8061. * scale: <float>,
  8062. * dashSize: <float>,
  8063. * gapSize: <float>,
  8064. *
  8065. * vertexColors: <bool>
  8066. *
  8067. * fog: <bool>
  8068. * }
  8069. */
  8070. THREE.LineDashedMaterial = function ( parameters ) {
  8071. THREE.Material.call( this );
  8072. this.type = 'LineDashedMaterial';
  8073. this.color = new THREE.Color( 0xffffff );
  8074. this.linewidth = 1;
  8075. this.scale = 1;
  8076. this.dashSize = 3;
  8077. this.gapSize = 1;
  8078. this.vertexColors = false;
  8079. this.fog = true;
  8080. this.setValues( parameters );
  8081. };
  8082. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  8083. THREE.LineDashedMaterial.prototype.constructor = THREE.LineDashedMaterial;
  8084. THREE.LineDashedMaterial.prototype.clone = function () {
  8085. var material = new THREE.LineDashedMaterial();
  8086. THREE.Material.prototype.clone.call( this, material );
  8087. material.color.copy( this.color );
  8088. material.linewidth = this.linewidth;
  8089. material.scale = this.scale;
  8090. material.dashSize = this.dashSize;
  8091. material.gapSize = this.gapSize;
  8092. material.vertexColors = this.vertexColors;
  8093. material.fog = this.fog;
  8094. return material;
  8095. };
  8096. // File:src/materials/MeshBasicMaterial.js
  8097. /**
  8098. * @author mrdoob / http://mrdoob.com/
  8099. * @author alteredq / http://alteredqualia.com/
  8100. *
  8101. * parameters = {
  8102. * color: <hex>,
  8103. * opacity: <float>,
  8104. * map: new THREE.Texture( <Image> ),
  8105. *
  8106. * lightMap: new THREE.Texture( <Image> ),
  8107. *
  8108. * specularMap: new THREE.Texture( <Image> ),
  8109. *
  8110. * alphaMap: new THREE.Texture( <Image> ),
  8111. *
  8112. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8113. * combine: THREE.Multiply,
  8114. * reflectivity: <float>,
  8115. * refractionRatio: <float>,
  8116. *
  8117. * shading: THREE.SmoothShading,
  8118. * blending: THREE.NormalBlending,
  8119. * depthTest: <bool>,
  8120. * depthWrite: <bool>,
  8121. *
  8122. * wireframe: <boolean>,
  8123. * wireframeLinewidth: <float>,
  8124. *
  8125. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8126. *
  8127. * skinning: <bool>,
  8128. * morphTargets: <bool>,
  8129. *
  8130. * fog: <bool>
  8131. * }
  8132. */
  8133. THREE.MeshBasicMaterial = function ( parameters ) {
  8134. THREE.Material.call( this );
  8135. this.type = 'MeshBasicMaterial';
  8136. this.color = new THREE.Color( 0xffffff ); // emissive
  8137. this.map = null;
  8138. this.lightMap = null;
  8139. this.specularMap = null;
  8140. this.alphaMap = null;
  8141. this.envMap = null;
  8142. this.combine = THREE.MultiplyOperation;
  8143. this.reflectivity = 1;
  8144. this.refractionRatio = 0.98;
  8145. this.fog = true;
  8146. this.shading = THREE.SmoothShading;
  8147. this.wireframe = false;
  8148. this.wireframeLinewidth = 1;
  8149. this.wireframeLinecap = 'round';
  8150. this.wireframeLinejoin = 'round';
  8151. this.vertexColors = THREE.NoColors;
  8152. this.skinning = false;
  8153. this.morphTargets = false;
  8154. this.setValues( parameters );
  8155. };
  8156. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8157. THREE.MeshBasicMaterial.prototype.constructor = THREE.MeshBasicMaterial;
  8158. THREE.MeshBasicMaterial.prototype.clone = function () {
  8159. var material = new THREE.MeshBasicMaterial();
  8160. THREE.Material.prototype.clone.call( this, material );
  8161. material.color.copy( this.color );
  8162. material.map = this.map;
  8163. material.lightMap = this.lightMap;
  8164. material.specularMap = this.specularMap;
  8165. material.alphaMap = this.alphaMap;
  8166. material.envMap = this.envMap;
  8167. material.combine = this.combine;
  8168. material.reflectivity = this.reflectivity;
  8169. material.refractionRatio = this.refractionRatio;
  8170. material.fog = this.fog;
  8171. material.shading = this.shading;
  8172. material.wireframe = this.wireframe;
  8173. material.wireframeLinewidth = this.wireframeLinewidth;
  8174. material.wireframeLinecap = this.wireframeLinecap;
  8175. material.wireframeLinejoin = this.wireframeLinejoin;
  8176. material.vertexColors = this.vertexColors;
  8177. material.skinning = this.skinning;
  8178. material.morphTargets = this.morphTargets;
  8179. return material;
  8180. };
  8181. // File:src/materials/MeshLambertMaterial.js
  8182. /**
  8183. * @author mrdoob / http://mrdoob.com/
  8184. * @author alteredq / http://alteredqualia.com/
  8185. *
  8186. * parameters = {
  8187. * color: <hex>,
  8188. * emissive: <hex>,
  8189. * opacity: <float>,
  8190. *
  8191. * map: new THREE.Texture( <Image> ),
  8192. *
  8193. * lightMap: new THREE.Texture( <Image> ),
  8194. *
  8195. * specularMap: new THREE.Texture( <Image> ),
  8196. *
  8197. * alphaMap: new THREE.Texture( <Image> ),
  8198. *
  8199. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8200. * combine: THREE.Multiply,
  8201. * reflectivity: <float>,
  8202. * refractionRatio: <float>,
  8203. *
  8204. * shading: THREE.SmoothShading,
  8205. * blending: THREE.NormalBlending,
  8206. * depthTest: <bool>,
  8207. * depthWrite: <bool>,
  8208. *
  8209. * wireframe: <boolean>,
  8210. * wireframeLinewidth: <float>,
  8211. *
  8212. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8213. *
  8214. * skinning: <bool>,
  8215. * morphTargets: <bool>,
  8216. * morphNormals: <bool>,
  8217. *
  8218. * fog: <bool>
  8219. * }
  8220. */
  8221. THREE.MeshLambertMaterial = function ( parameters ) {
  8222. THREE.Material.call( this );
  8223. this.type = 'MeshLambertMaterial';
  8224. this.color = new THREE.Color( 0xffffff ); // diffuse
  8225. this.emissive = new THREE.Color( 0x000000 );
  8226. this.wrapAround = false;
  8227. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8228. this.map = null;
  8229. this.lightMap = null;
  8230. this.specularMap = null;
  8231. this.alphaMap = null;
  8232. this.envMap = null;
  8233. this.combine = THREE.MultiplyOperation;
  8234. this.reflectivity = 1;
  8235. this.refractionRatio = 0.98;
  8236. this.fog = true;
  8237. this.shading = THREE.SmoothShading;
  8238. this.wireframe = false;
  8239. this.wireframeLinewidth = 1;
  8240. this.wireframeLinecap = 'round';
  8241. this.wireframeLinejoin = 'round';
  8242. this.vertexColors = THREE.NoColors;
  8243. this.skinning = false;
  8244. this.morphTargets = false;
  8245. this.morphNormals = false;
  8246. this.setValues( parameters );
  8247. };
  8248. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  8249. THREE.MeshLambertMaterial.prototype.constructor = THREE.MeshLambertMaterial;
  8250. THREE.MeshLambertMaterial.prototype.clone = function () {
  8251. var material = new THREE.MeshLambertMaterial();
  8252. THREE.Material.prototype.clone.call( this, material );
  8253. material.color.copy( this.color );
  8254. material.emissive.copy( this.emissive );
  8255. material.wrapAround = this.wrapAround;
  8256. material.wrapRGB.copy( this.wrapRGB );
  8257. material.map = this.map;
  8258. material.lightMap = this.lightMap;
  8259. material.specularMap = this.specularMap;
  8260. material.alphaMap = this.alphaMap;
  8261. material.envMap = this.envMap;
  8262. material.combine = this.combine;
  8263. material.reflectivity = this.reflectivity;
  8264. material.refractionRatio = this.refractionRatio;
  8265. material.fog = this.fog;
  8266. material.shading = this.shading;
  8267. material.wireframe = this.wireframe;
  8268. material.wireframeLinewidth = this.wireframeLinewidth;
  8269. material.wireframeLinecap = this.wireframeLinecap;
  8270. material.wireframeLinejoin = this.wireframeLinejoin;
  8271. material.vertexColors = this.vertexColors;
  8272. material.skinning = this.skinning;
  8273. material.morphTargets = this.morphTargets;
  8274. material.morphNormals = this.morphNormals;
  8275. return material;
  8276. };
  8277. // File:src/materials/MeshPhongMaterial.js
  8278. /**
  8279. * @author mrdoob / http://mrdoob.com/
  8280. * @author alteredq / http://alteredqualia.com/
  8281. *
  8282. * parameters = {
  8283. * color: <hex>,
  8284. * emissive: <hex>,
  8285. * specular: <hex>,
  8286. * shininess: <float>,
  8287. * opacity: <float>,
  8288. *
  8289. * map: new THREE.Texture( <Image> ),
  8290. *
  8291. * lightMap: new THREE.Texture( <Image> ),
  8292. *
  8293. * bumpMap: new THREE.Texture( <Image> ),
  8294. * bumpScale: <float>,
  8295. *
  8296. * normalMap: new THREE.Texture( <Image> ),
  8297. * normalScale: <Vector2>,
  8298. *
  8299. * specularMap: new THREE.Texture( <Image> ),
  8300. *
  8301. * alphaMap: new THREE.Texture( <Image> ),
  8302. *
  8303. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8304. * combine: THREE.Multiply,
  8305. * reflectivity: <float>,
  8306. * refractionRatio: <float>,
  8307. *
  8308. * shading: THREE.SmoothShading,
  8309. * blending: THREE.NormalBlending,
  8310. * depthTest: <bool>,
  8311. * depthWrite: <bool>,
  8312. *
  8313. * wireframe: <boolean>,
  8314. * wireframeLinewidth: <float>,
  8315. *
  8316. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8317. *
  8318. * skinning: <bool>,
  8319. * morphTargets: <bool>,
  8320. * morphNormals: <bool>,
  8321. *
  8322. * fog: <bool>
  8323. * }
  8324. */
  8325. THREE.MeshPhongMaterial = function ( parameters ) {
  8326. THREE.Material.call( this );
  8327. this.type = 'MeshPhongMaterial';
  8328. this.color = new THREE.Color( 0xffffff ); // diffuse
  8329. this.emissive = new THREE.Color( 0x000000 );
  8330. this.specular = new THREE.Color( 0x111111 );
  8331. this.shininess = 30;
  8332. this.metal = false;
  8333. this.wrapAround = false;
  8334. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8335. this.map = null;
  8336. this.lightMap = null;
  8337. this.bumpMap = null;
  8338. this.bumpScale = 1;
  8339. this.normalMap = null;
  8340. this.normalScale = new THREE.Vector2( 1, 1 );
  8341. this.specularMap = null;
  8342. this.alphaMap = null;
  8343. this.envMap = null;
  8344. this.combine = THREE.MultiplyOperation;
  8345. this.reflectivity = 1;
  8346. this.refractionRatio = 0.98;
  8347. this.fog = true;
  8348. this.shading = THREE.SmoothShading;
  8349. this.wireframe = false;
  8350. this.wireframeLinewidth = 1;
  8351. this.wireframeLinecap = 'round';
  8352. this.wireframeLinejoin = 'round';
  8353. this.vertexColors = THREE.NoColors;
  8354. this.skinning = false;
  8355. this.morphTargets = false;
  8356. this.morphNormals = false;
  8357. this.setValues( parameters );
  8358. };
  8359. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  8360. THREE.MeshPhongMaterial.prototype.constructor = THREE.MeshPhongMaterial;
  8361. THREE.MeshPhongMaterial.prototype.clone = function () {
  8362. var material = new THREE.MeshPhongMaterial();
  8363. THREE.Material.prototype.clone.call( this, material );
  8364. material.color.copy( this.color );
  8365. material.emissive.copy( this.emissive );
  8366. material.specular.copy( this.specular );
  8367. material.shininess = this.shininess;
  8368. material.metal = this.metal;
  8369. material.wrapAround = this.wrapAround;
  8370. material.wrapRGB.copy( this.wrapRGB );
  8371. material.map = this.map;
  8372. material.lightMap = this.lightMap;
  8373. material.bumpMap = this.bumpMap;
  8374. material.bumpScale = this.bumpScale;
  8375. material.normalMap = this.normalMap;
  8376. material.normalScale.copy( this.normalScale );
  8377. material.specularMap = this.specularMap;
  8378. material.alphaMap = this.alphaMap;
  8379. material.envMap = this.envMap;
  8380. material.combine = this.combine;
  8381. material.reflectivity = this.reflectivity;
  8382. material.refractionRatio = this.refractionRatio;
  8383. material.fog = this.fog;
  8384. material.shading = this.shading;
  8385. material.wireframe = this.wireframe;
  8386. material.wireframeLinewidth = this.wireframeLinewidth;
  8387. material.wireframeLinecap = this.wireframeLinecap;
  8388. material.wireframeLinejoin = this.wireframeLinejoin;
  8389. material.vertexColors = this.vertexColors;
  8390. material.skinning = this.skinning;
  8391. material.morphTargets = this.morphTargets;
  8392. material.morphNormals = this.morphNormals;
  8393. return material;
  8394. };
  8395. // File:src/materials/MeshDepthMaterial.js
  8396. /**
  8397. * @author mrdoob / http://mrdoob.com/
  8398. * @author alteredq / http://alteredqualia.com/
  8399. *
  8400. * parameters = {
  8401. * opacity: <float>,
  8402. *
  8403. * blending: THREE.NormalBlending,
  8404. * depthTest: <bool>,
  8405. * depthWrite: <bool>,
  8406. *
  8407. * wireframe: <boolean>,
  8408. * wireframeLinewidth: <float>
  8409. * }
  8410. */
  8411. THREE.MeshDepthMaterial = function ( parameters ) {
  8412. THREE.Material.call( this );
  8413. this.type = 'MeshDepthMaterial';
  8414. this.morphTargets = false;
  8415. this.wireframe = false;
  8416. this.wireframeLinewidth = 1;
  8417. this.setValues( parameters );
  8418. };
  8419. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  8420. THREE.MeshDepthMaterial.prototype.constructor = THREE.MeshDepthMaterial;
  8421. THREE.MeshDepthMaterial.prototype.clone = function () {
  8422. var material = new THREE.MeshDepthMaterial();
  8423. THREE.Material.prototype.clone.call( this, material );
  8424. material.wireframe = this.wireframe;
  8425. material.wireframeLinewidth = this.wireframeLinewidth;
  8426. return material;
  8427. };
  8428. // File:src/materials/MeshNormalMaterial.js
  8429. /**
  8430. * @author mrdoob / http://mrdoob.com/
  8431. *
  8432. * parameters = {
  8433. * opacity: <float>,
  8434. *
  8435. * shading: THREE.FlatShading,
  8436. * blending: THREE.NormalBlending,
  8437. * depthTest: <bool>,
  8438. * depthWrite: <bool>,
  8439. *
  8440. * wireframe: <boolean>,
  8441. * wireframeLinewidth: <float>
  8442. * }
  8443. */
  8444. THREE.MeshNormalMaterial = function ( parameters ) {
  8445. THREE.Material.call( this, parameters );
  8446. this.type = 'MeshNormalMaterial';
  8447. this.shading = THREE.FlatShading;
  8448. this.wireframe = false;
  8449. this.wireframeLinewidth = 1;
  8450. this.morphTargets = false;
  8451. this.setValues( parameters );
  8452. };
  8453. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  8454. THREE.MeshNormalMaterial.prototype.constructor = THREE.MeshNormalMaterial;
  8455. THREE.MeshNormalMaterial.prototype.clone = function () {
  8456. var material = new THREE.MeshNormalMaterial();
  8457. THREE.Material.prototype.clone.call( this, material );
  8458. material.shading = this.shading;
  8459. material.wireframe = this.wireframe;
  8460. material.wireframeLinewidth = this.wireframeLinewidth;
  8461. return material;
  8462. };
  8463. // File:src/materials/MeshFaceMaterial.js
  8464. /**
  8465. * @author mrdoob / http://mrdoob.com/
  8466. */
  8467. THREE.MeshFaceMaterial = function ( materials ) {
  8468. this.uuid = THREE.Math.generateUUID();
  8469. this.type = 'MeshFaceMaterial';
  8470. this.materials = materials instanceof Array ? materials : [];
  8471. };
  8472. THREE.MeshFaceMaterial.prototype = {
  8473. constructor: THREE.MeshFaceMaterial,
  8474. toJSON: function () {
  8475. var output = {
  8476. metadata: {
  8477. version: 4.2,
  8478. type: 'material',
  8479. generator: 'MaterialExporter'
  8480. },
  8481. uuid: this.uuid,
  8482. type: this.type,
  8483. materials: []
  8484. };
  8485. for ( var i = 0, l = this.materials.length; i < l; i ++ ) {
  8486. output.materials.push( this.materials[ i ].toJSON() );
  8487. }
  8488. return output;
  8489. },
  8490. clone: function () {
  8491. var material = new THREE.MeshFaceMaterial();
  8492. for ( var i = 0; i < this.materials.length; i ++ ) {
  8493. material.materials.push( this.materials[ i ].clone() );
  8494. }
  8495. return material;
  8496. }
  8497. };
  8498. // File:src/materials/PointCloudMaterial.js
  8499. /**
  8500. * @author mrdoob / http://mrdoob.com/
  8501. * @author alteredq / http://alteredqualia.com/
  8502. *
  8503. * parameters = {
  8504. * color: <hex>,
  8505. * opacity: <float>,
  8506. * map: new THREE.Texture( <Image> ),
  8507. *
  8508. * size: <float>,
  8509. * sizeAttenuation: <bool>,
  8510. *
  8511. * blending: THREE.NormalBlending,
  8512. * depthTest: <bool>,
  8513. * depthWrite: <bool>,
  8514. *
  8515. * vertexColors: <bool>,
  8516. *
  8517. * fog: <bool>
  8518. * }
  8519. */
  8520. THREE.PointCloudMaterial = function ( parameters ) {
  8521. THREE.Material.call( this );
  8522. this.type = 'PointCloudMaterial';
  8523. this.color = new THREE.Color( 0xffffff );
  8524. this.map = null;
  8525. this.size = 1;
  8526. this.sizeAttenuation = true;
  8527. this.vertexColors = THREE.NoColors;
  8528. this.fog = true;
  8529. this.setValues( parameters );
  8530. };
  8531. THREE.PointCloudMaterial.prototype = Object.create( THREE.Material.prototype );
  8532. THREE.PointCloudMaterial.prototype.constructor = THREE.PointCloudMaterial;
  8533. THREE.PointCloudMaterial.prototype.clone = function () {
  8534. var material = new THREE.PointCloudMaterial();
  8535. THREE.Material.prototype.clone.call( this, material );
  8536. material.color.copy( this.color );
  8537. material.map = this.map;
  8538. material.size = this.size;
  8539. material.sizeAttenuation = this.sizeAttenuation;
  8540. material.vertexColors = this.vertexColors;
  8541. material.fog = this.fog;
  8542. return material;
  8543. };
  8544. // backwards compatibility
  8545. THREE.ParticleBasicMaterial = function ( parameters ) {
  8546. THREE.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointCloudMaterial.' );
  8547. return new THREE.PointCloudMaterial( parameters );
  8548. };
  8549. THREE.ParticleSystemMaterial = function ( parameters ) {
  8550. THREE.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointCloudMaterial.' );
  8551. return new THREE.PointCloudMaterial( parameters );
  8552. };
  8553. // File:src/materials/ShaderMaterial.js
  8554. /**
  8555. * @author alteredq / http://alteredqualia.com/
  8556. *
  8557. * parameters = {
  8558. * defines: { "label" : "value" },
  8559. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  8560. *
  8561. * fragmentShader: <string>,
  8562. * vertexShader: <string>,
  8563. *
  8564. * shading: THREE.SmoothShading,
  8565. * blending: THREE.NormalBlending,
  8566. * depthTest: <bool>,
  8567. * depthWrite: <bool>,
  8568. *
  8569. * wireframe: <boolean>,
  8570. * wireframeLinewidth: <float>,
  8571. *
  8572. * lights: <bool>,
  8573. *
  8574. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8575. *
  8576. * skinning: <bool>,
  8577. * morphTargets: <bool>,
  8578. * morphNormals: <bool>,
  8579. *
  8580. * fog: <bool>
  8581. * }
  8582. */
  8583. THREE.ShaderMaterial = function ( parameters ) {
  8584. THREE.Material.call( this );
  8585. this.type = 'ShaderMaterial';
  8586. this.defines = {};
  8587. this.uniforms = {};
  8588. this.attributes = null;
  8589. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  8590. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  8591. this.shading = THREE.SmoothShading;
  8592. this.linewidth = 1;
  8593. this.wireframe = false;
  8594. this.wireframeLinewidth = 1;
  8595. this.fog = false; // set to use scene fog
  8596. this.lights = false; // set to use scene lights
  8597. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  8598. this.skinning = false; // set to use skinning attribute streams
  8599. this.morphTargets = false; // set to use morph targets
  8600. this.morphNormals = false; // set to use morph normals
  8601. // When rendered geometry doesn't include these attributes but the material does,
  8602. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8603. this.defaultAttributeValues = {
  8604. 'color': [ 1, 1, 1 ],
  8605. 'uv': [ 0, 0 ],
  8606. 'uv2': [ 0, 0 ]
  8607. };
  8608. this.index0AttributeName = undefined;
  8609. this.setValues( parameters );
  8610. };
  8611. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  8612. THREE.ShaderMaterial.prototype.constructor = THREE.ShaderMaterial;
  8613. THREE.ShaderMaterial.prototype.clone = function () {
  8614. var material = new THREE.ShaderMaterial();
  8615. THREE.Material.prototype.clone.call( this, material );
  8616. material.fragmentShader = this.fragmentShader;
  8617. material.vertexShader = this.vertexShader;
  8618. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  8619. material.attributes = this.attributes;
  8620. material.defines = this.defines;
  8621. material.shading = this.shading;
  8622. material.wireframe = this.wireframe;
  8623. material.wireframeLinewidth = this.wireframeLinewidth;
  8624. material.fog = this.fog;
  8625. material.lights = this.lights;
  8626. material.vertexColors = this.vertexColors;
  8627. material.skinning = this.skinning;
  8628. material.morphTargets = this.morphTargets;
  8629. material.morphNormals = this.morphNormals;
  8630. return material;
  8631. };
  8632. // File:src/materials/RawShaderMaterial.js
  8633. /**
  8634. * @author mrdoob / http://mrdoob.com/
  8635. */
  8636. THREE.RawShaderMaterial = function ( parameters ) {
  8637. THREE.ShaderMaterial.call( this, parameters );
  8638. this.type = 'RawShaderMaterial';
  8639. };
  8640. THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype );
  8641. THREE.RawShaderMaterial.prototype.constructor = THREE.RawShaderMaterial;
  8642. THREE.RawShaderMaterial.prototype.clone = function () {
  8643. var material = new THREE.RawShaderMaterial();
  8644. THREE.ShaderMaterial.prototype.clone.call( this, material );
  8645. return material;
  8646. };
  8647. // File:src/materials/SpriteMaterial.js
  8648. /**
  8649. * @author alteredq / http://alteredqualia.com/
  8650. *
  8651. * parameters = {
  8652. * color: <hex>,
  8653. * opacity: <float>,
  8654. * map: new THREE.Texture( <Image> ),
  8655. *
  8656. * blending: THREE.NormalBlending,
  8657. * depthTest: <bool>,
  8658. * depthWrite: <bool>,
  8659. *
  8660. * uvOffset: new THREE.Vector2(),
  8661. * uvScale: new THREE.Vector2(),
  8662. *
  8663. * fog: <bool>
  8664. * }
  8665. */
  8666. THREE.SpriteMaterial = function ( parameters ) {
  8667. THREE.Material.call( this );
  8668. this.type = 'SpriteMaterial';
  8669. this.color = new THREE.Color( 0xffffff );
  8670. this.map = null;
  8671. this.rotation = 0;
  8672. this.fog = false;
  8673. // set parameters
  8674. this.setValues( parameters );
  8675. };
  8676. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  8677. THREE.SpriteMaterial.prototype.constructor = THREE.SpriteMaterial;
  8678. THREE.SpriteMaterial.prototype.clone = function () {
  8679. var material = new THREE.SpriteMaterial();
  8680. THREE.Material.prototype.clone.call( this, material );
  8681. material.color.copy( this.color );
  8682. material.map = this.map;
  8683. material.rotation = this.rotation;
  8684. material.fog = this.fog;
  8685. return material;
  8686. };
  8687. // File:src/textures/Texture.js
  8688. /**
  8689. * @author mrdoob / http://mrdoob.com/
  8690. * @author alteredq / http://alteredqualia.com/
  8691. * @author szimek / https://github.com/szimek/
  8692. */
  8693. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8694. Object.defineProperty( this, 'id', { value: THREE.TextureIdCount ++ } );
  8695. this.uuid = THREE.Math.generateUUID();
  8696. this.name = '';
  8697. this.image = image !== undefined ? image : THREE.Texture.DEFAULT_IMAGE;
  8698. this.mipmaps = [];
  8699. this.mapping = mapping !== undefined ? mapping : THREE.Texture.DEFAULT_MAPPING;
  8700. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  8701. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  8702. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  8703. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  8704. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  8705. this.format = format !== undefined ? format : THREE.RGBAFormat;
  8706. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  8707. this.offset = new THREE.Vector2( 0, 0 );
  8708. this.repeat = new THREE.Vector2( 1, 1 );
  8709. this.generateMipmaps = true;
  8710. this.premultiplyAlpha = false;
  8711. this.flipY = true;
  8712. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  8713. this._needsUpdate = false;
  8714. this.onUpdate = null;
  8715. };
  8716. THREE.Texture.DEFAULT_IMAGE = undefined;
  8717. THREE.Texture.DEFAULT_MAPPING = THREE.UVMapping;
  8718. THREE.Texture.prototype = {
  8719. constructor: THREE.Texture,
  8720. get needsUpdate () {
  8721. return this._needsUpdate;
  8722. },
  8723. set needsUpdate ( value ) {
  8724. if ( value === true ) this.update();
  8725. this._needsUpdate = value;
  8726. },
  8727. clone: function ( texture ) {
  8728. if ( texture === undefined ) texture = new THREE.Texture();
  8729. texture.image = this.image;
  8730. texture.mipmaps = this.mipmaps.slice( 0 );
  8731. texture.mapping = this.mapping;
  8732. texture.wrapS = this.wrapS;
  8733. texture.wrapT = this.wrapT;
  8734. texture.magFilter = this.magFilter;
  8735. texture.minFilter = this.minFilter;
  8736. texture.anisotropy = this.anisotropy;
  8737. texture.format = this.format;
  8738. texture.type = this.type;
  8739. texture.offset.copy( this.offset );
  8740. texture.repeat.copy( this.repeat );
  8741. texture.generateMipmaps = this.generateMipmaps;
  8742. texture.premultiplyAlpha = this.premultiplyAlpha;
  8743. texture.flipY = this.flipY;
  8744. texture.unpackAlignment = this.unpackAlignment;
  8745. return texture;
  8746. },
  8747. update: function () {
  8748. this.dispatchEvent( { type: 'update' } );
  8749. },
  8750. dispose: function () {
  8751. this.dispatchEvent( { type: 'dispose' } );
  8752. }
  8753. };
  8754. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  8755. THREE.TextureIdCount = 0;
  8756. // File:src/textures/CubeTexture.js
  8757. /**
  8758. * @author mrdoob / http://mrdoob.com/
  8759. */
  8760. THREE.CubeTexture = function ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8761. mapping = mapping !== undefined ? mapping : THREE.CubeReflectionMapping;
  8762. THREE.Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8763. this.images = images;
  8764. };
  8765. THREE.CubeTexture.prototype = Object.create( THREE.Texture.prototype );
  8766. THREE.CubeTexture.prototype.constructor = THREE.CubeTexture;
  8767. THREE.CubeTexture.clone = function ( texture ) {
  8768. if ( texture === undefined ) texture = new THREE.CubeTexture();
  8769. THREE.Texture.prototype.clone.call( this, texture );
  8770. texture.images = this.images;
  8771. return texture;
  8772. };
  8773. // File:src/textures/CompressedTexture.js
  8774. /**
  8775. * @author alteredq / http://alteredqualia.com/
  8776. */
  8777. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8778. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8779. this.image = { width: width, height: height };
  8780. this.mipmaps = mipmaps;
  8781. // no flipping for cube textures
  8782. // (also flipping doesn't work for compressed textures )
  8783. this.flipY = false;
  8784. // can't generate mipmaps for compressed textures
  8785. // mips must be embedded in DDS files
  8786. this.generateMipmaps = false;
  8787. };
  8788. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  8789. THREE.CompressedTexture.prototype.constructor = THREE.CompressedTexture;
  8790. THREE.CompressedTexture.prototype.clone = function () {
  8791. var texture = new THREE.CompressedTexture();
  8792. THREE.Texture.prototype.clone.call( this, texture );
  8793. return texture;
  8794. };
  8795. // File:src/textures/DataTexture.js
  8796. /**
  8797. * @author alteredq / http://alteredqualia.com/
  8798. */
  8799. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8800. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8801. this.image = { data: data, width: width, height: height };
  8802. };
  8803. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  8804. THREE.DataTexture.prototype.constructor = THREE.DataTexture;
  8805. THREE.DataTexture.prototype.clone = function () {
  8806. var texture = new THREE.DataTexture();
  8807. THREE.Texture.prototype.clone.call( this, texture );
  8808. return texture;
  8809. };
  8810. // File:src/textures/VideoTexture.js
  8811. /**
  8812. * @author mrdoob / http://mrdoob.com/
  8813. */
  8814. THREE.VideoTexture = function ( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8815. THREE.Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8816. this.generateMipmaps = false;
  8817. var scope = this;
  8818. var update = function () {
  8819. requestAnimationFrame( update );
  8820. if ( video.readyState === video.HAVE_ENOUGH_DATA ) {
  8821. scope.needsUpdate = true;
  8822. }
  8823. };
  8824. update();
  8825. };
  8826. THREE.VideoTexture.prototype = Object.create( THREE.Texture.prototype );
  8827. THREE.VideoTexture.prototype.constructor = THREE.VideoTexture;
  8828. // File:src/objects/Group.js
  8829. /**
  8830. * @author mrdoob / http://mrdoob.com/
  8831. */
  8832. THREE.Group = function () {
  8833. THREE.Object3D.call( this );
  8834. this.type = 'Group';
  8835. };
  8836. THREE.Group.prototype = Object.create( THREE.Object3D.prototype );
  8837. THREE.Group.prototype.constructor = THREE.Group;
  8838. // File:src/objects/PointCloud.js
  8839. /**
  8840. * @author alteredq / http://alteredqualia.com/
  8841. */
  8842. THREE.PointCloud = function ( geometry, material ) {
  8843. THREE.Object3D.call( this );
  8844. this.type = 'PointCloud';
  8845. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8846. this.material = material !== undefined ? material : new THREE.PointCloudMaterial( { color: Math.random() * 0xffffff } );
  8847. };
  8848. THREE.PointCloud.prototype = Object.create( THREE.Object3D.prototype );
  8849. THREE.PointCloud.prototype.constructor = THREE.PointCloud;
  8850. THREE.PointCloud.prototype.raycast = ( function () {
  8851. var inverseMatrix = new THREE.Matrix4();
  8852. var ray = new THREE.Ray();
  8853. return function ( raycaster, intersects ) {
  8854. var object = this;
  8855. var geometry = object.geometry;
  8856. var threshold = raycaster.params.PointCloud.threshold;
  8857. inverseMatrix.getInverse( this.matrixWorld );
  8858. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  8859. if ( geometry.boundingBox !== null ) {
  8860. if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) {
  8861. return;
  8862. }
  8863. }
  8864. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  8865. var position = new THREE.Vector3();
  8866. var testPoint = function ( point, index ) {
  8867. var rayPointDistance = ray.distanceToPoint( point );
  8868. if ( rayPointDistance < localThreshold ) {
  8869. var intersectPoint = ray.closestPointToPoint( point );
  8870. intersectPoint.applyMatrix4( object.matrixWorld );
  8871. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  8872. intersects.push( {
  8873. distance: distance,
  8874. distanceToRay: rayPointDistance,
  8875. point: intersectPoint.clone(),
  8876. index: index,
  8877. face: null,
  8878. object: object
  8879. } );
  8880. }
  8881. };
  8882. if ( geometry instanceof THREE.BufferGeometry ) {
  8883. var attributes = geometry.attributes;
  8884. var positions = attributes.position.array;
  8885. if ( attributes.index !== undefined ) {
  8886. var indices = attributes.index.array;
  8887. var offsets = geometry.offsets;
  8888. if ( offsets.length === 0 ) {
  8889. var offset = {
  8890. start: 0,
  8891. count: indices.length,
  8892. index: 0
  8893. };
  8894. offsets = [ offset ];
  8895. }
  8896. for ( var oi = 0, ol = offsets.length; oi < ol; ++oi ) {
  8897. var start = offsets[ oi ].start;
  8898. var count = offsets[ oi ].count;
  8899. var index = offsets[ oi ].index;
  8900. for ( var i = start, il = start + count; i < il; i ++ ) {
  8901. var a = index + indices[ i ];
  8902. position.fromArray( positions, a * 3 );
  8903. testPoint( position, a );
  8904. }
  8905. }
  8906. } else {
  8907. var pointCount = positions.length / 3;
  8908. for ( var i = 0; i < pointCount; i ++ ) {
  8909. position.set(
  8910. positions[ 3 * i ],
  8911. positions[ 3 * i + 1 ],
  8912. positions[ 3 * i + 2 ]
  8913. );
  8914. testPoint( position, i );
  8915. }
  8916. }
  8917. } else {
  8918. var vertices = this.geometry.vertices;
  8919. for ( var i = 0; i < vertices.length; i ++ ) {
  8920. testPoint( vertices[ i ], i );
  8921. }
  8922. }
  8923. };
  8924. }() );
  8925. THREE.PointCloud.prototype.clone = function ( object ) {
  8926. if ( object === undefined ) object = new THREE.PointCloud( this.geometry, this.material );
  8927. THREE.Object3D.prototype.clone.call( this, object );
  8928. return object;
  8929. };
  8930. // Backwards compatibility
  8931. THREE.ParticleSystem = function ( geometry, material ) {
  8932. THREE.warn( 'THREE.ParticleSystem has been renamed to THREE.PointCloud.' );
  8933. return new THREE.PointCloud( geometry, material );
  8934. };
  8935. // File:src/objects/Line.js
  8936. /**
  8937. * @author mrdoob / http://mrdoob.com/
  8938. */
  8939. THREE.Line = function ( geometry, material, mode ) {
  8940. THREE.Object3D.call( this );
  8941. this.type = 'Line';
  8942. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8943. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  8944. this.mode = ( mode !== undefined ) ? mode : THREE.LineStrip;
  8945. };
  8946. THREE.LineStrip = 0;
  8947. THREE.LinePieces = 1;
  8948. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  8949. THREE.Line.prototype.constructor = THREE.Line;
  8950. THREE.Line.prototype.raycast = ( function () {
  8951. var inverseMatrix = new THREE.Matrix4();
  8952. var ray = new THREE.Ray();
  8953. var sphere = new THREE.Sphere();
  8954. return function ( raycaster, intersects ) {
  8955. var precision = raycaster.linePrecision;
  8956. var precisionSq = precision * precision;
  8957. var geometry = this.geometry;
  8958. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8959. // Checking boundingSphere distance to ray
  8960. sphere.copy( geometry.boundingSphere );
  8961. sphere.applyMatrix4( this.matrixWorld );
  8962. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  8963. return;
  8964. }
  8965. inverseMatrix.getInverse( this.matrixWorld );
  8966. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  8967. var vStart = new THREE.Vector3();
  8968. var vEnd = new THREE.Vector3();
  8969. var interSegment = new THREE.Vector3();
  8970. var interRay = new THREE.Vector3();
  8971. var step = this.mode === THREE.LineStrip ? 1 : 2;
  8972. if ( geometry instanceof THREE.BufferGeometry ) {
  8973. var attributes = geometry.attributes;
  8974. if ( attributes.index !== undefined ) {
  8975. var indices = attributes.index.array;
  8976. var positions = attributes.position.array;
  8977. var offsets = geometry.offsets;
  8978. if ( offsets.length === 0 ) {
  8979. offsets = [ { start: 0, count: indices.length, index: 0 } ];
  8980. }
  8981. for ( var oi = 0; oi < offsets.length; oi++){
  8982. var start = offsets[ oi ].start;
  8983. var count = offsets[ oi ].count;
  8984. var index = offsets[ oi ].index;
  8985. for ( var i = start; i < start + count - 1; i += step ) {
  8986. var a = index + indices[ i ];
  8987. var b = index + indices[ i + 1 ];
  8988. vStart.fromArray( positions, a * 3 );
  8989. vEnd.fromArray( positions, b * 3 );
  8990. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  8991. if ( distSq > precisionSq ) continue;
  8992. var distance = ray.origin.distanceTo( interRay );
  8993. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  8994. intersects.push( {
  8995. distance: distance,
  8996. // What do we want? intersection point on the ray or on the segment??
  8997. // point: raycaster.ray.at( distance ),
  8998. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  8999. index: i,
  9000. offsetIndex: oi,
  9001. face: null,
  9002. faceIndex: null,
  9003. object: this
  9004. } );
  9005. }
  9006. }
  9007. } else {
  9008. var positions = attributes.position.array;
  9009. for ( var i = 0; i < positions.length / 3 - 1; i += step ) {
  9010. vStart.fromArray( positions, 3 * i );
  9011. vEnd.fromArray( positions, 3 * i + 3 );
  9012. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  9013. if ( distSq > precisionSq ) continue;
  9014. var distance = ray.origin.distanceTo( interRay );
  9015. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  9016. intersects.push( {
  9017. distance: distance,
  9018. // What do we want? intersection point on the ray or on the segment??
  9019. // point: raycaster.ray.at( distance ),
  9020. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  9021. index: i,
  9022. face: null,
  9023. faceIndex: null,
  9024. object: this
  9025. } );
  9026. }
  9027. }
  9028. } else if ( geometry instanceof THREE.Geometry ) {
  9029. var vertices = geometry.vertices;
  9030. var nbVertices = vertices.length;
  9031. for ( var i = 0; i < nbVertices - 1; i += step ) {
  9032. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  9033. if ( distSq > precisionSq ) continue;
  9034. var distance = ray.origin.distanceTo( interRay );
  9035. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  9036. intersects.push( {
  9037. distance: distance,
  9038. // What do we want? intersection point on the ray or on the segment??
  9039. // point: raycaster.ray.at( distance ),
  9040. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  9041. index: i,
  9042. face: null,
  9043. faceIndex: null,
  9044. object: this
  9045. } );
  9046. }
  9047. }
  9048. };
  9049. }() );
  9050. THREE.Line.prototype.clone = function ( object ) {
  9051. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.mode );
  9052. THREE.Object3D.prototype.clone.call( this, object );
  9053. return object;
  9054. };
  9055. // File:src/objects/Mesh.js
  9056. /**
  9057. * @author mrdoob / http://mrdoob.com/
  9058. * @author alteredq / http://alteredqualia.com/
  9059. * @author mikael emtinger / http://gomo.se/
  9060. * @author jonobr1 / http://jonobr1.com/
  9061. */
  9062. THREE.Mesh = function ( geometry, material ) {
  9063. THREE.Object3D.call( this );
  9064. this.type = 'Mesh';
  9065. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9066. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  9067. this.updateMorphTargets();
  9068. };
  9069. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  9070. THREE.Mesh.prototype.constructor = THREE.Mesh;
  9071. THREE.Mesh.prototype.updateMorphTargets = function () {
  9072. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  9073. this.morphTargetBase = - 1;
  9074. this.morphTargetForcedOrder = [];
  9075. this.morphTargetInfluences = [];
  9076. this.morphTargetDictionary = {};
  9077. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  9078. this.morphTargetInfluences.push( 0 );
  9079. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  9080. }
  9081. }
  9082. };
  9083. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  9084. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  9085. return this.morphTargetDictionary[ name ];
  9086. }
  9087. THREE.warn( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' );
  9088. return 0;
  9089. };
  9090. THREE.Mesh.prototype.raycast = ( function () {
  9091. var inverseMatrix = new THREE.Matrix4();
  9092. var ray = new THREE.Ray();
  9093. var sphere = new THREE.Sphere();
  9094. var vA = new THREE.Vector3();
  9095. var vB = new THREE.Vector3();
  9096. var vC = new THREE.Vector3();
  9097. return function ( raycaster, intersects ) {
  9098. var geometry = this.geometry;
  9099. // Checking boundingSphere distance to ray
  9100. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9101. sphere.copy( geometry.boundingSphere );
  9102. sphere.applyMatrix4( this.matrixWorld );
  9103. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  9104. return;
  9105. }
  9106. // Check boundingBox before continuing
  9107. inverseMatrix.getInverse( this.matrixWorld );
  9108. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  9109. if ( geometry.boundingBox !== null ) {
  9110. if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) {
  9111. return;
  9112. }
  9113. }
  9114. if ( geometry instanceof THREE.BufferGeometry ) {
  9115. var material = this.material;
  9116. if ( material === undefined ) return;
  9117. var attributes = geometry.attributes;
  9118. var a, b, c;
  9119. var precision = raycaster.precision;
  9120. if ( attributes.index !== undefined ) {
  9121. var indices = attributes.index.array;
  9122. var positions = attributes.position.array;
  9123. var offsets = geometry.offsets;
  9124. if ( offsets.length === 0 ) {
  9125. offsets = [ { start: 0, count: indices.length, index: 0 } ];
  9126. }
  9127. for ( var oi = 0, ol = offsets.length; oi < ol; ++oi ) {
  9128. var start = offsets[ oi ].start;
  9129. var count = offsets[ oi ].count;
  9130. var index = offsets[ oi ].index;
  9131. for ( var i = start, il = start + count; i < il; i += 3 ) {
  9132. a = index + indices[ i ];
  9133. b = index + indices[ i + 1 ];
  9134. c = index + indices[ i + 2 ];
  9135. vA.fromArray( positions, a * 3 );
  9136. vB.fromArray( positions, b * 3 );
  9137. vC.fromArray( positions, c * 3 );
  9138. if ( material.side === THREE.BackSide ) {
  9139. var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true );
  9140. } else {
  9141. var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  9142. }
  9143. if ( intersectionPoint === null ) continue;
  9144. intersectionPoint.applyMatrix4( this.matrixWorld );
  9145. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  9146. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  9147. intersects.push( {
  9148. distance: distance,
  9149. point: intersectionPoint,
  9150. face: new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) ),
  9151. faceIndex: null,
  9152. object: this
  9153. } );
  9154. }
  9155. }
  9156. } else {
  9157. var positions = attributes.position.array;
  9158. for ( var i = 0, j = 0, il = positions.length; i < il; i += 3, j += 9 ) {
  9159. a = i;
  9160. b = i + 1;
  9161. c = i + 2;
  9162. vA.fromArray( positions, j );
  9163. vB.fromArray( positions, j + 3 );
  9164. vC.fromArray( positions, j + 6 );
  9165. if ( material.side === THREE.BackSide ) {
  9166. var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true );
  9167. } else {
  9168. var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  9169. }
  9170. if ( intersectionPoint === null ) continue;
  9171. intersectionPoint.applyMatrix4( this.matrixWorld );
  9172. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  9173. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  9174. intersects.push( {
  9175. distance: distance,
  9176. point: intersectionPoint,
  9177. face: new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) ),
  9178. faceIndex: null,
  9179. object: this
  9180. } );
  9181. }
  9182. }
  9183. } else if ( geometry instanceof THREE.Geometry ) {
  9184. var isFaceMaterial = this.material instanceof THREE.MeshFaceMaterial;
  9185. var objectMaterials = isFaceMaterial === true ? this.material.materials : null;
  9186. var a, b, c, d;
  9187. var precision = raycaster.precision;
  9188. var vertices = geometry.vertices;
  9189. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  9190. var face = geometry.faces[ f ];
  9191. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : this.material;
  9192. if ( material === undefined ) continue;
  9193. a = vertices[ face.a ];
  9194. b = vertices[ face.b ];
  9195. c = vertices[ face.c ];
  9196. if ( material.morphTargets === true ) {
  9197. var morphTargets = geometry.morphTargets;
  9198. var morphInfluences = this.morphTargetInfluences;
  9199. vA.set( 0, 0, 0 );
  9200. vB.set( 0, 0, 0 );
  9201. vC.set( 0, 0, 0 );
  9202. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  9203. var influence = morphInfluences[ t ];
  9204. if ( influence === 0 ) continue;
  9205. var targets = morphTargets[ t ].vertices;
  9206. vA.x += ( targets[ face.a ].x - a.x ) * influence;
  9207. vA.y += ( targets[ face.a ].y - a.y ) * influence;
  9208. vA.z += ( targets[ face.a ].z - a.z ) * influence;
  9209. vB.x += ( targets[ face.b ].x - b.x ) * influence;
  9210. vB.y += ( targets[ face.b ].y - b.y ) * influence;
  9211. vB.z += ( targets[ face.b ].z - b.z ) * influence;
  9212. vC.x += ( targets[ face.c ].x - c.x ) * influence;
  9213. vC.y += ( targets[ face.c ].y - c.y ) * influence;
  9214. vC.z += ( targets[ face.c ].z - c.z ) * influence;
  9215. }
  9216. vA.add( a );
  9217. vB.add( b );
  9218. vC.add( c );
  9219. a = vA;
  9220. b = vB;
  9221. c = vC;
  9222. }
  9223. if ( material.side === THREE.BackSide ) {
  9224. var intersectionPoint = ray.intersectTriangle( c, b, a, true );
  9225. } else {
  9226. var intersectionPoint = ray.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide );
  9227. }
  9228. if ( intersectionPoint === null ) continue;
  9229. intersectionPoint.applyMatrix4( this.matrixWorld );
  9230. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  9231. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  9232. intersects.push( {
  9233. distance: distance,
  9234. point: intersectionPoint,
  9235. face: face,
  9236. faceIndex: f,
  9237. object: this
  9238. } );
  9239. }
  9240. }
  9241. };
  9242. }() );
  9243. THREE.Mesh.prototype.clone = function ( object, recursive ) {
  9244. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  9245. THREE.Object3D.prototype.clone.call( this, object, recursive );
  9246. return object;
  9247. };
  9248. // File:src/objects/Bone.js
  9249. /**
  9250. * @author mikael emtinger / http://gomo.se/
  9251. * @author alteredq / http://alteredqualia.com/
  9252. * @author ikerr / http://verold.com
  9253. */
  9254. THREE.Bone = function ( belongsToSkin ) {
  9255. THREE.Object3D.call( this );
  9256. this.skin = belongsToSkin;
  9257. };
  9258. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  9259. THREE.Bone.prototype.constructor = THREE.Bone;
  9260. // File:src/objects/Skeleton.js
  9261. /**
  9262. * @author mikael emtinger / http://gomo.se/
  9263. * @author alteredq / http://alteredqualia.com/
  9264. * @author michael guerrero / http://realitymeltdown.com
  9265. * @author ikerr / http://verold.com
  9266. */
  9267. THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) {
  9268. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  9269. this.identityMatrix = new THREE.Matrix4();
  9270. // copy the bone array
  9271. bones = bones || [];
  9272. this.bones = bones.slice( 0 );
  9273. // create a bone texture or an array of floats
  9274. if ( this.useVertexTexture ) {
  9275. // layout (1 matrix = 4 pixels)
  9276. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  9277. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  9278. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  9279. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  9280. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  9281. var size;
  9282. if ( this.bones.length > 256 )
  9283. size = 64;
  9284. else if ( this.bones.length > 64 )
  9285. size = 32;
  9286. else if ( this.bones.length > 16 )
  9287. size = 16;
  9288. else
  9289. size = 8;
  9290. this.boneTextureWidth = size;
  9291. this.boneTextureHeight = size;
  9292. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  9293. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  9294. this.boneTexture.minFilter = THREE.NearestFilter;
  9295. this.boneTexture.magFilter = THREE.NearestFilter;
  9296. this.boneTexture.generateMipmaps = false;
  9297. this.boneTexture.flipY = false;
  9298. } else {
  9299. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  9300. }
  9301. // use the supplied bone inverses or calculate the inverses
  9302. if ( boneInverses === undefined ) {
  9303. this.calculateInverses();
  9304. } else {
  9305. if ( this.bones.length === boneInverses.length ) {
  9306. this.boneInverses = boneInverses.slice( 0 );
  9307. } else {
  9308. THREE.warn( 'THREE.Skeleton bonInverses is the wrong length.' );
  9309. this.boneInverses = [];
  9310. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9311. this.boneInverses.push( new THREE.Matrix4() );
  9312. }
  9313. }
  9314. }
  9315. };
  9316. THREE.Skeleton.prototype.calculateInverses = function () {
  9317. this.boneInverses = [];
  9318. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9319. var inverse = new THREE.Matrix4();
  9320. if ( this.bones[ b ] ) {
  9321. inverse.getInverse( this.bones[ b ].matrixWorld );
  9322. }
  9323. this.boneInverses.push( inverse );
  9324. }
  9325. };
  9326. THREE.Skeleton.prototype.pose = function () {
  9327. var bone;
  9328. // recover the bind-time world matrices
  9329. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9330. bone = this.bones[ b ];
  9331. if ( bone ) {
  9332. bone.matrixWorld.getInverse( this.boneInverses[ b ] );
  9333. }
  9334. }
  9335. // compute the local matrices, positions, rotations and scales
  9336. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9337. bone = this.bones[ b ];
  9338. if ( bone ) {
  9339. if ( bone.parent ) {
  9340. bone.matrix.getInverse( bone.parent.matrixWorld );
  9341. bone.matrix.multiply( bone.matrixWorld );
  9342. } else {
  9343. bone.matrix.copy( bone.matrixWorld );
  9344. }
  9345. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  9346. }
  9347. }
  9348. };
  9349. THREE.Skeleton.prototype.update = ( function () {
  9350. var offsetMatrix = new THREE.Matrix4();
  9351. return function () {
  9352. // flatten bone matrices to array
  9353. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9354. // compute the offset between the current and the original transform
  9355. var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix;
  9356. offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] );
  9357. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  9358. }
  9359. if ( this.useVertexTexture ) {
  9360. this.boneTexture.needsUpdate = true;
  9361. }
  9362. };
  9363. } )();
  9364. // File:src/objects/SkinnedMesh.js
  9365. /**
  9366. * @author mikael emtinger / http://gomo.se/
  9367. * @author alteredq / http://alteredqualia.com/
  9368. * @author ikerr / http://verold.com
  9369. */
  9370. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  9371. THREE.Mesh.call( this, geometry, material );
  9372. this.type = 'SkinnedMesh';
  9373. this.bindMode = "attached";
  9374. this.bindMatrix = new THREE.Matrix4();
  9375. this.bindMatrixInverse = new THREE.Matrix4();
  9376. // init bones
  9377. // TODO: remove bone creation as there is no reason (other than
  9378. // convenience) for THREE.SkinnedMesh to do this.
  9379. var bones = [];
  9380. if ( this.geometry && this.geometry.bones !== undefined ) {
  9381. var bone, gbone, p, q, s;
  9382. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++b ) {
  9383. gbone = this.geometry.bones[ b ];
  9384. p = gbone.pos;
  9385. q = gbone.rotq;
  9386. s = gbone.scl;
  9387. bone = new THREE.Bone( this );
  9388. bones.push( bone );
  9389. bone.name = gbone.name;
  9390. bone.position.set( p[ 0 ], p[ 1 ], p[ 2 ] );
  9391. bone.quaternion.set( q[ 0 ], q[ 1 ], q[ 2 ], q[ 3 ] );
  9392. if ( s !== undefined ) {
  9393. bone.scale.set( s[ 0 ], s[ 1 ], s[ 2 ] );
  9394. } else {
  9395. bone.scale.set( 1, 1, 1 );
  9396. }
  9397. }
  9398. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++b ) {
  9399. gbone = this.geometry.bones[ b ];
  9400. if ( gbone.parent !== - 1 ) {
  9401. bones[ gbone.parent ].add( bones[ b ] );
  9402. } else {
  9403. this.add( bones[ b ] );
  9404. }
  9405. }
  9406. }
  9407. this.normalizeSkinWeights();
  9408. this.updateMatrixWorld( true );
  9409. this.bind( new THREE.Skeleton( bones, undefined, useVertexTexture ) );
  9410. };
  9411. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  9412. THREE.SkinnedMesh.prototype.constructor = THREE.SkinnedMesh;
  9413. THREE.SkinnedMesh.prototype.bind = function( skeleton, bindMatrix ) {
  9414. this.skeleton = skeleton;
  9415. if ( bindMatrix === undefined ) {
  9416. this.updateMatrixWorld( true );
  9417. bindMatrix = this.matrixWorld;
  9418. }
  9419. this.bindMatrix.copy( bindMatrix );
  9420. this.bindMatrixInverse.getInverse( bindMatrix );
  9421. };
  9422. THREE.SkinnedMesh.prototype.pose = function () {
  9423. this.skeleton.pose();
  9424. };
  9425. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  9426. if ( this.geometry instanceof THREE.Geometry ) {
  9427. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  9428. var sw = this.geometry.skinWeights[ i ];
  9429. var scale = 1.0 / sw.lengthManhattan();
  9430. if ( scale !== Infinity ) {
  9431. sw.multiplyScalar( scale );
  9432. } else {
  9433. sw.set( 1 ); // this will be normalized by the shader anyway
  9434. }
  9435. }
  9436. } else {
  9437. // skinning weights assumed to be normalized for THREE.BufferGeometry
  9438. }
  9439. };
  9440. THREE.SkinnedMesh.prototype.updateMatrixWorld = function( force ) {
  9441. THREE.Mesh.prototype.updateMatrixWorld.call( this, true );
  9442. if ( this.bindMode === "attached" ) {
  9443. this.bindMatrixInverse.getInverse( this.matrixWorld );
  9444. } else if ( this.bindMode === "detached" ) {
  9445. this.bindMatrixInverse.getInverse( this.bindMatrix );
  9446. } else {
  9447. THREE.warn( 'THREE.SkinnedMesh unreckognized bindMode: ' + this.bindMode );
  9448. }
  9449. };
  9450. THREE.SkinnedMesh.prototype.clone = function( object ) {
  9451. if ( object === undefined ) {
  9452. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  9453. }
  9454. THREE.Mesh.prototype.clone.call( this, object );
  9455. return object;
  9456. };
  9457. // File:src/objects/MorphAnimMesh.js
  9458. /**
  9459. * @author alteredq / http://alteredqualia.com/
  9460. */
  9461. THREE.MorphAnimMesh = function ( geometry, material ) {
  9462. THREE.Mesh.call( this, geometry, material );
  9463. this.type = 'MorphAnimMesh';
  9464. // API
  9465. this.duration = 1000; // milliseconds
  9466. this.mirroredLoop = false;
  9467. this.time = 0;
  9468. // internals
  9469. this.lastKeyframe = 0;
  9470. this.currentKeyframe = 0;
  9471. this.direction = 1;
  9472. this.directionBackwards = false;
  9473. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  9474. };
  9475. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  9476. THREE.MorphAnimMesh.prototype.constructor = THREE.MorphAnimMesh;
  9477. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  9478. this.startKeyframe = start;
  9479. this.endKeyframe = end;
  9480. this.length = this.endKeyframe - this.startKeyframe + 1;
  9481. };
  9482. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  9483. this.direction = 1;
  9484. this.directionBackwards = false;
  9485. };
  9486. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  9487. this.direction = - 1;
  9488. this.directionBackwards = true;
  9489. };
  9490. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  9491. var geometry = this.geometry;
  9492. if ( ! geometry.animations ) geometry.animations = {};
  9493. var firstAnimation, animations = geometry.animations;
  9494. var pattern = /([a-z]+)_?(\d+)/;
  9495. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  9496. var morph = geometry.morphTargets[ i ];
  9497. var parts = morph.name.match( pattern );
  9498. if ( parts && parts.length > 1 ) {
  9499. var label = parts[ 1 ];
  9500. var num = parts[ 2 ];
  9501. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: - Infinity };
  9502. var animation = animations[ label ];
  9503. if ( i < animation.start ) animation.start = i;
  9504. if ( i > animation.end ) animation.end = i;
  9505. if ( ! firstAnimation ) firstAnimation = label;
  9506. }
  9507. }
  9508. geometry.firstAnimation = firstAnimation;
  9509. };
  9510. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  9511. if ( ! this.geometry.animations ) this.geometry.animations = {};
  9512. this.geometry.animations[ label ] = { start: start, end: end };
  9513. };
  9514. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  9515. var animation = this.geometry.animations[ label ];
  9516. if ( animation ) {
  9517. this.setFrameRange( animation.start, animation.end );
  9518. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  9519. this.time = 0;
  9520. } else {
  9521. THREE.warn( 'THREE.MorphAnimMesh: animation[' + label + '] undefined in .playAnimation()' );
  9522. }
  9523. };
  9524. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  9525. var frameTime = this.duration / this.length;
  9526. this.time += this.direction * delta;
  9527. if ( this.mirroredLoop ) {
  9528. if ( this.time > this.duration || this.time < 0 ) {
  9529. this.direction *= - 1;
  9530. if ( this.time > this.duration ) {
  9531. this.time = this.duration;
  9532. this.directionBackwards = true;
  9533. }
  9534. if ( this.time < 0 ) {
  9535. this.time = 0;
  9536. this.directionBackwards = false;
  9537. }
  9538. }
  9539. } else {
  9540. this.time = this.time % this.duration;
  9541. if ( this.time < 0 ) this.time += this.duration;
  9542. }
  9543. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  9544. if ( keyframe !== this.currentKeyframe ) {
  9545. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  9546. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  9547. this.morphTargetInfluences[ keyframe ] = 0;
  9548. this.lastKeyframe = this.currentKeyframe;
  9549. this.currentKeyframe = keyframe;
  9550. }
  9551. var mix = ( this.time % frameTime ) / frameTime;
  9552. if ( this.directionBackwards ) {
  9553. mix = 1 - mix;
  9554. }
  9555. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  9556. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  9557. };
  9558. THREE.MorphAnimMesh.prototype.interpolateTargets = function ( a, b, t ) {
  9559. var influences = this.morphTargetInfluences;
  9560. for ( var i = 0, l = influences.length; i < l; i ++ ) {
  9561. influences[ i ] = 0;
  9562. }
  9563. if ( a > -1 ) influences[ a ] = 1 - t;
  9564. if ( b > -1 ) influences[ b ] = t;
  9565. };
  9566. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  9567. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  9568. object.duration = this.duration;
  9569. object.mirroredLoop = this.mirroredLoop;
  9570. object.time = this.time;
  9571. object.lastKeyframe = this.lastKeyframe;
  9572. object.currentKeyframe = this.currentKeyframe;
  9573. object.direction = this.direction;
  9574. object.directionBackwards = this.directionBackwards;
  9575. THREE.Mesh.prototype.clone.call( this, object );
  9576. return object;
  9577. };
  9578. // File:src/objects/LOD.js
  9579. /**
  9580. * @author mikael emtinger / http://gomo.se/
  9581. * @author alteredq / http://alteredqualia.com/
  9582. * @author mrdoob / http://mrdoob.com/
  9583. */
  9584. THREE.LOD = function () {
  9585. THREE.Object3D.call( this );
  9586. this.objects = [];
  9587. };
  9588. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  9589. THREE.LOD.prototype.constructor = THREE.LOD;
  9590. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  9591. if ( distance === undefined ) distance = 0;
  9592. distance = Math.abs( distance );
  9593. for ( var l = 0; l < this.objects.length; l ++ ) {
  9594. if ( distance < this.objects[ l ].distance ) {
  9595. break;
  9596. }
  9597. }
  9598. this.objects.splice( l, 0, { distance: distance, object: object } );
  9599. this.add( object );
  9600. };
  9601. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  9602. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9603. if ( distance < this.objects[ i ].distance ) {
  9604. break;
  9605. }
  9606. }
  9607. return this.objects[ i - 1 ].object;
  9608. };
  9609. THREE.LOD.prototype.raycast = ( function () {
  9610. var matrixPosition = new THREE.Vector3();
  9611. return function ( raycaster, intersects ) {
  9612. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  9613. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  9614. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  9615. };
  9616. }() );
  9617. THREE.LOD.prototype.update = function () {
  9618. var v1 = new THREE.Vector3();
  9619. var v2 = new THREE.Vector3();
  9620. return function ( camera ) {
  9621. if ( this.objects.length > 1 ) {
  9622. v1.setFromMatrixPosition( camera.matrixWorld );
  9623. v2.setFromMatrixPosition( this.matrixWorld );
  9624. var distance = v1.distanceTo( v2 );
  9625. this.objects[ 0 ].object.visible = true;
  9626. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9627. if ( distance >= this.objects[ i ].distance ) {
  9628. this.objects[ i - 1 ].object.visible = false;
  9629. this.objects[ i ].object.visible = true;
  9630. } else {
  9631. break;
  9632. }
  9633. }
  9634. for ( ; i < l; i ++ ) {
  9635. this.objects[ i ].object.visible = false;
  9636. }
  9637. }
  9638. };
  9639. }();
  9640. THREE.LOD.prototype.clone = function ( object ) {
  9641. if ( object === undefined ) object = new THREE.LOD();
  9642. THREE.Object3D.prototype.clone.call( this, object );
  9643. for ( var i = 0, l = this.objects.length; i < l; i ++ ) {
  9644. var x = this.objects[ i ].object.clone();
  9645. x.visible = i === 0;
  9646. object.addLevel( x, this.objects[ i ].distance );
  9647. }
  9648. return object;
  9649. };
  9650. // File:src/objects/Sprite.js
  9651. /**
  9652. * @author mikael emtinger / http://gomo.se/
  9653. * @author alteredq / http://alteredqualia.com/
  9654. */
  9655. THREE.Sprite = ( function () {
  9656. var indices = new Uint16Array( [ 0, 1, 2, 0, 2, 3 ] );
  9657. var vertices = new Float32Array( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0, - 0.5, 0.5, 0 ] );
  9658. var uvs = new Float32Array( [ 0, 0, 1, 0, 1, 1, 0, 1 ] );
  9659. var geometry = new THREE.BufferGeometry();
  9660. geometry.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) );
  9661. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  9662. geometry.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  9663. return function ( material ) {
  9664. THREE.Object3D.call( this );
  9665. this.type = 'Sprite';
  9666. this.geometry = geometry;
  9667. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  9668. };
  9669. } )();
  9670. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  9671. THREE.Sprite.prototype.constructor = THREE.Sprite;
  9672. THREE.Sprite.prototype.raycast = ( function () {
  9673. var matrixPosition = new THREE.Vector3();
  9674. return function ( raycaster, intersects ) {
  9675. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  9676. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  9677. if ( distance > this.scale.x ) {
  9678. return;
  9679. }
  9680. intersects.push( {
  9681. distance: distance,
  9682. point: this.position,
  9683. face: null,
  9684. object: this
  9685. } );
  9686. };
  9687. }() );
  9688. THREE.Sprite.prototype.clone = function ( object ) {
  9689. if ( object === undefined ) object = new THREE.Sprite( this.material );
  9690. THREE.Object3D.prototype.clone.call( this, object );
  9691. return object;
  9692. };
  9693. // Backwards compatibility
  9694. THREE.Particle = THREE.Sprite;
  9695. // File:src/objects/LensFlare.js
  9696. /**
  9697. * @author mikael emtinger / http://gomo.se/
  9698. * @author alteredq / http://alteredqualia.com/
  9699. */
  9700. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  9701. THREE.Object3D.call( this );
  9702. this.lensFlares = [];
  9703. this.positionScreen = new THREE.Vector3();
  9704. this.customUpdateCallback = undefined;
  9705. if( texture !== undefined ) {
  9706. this.add( texture, size, distance, blending, color );
  9707. }
  9708. };
  9709. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  9710. THREE.LensFlare.prototype.constructor = THREE.LensFlare;
  9711. /*
  9712. * Add: adds another flare
  9713. */
  9714. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  9715. if ( size === undefined ) size = - 1;
  9716. if ( distance === undefined ) distance = 0;
  9717. if ( opacity === undefined ) opacity = 1;
  9718. if ( color === undefined ) color = new THREE.Color( 0xffffff );
  9719. if ( blending === undefined ) blending = THREE.NormalBlending;
  9720. distance = Math.min( distance, Math.max( 0, distance ) );
  9721. this.lensFlares.push( {
  9722. texture: texture, // THREE.Texture
  9723. size: size, // size in pixels (-1 = use texture.width)
  9724. distance: distance, // distance (0-1) from light source (0=at light source)
  9725. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  9726. scale: 1, // scale
  9727. rotation: 1, // rotation
  9728. opacity: opacity, // opacity
  9729. color: color, // color
  9730. blending: blending // blending
  9731. } );
  9732. };
  9733. /*
  9734. * Update lens flares update positions on all flares based on the screen position
  9735. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  9736. */
  9737. THREE.LensFlare.prototype.updateLensFlares = function () {
  9738. var f, fl = this.lensFlares.length;
  9739. var flare;
  9740. var vecX = - this.positionScreen.x * 2;
  9741. var vecY = - this.positionScreen.y * 2;
  9742. for( f = 0; f < fl; f ++ ) {
  9743. flare = this.lensFlares[ f ];
  9744. flare.x = this.positionScreen.x + vecX * flare.distance;
  9745. flare.y = this.positionScreen.y + vecY * flare.distance;
  9746. flare.wantedRotation = flare.x * Math.PI * 0.25;
  9747. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  9748. }
  9749. };
  9750. // File:src/scenes/Scene.js
  9751. /**
  9752. * @author mrdoob / http://mrdoob.com/
  9753. */
  9754. THREE.Scene = function () {
  9755. THREE.Object3D.call( this );
  9756. this.type = 'Scene';
  9757. this.fog = null;
  9758. this.overrideMaterial = null;
  9759. this.autoUpdate = true; // checked by the renderer
  9760. };
  9761. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  9762. THREE.Scene.prototype.constructor = THREE.Scene;
  9763. THREE.Scene.prototype.clone = function ( object ) {
  9764. if ( object === undefined ) object = new THREE.Scene();
  9765. THREE.Object3D.prototype.clone.call( this, object );
  9766. if ( this.fog !== null ) object.fog = this.fog.clone();
  9767. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  9768. object.autoUpdate = this.autoUpdate;
  9769. object.matrixAutoUpdate = this.matrixAutoUpdate;
  9770. return object;
  9771. };
  9772. // File:src/scenes/Fog.js
  9773. /**
  9774. * @author mrdoob / http://mrdoob.com/
  9775. * @author alteredq / http://alteredqualia.com/
  9776. */
  9777. THREE.Fog = function ( color, near, far ) {
  9778. this.name = '';
  9779. this.color = new THREE.Color( color );
  9780. this.near = ( near !== undefined ) ? near : 1;
  9781. this.far = ( far !== undefined ) ? far : 1000;
  9782. };
  9783. THREE.Fog.prototype.clone = function () {
  9784. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  9785. };
  9786. // File:src/scenes/FogExp2.js
  9787. /**
  9788. * @author mrdoob / http://mrdoob.com/
  9789. * @author alteredq / http://alteredqualia.com/
  9790. */
  9791. THREE.FogExp2 = function ( color, density ) {
  9792. this.name = '';
  9793. this.color = new THREE.Color( color );
  9794. this.density = ( density !== undefined ) ? density : 0.00025;
  9795. };
  9796. THREE.FogExp2.prototype.clone = function () {
  9797. return new THREE.FogExp2( this.color.getHex(), this.density );
  9798. };
  9799. // File:src/renderers/shaders/ShaderChunk.js
  9800. THREE.ShaderChunk = {};
  9801. // File:src/renderers/shaders/ShaderChunk/common.glsl
  9802. 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";
  9803. // File:src/renderers/shaders/ShaderChunk/alphatest_fragment.glsl
  9804. THREE.ShaderChunk[ 'alphatest_fragment'] = "#ifdef ALPHATEST\n\n if ( gl_FragColor.a < ALPHATEST ) discard;\n\n#endif\n";
  9805. // File:src/renderers/shaders/ShaderChunk/lights_lambert_vertex.glsl
  9806. 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 = vLightFront * diffuse + diffuse * ambientLightColor + emissive;\n\n#ifdef DOUBLE_SIDED\n\n vLightBack = vLightBack * diffuse + diffuse * ambientLightColor + emissive;\n\n#endif\n";
  9807. // File:src/renderers/shaders/ShaderChunk/map_particle_pars_fragment.glsl
  9808. THREE.ShaderChunk[ 'map_particle_pars_fragment'] = "#ifdef USE_MAP\n\n uniform sampler2D map;\n\n#endif";
  9809. // File:src/renderers/shaders/ShaderChunk/default_vertex.glsl
  9810. 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";
  9811. // File:src/renderers/shaders/ShaderChunk/map_pars_fragment.glsl
  9812. THREE.ShaderChunk[ 'map_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\n\n#ifdef USE_MAP\n\n uniform sampler2D map;\n\n#endif";
  9813. // File:src/renderers/shaders/ShaderChunk/skinnormal_vertex.glsl
  9814. 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";
  9815. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl
  9816. 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";
  9817. // File:src/renderers/shaders/ShaderChunk/lightmap_pars_vertex.glsl
  9818. THREE.ShaderChunk[ 'lightmap_pars_vertex'] = "#ifdef USE_LIGHTMAP\n\n varying vec2 vUv2;\n\n#endif";
  9819. // File:src/renderers/shaders/ShaderChunk/lights_phong_fragment.glsl
  9820. THREE.ShaderChunk[ 'lights_phong_fragment'] = "vec3 normal = normalize( vNormal );\nvec3 viewPosition = normalize( vViewPosition );\n\n#ifdef DOUBLE_SIDED\n\n normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );\n\n#endif\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\n#if MAX_POINT_LIGHTS > 0\n\n vec3 pointDiffuse = vec3( 0.0 );\n vec3 pointSpecular = vec3( 0.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 pointDiffuse += diffuse * 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 pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * attenuation * specularNormalization;\n\n }\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n vec3 spotDiffuse = vec3( 0.0 );\n vec3 spotSpecular = vec3( 0.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 spotDiffuse += diffuse * 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 spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * attenuation * specularNormalization * spotEffect;\n\n }\n\n }\n\n#endif\n\n#if MAX_DIR_LIGHTS > 0\n\n vec3 dirDiffuse = vec3( 0.0 );\n vec3 dirSpecular = vec3( 0.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 dirDiffuse += diffuse * 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 dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;\n\n\n }\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n vec3 hemiDiffuse = vec3( 0.0 );\n vec3 hemiSpecular = vec3( 0.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 hemiDiffuse += diffuse * 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 hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );\n\n }\n\n#endif\n\nvec3 totalDiffuse = vec3( 0.0 );\nvec3 totalSpecular = vec3( 0.0 );\n\n#if MAX_DIR_LIGHTS > 0\n\n totalDiffuse += dirDiffuse;\n totalSpecular += dirSpecular;\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n totalDiffuse += hemiDiffuse;\n totalSpecular += hemiSpecular;\n\n#endif\n\n#if MAX_POINT_LIGHTS > 0\n\n totalDiffuse += pointDiffuse;\n totalSpecular += pointSpecular;\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n totalDiffuse += spotDiffuse;\n totalSpecular += spotSpecular;\n\n#endif\n\n#ifdef METAL\n\n gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * diffuse + totalSpecular );\n\n#else\n\n gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * diffuse ) + totalSpecular;\n\n#endif\n";
  9821. // File:src/renderers/shaders/ShaderChunk/fog_pars_fragment.glsl
  9822. 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";
  9823. // File:src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl
  9824. 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";
  9825. // File:src/renderers/shaders/ShaderChunk/envmap_pars_fragment.glsl
  9826. 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";
  9827. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl
  9828. THREE.ShaderChunk[ 'logdepthbuf_fragment'] = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\n gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n\n#endif";
  9829. // File:src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl
  9830. 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";
  9831. // File:src/renderers/shaders/ShaderChunk/lights_phong_pars_vertex.glsl
  9832. 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";
  9833. // File:src/renderers/shaders/ShaderChunk/lightmap_pars_fragment.glsl
  9834. THREE.ShaderChunk[ 'lightmap_pars_fragment'] = "#ifdef USE_LIGHTMAP\n\n varying vec2 vUv2;\n uniform sampler2D lightMap;\n\n#endif";
  9835. // File:src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl
  9836. 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";
  9837. // File:src/renderers/shaders/ShaderChunk/lights_phong_vertex.glsl
  9838. THREE.ShaderChunk[ 'lights_phong_vertex'] = "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )\n\n vWorldPosition = worldPosition.xyz;\n\n#endif";
  9839. // File:src/renderers/shaders/ShaderChunk/map_fragment.glsl
  9840. THREE.ShaderChunk[ 'map_fragment'] = "#ifdef USE_MAP\n\n vec4 texelColor = texture2D( map, vUv );\n\n texelColor.xyz = inputToLinear( texelColor.xyz );\n\n gl_FragColor = gl_FragColor * texelColor;\n\n#endif";
  9841. // File:src/renderers/shaders/ShaderChunk/lightmap_vertex.glsl
  9842. THREE.ShaderChunk[ 'lightmap_vertex'] = "#ifdef USE_LIGHTMAP\n\n vUv2 = uv2;\n\n#endif";
  9843. // File:src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl
  9844. THREE.ShaderChunk[ 'map_particle_fragment'] = "#ifdef USE_MAP\n\n gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );\n\n#endif";
  9845. // File:src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl
  9846. THREE.ShaderChunk[ 'color_pars_fragment'] = "#ifdef USE_COLOR\n\n varying vec3 vColor;\n\n#endif\n";
  9847. // File:src/renderers/shaders/ShaderChunk/color_vertex.glsl
  9848. THREE.ShaderChunk[ 'color_vertex'] = "#ifdef USE_COLOR\n\n vColor.xyz = inputToLinear( color.xyz );\n\n#endif";
  9849. // File:src/renderers/shaders/ShaderChunk/skinning_vertex.glsl
  9850. 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";
  9851. // File:src/renderers/shaders/ShaderChunk/envmap_pars_vertex.glsl
  9852. 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";
  9853. // File:src/renderers/shaders/ShaderChunk/linear_to_gamma_fragment.glsl
  9854. THREE.ShaderChunk[ 'linear_to_gamma_fragment'] = "\n gl_FragColor.xyz = linearToOutput( gl_FragColor.xyz );\n";
  9855. // File:src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl
  9856. THREE.ShaderChunk[ 'color_pars_vertex'] = "#ifdef USE_COLOR\n\n varying vec3 vColor;\n\n#endif";
  9857. // File:src/renderers/shaders/ShaderChunk/lights_lambert_pars_vertex.glsl
  9858. THREE.ShaderChunk[ 'lights_lambert_pars_vertex'] = "uniform vec3 diffuse;\nuniform vec3 emissive;\n\nuniform 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";
  9859. // File:src/renderers/shaders/ShaderChunk/map_pars_vertex.glsl
  9860. THREE.ShaderChunk[ 'map_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";
  9861. // File:src/renderers/shaders/ShaderChunk/envmap_fragment.glsl
  9862. 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 gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * envColor.xyz, specularStrength * reflectivity );\n\n #elif defined( ENVMAP_BLENDING_MIX )\n\n gl_FragColor.xyz = mix( gl_FragColor.xyz, envColor.xyz, specularStrength * reflectivity );\n\n #elif defined( ENVMAP_BLENDING_ADD )\n\n gl_FragColor.xyz += envColor.xyz * specularStrength * reflectivity;\n\n #endif\n\n#endif\n";
  9863. // File:src/renderers/shaders/ShaderChunk/specularmap_pars_fragment.glsl
  9864. THREE.ShaderChunk[ 'specularmap_pars_fragment'] = "#ifdef USE_SPECULARMAP\n\n uniform sampler2D specularMap;\n\n#endif";
  9865. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl
  9866. 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";
  9867. // File:src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl
  9868. 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";
  9869. // File:src/renderers/shaders/ShaderChunk/specularmap_fragment.glsl
  9870. 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";
  9871. // File:src/renderers/shaders/ShaderChunk/fog_fragment.glsl
  9872. 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 gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );\n\n#endif";
  9873. // File:src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl
  9874. 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";
  9875. // File:src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl
  9876. 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";
  9877. // File:src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl
  9878. 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;\nvarying vec3 vNormal;\n";
  9879. // File:src/renderers/shaders/ShaderChunk/skinbase_vertex.glsl
  9880. 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";
  9881. // File:src/renderers/shaders/ShaderChunk/map_vertex.glsl
  9882. THREE.ShaderChunk[ 'map_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";
  9883. // File:src/renderers/shaders/ShaderChunk/lightmap_fragment.glsl
  9884. THREE.ShaderChunk[ 'lightmap_fragment'] = "#ifdef USE_LIGHTMAP\n\n gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );\n\n#endif";
  9885. // File:src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl
  9886. THREE.ShaderChunk[ 'shadowmap_pars_vertex'] = "#ifdef USE_SHADOWMAP\n\n varying vec4 vShadowCoord[ MAX_SHADOWS ];\n uniform mat4 shadowMatrix[ MAX_SHADOWS ];\n\n#endif";
  9887. // File:src/renderers/shaders/ShaderChunk/color_fragment.glsl
  9888. THREE.ShaderChunk[ 'color_fragment'] = "#ifdef USE_COLOR\n\n gl_FragColor = gl_FragColor * vec4( vColor, 1.0 );\n\n#endif";
  9889. // File:src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl
  9890. 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";
  9891. // File:src/renderers/shaders/ShaderChunk/envmap_vertex.glsl
  9892. 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";
  9893. // File:src/renderers/shaders/ShaderChunk/shadowmap_fragment.glsl
  9894. 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 ) gl_FragColor.xyz *= frustumColors[ i ];\n\n #else\n\n if ( inFrustum ) gl_FragColor.xyz *= 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 gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;\n\n#endif\n";
  9895. // File:src/renderers/shaders/ShaderChunk/worldpos_vertex.glsl
  9896. 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";
  9897. // File:src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl
  9898. 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";
  9899. // File:src/renderers/shaders/ShaderChunk/skinning_pars_vertex.glsl
  9900. 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";
  9901. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl
  9902. 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";
  9903. // File:src/renderers/shaders/ShaderChunk/alphamap_fragment.glsl
  9904. THREE.ShaderChunk[ 'alphamap_fragment'] = "#ifdef USE_ALPHAMAP\n\n gl_FragColor.a *= texture2D( alphaMap, vUv ).g;\n\n#endif\n";
  9905. // File:src/renderers/shaders/ShaderChunk/alphamap_pars_fragment.glsl
  9906. THREE.ShaderChunk[ 'alphamap_pars_fragment'] = "#ifdef USE_ALPHAMAP\n\n uniform sampler2D alphaMap;\n\n#endif\n";
  9907. // File:src/renderers/shaders/UniformsUtils.js
  9908. /**
  9909. * Uniform Utilities
  9910. */
  9911. THREE.UniformsUtils = {
  9912. merge: function ( uniforms ) {
  9913. var merged = {};
  9914. for ( var u = 0; u < uniforms.length; u ++ ) {
  9915. var tmp = this.clone( uniforms[ u ] );
  9916. for ( var p in tmp ) {
  9917. merged[ p ] = tmp[ p ];
  9918. }
  9919. }
  9920. return merged;
  9921. },
  9922. clone: function ( uniforms_src ) {
  9923. var uniforms_dst = {};
  9924. for ( var u in uniforms_src ) {
  9925. uniforms_dst[ u ] = {};
  9926. for ( var p in uniforms_src[ u ] ) {
  9927. var parameter_src = uniforms_src[ u ][ p ];
  9928. if ( parameter_src instanceof THREE.Color ||
  9929. parameter_src instanceof THREE.Vector2 ||
  9930. parameter_src instanceof THREE.Vector3 ||
  9931. parameter_src instanceof THREE.Vector4 ||
  9932. parameter_src instanceof THREE.Matrix4 ||
  9933. parameter_src instanceof THREE.Texture ) {
  9934. uniforms_dst[ u ][ p ] = parameter_src.clone();
  9935. } else if ( parameter_src instanceof Array ) {
  9936. uniforms_dst[ u ][ p ] = parameter_src.slice();
  9937. } else {
  9938. uniforms_dst[ u ][ p ] = parameter_src;
  9939. }
  9940. }
  9941. }
  9942. return uniforms_dst;
  9943. }
  9944. };
  9945. // File:src/renderers/shaders/UniformsLib.js
  9946. /**
  9947. * Uniforms library for shared webgl shaders
  9948. */
  9949. THREE.UniformsLib = {
  9950. common: {
  9951. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9952. "opacity" : { type: "f", value: 1.0 },
  9953. "map" : { type: "t", value: null },
  9954. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  9955. "lightMap" : { type: "t", value: null },
  9956. "specularMap" : { type: "t", value: null },
  9957. "alphaMap" : { type: "t", value: null },
  9958. "envMap" : { type: "t", value: null },
  9959. "flipEnvMap" : { type: "f", value: - 1 },
  9960. "reflectivity" : { type: "f", value: 1.0 },
  9961. "refractionRatio" : { type: "f", value: 0.98 },
  9962. "morphTargetInfluences" : { type: "f", value: 0 }
  9963. },
  9964. bump: {
  9965. "bumpMap" : { type: "t", value: null },
  9966. "bumpScale" : { type: "f", value: 1 }
  9967. },
  9968. normalmap: {
  9969. "normalMap" : { type: "t", value: null },
  9970. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  9971. },
  9972. fog : {
  9973. "fogDensity" : { type: "f", value: 0.00025 },
  9974. "fogNear" : { type: "f", value: 1 },
  9975. "fogFar" : { type: "f", value: 2000 },
  9976. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9977. },
  9978. lights: {
  9979. "ambientLightColor" : { type: "fv", value: [] },
  9980. "directionalLightDirection" : { type: "fv", value: [] },
  9981. "directionalLightColor" : { type: "fv", value: [] },
  9982. "hemisphereLightDirection" : { type: "fv", value: [] },
  9983. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  9984. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  9985. "pointLightColor" : { type: "fv", value: [] },
  9986. "pointLightPosition" : { type: "fv", value: [] },
  9987. "pointLightDistance" : { type: "fv1", value: [] },
  9988. "pointLightDecay" : { type: "fv1", value: [] },
  9989. "spotLightColor" : { type: "fv", value: [] },
  9990. "spotLightPosition" : { type: "fv", value: [] },
  9991. "spotLightDirection" : { type: "fv", value: [] },
  9992. "spotLightDistance" : { type: "fv1", value: [] },
  9993. "spotLightAngleCos" : { type: "fv1", value: [] },
  9994. "spotLightExponent" : { type: "fv1", value: [] },
  9995. "spotLightDecay" : { type: "fv1", value: [] }
  9996. },
  9997. particle: {
  9998. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9999. "opacity" : { type: "f", value: 1.0 },
  10000. "size" : { type: "f", value: 1.0 },
  10001. "scale" : { type: "f", value: 1.0 },
  10002. "map" : { type: "t", value: null },
  10003. "fogDensity" : { type: "f", value: 0.00025 },
  10004. "fogNear" : { type: "f", value: 1 },
  10005. "fogFar" : { type: "f", value: 2000 },
  10006. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10007. },
  10008. shadowmap: {
  10009. "shadowMap": { type: "tv", value: [] },
  10010. "shadowMapSize": { type: "v2v", value: [] },
  10011. "shadowBias" : { type: "fv1", value: [] },
  10012. "shadowDarkness": { type: "fv1", value: [] },
  10013. "shadowMatrix" : { type: "m4v", value: [] }
  10014. }
  10015. };
  10016. // File:src/renderers/shaders/ShaderLib.js
  10017. /**
  10018. * Webgl Shader Library for three.js
  10019. *
  10020. * @author alteredq / http://alteredqualia.com/
  10021. * @author mrdoob / http://mrdoob.com/
  10022. * @author mikael emtinger / http://gomo.se/
  10023. */
  10024. THREE.ShaderLib = {
  10025. 'basic': {
  10026. uniforms: THREE.UniformsUtils.merge( [
  10027. THREE.UniformsLib[ "common" ],
  10028. THREE.UniformsLib[ "fog" ],
  10029. THREE.UniformsLib[ "shadowmap" ]
  10030. ] ),
  10031. vertexShader: [
  10032. THREE.ShaderChunk[ "common" ],
  10033. THREE.ShaderChunk[ "map_pars_vertex" ],
  10034. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10035. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10036. THREE.ShaderChunk[ "color_pars_vertex" ],
  10037. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10038. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10039. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10040. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10041. "void main() {",
  10042. THREE.ShaderChunk[ "map_vertex" ],
  10043. THREE.ShaderChunk[ "lightmap_vertex" ],
  10044. THREE.ShaderChunk[ "color_vertex" ],
  10045. THREE.ShaderChunk[ "skinbase_vertex" ],
  10046. " #ifdef USE_ENVMAP",
  10047. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10048. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10049. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10050. " #endif",
  10051. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10052. THREE.ShaderChunk[ "skinning_vertex" ],
  10053. THREE.ShaderChunk[ "default_vertex" ],
  10054. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10055. THREE.ShaderChunk[ "worldpos_vertex" ],
  10056. THREE.ShaderChunk[ "envmap_vertex" ],
  10057. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10058. "}"
  10059. ].join("\n"),
  10060. fragmentShader: [
  10061. "uniform vec3 diffuse;",
  10062. "uniform float opacity;",
  10063. THREE.ShaderChunk[ "common" ],
  10064. THREE.ShaderChunk[ "color_pars_fragment" ],
  10065. THREE.ShaderChunk[ "map_pars_fragment" ],
  10066. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  10067. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10068. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10069. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10070. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10071. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10072. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10073. "void main() {",
  10074. " gl_FragColor = vec4( diffuse, opacity );",
  10075. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10076. THREE.ShaderChunk[ "map_fragment" ],
  10077. THREE.ShaderChunk[ "alphamap_fragment" ],
  10078. THREE.ShaderChunk[ "alphatest_fragment" ],
  10079. THREE.ShaderChunk[ "specularmap_fragment" ],
  10080. THREE.ShaderChunk[ "lightmap_fragment" ],
  10081. THREE.ShaderChunk[ "color_fragment" ],
  10082. THREE.ShaderChunk[ "envmap_fragment" ],
  10083. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10084. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10085. THREE.ShaderChunk[ "fog_fragment" ],
  10086. "}"
  10087. ].join("\n")
  10088. },
  10089. 'lambert': {
  10090. uniforms: THREE.UniformsUtils.merge( [
  10091. THREE.UniformsLib[ "common" ],
  10092. THREE.UniformsLib[ "fog" ],
  10093. THREE.UniformsLib[ "lights" ],
  10094. THREE.UniformsLib[ "shadowmap" ],
  10095. {
  10096. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10097. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10098. }
  10099. ] ),
  10100. vertexShader: [
  10101. "#define LAMBERT",
  10102. "varying vec3 vLightFront;",
  10103. "#ifdef DOUBLE_SIDED",
  10104. " varying vec3 vLightBack;",
  10105. "#endif",
  10106. THREE.ShaderChunk[ "common" ],
  10107. THREE.ShaderChunk[ "map_pars_vertex" ],
  10108. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10109. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10110. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  10111. THREE.ShaderChunk[ "color_pars_vertex" ],
  10112. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10113. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10114. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10115. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10116. "void main() {",
  10117. THREE.ShaderChunk[ "map_vertex" ],
  10118. THREE.ShaderChunk[ "lightmap_vertex" ],
  10119. THREE.ShaderChunk[ "color_vertex" ],
  10120. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10121. THREE.ShaderChunk[ "skinbase_vertex" ],
  10122. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10123. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10124. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10125. THREE.ShaderChunk[ "skinning_vertex" ],
  10126. THREE.ShaderChunk[ "default_vertex" ],
  10127. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10128. THREE.ShaderChunk[ "worldpos_vertex" ],
  10129. THREE.ShaderChunk[ "envmap_vertex" ],
  10130. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  10131. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10132. "}"
  10133. ].join("\n"),
  10134. fragmentShader: [
  10135. "uniform float opacity;",
  10136. "varying vec3 vLightFront;",
  10137. "#ifdef DOUBLE_SIDED",
  10138. " varying vec3 vLightBack;",
  10139. "#endif",
  10140. THREE.ShaderChunk[ "common" ],
  10141. THREE.ShaderChunk[ "color_pars_fragment" ],
  10142. THREE.ShaderChunk[ "map_pars_fragment" ],
  10143. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  10144. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10145. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10146. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10147. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10148. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10149. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10150. "void main() {",
  10151. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  10152. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10153. THREE.ShaderChunk[ "map_fragment" ],
  10154. THREE.ShaderChunk[ "alphamap_fragment" ],
  10155. THREE.ShaderChunk[ "alphatest_fragment" ],
  10156. THREE.ShaderChunk[ "specularmap_fragment" ],
  10157. " #ifdef DOUBLE_SIDED",
  10158. //"float isFront = float( gl_FrontFacing );",
  10159. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  10160. " if ( gl_FrontFacing )",
  10161. " gl_FragColor.xyz *= vLightFront;",
  10162. " else",
  10163. " gl_FragColor.xyz *= vLightBack;",
  10164. " #else",
  10165. " gl_FragColor.xyz *= vLightFront;",
  10166. " #endif",
  10167. THREE.ShaderChunk[ "lightmap_fragment" ],
  10168. THREE.ShaderChunk[ "color_fragment" ],
  10169. THREE.ShaderChunk[ "envmap_fragment" ],
  10170. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10171. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10172. THREE.ShaderChunk[ "fog_fragment" ],
  10173. "}"
  10174. ].join("\n")
  10175. },
  10176. 'phong': {
  10177. uniforms: THREE.UniformsUtils.merge( [
  10178. THREE.UniformsLib[ "common" ],
  10179. THREE.UniformsLib[ "bump" ],
  10180. THREE.UniformsLib[ "normalmap" ],
  10181. THREE.UniformsLib[ "fog" ],
  10182. THREE.UniformsLib[ "lights" ],
  10183. THREE.UniformsLib[ "shadowmap" ],
  10184. {
  10185. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10186. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10187. "shininess": { type: "f", value: 30 },
  10188. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10189. }
  10190. ] ),
  10191. vertexShader: [
  10192. "#define PHONG",
  10193. "varying vec3 vViewPosition;",
  10194. "varying vec3 vNormal;",
  10195. THREE.ShaderChunk[ "common" ],
  10196. THREE.ShaderChunk[ "map_pars_vertex" ],
  10197. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10198. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10199. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10200. THREE.ShaderChunk[ "color_pars_vertex" ],
  10201. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10202. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10203. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10204. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10205. "void main() {",
  10206. THREE.ShaderChunk[ "map_vertex" ],
  10207. THREE.ShaderChunk[ "lightmap_vertex" ],
  10208. THREE.ShaderChunk[ "color_vertex" ],
  10209. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10210. THREE.ShaderChunk[ "skinbase_vertex" ],
  10211. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10212. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10213. " vNormal = normalize( transformedNormal );",
  10214. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10215. THREE.ShaderChunk[ "skinning_vertex" ],
  10216. THREE.ShaderChunk[ "default_vertex" ],
  10217. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10218. " vViewPosition = -mvPosition.xyz;",
  10219. THREE.ShaderChunk[ "worldpos_vertex" ],
  10220. THREE.ShaderChunk[ "envmap_vertex" ],
  10221. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10222. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10223. "}"
  10224. ].join("\n"),
  10225. fragmentShader: [
  10226. "#define PHONG",
  10227. "uniform vec3 diffuse;",
  10228. "uniform float opacity;",
  10229. "uniform vec3 emissive;",
  10230. "uniform vec3 specular;",
  10231. "uniform float shininess;",
  10232. THREE.ShaderChunk[ "common" ],
  10233. THREE.ShaderChunk[ "color_pars_fragment" ],
  10234. THREE.ShaderChunk[ "map_pars_fragment" ],
  10235. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  10236. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10237. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10238. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10239. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10240. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10241. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10242. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10243. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10244. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10245. "void main() {",
  10246. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  10247. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10248. THREE.ShaderChunk[ "map_fragment" ],
  10249. THREE.ShaderChunk[ "alphamap_fragment" ],
  10250. THREE.ShaderChunk[ "alphatest_fragment" ],
  10251. THREE.ShaderChunk[ "specularmap_fragment" ],
  10252. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10253. THREE.ShaderChunk[ "lightmap_fragment" ],
  10254. THREE.ShaderChunk[ "color_fragment" ],
  10255. THREE.ShaderChunk[ "envmap_fragment" ],
  10256. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10257. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10258. THREE.ShaderChunk[ "fog_fragment" ],
  10259. "}"
  10260. ].join("\n")
  10261. },
  10262. 'particle_basic': {
  10263. uniforms: THREE.UniformsUtils.merge( [
  10264. THREE.UniformsLib[ "particle" ],
  10265. THREE.UniformsLib[ "shadowmap" ]
  10266. ] ),
  10267. vertexShader: [
  10268. "uniform float size;",
  10269. "uniform float scale;",
  10270. THREE.ShaderChunk[ "common" ],
  10271. THREE.ShaderChunk[ "color_pars_vertex" ],
  10272. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10273. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10274. "void main() {",
  10275. THREE.ShaderChunk[ "color_vertex" ],
  10276. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10277. " #ifdef USE_SIZEATTENUATION",
  10278. " gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  10279. " #else",
  10280. " gl_PointSize = size;",
  10281. " #endif",
  10282. " gl_Position = projectionMatrix * mvPosition;",
  10283. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10284. THREE.ShaderChunk[ "worldpos_vertex" ],
  10285. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10286. "}"
  10287. ].join("\n"),
  10288. fragmentShader: [
  10289. "uniform vec3 psColor;",
  10290. "uniform float opacity;",
  10291. THREE.ShaderChunk[ "common" ],
  10292. THREE.ShaderChunk[ "color_pars_fragment" ],
  10293. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  10294. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10295. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10296. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10297. "void main() {",
  10298. " gl_FragColor = vec4( psColor, opacity );",
  10299. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10300. THREE.ShaderChunk[ "map_particle_fragment" ],
  10301. THREE.ShaderChunk[ "alphatest_fragment" ],
  10302. THREE.ShaderChunk[ "color_fragment" ],
  10303. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10304. THREE.ShaderChunk[ "fog_fragment" ],
  10305. "}"
  10306. ].join("\n")
  10307. },
  10308. 'dashed': {
  10309. uniforms: THREE.UniformsUtils.merge( [
  10310. THREE.UniformsLib[ "common" ],
  10311. THREE.UniformsLib[ "fog" ],
  10312. {
  10313. "scale" : { type: "f", value: 1 },
  10314. "dashSize" : { type: "f", value: 1 },
  10315. "totalSize": { type: "f", value: 2 }
  10316. }
  10317. ] ),
  10318. vertexShader: [
  10319. "uniform float scale;",
  10320. "attribute float lineDistance;",
  10321. "varying float vLineDistance;",
  10322. THREE.ShaderChunk[ "common" ],
  10323. THREE.ShaderChunk[ "color_pars_vertex" ],
  10324. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10325. "void main() {",
  10326. THREE.ShaderChunk[ "color_vertex" ],
  10327. " vLineDistance = scale * lineDistance;",
  10328. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10329. " gl_Position = projectionMatrix * mvPosition;",
  10330. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10331. "}"
  10332. ].join("\n"),
  10333. fragmentShader: [
  10334. "uniform vec3 diffuse;",
  10335. "uniform float opacity;",
  10336. "uniform float dashSize;",
  10337. "uniform float totalSize;",
  10338. "varying float vLineDistance;",
  10339. THREE.ShaderChunk[ "common" ],
  10340. THREE.ShaderChunk[ "color_pars_fragment" ],
  10341. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10342. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10343. "void main() {",
  10344. " if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  10345. " discard;",
  10346. " }",
  10347. " gl_FragColor = vec4( diffuse, opacity );",
  10348. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10349. THREE.ShaderChunk[ "color_fragment" ],
  10350. THREE.ShaderChunk[ "fog_fragment" ],
  10351. "}"
  10352. ].join("\n")
  10353. },
  10354. 'depth': {
  10355. uniforms: {
  10356. "mNear": { type: "f", value: 1.0 },
  10357. "mFar" : { type: "f", value: 2000.0 },
  10358. "opacity" : { type: "f", value: 1.0 }
  10359. },
  10360. vertexShader: [
  10361. THREE.ShaderChunk[ "common" ],
  10362. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10363. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10364. "void main() {",
  10365. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10366. THREE.ShaderChunk[ "default_vertex" ],
  10367. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10368. "}"
  10369. ].join("\n"),
  10370. fragmentShader: [
  10371. "uniform float mNear;",
  10372. "uniform float mFar;",
  10373. "uniform float opacity;",
  10374. THREE.ShaderChunk[ "common" ],
  10375. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10376. "void main() {",
  10377. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10378. " #ifdef USE_LOGDEPTHBUF_EXT",
  10379. " float depth = gl_FragDepthEXT / gl_FragCoord.w;",
  10380. " #else",
  10381. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10382. " #endif",
  10383. " float color = 1.0 - smoothstep( mNear, mFar, depth );",
  10384. " gl_FragColor = vec4( vec3( color ), opacity );",
  10385. "}"
  10386. ].join("\n")
  10387. },
  10388. 'normal': {
  10389. uniforms: {
  10390. "opacity" : { type: "f", value: 1.0 }
  10391. },
  10392. vertexShader: [
  10393. "varying vec3 vNormal;",
  10394. THREE.ShaderChunk[ "common" ],
  10395. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10396. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10397. "void main() {",
  10398. " vNormal = normalize( normalMatrix * normal );",
  10399. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10400. THREE.ShaderChunk[ "default_vertex" ],
  10401. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10402. "}"
  10403. ].join("\n"),
  10404. fragmentShader: [
  10405. "uniform float opacity;",
  10406. "varying vec3 vNormal;",
  10407. THREE.ShaderChunk[ "common" ],
  10408. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10409. "void main() {",
  10410. " gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  10411. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10412. "}"
  10413. ].join("\n")
  10414. },
  10415. /* -------------------------------------------------------------------------
  10416. // Cube map shader
  10417. ------------------------------------------------------------------------- */
  10418. 'cube': {
  10419. uniforms: { "tCube": { type: "t", value: null },
  10420. "tFlip": { type: "f", value: - 1 } },
  10421. vertexShader: [
  10422. "varying vec3 vWorldPosition;",
  10423. THREE.ShaderChunk[ "common" ],
  10424. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10425. "void main() {",
  10426. " vWorldPosition = transformDirection( position, modelMatrix );",
  10427. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10428. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10429. "}"
  10430. ].join("\n"),
  10431. fragmentShader: [
  10432. "uniform samplerCube tCube;",
  10433. "uniform float tFlip;",
  10434. "varying vec3 vWorldPosition;",
  10435. THREE.ShaderChunk[ "common" ],
  10436. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10437. "void main() {",
  10438. " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  10439. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10440. "}"
  10441. ].join("\n")
  10442. },
  10443. /* -------------------------------------------------------------------------
  10444. // Cube map shader
  10445. ------------------------------------------------------------------------- */
  10446. 'equirect': {
  10447. uniforms: { "tEquirect": { type: "t", value: null },
  10448. "tFlip": { type: "f", value: - 1 } },
  10449. vertexShader: [
  10450. "varying vec3 vWorldPosition;",
  10451. THREE.ShaderChunk[ "common" ],
  10452. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10453. "void main() {",
  10454. " vWorldPosition = transformDirection( position, modelMatrix );",
  10455. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10456. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10457. "}"
  10458. ].join("\n"),
  10459. fragmentShader: [
  10460. "uniform sampler2D tEquirect;",
  10461. "uniform float tFlip;",
  10462. "varying vec3 vWorldPosition;",
  10463. THREE.ShaderChunk[ "common" ],
  10464. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10465. "void main() {",
  10466. // " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  10467. "vec3 direction = normalize( vWorldPosition );",
  10468. "vec2 sampleUV;",
  10469. "sampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );",
  10470. "sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;",
  10471. "gl_FragColor = texture2D( tEquirect, sampleUV );",
  10472. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10473. "}"
  10474. ].join("\n")
  10475. },
  10476. /* Depth encoding into RGBA texture
  10477. *
  10478. * based on SpiderGL shadow map example
  10479. * http://spidergl.org/example.php?id=6
  10480. *
  10481. * originally from
  10482. * http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  10483. *
  10484. * see also
  10485. * http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  10486. */
  10487. 'depthRGBA': {
  10488. uniforms: {},
  10489. vertexShader: [
  10490. THREE.ShaderChunk[ "common" ],
  10491. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10492. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10493. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10494. "void main() {",
  10495. THREE.ShaderChunk[ "skinbase_vertex" ],
  10496. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10497. THREE.ShaderChunk[ "skinning_vertex" ],
  10498. THREE.ShaderChunk[ "default_vertex" ],
  10499. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10500. "}"
  10501. ].join("\n"),
  10502. fragmentShader: [
  10503. THREE.ShaderChunk[ "common" ],
  10504. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10505. "vec4 pack_depth( const in float depth ) {",
  10506. " const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  10507. " const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  10508. " vec4 res = mod( depth * bit_shift * vec4( 255 ), vec4( 256 ) ) / vec4( 255 );", // " vec4 res = fract( depth * bit_shift );",
  10509. " res -= res.xxyz * bit_mask;",
  10510. " return res;",
  10511. "}",
  10512. "void main() {",
  10513. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10514. " #ifdef USE_LOGDEPTHBUF_EXT",
  10515. " gl_FragData[ 0 ] = pack_depth( gl_FragDepthEXT );",
  10516. " #else",
  10517. " gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  10518. " #endif",
  10519. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  10520. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  10521. //"gl_FragData[ 0 ] = pack_depth( z );",
  10522. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  10523. "}"
  10524. ].join("\n")
  10525. }
  10526. };
  10527. // File:src/renderers/WebGLRenderer.js
  10528. /**
  10529. * @author supereggbert / http://www.paulbrunt.co.uk/
  10530. * @author mrdoob / http://mrdoob.com/
  10531. * @author alteredq / http://alteredqualia.com/
  10532. * @author szimek / https://github.com/szimek/
  10533. */
  10534. THREE.WebGLRenderer = function ( parameters ) {
  10535. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  10536. parameters = parameters || {};
  10537. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  10538. _context = parameters.context !== undefined ? parameters.context : null,
  10539. pixelRatio = 1,
  10540. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  10541. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  10542. _depth = parameters.depth !== undefined ? parameters.depth : true,
  10543. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  10544. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  10545. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  10546. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  10547. _logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false,
  10548. _clearColor = new THREE.Color( 0x000000 ),
  10549. _clearAlpha = 0;
  10550. var lights = [];
  10551. var _webglObjects = {};
  10552. var _webglObjectsImmediate = [];
  10553. var opaqueObjects = [];
  10554. var transparentObjects = [];
  10555. var sprites = [];
  10556. var lensFlares = [];
  10557. // public properties
  10558. this.domElement = _canvas;
  10559. this.context = null;
  10560. // clearing
  10561. this.autoClear = true;
  10562. this.autoClearColor = true;
  10563. this.autoClearDepth = true;
  10564. this.autoClearStencil = true;
  10565. // scene graph
  10566. this.sortObjects = true;
  10567. // physically based shading
  10568. this.gammaFactor = 2.0; // for backwards compatibility
  10569. this.gammaInput = false;
  10570. this.gammaOutput = false;
  10571. // shadow map
  10572. this.shadowMapEnabled = false;
  10573. this.shadowMapType = THREE.PCFShadowMap;
  10574. this.shadowMapCullFace = THREE.CullFaceFront;
  10575. this.shadowMapDebug = false;
  10576. this.shadowMapCascade = false;
  10577. // morphs
  10578. this.maxMorphTargets = 8;
  10579. this.maxMorphNormals = 4;
  10580. // flags
  10581. this.autoScaleCubemaps = true;
  10582. // info
  10583. this.info = {
  10584. memory: {
  10585. programs: 0,
  10586. geometries: 0,
  10587. textures: 0
  10588. },
  10589. render: {
  10590. calls: 0,
  10591. vertices: 0,
  10592. faces: 0,
  10593. points: 0
  10594. }
  10595. };
  10596. // internal properties
  10597. var _this = this,
  10598. _programs = [],
  10599. // internal state cache
  10600. _currentProgram = null,
  10601. _currentFramebuffer = null,
  10602. _currentMaterialId = - 1,
  10603. _currentGeometryProgram = '',
  10604. _currentCamera = null,
  10605. _usedTextureUnits = 0,
  10606. // GL state cache
  10607. _oldDoubleSided = - 1,
  10608. _oldFlipSided = - 1,
  10609. _oldBlending = - 1,
  10610. _oldBlendEquation = - 1,
  10611. _oldBlendSrc = - 1,
  10612. _oldBlendDst = - 1,
  10613. _oldBlendEquationAlpha = - 1,
  10614. _oldBlendSrcAlpha = - 1,
  10615. _oldBlendDstAlpha = - 1,
  10616. _oldDepthTest = - 1,
  10617. _oldDepthWrite = - 1,
  10618. _oldPolygonOffset = null,
  10619. _oldPolygonOffsetFactor = null,
  10620. _oldPolygonOffsetUnits = null,
  10621. _oldLineWidth = null,
  10622. _viewportX = 0,
  10623. _viewportY = 0,
  10624. _viewportWidth = _canvas.width,
  10625. _viewportHeight = _canvas.height,
  10626. _currentWidth = 0,
  10627. _currentHeight = 0,
  10628. _newAttributes = new Uint8Array( 16 ),
  10629. _enabledAttributes = new Uint8Array( 16 ),
  10630. // frustum
  10631. _frustum = new THREE.Frustum(),
  10632. // camera matrices cache
  10633. _projScreenMatrix = new THREE.Matrix4(),
  10634. _projScreenMatrixPS = new THREE.Matrix4(),
  10635. _vector3 = new THREE.Vector3(),
  10636. // light arrays cache
  10637. _direction = new THREE.Vector3(),
  10638. _lightsNeedUpdate = true,
  10639. _lights = {
  10640. ambient: [ 0, 0, 0 ],
  10641. directional: { length: 0, colors:[], positions: [] },
  10642. point: { length: 0, colors: [], positions: [], distances: [], decays: [] },
  10643. spot: { length: 0, colors: [], positions: [], distances: [], directions: [], anglesCos: [], exponents: [], decays: [] },
  10644. hemi: { length: 0, skyColors: [], groundColors: [], positions: [] }
  10645. };
  10646. // initialize
  10647. var _gl;
  10648. try {
  10649. var attributes = {
  10650. alpha: _alpha,
  10651. depth: _depth,
  10652. stencil: _stencil,
  10653. antialias: _antialias,
  10654. premultipliedAlpha: _premultipliedAlpha,
  10655. preserveDrawingBuffer: _preserveDrawingBuffer
  10656. };
  10657. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  10658. if ( _gl === null ) {
  10659. if ( _canvas.getContext( 'webgl') !== null ) {
  10660. throw 'Error creating WebGL context with your selected attributes.';
  10661. } else {
  10662. throw 'Error creating WebGL context.';
  10663. }
  10664. }
  10665. _canvas.addEventListener( 'webglcontextlost', function ( event ) {
  10666. event.preventDefault();
  10667. resetGLState();
  10668. setDefaultGLState();
  10669. _webglObjects = {};
  10670. }, false);
  10671. } catch ( error ) {
  10672. THREE.error( 'THREE.WebGLRenderer: ' + error );
  10673. }
  10674. if ( _gl.getShaderPrecisionFormat === undefined ) {
  10675. _gl.getShaderPrecisionFormat = function () {
  10676. return {
  10677. 'rangeMin': 1,
  10678. 'rangeMax': 1,
  10679. 'precision': 1
  10680. };
  10681. }
  10682. }
  10683. var extensions = new THREE.WebGLExtensions( _gl );
  10684. extensions.get( 'OES_texture_float' );
  10685. extensions.get( 'OES_texture_float_linear' );
  10686. extensions.get( 'OES_texture_half_float' );
  10687. extensions.get( 'OES_texture_half_float_linear' );
  10688. extensions.get( 'OES_standard_derivatives' );
  10689. if ( _logarithmicDepthBuffer ) {
  10690. extensions.get( 'EXT_frag_depth' );
  10691. }
  10692. //
  10693. var glClearColor = function ( r, g, b, a ) {
  10694. if ( _premultipliedAlpha === true ) {
  10695. r *= a; g *= a; b *= a;
  10696. }
  10697. _gl.clearColor( r, g, b, a );
  10698. };
  10699. var setDefaultGLState = function () {
  10700. _gl.clearColor( 0, 0, 0, 1 );
  10701. _gl.clearDepth( 1 );
  10702. _gl.clearStencil( 0 );
  10703. _gl.enable( _gl.DEPTH_TEST );
  10704. _gl.depthFunc( _gl.LEQUAL );
  10705. _gl.frontFace( _gl.CCW );
  10706. _gl.cullFace( _gl.BACK );
  10707. _gl.enable( _gl.CULL_FACE );
  10708. _gl.enable( _gl.BLEND );
  10709. _gl.blendEquation( _gl.FUNC_ADD );
  10710. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  10711. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  10712. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10713. };
  10714. var resetGLState = function () {
  10715. _currentProgram = null;
  10716. _currentCamera = null;
  10717. _oldBlending = - 1;
  10718. _oldDepthTest = - 1;
  10719. _oldDepthWrite = - 1;
  10720. _oldDoubleSided = - 1;
  10721. _oldFlipSided = - 1;
  10722. _currentGeometryProgram = '';
  10723. _currentMaterialId = - 1;
  10724. _lightsNeedUpdate = true;
  10725. for ( var i = 0; i < _enabledAttributes.length; i ++ ) {
  10726. _enabledAttributes[ i ] = 0;
  10727. }
  10728. };
  10729. setDefaultGLState();
  10730. this.context = _gl;
  10731. // GPU capabilities
  10732. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  10733. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  10734. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  10735. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  10736. var _supportsVertexTextures = _maxVertexTextures > 0;
  10737. var _supportsBoneTextures = _supportsVertexTextures && extensions.get( 'OES_texture_float' );
  10738. //
  10739. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  10740. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  10741. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  10742. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  10743. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  10744. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  10745. var getCompressedTextureFormats = ( function () {
  10746. var array;
  10747. return function () {
  10748. if ( array !== undefined ) {
  10749. return array;
  10750. }
  10751. array = [];
  10752. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) || extensions.get( 'WEBGL_compressed_texture_s3tc' ) ) {
  10753. var formats = _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS );
  10754. for ( var i = 0; i < formats.length; i ++ ){
  10755. array.push( formats[ i ] );
  10756. }
  10757. }
  10758. return array;
  10759. };
  10760. } )();
  10761. // clamp precision to maximum available
  10762. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  10763. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  10764. if ( _precision === 'highp' && ! highpAvailable ) {
  10765. if ( mediumpAvailable ) {
  10766. _precision = 'mediump';
  10767. THREE.warn( 'THREE.WebGLRenderer: highp not supported, using mediump.' );
  10768. } else {
  10769. _precision = 'lowp';
  10770. THREE.warn( 'THREE.WebGLRenderer: highp and mediump not supported, using lowp.' );
  10771. }
  10772. }
  10773. if ( _precision === 'mediump' && ! mediumpAvailable ) {
  10774. _precision = 'lowp';
  10775. THREE.warn( 'THREE.WebGLRenderer: mediump not supported, using lowp.' );
  10776. }
  10777. // Plugins
  10778. var shadowMapPlugin = new THREE.ShadowMapPlugin( this, lights, _webglObjects, _webglObjectsImmediate );
  10779. var spritePlugin = new THREE.SpritePlugin( this, sprites );
  10780. var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares );
  10781. // API
  10782. this.getContext = function () {
  10783. return _gl;
  10784. };
  10785. this.forceContextLoss = function () {
  10786. extensions.get( 'WEBGL_lose_context' ).loseContext();
  10787. };
  10788. this.supportsVertexTextures = function () {
  10789. return _supportsVertexTextures;
  10790. };
  10791. this.supportsFloatTextures = function () {
  10792. return extensions.get( 'OES_texture_float' );
  10793. };
  10794. this.supportsHalfFloatTextures = function () {
  10795. return extensions.get( 'OES_texture_half_float' );
  10796. };
  10797. this.supportsStandardDerivatives = function () {
  10798. return extensions.get( 'OES_standard_derivatives' );
  10799. };
  10800. this.supportsCompressedTextureS3TC = function () {
  10801. return extensions.get( 'WEBGL_compressed_texture_s3tc' );
  10802. };
  10803. this.supportsCompressedTexturePVRTC = function () {
  10804. return extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  10805. };
  10806. this.supportsBlendMinMax = function () {
  10807. return extensions.get( 'EXT_blend_minmax' );
  10808. };
  10809. this.getMaxAnisotropy = ( function () {
  10810. var value;
  10811. return function () {
  10812. if ( value !== undefined ) {
  10813. return value;
  10814. }
  10815. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  10816. value = extension !== null ? _gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  10817. return value;
  10818. }
  10819. } )();
  10820. this.getPrecision = function () {
  10821. return _precision;
  10822. };
  10823. this.getPixelRatio = function () {
  10824. return pixelRatio;
  10825. };
  10826. this.setPixelRatio = function ( value ) {
  10827. pixelRatio = value;
  10828. };
  10829. this.setSize = function ( width, height, updateStyle ) {
  10830. _canvas.width = width * pixelRatio;
  10831. _canvas.height = height * pixelRatio;
  10832. if ( updateStyle !== false ) {
  10833. _canvas.style.width = width + 'px';
  10834. _canvas.style.height = height + 'px';
  10835. }
  10836. this.setViewport( 0, 0, width, height );
  10837. };
  10838. this.setViewport = function ( x, y, width, height ) {
  10839. _viewportX = x * pixelRatio;
  10840. _viewportY = y * pixelRatio;
  10841. _viewportWidth = width * pixelRatio;
  10842. _viewportHeight = height * pixelRatio;
  10843. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  10844. };
  10845. this.setScissor = function ( x, y, width, height ) {
  10846. _gl.scissor(
  10847. x * pixelRatio,
  10848. y * pixelRatio,
  10849. width * pixelRatio,
  10850. height * pixelRatio
  10851. );
  10852. };
  10853. this.enableScissorTest = function ( enable ) {
  10854. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  10855. };
  10856. // Clearing
  10857. this.getClearColor = function () {
  10858. return _clearColor;
  10859. };
  10860. this.setClearColor = function ( color, alpha ) {
  10861. _clearColor.set( color );
  10862. _clearAlpha = alpha !== undefined ? alpha : 1;
  10863. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10864. };
  10865. this.getClearAlpha = function () {
  10866. return _clearAlpha;
  10867. };
  10868. this.setClearAlpha = function ( alpha ) {
  10869. _clearAlpha = alpha;
  10870. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10871. };
  10872. this.clear = function ( color, depth, stencil ) {
  10873. var bits = 0;
  10874. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  10875. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  10876. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  10877. _gl.clear( bits );
  10878. };
  10879. this.clearColor = function () {
  10880. _gl.clear( _gl.COLOR_BUFFER_BIT );
  10881. };
  10882. this.clearDepth = function () {
  10883. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  10884. };
  10885. this.clearStencil = function () {
  10886. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  10887. };
  10888. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  10889. this.setRenderTarget( renderTarget );
  10890. this.clear( color, depth, stencil );
  10891. };
  10892. // Reset
  10893. this.resetGLState = resetGLState;
  10894. // Buffer allocation
  10895. function createParticleBuffers ( geometry ) {
  10896. geometry.__webglVertexBuffer = _gl.createBuffer();
  10897. geometry.__webglColorBuffer = _gl.createBuffer();
  10898. _this.info.memory.geometries ++;
  10899. };
  10900. function createLineBuffers ( geometry ) {
  10901. geometry.__webglVertexBuffer = _gl.createBuffer();
  10902. geometry.__webglColorBuffer = _gl.createBuffer();
  10903. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  10904. _this.info.memory.geometries ++;
  10905. };
  10906. function createMeshBuffers ( geometryGroup ) {
  10907. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  10908. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  10909. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  10910. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  10911. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  10912. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  10913. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  10914. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  10915. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  10916. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  10917. var numMorphTargets = geometryGroup.numMorphTargets;
  10918. if ( numMorphTargets ) {
  10919. geometryGroup.__webglMorphTargetsBuffers = [];
  10920. for ( var m = 0, ml = numMorphTargets; m < ml; m ++ ) {
  10921. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  10922. }
  10923. }
  10924. var numMorphNormals = geometryGroup.numMorphNormals;
  10925. if ( numMorphNormals ) {
  10926. geometryGroup.__webglMorphNormalsBuffers = [];
  10927. for ( var m = 0, ml = numMorphNormals; m < ml; m ++ ) {
  10928. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  10929. }
  10930. }
  10931. _this.info.memory.geometries ++;
  10932. };
  10933. // Events
  10934. var onObjectRemoved = function ( event ) {
  10935. var object = event.target;
  10936. object.traverse( function ( child ) {
  10937. child.removeEventListener( 'remove', onObjectRemoved );
  10938. removeObject( child );
  10939. } );
  10940. };
  10941. var onGeometryDispose = function ( event ) {
  10942. var geometry = event.target;
  10943. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10944. deallocateGeometry( geometry );
  10945. };
  10946. var onTextureDispose = function ( event ) {
  10947. var texture = event.target;
  10948. texture.removeEventListener( 'dispose', onTextureDispose );
  10949. deallocateTexture( texture );
  10950. _this.info.memory.textures --;
  10951. };
  10952. var onRenderTargetDispose = function ( event ) {
  10953. var renderTarget = event.target;
  10954. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  10955. deallocateRenderTarget( renderTarget );
  10956. _this.info.memory.textures --;
  10957. };
  10958. var onMaterialDispose = function ( event ) {
  10959. var material = event.target;
  10960. material.removeEventListener( 'dispose', onMaterialDispose );
  10961. deallocateMaterial( material );
  10962. };
  10963. // Buffer deallocation
  10964. var deleteBuffers = function ( geometry ) {
  10965. var buffers = [
  10966. '__webglVertexBuffer',
  10967. '__webglNormalBuffer',
  10968. '__webglTangentBuffer',
  10969. '__webglColorBuffer',
  10970. '__webglUVBuffer',
  10971. '__webglUV2Buffer',
  10972. '__webglSkinIndicesBuffer',
  10973. '__webglSkinWeightsBuffer',
  10974. '__webglFaceBuffer',
  10975. '__webglLineBuffer',
  10976. '__webglLineDistanceBuffer'
  10977. ];
  10978. for ( var i = 0, l = buffers.length; i < l; i ++ ) {
  10979. var name = buffers[ i ];
  10980. if ( geometry[ name ] !== undefined ) {
  10981. _gl.deleteBuffer( geometry[ name ] );
  10982. delete geometry[ name ];
  10983. }
  10984. }
  10985. // custom attributes
  10986. if ( geometry.__webglCustomAttributesList !== undefined ) {
  10987. for ( var name in geometry.__webglCustomAttributesList ) {
  10988. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ name ].buffer );
  10989. }
  10990. delete geometry.__webglCustomAttributesList;
  10991. }
  10992. _this.info.memory.geometries --;
  10993. };
  10994. var deallocateGeometry = function ( geometry ) {
  10995. delete geometry.__webglInit;
  10996. if ( geometry instanceof THREE.BufferGeometry ) {
  10997. for ( var name in geometry.attributes ) {
  10998. var attribute = geometry.attributes[ name ];
  10999. if ( attribute.buffer !== undefined ) {
  11000. _gl.deleteBuffer( attribute.buffer );
  11001. delete attribute.buffer;
  11002. }
  11003. }
  11004. _this.info.memory.geometries --;
  11005. } else {
  11006. var geometryGroupsList = geometryGroups[ geometry.id ];
  11007. if ( geometryGroupsList !== undefined ) {
  11008. for ( var i = 0, l = geometryGroupsList.length; i < l; i ++ ) {
  11009. var geometryGroup = geometryGroupsList[ i ];
  11010. if ( geometryGroup.numMorphTargets !== undefined ) {
  11011. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11012. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  11013. }
  11014. delete geometryGroup.__webglMorphTargetsBuffers;
  11015. }
  11016. if ( geometryGroup.numMorphNormals !== undefined ) {
  11017. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11018. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  11019. }
  11020. delete geometryGroup.__webglMorphNormalsBuffers;
  11021. }
  11022. deleteBuffers( geometryGroup );
  11023. }
  11024. delete geometryGroups[ geometry.id ];
  11025. } else {
  11026. deleteBuffers( geometry );
  11027. }
  11028. }
  11029. // TOFIX: Workaround for deleted geometry being currently bound
  11030. _currentGeometryProgram = '';
  11031. };
  11032. var deallocateTexture = function ( texture ) {
  11033. if ( texture.image && texture.image.__webglTextureCube ) {
  11034. // cube texture
  11035. _gl.deleteTexture( texture.image.__webglTextureCube );
  11036. delete texture.image.__webglTextureCube;
  11037. } else {
  11038. // 2D texture
  11039. if ( texture.__webglInit === undefined ) return;
  11040. _gl.deleteTexture( texture.__webglTexture );
  11041. delete texture.__webglTexture;
  11042. delete texture.__webglInit;
  11043. }
  11044. };
  11045. var deallocateRenderTarget = function ( renderTarget ) {
  11046. if ( ! renderTarget || renderTarget.__webglTexture === undefined ) return;
  11047. _gl.deleteTexture( renderTarget.__webglTexture );
  11048. delete renderTarget.__webglTexture;
  11049. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  11050. for ( var i = 0; i < 6; i ++ ) {
  11051. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  11052. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  11053. }
  11054. } else {
  11055. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  11056. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  11057. }
  11058. delete renderTarget.__webglFramebuffer;
  11059. delete renderTarget.__webglRenderbuffer;
  11060. };
  11061. var deallocateMaterial = function ( material ) {
  11062. var program = material.program.program;
  11063. if ( program === undefined ) return;
  11064. material.program = undefined;
  11065. // only deallocate GL program if this was the last use of shared program
  11066. // assumed there is only single copy of any program in the _programs list
  11067. // (that's how it's constructed)
  11068. var i, il, programInfo;
  11069. var deleteProgram = false;
  11070. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11071. programInfo = _programs[ i ];
  11072. if ( programInfo.program === program ) {
  11073. programInfo.usedTimes --;
  11074. if ( programInfo.usedTimes === 0 ) {
  11075. deleteProgram = true;
  11076. }
  11077. break;
  11078. }
  11079. }
  11080. if ( deleteProgram === true ) {
  11081. // avoid using array.splice, this is costlier than creating new array from scratch
  11082. var newPrograms = [];
  11083. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11084. programInfo = _programs[ i ];
  11085. if ( programInfo.program !== program ) {
  11086. newPrograms.push( programInfo );
  11087. }
  11088. }
  11089. _programs = newPrograms;
  11090. _gl.deleteProgram( program );
  11091. _this.info.memory.programs --;
  11092. }
  11093. };
  11094. // Buffer initialization
  11095. function initCustomAttributes ( object ) {
  11096. var geometry = object.geometry;
  11097. var material = object.material;
  11098. var nvertices = geometry.vertices.length;
  11099. if ( material.attributes ) {
  11100. if ( geometry.__webglCustomAttributesList === undefined ) {
  11101. geometry.__webglCustomAttributesList = [];
  11102. }
  11103. for ( var name in material.attributes ) {
  11104. var attribute = material.attributes[ name ];
  11105. if ( ! attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11106. attribute.__webglInitialized = true;
  11107. var size = 1; // "f" and "i"
  11108. if ( attribute.type === 'v2' ) size = 2;
  11109. else if ( attribute.type === 'v3' ) size = 3;
  11110. else if ( attribute.type === 'v4' ) size = 4;
  11111. else if ( attribute.type === 'c' ) size = 3;
  11112. attribute.size = size;
  11113. attribute.array = new Float32Array( nvertices * size );
  11114. attribute.buffer = _gl.createBuffer();
  11115. attribute.buffer.belongsToAttribute = name;
  11116. attribute.needsUpdate = true;
  11117. }
  11118. geometry.__webglCustomAttributesList.push( attribute );
  11119. }
  11120. }
  11121. };
  11122. function initParticleBuffers ( geometry, object ) {
  11123. var nvertices = geometry.vertices.length;
  11124. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11125. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11126. geometry.__sortArray = [];
  11127. geometry.__webglParticleCount = nvertices;
  11128. initCustomAttributes( object );
  11129. };
  11130. function initLineBuffers ( geometry, object ) {
  11131. var nvertices = geometry.vertices.length;
  11132. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11133. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11134. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  11135. geometry.__webglLineCount = nvertices;
  11136. initCustomAttributes( object );
  11137. };
  11138. function initMeshBuffers ( geometryGroup, object ) {
  11139. var geometry = object.geometry,
  11140. faces3 = geometryGroup.faces3,
  11141. nvertices = faces3.length * 3,
  11142. ntris = faces3.length * 1,
  11143. nlines = faces3.length * 3,
  11144. material = getBufferMaterial( object, geometryGroup );
  11145. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  11146. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  11147. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  11148. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  11149. if ( geometry.faceVertexUvs.length > 1 ) {
  11150. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  11151. }
  11152. if ( geometry.hasTangents ) {
  11153. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  11154. }
  11155. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  11156. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  11157. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  11158. }
  11159. var UintArray = extensions.get( 'OES_element_index_uint' ) !== null && ntris > 21845 ? Uint32Array : Uint16Array; // 65535 / 3
  11160. geometryGroup.__typeArray = UintArray;
  11161. geometryGroup.__faceArray = new UintArray( ntris * 3 );
  11162. geometryGroup.__lineArray = new UintArray( nlines * 2 );
  11163. var numMorphTargets = geometryGroup.numMorphTargets;
  11164. if ( numMorphTargets ) {
  11165. geometryGroup.__morphTargetsArrays = [];
  11166. for ( var m = 0, ml = numMorphTargets; m < ml; m ++ ) {
  11167. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  11168. }
  11169. }
  11170. var numMorphNormals = geometryGroup.numMorphNormals;
  11171. if ( numMorphNormals ) {
  11172. geometryGroup.__morphNormalsArrays = [];
  11173. for ( var m = 0, ml = numMorphNormals; m < ml; m ++ ) {
  11174. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  11175. }
  11176. }
  11177. geometryGroup.__webglFaceCount = ntris * 3;
  11178. geometryGroup.__webglLineCount = nlines * 2;
  11179. // custom attributes
  11180. if ( material.attributes ) {
  11181. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  11182. geometryGroup.__webglCustomAttributesList = [];
  11183. }
  11184. for ( var name in material.attributes ) {
  11185. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  11186. // attribute buffers which are correctly indexed in the setMeshBuffers function
  11187. var originalAttribute = material.attributes[ name ];
  11188. var attribute = {};
  11189. for ( var property in originalAttribute ) {
  11190. attribute[ property ] = originalAttribute[ property ];
  11191. }
  11192. if ( ! attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11193. attribute.__webglInitialized = true;
  11194. var size = 1; // "f" and "i"
  11195. if ( attribute.type === 'v2' ) size = 2;
  11196. else if ( attribute.type === 'v3' ) size = 3;
  11197. else if ( attribute.type === 'v4' ) size = 4;
  11198. else if ( attribute.type === 'c' ) size = 3;
  11199. attribute.size = size;
  11200. attribute.array = new Float32Array( nvertices * size );
  11201. attribute.buffer = _gl.createBuffer();
  11202. attribute.buffer.belongsToAttribute = name;
  11203. originalAttribute.needsUpdate = true;
  11204. attribute.__original = originalAttribute;
  11205. }
  11206. geometryGroup.__webglCustomAttributesList.push( attribute );
  11207. }
  11208. }
  11209. geometryGroup.__inittedArrays = true;
  11210. };
  11211. function getBufferMaterial( object, geometryGroup ) {
  11212. return object.material instanceof THREE.MeshFaceMaterial
  11213. ? object.material.materials[ geometryGroup.materialIndex ]
  11214. : object.material;
  11215. };
  11216. function materialNeedsSmoothNormals ( material ) {
  11217. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  11218. };
  11219. // Buffer setting
  11220. function setParticleBuffers ( geometry, hint, object ) {
  11221. var v, c, vertex, offset, index, color,
  11222. vertices = geometry.vertices,
  11223. vl = vertices.length,
  11224. colors = geometry.colors,
  11225. cl = colors.length,
  11226. vertexArray = geometry.__vertexArray,
  11227. colorArray = geometry.__colorArray,
  11228. sortArray = geometry.__sortArray,
  11229. dirtyVertices = geometry.verticesNeedUpdate,
  11230. dirtyElements = geometry.elementsNeedUpdate,
  11231. dirtyColors = geometry.colorsNeedUpdate,
  11232. customAttributes = geometry.__webglCustomAttributesList,
  11233. i, il,
  11234. a, ca, cal, value,
  11235. customAttribute;
  11236. if ( dirtyVertices ) {
  11237. for ( v = 0; v < vl; v ++ ) {
  11238. vertex = vertices[ v ];
  11239. offset = v * 3;
  11240. vertexArray[ offset ] = vertex.x;
  11241. vertexArray[ offset + 1 ] = vertex.y;
  11242. vertexArray[ offset + 2 ] = vertex.z;
  11243. }
  11244. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11245. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11246. }
  11247. if ( dirtyColors ) {
  11248. for ( c = 0; c < cl; c ++ ) {
  11249. color = colors[ c ];
  11250. offset = c * 3;
  11251. colorArray[ offset ] = color.r;
  11252. colorArray[ offset + 1 ] = color.g;
  11253. colorArray[ offset + 2 ] = color.b;
  11254. }
  11255. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11256. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11257. }
  11258. if ( customAttributes ) {
  11259. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11260. customAttribute = customAttributes[ i ];
  11261. if ( customAttribute.needsUpdate && ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) ) {
  11262. cal = customAttribute.value.length;
  11263. offset = 0;
  11264. if ( customAttribute.size === 1 ) {
  11265. for ( ca = 0; ca < cal; ca ++ ) {
  11266. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11267. }
  11268. } else if ( customAttribute.size === 2 ) {
  11269. for ( ca = 0; ca < cal; ca ++ ) {
  11270. value = customAttribute.value[ ca ];
  11271. customAttribute.array[ offset ] = value.x;
  11272. customAttribute.array[ offset + 1 ] = value.y;
  11273. offset += 2;
  11274. }
  11275. } else if ( customAttribute.size === 3 ) {
  11276. if ( customAttribute.type === 'c' ) {
  11277. for ( ca = 0; ca < cal; ca ++ ) {
  11278. value = customAttribute.value[ ca ];
  11279. customAttribute.array[ offset ] = value.r;
  11280. customAttribute.array[ offset + 1 ] = value.g;
  11281. customAttribute.array[ offset + 2 ] = value.b;
  11282. offset += 3;
  11283. }
  11284. } else {
  11285. for ( ca = 0; ca < cal; ca ++ ) {
  11286. value = customAttribute.value[ ca ];
  11287. customAttribute.array[ offset ] = value.x;
  11288. customAttribute.array[ offset + 1 ] = value.y;
  11289. customAttribute.array[ offset + 2 ] = value.z;
  11290. offset += 3;
  11291. }
  11292. }
  11293. } else if ( customAttribute.size === 4 ) {
  11294. for ( ca = 0; ca < cal; ca ++ ) {
  11295. value = customAttribute.value[ ca ];
  11296. customAttribute.array[ offset ] = value.x;
  11297. customAttribute.array[ offset + 1 ] = value.y;
  11298. customAttribute.array[ offset + 2 ] = value.z;
  11299. customAttribute.array[ offset + 3 ] = value.w;
  11300. offset += 4;
  11301. }
  11302. }
  11303. }
  11304. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11305. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11306. customAttribute.needsUpdate = false;
  11307. }
  11308. }
  11309. }
  11310. function setLineBuffers ( geometry, hint ) {
  11311. var v, c, d, vertex, offset, color,
  11312. vertices = geometry.vertices,
  11313. colors = geometry.colors,
  11314. lineDistances = geometry.lineDistances,
  11315. vl = vertices.length,
  11316. cl = colors.length,
  11317. dl = lineDistances.length,
  11318. vertexArray = geometry.__vertexArray,
  11319. colorArray = geometry.__colorArray,
  11320. lineDistanceArray = geometry.__lineDistanceArray,
  11321. dirtyVertices = geometry.verticesNeedUpdate,
  11322. dirtyColors = geometry.colorsNeedUpdate,
  11323. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  11324. customAttributes = geometry.__webglCustomAttributesList,
  11325. i, il,
  11326. a, ca, cal, value,
  11327. customAttribute;
  11328. if ( dirtyVertices ) {
  11329. for ( v = 0; v < vl; v ++ ) {
  11330. vertex = vertices[ v ];
  11331. offset = v * 3;
  11332. vertexArray[ offset ] = vertex.x;
  11333. vertexArray[ offset + 1 ] = vertex.y;
  11334. vertexArray[ offset + 2 ] = vertex.z;
  11335. }
  11336. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11337. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11338. }
  11339. if ( dirtyColors ) {
  11340. for ( c = 0; c < cl; c ++ ) {
  11341. color = colors[ c ];
  11342. offset = c * 3;
  11343. colorArray[ offset ] = color.r;
  11344. colorArray[ offset + 1 ] = color.g;
  11345. colorArray[ offset + 2 ] = color.b;
  11346. }
  11347. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11348. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11349. }
  11350. if ( dirtyLineDistances ) {
  11351. for ( d = 0; d < dl; d ++ ) {
  11352. lineDistanceArray[ d ] = lineDistances[ d ];
  11353. }
  11354. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  11355. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  11356. }
  11357. if ( customAttributes ) {
  11358. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11359. customAttribute = customAttributes[ i ];
  11360. if ( customAttribute.needsUpdate && ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) ) {
  11361. offset = 0;
  11362. cal = customAttribute.value.length;
  11363. if ( customAttribute.size === 1 ) {
  11364. for ( ca = 0; ca < cal; ca ++ ) {
  11365. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11366. }
  11367. } else if ( customAttribute.size === 2 ) {
  11368. for ( ca = 0; ca < cal; ca ++ ) {
  11369. value = customAttribute.value[ ca ];
  11370. customAttribute.array[ offset ] = value.x;
  11371. customAttribute.array[ offset + 1 ] = value.y;
  11372. offset += 2;
  11373. }
  11374. } else if ( customAttribute.size === 3 ) {
  11375. if ( customAttribute.type === 'c' ) {
  11376. for ( ca = 0; ca < cal; ca ++ ) {
  11377. value = customAttribute.value[ ca ];
  11378. customAttribute.array[ offset ] = value.r;
  11379. customAttribute.array[ offset + 1 ] = value.g;
  11380. customAttribute.array[ offset + 2 ] = value.b;
  11381. offset += 3;
  11382. }
  11383. } else {
  11384. for ( ca = 0; ca < cal; ca ++ ) {
  11385. value = customAttribute.value[ ca ];
  11386. customAttribute.array[ offset ] = value.x;
  11387. customAttribute.array[ offset + 1 ] = value.y;
  11388. customAttribute.array[ offset + 2 ] = value.z;
  11389. offset += 3;
  11390. }
  11391. }
  11392. } else if ( customAttribute.size === 4 ) {
  11393. for ( ca = 0; ca < cal; ca ++ ) {
  11394. value = customAttribute.value[ ca ];
  11395. customAttribute.array[ offset ] = value.x;
  11396. customAttribute.array[ offset + 1 ] = value.y;
  11397. customAttribute.array[ offset + 2 ] = value.z;
  11398. customAttribute.array[ offset + 3 ] = value.w;
  11399. offset += 4;
  11400. }
  11401. }
  11402. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11403. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11404. customAttribute.needsUpdate = false;
  11405. }
  11406. }
  11407. }
  11408. }
  11409. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  11410. if ( ! geometryGroup.__inittedArrays ) {
  11411. return;
  11412. }
  11413. var needsSmoothNormals = materialNeedsSmoothNormals( material );
  11414. var f, fl, fi, face,
  11415. vertexNormals, faceNormal, normal,
  11416. vertexColors, faceColor,
  11417. vertexTangents,
  11418. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  11419. c1, c2, c3,
  11420. sw1, sw2, sw3, sw4,
  11421. si1, si2, si3, si4,
  11422. sa1, sa2, sa3, sa4,
  11423. sb1, sb2, sb3, sb4,
  11424. m, ml, i, il,
  11425. vn, uvi, uv2i,
  11426. vk, vkl, vka,
  11427. nka, chf, faceVertexNormals,
  11428. a,
  11429. vertexIndex = 0,
  11430. offset = 0,
  11431. offset_uv = 0,
  11432. offset_uv2 = 0,
  11433. offset_face = 0,
  11434. offset_normal = 0,
  11435. offset_tangent = 0,
  11436. offset_line = 0,
  11437. offset_color = 0,
  11438. offset_skin = 0,
  11439. offset_morphTarget = 0,
  11440. offset_custom = 0,
  11441. offset_customSrc = 0,
  11442. value,
  11443. vertexArray = geometryGroup.__vertexArray,
  11444. uvArray = geometryGroup.__uvArray,
  11445. uv2Array = geometryGroup.__uv2Array,
  11446. normalArray = geometryGroup.__normalArray,
  11447. tangentArray = geometryGroup.__tangentArray,
  11448. colorArray = geometryGroup.__colorArray,
  11449. skinIndexArray = geometryGroup.__skinIndexArray,
  11450. skinWeightArray = geometryGroup.__skinWeightArray,
  11451. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  11452. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  11453. customAttributes = geometryGroup.__webglCustomAttributesList,
  11454. customAttribute,
  11455. faceArray = geometryGroup.__faceArray,
  11456. lineArray = geometryGroup.__lineArray,
  11457. geometry = object.geometry, // this is shared for all chunks
  11458. dirtyVertices = geometry.verticesNeedUpdate,
  11459. dirtyElements = geometry.elementsNeedUpdate,
  11460. dirtyUvs = geometry.uvsNeedUpdate,
  11461. dirtyNormals = geometry.normalsNeedUpdate,
  11462. dirtyTangents = geometry.tangentsNeedUpdate,
  11463. dirtyColors = geometry.colorsNeedUpdate,
  11464. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  11465. vertices = geometry.vertices,
  11466. chunk_faces3 = geometryGroup.faces3,
  11467. obj_faces = geometry.faces,
  11468. obj_uvs = geometry.faceVertexUvs[ 0 ],
  11469. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  11470. obj_colors = geometry.colors,
  11471. obj_skinIndices = geometry.skinIndices,
  11472. obj_skinWeights = geometry.skinWeights,
  11473. morphTargets = geometry.morphTargets,
  11474. morphNormals = geometry.morphNormals;
  11475. if ( dirtyVertices ) {
  11476. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11477. face = obj_faces[ chunk_faces3[ f ] ];
  11478. v1 = vertices[ face.a ];
  11479. v2 = vertices[ face.b ];
  11480. v3 = vertices[ face.c ];
  11481. vertexArray[ offset ] = v1.x;
  11482. vertexArray[ offset + 1 ] = v1.y;
  11483. vertexArray[ offset + 2 ] = v1.z;
  11484. vertexArray[ offset + 3 ] = v2.x;
  11485. vertexArray[ offset + 4 ] = v2.y;
  11486. vertexArray[ offset + 5 ] = v2.z;
  11487. vertexArray[ offset + 6 ] = v3.x;
  11488. vertexArray[ offset + 7 ] = v3.y;
  11489. vertexArray[ offset + 8 ] = v3.z;
  11490. offset += 9;
  11491. }
  11492. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11493. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11494. }
  11495. if ( dirtyMorphTargets ) {
  11496. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  11497. offset_morphTarget = 0;
  11498. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11499. chf = chunk_faces3[ f ];
  11500. face = obj_faces[ chf ];
  11501. // morph positions
  11502. v1 = morphTargets[ vk ].vertices[ face.a ];
  11503. v2 = morphTargets[ vk ].vertices[ face.b ];
  11504. v3 = morphTargets[ vk ].vertices[ face.c ];
  11505. vka = morphTargetsArrays[ vk ];
  11506. vka[ offset_morphTarget ] = v1.x;
  11507. vka[ offset_morphTarget + 1 ] = v1.y;
  11508. vka[ offset_morphTarget + 2 ] = v1.z;
  11509. vka[ offset_morphTarget + 3 ] = v2.x;
  11510. vka[ offset_morphTarget + 4 ] = v2.y;
  11511. vka[ offset_morphTarget + 5 ] = v2.z;
  11512. vka[ offset_morphTarget + 6 ] = v3.x;
  11513. vka[ offset_morphTarget + 7 ] = v3.y;
  11514. vka[ offset_morphTarget + 8 ] = v3.z;
  11515. // morph normals
  11516. if ( material.morphNormals ) {
  11517. if ( needsSmoothNormals ) {
  11518. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  11519. n1 = faceVertexNormals.a;
  11520. n2 = faceVertexNormals.b;
  11521. n3 = faceVertexNormals.c;
  11522. } else {
  11523. n1 = morphNormals[ vk ].faceNormals[ chf ];
  11524. n2 = n1;
  11525. n3 = n1;
  11526. }
  11527. nka = morphNormalsArrays[ vk ];
  11528. nka[ offset_morphTarget ] = n1.x;
  11529. nka[ offset_morphTarget + 1 ] = n1.y;
  11530. nka[ offset_morphTarget + 2 ] = n1.z;
  11531. nka[ offset_morphTarget + 3 ] = n2.x;
  11532. nka[ offset_morphTarget + 4 ] = n2.y;
  11533. nka[ offset_morphTarget + 5 ] = n2.z;
  11534. nka[ offset_morphTarget + 6 ] = n3.x;
  11535. nka[ offset_morphTarget + 7 ] = n3.y;
  11536. nka[ offset_morphTarget + 8 ] = n3.z;
  11537. }
  11538. //
  11539. offset_morphTarget += 9;
  11540. }
  11541. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  11542. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  11543. if ( material.morphNormals ) {
  11544. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  11545. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  11546. }
  11547. }
  11548. }
  11549. if ( obj_skinWeights.length ) {
  11550. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11551. face = obj_faces[ chunk_faces3[ f ] ];
  11552. // weights
  11553. sw1 = obj_skinWeights[ face.a ];
  11554. sw2 = obj_skinWeights[ face.b ];
  11555. sw3 = obj_skinWeights[ face.c ];
  11556. skinWeightArray[ offset_skin ] = sw1.x;
  11557. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  11558. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  11559. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  11560. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  11561. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  11562. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  11563. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  11564. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  11565. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  11566. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  11567. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  11568. // indices
  11569. si1 = obj_skinIndices[ face.a ];
  11570. si2 = obj_skinIndices[ face.b ];
  11571. si3 = obj_skinIndices[ face.c ];
  11572. skinIndexArray[ offset_skin ] = si1.x;
  11573. skinIndexArray[ offset_skin + 1 ] = si1.y;
  11574. skinIndexArray[ offset_skin + 2 ] = si1.z;
  11575. skinIndexArray[ offset_skin + 3 ] = si1.w;
  11576. skinIndexArray[ offset_skin + 4 ] = si2.x;
  11577. skinIndexArray[ offset_skin + 5 ] = si2.y;
  11578. skinIndexArray[ offset_skin + 6 ] = si2.z;
  11579. skinIndexArray[ offset_skin + 7 ] = si2.w;
  11580. skinIndexArray[ offset_skin + 8 ] = si3.x;
  11581. skinIndexArray[ offset_skin + 9 ] = si3.y;
  11582. skinIndexArray[ offset_skin + 10 ] = si3.z;
  11583. skinIndexArray[ offset_skin + 11 ] = si3.w;
  11584. offset_skin += 12;
  11585. }
  11586. if ( offset_skin > 0 ) {
  11587. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  11588. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  11589. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  11590. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  11591. }
  11592. }
  11593. if ( dirtyColors ) {
  11594. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11595. face = obj_faces[ chunk_faces3[ f ] ];
  11596. vertexColors = face.vertexColors;
  11597. faceColor = face.color;
  11598. if ( vertexColors.length === 3 && material.vertexColors === THREE.VertexColors ) {
  11599. c1 = vertexColors[ 0 ];
  11600. c2 = vertexColors[ 1 ];
  11601. c3 = vertexColors[ 2 ];
  11602. } else {
  11603. c1 = faceColor;
  11604. c2 = faceColor;
  11605. c3 = faceColor;
  11606. }
  11607. colorArray[ offset_color ] = c1.r;
  11608. colorArray[ offset_color + 1 ] = c1.g;
  11609. colorArray[ offset_color + 2 ] = c1.b;
  11610. colorArray[ offset_color + 3 ] = c2.r;
  11611. colorArray[ offset_color + 4 ] = c2.g;
  11612. colorArray[ offset_color + 5 ] = c2.b;
  11613. colorArray[ offset_color + 6 ] = c3.r;
  11614. colorArray[ offset_color + 7 ] = c3.g;
  11615. colorArray[ offset_color + 8 ] = c3.b;
  11616. offset_color += 9;
  11617. }
  11618. if ( offset_color > 0 ) {
  11619. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  11620. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11621. }
  11622. }
  11623. if ( dirtyTangents && geometry.hasTangents ) {
  11624. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11625. face = obj_faces[ chunk_faces3[ f ] ];
  11626. vertexTangents = face.vertexTangents;
  11627. t1 = vertexTangents[ 0 ];
  11628. t2 = vertexTangents[ 1 ];
  11629. t3 = vertexTangents[ 2 ];
  11630. tangentArray[ offset_tangent ] = t1.x;
  11631. tangentArray[ offset_tangent + 1 ] = t1.y;
  11632. tangentArray[ offset_tangent + 2 ] = t1.z;
  11633. tangentArray[ offset_tangent + 3 ] = t1.w;
  11634. tangentArray[ offset_tangent + 4 ] = t2.x;
  11635. tangentArray[ offset_tangent + 5 ] = t2.y;
  11636. tangentArray[ offset_tangent + 6 ] = t2.z;
  11637. tangentArray[ offset_tangent + 7 ] = t2.w;
  11638. tangentArray[ offset_tangent + 8 ] = t3.x;
  11639. tangentArray[ offset_tangent + 9 ] = t3.y;
  11640. tangentArray[ offset_tangent + 10 ] = t3.z;
  11641. tangentArray[ offset_tangent + 11 ] = t3.w;
  11642. offset_tangent += 12;
  11643. }
  11644. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  11645. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  11646. }
  11647. if ( dirtyNormals ) {
  11648. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11649. face = obj_faces[ chunk_faces3[ f ] ];
  11650. vertexNormals = face.vertexNormals;
  11651. faceNormal = face.normal;
  11652. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  11653. for ( i = 0; i < 3; i ++ ) {
  11654. vn = vertexNormals[ i ];
  11655. normalArray[ offset_normal ] = vn.x;
  11656. normalArray[ offset_normal + 1 ] = vn.y;
  11657. normalArray[ offset_normal + 2 ] = vn.z;
  11658. offset_normal += 3;
  11659. }
  11660. } else {
  11661. for ( i = 0; i < 3; i ++ ) {
  11662. normalArray[ offset_normal ] = faceNormal.x;
  11663. normalArray[ offset_normal + 1 ] = faceNormal.y;
  11664. normalArray[ offset_normal + 2 ] = faceNormal.z;
  11665. offset_normal += 3;
  11666. }
  11667. }
  11668. }
  11669. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  11670. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  11671. }
  11672. if ( dirtyUvs && obj_uvs ) {
  11673. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11674. fi = chunk_faces3[ f ];
  11675. uv = obj_uvs[ fi ];
  11676. if ( uv === undefined ) continue;
  11677. for ( i = 0; i < 3; i ++ ) {
  11678. uvi = uv[ i ];
  11679. uvArray[ offset_uv ] = uvi.x;
  11680. uvArray[ offset_uv + 1 ] = uvi.y;
  11681. offset_uv += 2;
  11682. }
  11683. }
  11684. if ( offset_uv > 0 ) {
  11685. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  11686. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  11687. }
  11688. }
  11689. if ( dirtyUvs && obj_uvs2 ) {
  11690. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11691. fi = chunk_faces3[ f ];
  11692. uv2 = obj_uvs2[ fi ];
  11693. if ( uv2 === undefined ) continue;
  11694. for ( i = 0; i < 3; i ++ ) {
  11695. uv2i = uv2[ i ];
  11696. uv2Array[ offset_uv2 ] = uv2i.x;
  11697. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  11698. offset_uv2 += 2;
  11699. }
  11700. }
  11701. if ( offset_uv2 > 0 ) {
  11702. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  11703. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  11704. }
  11705. }
  11706. if ( dirtyElements ) {
  11707. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11708. faceArray[ offset_face ] = vertexIndex;
  11709. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  11710. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  11711. offset_face += 3;
  11712. lineArray[ offset_line ] = vertexIndex;
  11713. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  11714. lineArray[ offset_line + 2 ] = vertexIndex;
  11715. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  11716. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  11717. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  11718. offset_line += 6;
  11719. vertexIndex += 3;
  11720. }
  11721. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  11722. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  11723. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  11724. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  11725. }
  11726. if ( customAttributes ) {
  11727. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11728. customAttribute = customAttributes[ i ];
  11729. if ( ! customAttribute.__original.needsUpdate ) continue;
  11730. offset_custom = 0;
  11731. offset_customSrc = 0;
  11732. if ( customAttribute.size === 1 ) {
  11733. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  11734. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11735. face = obj_faces[ chunk_faces3[ f ] ];
  11736. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  11737. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  11738. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  11739. offset_custom += 3;
  11740. }
  11741. } else if ( customAttribute.boundTo === 'faces' ) {
  11742. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11743. value = customAttribute.value[ chunk_faces3[ f ] ];
  11744. customAttribute.array[ offset_custom ] = value;
  11745. customAttribute.array[ offset_custom + 1 ] = value;
  11746. customAttribute.array[ offset_custom + 2 ] = value;
  11747. offset_custom += 3;
  11748. }
  11749. }
  11750. } else if ( customAttribute.size === 2 ) {
  11751. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  11752. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11753. face = obj_faces[ chunk_faces3[ f ] ];
  11754. v1 = customAttribute.value[ face.a ];
  11755. v2 = customAttribute.value[ face.b ];
  11756. v3 = customAttribute.value[ face.c ];
  11757. customAttribute.array[ offset_custom ] = v1.x;
  11758. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11759. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11760. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11761. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11762. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11763. offset_custom += 6;
  11764. }
  11765. } else if ( customAttribute.boundTo === 'faces' ) {
  11766. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11767. value = customAttribute.value[ chunk_faces3[ f ] ];
  11768. v1 = value;
  11769. v2 = value;
  11770. v3 = value;
  11771. customAttribute.array[ offset_custom ] = v1.x;
  11772. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11773. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11774. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11775. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11776. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11777. offset_custom += 6;
  11778. }
  11779. }
  11780. } else if ( customAttribute.size === 3 ) {
  11781. var pp;
  11782. if ( customAttribute.type === 'c' ) {
  11783. pp = [ 'r', 'g', 'b' ];
  11784. } else {
  11785. pp = [ 'x', 'y', 'z' ];
  11786. }
  11787. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  11788. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11789. face = obj_faces[ chunk_faces3[ f ] ];
  11790. v1 = customAttribute.value[ face.a ];
  11791. v2 = customAttribute.value[ face.b ];
  11792. v3 = customAttribute.value[ face.c ];
  11793. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11794. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11795. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11796. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11797. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11798. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11799. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11800. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11801. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11802. offset_custom += 9;
  11803. }
  11804. } else if ( customAttribute.boundTo === 'faces' ) {
  11805. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11806. value = customAttribute.value[ chunk_faces3[ f ] ];
  11807. v1 = value;
  11808. v2 = value;
  11809. v3 = value;
  11810. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11811. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11812. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11813. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11814. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11815. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11816. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11817. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11818. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11819. offset_custom += 9;
  11820. }
  11821. } else if ( customAttribute.boundTo === 'faceVertices' ) {
  11822. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11823. value = customAttribute.value[ chunk_faces3[ f ] ];
  11824. v1 = value[ 0 ];
  11825. v2 = value[ 1 ];
  11826. v3 = value[ 2 ];
  11827. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11828. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11829. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11830. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11831. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11832. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11833. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11834. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11835. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11836. offset_custom += 9;
  11837. }
  11838. }
  11839. } else if ( customAttribute.size === 4 ) {
  11840. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === 'vertices' ) {
  11841. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11842. face = obj_faces[ chunk_faces3[ f ] ];
  11843. v1 = customAttribute.value[ face.a ];
  11844. v2 = customAttribute.value[ face.b ];
  11845. v3 = customAttribute.value[ face.c ];
  11846. customAttribute.array[ offset_custom ] = v1.x;
  11847. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11848. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11849. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11850. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11851. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11852. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11853. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11854. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11855. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11856. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11857. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11858. offset_custom += 12;
  11859. }
  11860. } else if ( customAttribute.boundTo === 'faces' ) {
  11861. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11862. value = customAttribute.value[ chunk_faces3[ f ] ];
  11863. v1 = value;
  11864. v2 = value;
  11865. v3 = value;
  11866. customAttribute.array[ offset_custom ] = v1.x;
  11867. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11868. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11869. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11870. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11871. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11872. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11873. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11874. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11875. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11876. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11877. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11878. offset_custom += 12;
  11879. }
  11880. } else if ( customAttribute.boundTo === 'faceVertices' ) {
  11881. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11882. value = customAttribute.value[ chunk_faces3[ f ] ];
  11883. v1 = value[ 0 ];
  11884. v2 = value[ 1 ];
  11885. v3 = value[ 2 ];
  11886. customAttribute.array[ offset_custom ] = v1.x;
  11887. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11888. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11889. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11890. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11891. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11892. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11893. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11894. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11895. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11896. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11897. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11898. offset_custom += 12;
  11899. }
  11900. }
  11901. }
  11902. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11903. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11904. }
  11905. }
  11906. if ( dispose ) {
  11907. delete geometryGroup.__inittedArrays;
  11908. delete geometryGroup.__colorArray;
  11909. delete geometryGroup.__normalArray;
  11910. delete geometryGroup.__tangentArray;
  11911. delete geometryGroup.__uvArray;
  11912. delete geometryGroup.__uv2Array;
  11913. delete geometryGroup.__faceArray;
  11914. delete geometryGroup.__vertexArray;
  11915. delete geometryGroup.__lineArray;
  11916. delete geometryGroup.__skinIndexArray;
  11917. delete geometryGroup.__skinWeightArray;
  11918. }
  11919. };
  11920. // Buffer rendering
  11921. this.renderBufferImmediate = function ( object, program, material ) {
  11922. initAttributes();
  11923. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  11924. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  11925. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  11926. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  11927. if ( object.hasPositions ) {
  11928. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  11929. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  11930. enableAttribute( program.attributes.position );
  11931. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11932. }
  11933. if ( object.hasNormals ) {
  11934. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  11935. if ( material.shading === THREE.FlatShading ) {
  11936. var nx, ny, nz,
  11937. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  11938. normalArray,
  11939. i, il = object.count * 3;
  11940. for ( i = 0; i < il; i += 9 ) {
  11941. normalArray = object.normalArray;
  11942. nax = normalArray[ i ];
  11943. nay = normalArray[ i + 1 ];
  11944. naz = normalArray[ i + 2 ];
  11945. nbx = normalArray[ i + 3 ];
  11946. nby = normalArray[ i + 4 ];
  11947. nbz = normalArray[ i + 5 ];
  11948. ncx = normalArray[ i + 6 ];
  11949. ncy = normalArray[ i + 7 ];
  11950. ncz = normalArray[ i + 8 ];
  11951. nx = ( nax + nbx + ncx ) / 3;
  11952. ny = ( nay + nby + ncy ) / 3;
  11953. nz = ( naz + nbz + ncz ) / 3;
  11954. normalArray[ i ] = nx;
  11955. normalArray[ i + 1 ] = ny;
  11956. normalArray[ i + 2 ] = nz;
  11957. normalArray[ i + 3 ] = nx;
  11958. normalArray[ i + 4 ] = ny;
  11959. normalArray[ i + 5 ] = nz;
  11960. normalArray[ i + 6 ] = nx;
  11961. normalArray[ i + 7 ] = ny;
  11962. normalArray[ i + 8 ] = nz;
  11963. }
  11964. }
  11965. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  11966. enableAttribute( program.attributes.normal );
  11967. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11968. }
  11969. if ( object.hasUvs && material.map ) {
  11970. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  11971. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  11972. enableAttribute( program.attributes.uv );
  11973. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11974. }
  11975. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  11976. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  11977. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  11978. enableAttribute( program.attributes.color );
  11979. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11980. }
  11981. disableUnusedAttributes();
  11982. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  11983. object.count = 0;
  11984. };
  11985. function setupVertexAttributes( material, program, geometry, startIndex ) {
  11986. var geometryAttributes = geometry.attributes;
  11987. var programAttributes = program.attributes;
  11988. var programAttributesKeys = program.attributesKeys;
  11989. for ( var i = 0, l = programAttributesKeys.length; i < l; i ++ ) {
  11990. var key = programAttributesKeys[ i ];
  11991. var programAttribute = programAttributes[ key ];
  11992. if ( programAttribute >= 0 ) {
  11993. var geometryAttribute = geometryAttributes[ key ];
  11994. if ( geometryAttribute !== undefined ) {
  11995. var size = geometryAttribute.itemSize;
  11996. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryAttribute.buffer );
  11997. enableAttribute( programAttribute );
  11998. _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, 0, startIndex * size * 4 ); // 4 bytes per Float32
  11999. } else if ( material.defaultAttributeValues !== undefined ) {
  12000. if ( material.defaultAttributeValues[ key ].length === 2 ) {
  12001. _gl.vertexAttrib2fv( programAttribute, material.defaultAttributeValues[ key ] );
  12002. } else if ( material.defaultAttributeValues[ key ].length === 3 ) {
  12003. _gl.vertexAttrib3fv( programAttribute, material.defaultAttributeValues[ key ] );
  12004. }
  12005. }
  12006. }
  12007. }
  12008. disableUnusedAttributes();
  12009. }
  12010. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  12011. if ( material.visible === false ) return;
  12012. updateObject( object );
  12013. var program = setProgram( camera, lights, fog, material, object );
  12014. var updateBuffers = false,
  12015. wireframeBit = material.wireframe ? 1 : 0,
  12016. geometryProgram = 'direct_' + geometry.id + '_' + program.id + '_' + wireframeBit;
  12017. if ( geometryProgram !== _currentGeometryProgram ) {
  12018. _currentGeometryProgram = geometryProgram;
  12019. updateBuffers = true;
  12020. }
  12021. if ( updateBuffers ) {
  12022. initAttributes();
  12023. }
  12024. // render mesh
  12025. if ( object instanceof THREE.Mesh ) {
  12026. var mode = material.wireframe === true ? _gl.LINES : _gl.TRIANGLES;
  12027. var index = geometry.attributes.index;
  12028. if ( index ) {
  12029. // indexed triangles
  12030. var type, size;
  12031. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  12032. type = _gl.UNSIGNED_INT;
  12033. size = 4;
  12034. } else {
  12035. type = _gl.UNSIGNED_SHORT;
  12036. size = 2;
  12037. }
  12038. var offsets = geometry.offsets;
  12039. if ( offsets.length === 0 ) {
  12040. if ( updateBuffers ) {
  12041. setupVertexAttributes( material, program, geometry, 0 );
  12042. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12043. }
  12044. _gl.drawElements( mode, index.array.length, type, 0 );
  12045. _this.info.render.calls ++;
  12046. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  12047. _this.info.render.faces += index.array.length / 3;
  12048. } else {
  12049. // if there is more than 1 chunk
  12050. // must set attribute pointers to use new offsets for each chunk
  12051. // even if geometry and materials didn't change
  12052. updateBuffers = true;
  12053. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12054. var startIndex = offsets[ i ].index;
  12055. if ( updateBuffers ) {
  12056. setupVertexAttributes( material, program, geometry, startIndex );
  12057. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12058. }
  12059. // render indexed triangles
  12060. _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size );
  12061. _this.info.render.calls ++;
  12062. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  12063. _this.info.render.faces += offsets[ i ].count / 3;
  12064. }
  12065. }
  12066. } else {
  12067. // non-indexed triangles
  12068. if ( updateBuffers ) {
  12069. setupVertexAttributes( material, program, geometry, 0 );
  12070. }
  12071. var position = geometry.attributes[ 'position' ];
  12072. // render non-indexed triangles
  12073. _gl.drawArrays( mode, 0, position.array.length / position.itemSize );
  12074. _this.info.render.calls ++;
  12075. _this.info.render.vertices += position.array.length / position.itemSize;
  12076. _this.info.render.faces += position.array.length / ( 3 * position.itemsize );
  12077. }
  12078. } else if ( object instanceof THREE.PointCloud ) {
  12079. // render particles
  12080. var mode = _gl.POINTS;
  12081. var index = geometry.attributes.index;
  12082. if ( index ) {
  12083. // indexed points
  12084. var type, size;
  12085. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  12086. type = _gl.UNSIGNED_INT;
  12087. size = 4;
  12088. } else {
  12089. type = _gl.UNSIGNED_SHORT;
  12090. size = 2;
  12091. }
  12092. var offsets = geometry.offsets;
  12093. if ( offsets.length === 0 ) {
  12094. if ( updateBuffers ) {
  12095. setupVertexAttributes( material, program, geometry, 0 );
  12096. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12097. }
  12098. _gl.drawElements( mode, index.array.length, type, 0);
  12099. _this.info.render.calls ++;
  12100. _this.info.render.points += index.array.length;
  12101. } else {
  12102. // if there is more than 1 chunk
  12103. // must set attribute pointers to use new offsets for each chunk
  12104. // even if geometry and materials didn't change
  12105. if ( offsets.length > 1 ) updateBuffers = true;
  12106. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12107. var startIndex = offsets[ i ].index;
  12108. if ( updateBuffers ) {
  12109. setupVertexAttributes( material, program, geometry, startIndex );
  12110. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12111. }
  12112. // render indexed points
  12113. _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size );
  12114. _this.info.render.calls ++;
  12115. _this.info.render.points += offsets[ i ].count;
  12116. }
  12117. }
  12118. } else {
  12119. // non-indexed points
  12120. if ( updateBuffers ) {
  12121. setupVertexAttributes( material, program, geometry, 0 );
  12122. }
  12123. var position = geometry.attributes.position;
  12124. var offsets = geometry.offsets;
  12125. if ( offsets.length === 0 ) {
  12126. _gl.drawArrays( mode, 0, position.array.length / 3 );
  12127. _this.info.render.calls ++;
  12128. _this.info.render.points += position.array.length / 3;
  12129. } else {
  12130. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12131. _gl.drawArrays( mode, offsets[ i ].index, offsets[ i ].count );
  12132. _this.info.render.calls ++;
  12133. _this.info.render.points += offsets[ i ].count;
  12134. }
  12135. }
  12136. }
  12137. } else if ( object instanceof THREE.Line ) {
  12138. var mode = ( object.mode === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  12139. setLineWidth( material.linewidth );
  12140. var index = geometry.attributes.index;
  12141. if ( index ) {
  12142. // indexed lines
  12143. var type, size;
  12144. if ( index.array instanceof Uint32Array ) {
  12145. type = _gl.UNSIGNED_INT;
  12146. size = 4;
  12147. } else {
  12148. type = _gl.UNSIGNED_SHORT;
  12149. size = 2;
  12150. }
  12151. var offsets = geometry.offsets;
  12152. if ( offsets.length === 0 ) {
  12153. if ( updateBuffers ) {
  12154. setupVertexAttributes( material, program, geometry, 0 );
  12155. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12156. }
  12157. _gl.drawElements( mode, index.array.length, type, 0 ); // 2 bytes per Uint16Array
  12158. _this.info.render.calls ++;
  12159. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  12160. } else {
  12161. // if there is more than 1 chunk
  12162. // must set attribute pointers to use new offsets for each chunk
  12163. // even if geometry and materials didn't change
  12164. if ( offsets.length > 1 ) updateBuffers = true;
  12165. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12166. var startIndex = offsets[ i ].index;
  12167. if ( updateBuffers ) {
  12168. setupVertexAttributes( material, program, geometry, startIndex );
  12169. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12170. }
  12171. // render indexed lines
  12172. _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size ); // 2 bytes per Uint16Array
  12173. _this.info.render.calls ++;
  12174. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  12175. }
  12176. }
  12177. } else {
  12178. // non-indexed lines
  12179. if ( updateBuffers ) {
  12180. setupVertexAttributes( material, program, geometry, 0 );
  12181. }
  12182. var position = geometry.attributes.position;
  12183. var offsets = geometry.offsets;
  12184. if ( offsets.length === 0 ) {
  12185. _gl.drawArrays( mode, 0, position.array.length / 3 );
  12186. _this.info.render.calls ++;
  12187. _this.info.render.vertices += position.array.length / 3;
  12188. } else {
  12189. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12190. _gl.drawArrays( mode, offsets[ i ].index, offsets[ i ].count );
  12191. _this.info.render.calls ++;
  12192. _this.info.render.vertices += offsets[ i ].count;
  12193. }
  12194. }
  12195. }
  12196. }
  12197. };
  12198. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  12199. if ( material.visible === false ) return;
  12200. updateObject( object );
  12201. var program = setProgram( camera, lights, fog, material, object );
  12202. var attributes = program.attributes;
  12203. var updateBuffers = false,
  12204. wireframeBit = material.wireframe ? 1 : 0,
  12205. geometryProgram = geometryGroup.id + '_' + program.id + '_' + wireframeBit;
  12206. if ( geometryProgram !== _currentGeometryProgram ) {
  12207. _currentGeometryProgram = geometryProgram;
  12208. updateBuffers = true;
  12209. }
  12210. if ( updateBuffers ) {
  12211. initAttributes();
  12212. }
  12213. // vertices
  12214. if ( ! material.morphTargets && attributes.position >= 0 ) {
  12215. if ( updateBuffers ) {
  12216. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12217. enableAttribute( attributes.position );
  12218. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12219. }
  12220. } else {
  12221. if ( object.morphTargetBase ) {
  12222. setupMorphTargets( material, geometryGroup, object );
  12223. }
  12224. }
  12225. if ( updateBuffers ) {
  12226. // custom attributes
  12227. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  12228. if ( geometryGroup.__webglCustomAttributesList ) {
  12229. for ( var i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  12230. var attribute = geometryGroup.__webglCustomAttributesList[ i ];
  12231. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  12232. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  12233. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  12234. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  12235. }
  12236. }
  12237. }
  12238. // colors
  12239. if ( attributes.color >= 0 ) {
  12240. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  12241. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12242. enableAttribute( attributes.color );
  12243. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12244. } else if ( material.defaultAttributeValues !== undefined ) {
  12245. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  12246. }
  12247. }
  12248. // normals
  12249. if ( attributes.normal >= 0 ) {
  12250. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12251. enableAttribute( attributes.normal );
  12252. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12253. }
  12254. // tangents
  12255. if ( attributes.tangent >= 0 ) {
  12256. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12257. enableAttribute( attributes.tangent );
  12258. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  12259. }
  12260. // uvs
  12261. if ( attributes.uv >= 0 ) {
  12262. if ( object.geometry.faceVertexUvs[ 0 ] ) {
  12263. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12264. enableAttribute( attributes.uv );
  12265. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12266. } else if ( material.defaultAttributeValues !== undefined ) {
  12267. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  12268. }
  12269. }
  12270. if ( attributes.uv2 >= 0 ) {
  12271. if ( object.geometry.faceVertexUvs[ 1 ] ) {
  12272. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12273. enableAttribute( attributes.uv2 );
  12274. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  12275. } else if ( material.defaultAttributeValues !== undefined ) {
  12276. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  12277. }
  12278. }
  12279. if ( material.skinning &&
  12280. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  12281. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12282. enableAttribute( attributes.skinIndex );
  12283. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  12284. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12285. enableAttribute( attributes.skinWeight );
  12286. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  12287. }
  12288. // line distances
  12289. if ( attributes.lineDistance >= 0 ) {
  12290. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  12291. enableAttribute( attributes.lineDistance );
  12292. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  12293. }
  12294. }
  12295. disableUnusedAttributes();
  12296. // render mesh
  12297. if ( object instanceof THREE.Mesh ) {
  12298. var type = geometryGroup.__typeArray === Uint32Array ? _gl.UNSIGNED_INT : _gl.UNSIGNED_SHORT;
  12299. // wireframe
  12300. if ( material.wireframe ) {
  12301. setLineWidth( material.wireframeLinewidth );
  12302. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12303. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, type, 0 );
  12304. // triangles
  12305. } else {
  12306. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12307. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, type, 0 );
  12308. }
  12309. _this.info.render.calls ++;
  12310. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  12311. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  12312. // render lines
  12313. } else if ( object instanceof THREE.Line ) {
  12314. var mode = ( object.mode === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  12315. setLineWidth( material.linewidth );
  12316. _gl.drawArrays( mode, 0, geometryGroup.__webglLineCount );
  12317. _this.info.render.calls ++;
  12318. // render particles
  12319. } else if ( object instanceof THREE.PointCloud ) {
  12320. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  12321. _this.info.render.calls ++;
  12322. _this.info.render.points += geometryGroup.__webglParticleCount;
  12323. }
  12324. };
  12325. function initAttributes() {
  12326. for ( var i = 0, l = _newAttributes.length; i < l; i ++ ) {
  12327. _newAttributes[ i ] = 0;
  12328. }
  12329. }
  12330. function enableAttribute( attribute ) {
  12331. _newAttributes[ attribute ] = 1;
  12332. if ( _enabledAttributes[ attribute ] === 0 ) {
  12333. _gl.enableVertexAttribArray( attribute );
  12334. _enabledAttributes[ attribute ] = 1;
  12335. }
  12336. }
  12337. function disableUnusedAttributes() {
  12338. for ( var i = 0, l = _enabledAttributes.length; i < l; i ++ ) {
  12339. if ( _enabledAttributes[ i ] !== _newAttributes[ i ] ) {
  12340. _gl.disableVertexAttribArray( i );
  12341. _enabledAttributes[ i ] = 0;
  12342. }
  12343. }
  12344. }
  12345. function setupMorphTargets ( material, geometryGroup, object ) {
  12346. // set base
  12347. var attributes = material.program.attributes;
  12348. if ( object.morphTargetBase !== - 1 && attributes.position >= 0 ) {
  12349. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  12350. enableAttribute( attributes.position );
  12351. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12352. } else if ( attributes.position >= 0 ) {
  12353. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12354. enableAttribute( attributes.position );
  12355. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12356. }
  12357. if ( object.morphTargetForcedOrder.length ) {
  12358. // set forced order
  12359. var m = 0;
  12360. var order = object.morphTargetForcedOrder;
  12361. var influences = object.morphTargetInfluences;
  12362. var attribute;
  12363. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  12364. attribute = attributes[ 'morphTarget' + m ];
  12365. if ( attribute >= 0 ) {
  12366. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  12367. enableAttribute( attribute );
  12368. _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 );
  12369. }
  12370. attribute = attributes[ 'morphNormal' + m ];
  12371. if ( attribute >= 0 && material.morphNormals ) {
  12372. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  12373. enableAttribute( attribute );
  12374. _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 );
  12375. }
  12376. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  12377. m ++;
  12378. }
  12379. } else {
  12380. // find the most influencing
  12381. var activeInfluenceIndices = [];
  12382. var influences = object.morphTargetInfluences;
  12383. var morphTargets = object.geometry.morphTargets;
  12384. if ( influences.length > morphTargets.length ) {
  12385. console.warn( 'THREE.WebGLRenderer: Influences array is bigger than morphTargets array.' );
  12386. influences.length = morphTargets.length;
  12387. }
  12388. for ( var i = 0, il = influences.length; i < il; i ++ ) {
  12389. var influence = influences[ i ];
  12390. activeInfluenceIndices.push( [ influence, i ] );
  12391. }
  12392. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  12393. activeInfluenceIndices.sort( numericalSort );
  12394. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  12395. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  12396. activeInfluenceIndices.sort( numericalSort );
  12397. } else if ( activeInfluenceIndices.length === 0 ) {
  12398. activeInfluenceIndices.push( [ 0, 0 ] );
  12399. }
  12400. var attribute;
  12401. for ( var m = 0, ml = material.numSupportedMorphTargets; m < ml; m ++ ) {
  12402. if ( activeInfluenceIndices[ m ] ) {
  12403. var influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  12404. attribute = attributes[ 'morphTarget' + m ];
  12405. if ( attribute >= 0 ) {
  12406. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  12407. enableAttribute( attribute );
  12408. _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 );
  12409. }
  12410. attribute = attributes[ 'morphNormal' + m ];
  12411. if ( attribute >= 0 && material.morphNormals ) {
  12412. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  12413. enableAttribute( attribute );
  12414. _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 );
  12415. }
  12416. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  12417. } else {
  12418. /*
  12419. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12420. if ( material.morphNormals ) {
  12421. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12422. }
  12423. */
  12424. object.__webglMorphTargetInfluences[ m ] = 0;
  12425. }
  12426. }
  12427. }
  12428. // load updated influences uniform
  12429. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  12430. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  12431. }
  12432. }
  12433. // Sorting
  12434. function painterSortStable ( a, b ) {
  12435. if ( a.material.id !== b.material.id ) {
  12436. return a.material.id - b.material.id;
  12437. } else if ( a.z !== b.z ) {
  12438. return a.z - b.z;
  12439. } else {
  12440. return a.id - b.id;
  12441. }
  12442. }
  12443. function reversePainterSortStable ( a, b ) {
  12444. if ( a.z !== b.z ) {
  12445. return b.z - a.z;
  12446. } else {
  12447. return a.id - b.id;
  12448. }
  12449. }
  12450. function numericalSort ( a, b ) {
  12451. return b[ 0 ] - a[ 0 ];
  12452. }
  12453. // Rendering
  12454. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12455. if ( camera instanceof THREE.Camera === false ) {
  12456. THREE.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12457. return;
  12458. }
  12459. var fog = scene.fog;
  12460. // reset caching for this frame
  12461. _currentGeometryProgram = '';
  12462. _currentMaterialId = - 1;
  12463. _currentCamera = null;
  12464. _lightsNeedUpdate = true;
  12465. // update scene graph
  12466. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  12467. // update camera matrices and frustum
  12468. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  12469. // update Skeleton objects
  12470. scene.traverse( function ( object ) {
  12471. if ( object instanceof THREE.SkinnedMesh ) {
  12472. object.skeleton.update();
  12473. }
  12474. } );
  12475. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  12476. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  12477. _frustum.setFromMatrix( _projScreenMatrix );
  12478. lights.length = 0;
  12479. opaqueObjects.length = 0;
  12480. transparentObjects.length = 0;
  12481. sprites.length = 0;
  12482. lensFlares.length = 0;
  12483. projectObject( scene );
  12484. if ( _this.sortObjects === true ) {
  12485. opaqueObjects.sort( painterSortStable );
  12486. transparentObjects.sort( reversePainterSortStable );
  12487. }
  12488. // custom render plugins (pre pass)
  12489. shadowMapPlugin.render( scene, camera );
  12490. //
  12491. _this.info.render.calls = 0;
  12492. _this.info.render.vertices = 0;
  12493. _this.info.render.faces = 0;
  12494. _this.info.render.points = 0;
  12495. this.setRenderTarget( renderTarget );
  12496. if ( this.autoClear || forceClear ) {
  12497. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  12498. }
  12499. // set matrices for immediate objects
  12500. for ( var i = 0, il = _webglObjectsImmediate.length; i < il; i ++ ) {
  12501. var webglObject = _webglObjectsImmediate[ i ];
  12502. var object = webglObject.object;
  12503. if ( object.visible ) {
  12504. setupMatrices( object, camera );
  12505. unrollImmediateBufferMaterial( webglObject );
  12506. }
  12507. }
  12508. if ( scene.overrideMaterial ) {
  12509. var material = scene.overrideMaterial;
  12510. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha );
  12511. this.setDepthTest( material.depthTest );
  12512. this.setDepthWrite( material.depthWrite );
  12513. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12514. renderObjects( opaqueObjects, camera, lights, fog, true, material );
  12515. renderObjects( transparentObjects, camera, lights, fog, true, material );
  12516. renderObjectsImmediate( _webglObjectsImmediate, '', camera, lights, fog, false, material );
  12517. } else {
  12518. var material = null;
  12519. // opaque pass (front-to-back order)
  12520. this.setBlending( THREE.NoBlending );
  12521. renderObjects( opaqueObjects, camera, lights, fog, false, material );
  12522. renderObjectsImmediate( _webglObjectsImmediate, 'opaque', camera, lights, fog, false, material );
  12523. // transparent pass (back-to-front order)
  12524. renderObjects( transparentObjects, camera, lights, fog, true, material );
  12525. renderObjectsImmediate( _webglObjectsImmediate, 'transparent', camera, lights, fog, true, material );
  12526. }
  12527. // custom render plugins (post pass)
  12528. spritePlugin.render( scene, camera );
  12529. lensFlarePlugin.render( scene, camera, _currentWidth, _currentHeight );
  12530. // Generate mipmap if we're using any kind of mipmap filtering
  12531. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  12532. updateRenderTargetMipmap( renderTarget );
  12533. }
  12534. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12535. this.setDepthTest( true );
  12536. this.setDepthWrite( true );
  12537. // _gl.finish();
  12538. };
  12539. function projectObject( object ) {
  12540. if ( object.visible === false ) return;
  12541. if ( object instanceof THREE.Scene || object instanceof THREE.Group ) {
  12542. // skip
  12543. } else {
  12544. initObject( object );
  12545. if ( object instanceof THREE.Light ) {
  12546. lights.push( object );
  12547. } else if ( object instanceof THREE.Sprite ) {
  12548. sprites.push( object );
  12549. } else if ( object instanceof THREE.LensFlare ) {
  12550. lensFlares.push( object );
  12551. } else {
  12552. var webglObjects = _webglObjects[ object.id ];
  12553. if ( webglObjects && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  12554. for ( var i = 0, l = webglObjects.length; i < l; i ++ ) {
  12555. var webglObject = webglObjects[ i ];
  12556. unrollBufferMaterial( webglObject );
  12557. webglObject.render = true;
  12558. if ( _this.sortObjects === true ) {
  12559. _vector3.setFromMatrixPosition( object.matrixWorld );
  12560. _vector3.applyProjection( _projScreenMatrix );
  12561. webglObject.z = _vector3.z;
  12562. }
  12563. }
  12564. }
  12565. }
  12566. }
  12567. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  12568. projectObject( object.children[ i ] );
  12569. }
  12570. }
  12571. function renderObjects( renderList, camera, lights, fog, useBlending, overrideMaterial ) {
  12572. var material;
  12573. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  12574. var webglObject = renderList[ i ];
  12575. var object = webglObject.object;
  12576. var buffer = webglObject.buffer;
  12577. setupMatrices( object, camera );
  12578. if ( overrideMaterial ) {
  12579. material = overrideMaterial;
  12580. } else {
  12581. material = webglObject.material;
  12582. if ( ! material ) continue;
  12583. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha );
  12584. _this.setDepthTest( material.depthTest );
  12585. _this.setDepthWrite( material.depthWrite );
  12586. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12587. }
  12588. _this.setMaterialFaces( material );
  12589. if ( buffer instanceof THREE.BufferGeometry ) {
  12590. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  12591. } else {
  12592. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  12593. }
  12594. }
  12595. }
  12596. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  12597. var material;
  12598. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  12599. var webglObject = renderList[ i ];
  12600. var object = webglObject.object;
  12601. if ( object.visible ) {
  12602. if ( overrideMaterial ) {
  12603. material = overrideMaterial;
  12604. } else {
  12605. material = webglObject[ materialType ];
  12606. if ( ! material ) continue;
  12607. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha );
  12608. _this.setDepthTest( material.depthTest );
  12609. _this.setDepthWrite( material.depthWrite );
  12610. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12611. }
  12612. _this.renderImmediateObject( camera, lights, fog, material, object );
  12613. }
  12614. }
  12615. }
  12616. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  12617. var program = setProgram( camera, lights, fog, material, object );
  12618. _currentGeometryProgram = '';
  12619. _this.setMaterialFaces( material );
  12620. if ( object.immediateRenderCallback ) {
  12621. object.immediateRenderCallback( program, _gl, _frustum );
  12622. } else {
  12623. object.render( function ( object ) { _this.renderBufferImmediate( object, program, material ); } );
  12624. }
  12625. };
  12626. function unrollImmediateBufferMaterial ( globject ) {
  12627. var object = globject.object,
  12628. material = object.material;
  12629. if ( material.transparent ) {
  12630. globject.transparent = material;
  12631. globject.opaque = null;
  12632. } else {
  12633. globject.opaque = material;
  12634. globject.transparent = null;
  12635. }
  12636. }
  12637. function unrollBufferMaterial ( globject ) {
  12638. var object = globject.object;
  12639. var buffer = globject.buffer;
  12640. var geometry = object.geometry;
  12641. var material = object.material;
  12642. if ( material instanceof THREE.MeshFaceMaterial ) {
  12643. var materialIndex = geometry instanceof THREE.BufferGeometry ? 0 : buffer.materialIndex;
  12644. material = material.materials[ materialIndex ];
  12645. globject.material = material;
  12646. if ( material.transparent ) {
  12647. transparentObjects.push( globject );
  12648. } else {
  12649. opaqueObjects.push( globject );
  12650. }
  12651. } else if ( material ) {
  12652. globject.material = material;
  12653. if ( material.transparent ) {
  12654. transparentObjects.push( globject );
  12655. } else {
  12656. opaqueObjects.push( globject );
  12657. }
  12658. }
  12659. }
  12660. function initObject( object ) {
  12661. if ( object.__webglInit === undefined ) {
  12662. object.__webglInit = true;
  12663. object._modelViewMatrix = new THREE.Matrix4();
  12664. object._normalMatrix = new THREE.Matrix3();
  12665. object.addEventListener( 'removed', onObjectRemoved );
  12666. }
  12667. var geometry = object.geometry;
  12668. if ( geometry === undefined ) {
  12669. // ImmediateRenderObject
  12670. } else if ( geometry.__webglInit === undefined ) {
  12671. geometry.__webglInit = true;
  12672. geometry.addEventListener( 'dispose', onGeometryDispose );
  12673. if ( geometry instanceof THREE.BufferGeometry ) {
  12674. _this.info.memory.geometries ++;
  12675. } else if ( object instanceof THREE.Mesh ) {
  12676. initGeometryGroups( object, geometry );
  12677. } else if ( object instanceof THREE.Line ) {
  12678. if ( geometry.__webglVertexBuffer === undefined ) {
  12679. createLineBuffers( geometry );
  12680. initLineBuffers( geometry, object );
  12681. geometry.verticesNeedUpdate = true;
  12682. geometry.colorsNeedUpdate = true;
  12683. geometry.lineDistancesNeedUpdate = true;
  12684. }
  12685. } else if ( object instanceof THREE.PointCloud ) {
  12686. if ( geometry.__webglVertexBuffer === undefined ) {
  12687. createParticleBuffers( geometry );
  12688. initParticleBuffers( geometry, object );
  12689. geometry.verticesNeedUpdate = true;
  12690. geometry.colorsNeedUpdate = true;
  12691. }
  12692. }
  12693. }
  12694. if ( object.__webglActive === undefined) {
  12695. object.__webglActive = true;
  12696. if ( object instanceof THREE.Mesh ) {
  12697. if ( geometry instanceof THREE.BufferGeometry ) {
  12698. addBuffer( _webglObjects, geometry, object );
  12699. } else if ( geometry instanceof THREE.Geometry ) {
  12700. var geometryGroupsList = geometryGroups[ geometry.id ];
  12701. for ( var i = 0,l = geometryGroupsList.length; i < l; i ++ ) {
  12702. addBuffer( _webglObjects, geometryGroupsList[ i ], object );
  12703. }
  12704. }
  12705. } else if ( object instanceof THREE.Line || object instanceof THREE.PointCloud ) {
  12706. addBuffer( _webglObjects, geometry, object );
  12707. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12708. addBufferImmediate( _webglObjectsImmediate, object );
  12709. }
  12710. }
  12711. }
  12712. // Geometry splitting
  12713. var geometryGroups = {};
  12714. var geometryGroupCounter = 0;
  12715. function makeGroups( geometry, usesFaceMaterial ) {
  12716. var maxVerticesInGroup = extensions.get( 'OES_element_index_uint' ) ? 4294967296 : 65535;
  12717. var groupHash, hash_map = {};
  12718. var numMorphTargets = geometry.morphTargets.length;
  12719. var numMorphNormals = geometry.morphNormals.length;
  12720. var group;
  12721. var groups = {};
  12722. var groupsList = [];
  12723. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  12724. var face = geometry.faces[ f ];
  12725. var materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  12726. if ( ! ( materialIndex in hash_map ) ) {
  12727. hash_map[ materialIndex ] = { hash: materialIndex, counter: 0 };
  12728. }
  12729. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  12730. if ( ! ( groupHash in groups ) ) {
  12731. group = {
  12732. id: geometryGroupCounter ++,
  12733. faces3: [],
  12734. materialIndex: materialIndex,
  12735. vertices: 0,
  12736. numMorphTargets: numMorphTargets,
  12737. numMorphNormals: numMorphNormals
  12738. };
  12739. groups[ groupHash ] = group;
  12740. groupsList.push( group );
  12741. }
  12742. if ( groups[ groupHash ].vertices + 3 > maxVerticesInGroup ) {
  12743. hash_map[ materialIndex ].counter += 1;
  12744. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  12745. if ( ! ( groupHash in groups ) ) {
  12746. group = {
  12747. id: geometryGroupCounter ++,
  12748. faces3: [],
  12749. materialIndex: materialIndex,
  12750. vertices: 0,
  12751. numMorphTargets: numMorphTargets,
  12752. numMorphNormals: numMorphNormals
  12753. };
  12754. groups[ groupHash ] = group;
  12755. groupsList.push( group );
  12756. }
  12757. }
  12758. groups[ groupHash ].faces3.push( f );
  12759. groups[ groupHash ].vertices += 3;
  12760. }
  12761. return groupsList;
  12762. }
  12763. function initGeometryGroups( object, geometry ) {
  12764. var material = object.material, addBuffers = false;
  12765. if ( geometryGroups[ geometry.id ] === undefined || geometry.groupsNeedUpdate === true ) {
  12766. delete _webglObjects[ object.id ];
  12767. geometryGroups[ geometry.id ] = makeGroups( geometry, material instanceof THREE.MeshFaceMaterial );
  12768. geometry.groupsNeedUpdate = false;
  12769. }
  12770. var geometryGroupsList = geometryGroups[ geometry.id ];
  12771. // create separate VBOs per geometry chunk
  12772. for ( var i = 0, il = geometryGroupsList.length; i < il; i ++ ) {
  12773. var geometryGroup = geometryGroupsList[ i ];
  12774. // initialise VBO on the first access
  12775. if ( geometryGroup.__webglVertexBuffer === undefined ) {
  12776. createMeshBuffers( geometryGroup );
  12777. initMeshBuffers( geometryGroup, object );
  12778. geometry.verticesNeedUpdate = true;
  12779. geometry.morphTargetsNeedUpdate = true;
  12780. geometry.elementsNeedUpdate = true;
  12781. geometry.uvsNeedUpdate = true;
  12782. geometry.normalsNeedUpdate = true;
  12783. geometry.tangentsNeedUpdate = true;
  12784. geometry.colorsNeedUpdate = true;
  12785. addBuffers = true;
  12786. } else {
  12787. addBuffers = false;
  12788. }
  12789. if ( addBuffers || object.__webglActive === undefined ) {
  12790. addBuffer( _webglObjects, geometryGroup, object );
  12791. }
  12792. }
  12793. object.__webglActive = true;
  12794. }
  12795. function addBuffer( objlist, buffer, object ) {
  12796. var id = object.id;
  12797. objlist[id] = objlist[id] || [];
  12798. objlist[id].push(
  12799. {
  12800. id: id,
  12801. buffer: buffer,
  12802. object: object,
  12803. material: null,
  12804. z: 0
  12805. }
  12806. );
  12807. };
  12808. function addBufferImmediate( objlist, object ) {
  12809. objlist.push(
  12810. {
  12811. id: null,
  12812. object: object,
  12813. opaque: null,
  12814. transparent: null,
  12815. z: 0
  12816. }
  12817. );
  12818. };
  12819. // Objects updates
  12820. function updateObject( object ) {
  12821. var geometry = object.geometry;
  12822. if ( geometry instanceof THREE.BufferGeometry ) {
  12823. var attributes = geometry.attributes;
  12824. var attributesKeys = geometry.attributesKeys;
  12825. for ( var i = 0, l = attributesKeys.length; i < l; i ++ ) {
  12826. var key = attributesKeys[ i ];
  12827. var attribute = attributes[ key ];
  12828. var bufferType = ( key === 'index' ) ? _gl.ELEMENT_ARRAY_BUFFER : _gl.ARRAY_BUFFER;
  12829. if ( attribute.buffer === undefined ) {
  12830. attribute.buffer = _gl.createBuffer();
  12831. _gl.bindBuffer( bufferType, attribute.buffer );
  12832. _gl.bufferData( bufferType, attribute.array, ( attribute instanceof THREE.DynamicBufferAttribute ) ? _gl.DYNAMIC_DRAW : _gl.STATIC_DRAW );
  12833. attribute.needsUpdate = false;
  12834. } else if ( attribute.needsUpdate === true ) {
  12835. _gl.bindBuffer( bufferType, attribute.buffer );
  12836. if ( attribute.updateRange === undefined || attribute.updateRange.count === -1 ) { // Not using update ranges
  12837. _gl.bufferSubData( bufferType, 0, attribute.array );
  12838. } else if ( attribute.updateRange.count === 0 ) {
  12839. console.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.' );
  12840. } else {
  12841. _gl.bufferSubData( bufferType, attribute.updateRange.offset * attribute.array.BYTES_PER_ELEMENT,
  12842. attribute.array.subarray( attribute.updateRange.offset, attribute.updateRange.offset + attribute.updateRange.count ) );
  12843. attribute.updateRange.count = 0; // reset range
  12844. }
  12845. attribute.needsUpdate = false;
  12846. }
  12847. }
  12848. } else if ( object instanceof THREE.Mesh ) {
  12849. // check all geometry groups
  12850. if ( geometry.groupsNeedUpdate === true ) {
  12851. initGeometryGroups( object, geometry );
  12852. }
  12853. var geometryGroupsList = geometryGroups[ geometry.id ];
  12854. for ( var i = 0, il = geometryGroupsList.length; i < il; i ++ ) {
  12855. var geometryGroup = geometryGroupsList[ i ];
  12856. var material = getBufferMaterial( object, geometryGroup );
  12857. var customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12858. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  12859. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  12860. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  12861. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, ! geometry.dynamic, material );
  12862. }
  12863. }
  12864. geometry.verticesNeedUpdate = false;
  12865. geometry.morphTargetsNeedUpdate = false;
  12866. geometry.elementsNeedUpdate = false;
  12867. geometry.uvsNeedUpdate = false;
  12868. geometry.normalsNeedUpdate = false;
  12869. geometry.colorsNeedUpdate = false;
  12870. geometry.tangentsNeedUpdate = false;
  12871. material.attributes && clearCustomAttributes( material );
  12872. } else if ( object instanceof THREE.Line ) {
  12873. var material = getBufferMaterial( object, geometry );
  12874. var customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12875. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  12876. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  12877. }
  12878. geometry.verticesNeedUpdate = false;
  12879. geometry.colorsNeedUpdate = false;
  12880. geometry.lineDistancesNeedUpdate = false;
  12881. material.attributes && clearCustomAttributes( material );
  12882. } else if ( object instanceof THREE.PointCloud ) {
  12883. var material = getBufferMaterial( object, geometry );
  12884. var customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12885. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || customAttributesDirty ) {
  12886. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  12887. }
  12888. geometry.verticesNeedUpdate = false;
  12889. geometry.colorsNeedUpdate = false;
  12890. material.attributes && clearCustomAttributes( material );
  12891. }
  12892. }
  12893. // Objects updates - custom attributes check
  12894. function areCustomAttributesDirty( material ) {
  12895. for ( var name in material.attributes ) {
  12896. if ( material.attributes[ name ].needsUpdate ) return true;
  12897. }
  12898. return false;
  12899. }
  12900. function clearCustomAttributes( material ) {
  12901. for ( var name in material.attributes ) {
  12902. material.attributes[ name ].needsUpdate = false;
  12903. }
  12904. }
  12905. // Objects removal
  12906. function removeObject( object ) {
  12907. if ( object instanceof THREE.Mesh ||
  12908. object instanceof THREE.PointCloud ||
  12909. object instanceof THREE.Line ) {
  12910. delete _webglObjects[ object.id ];
  12911. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12912. removeInstances( _webglObjectsImmediate, object );
  12913. }
  12914. delete object.__webglInit;
  12915. delete object._modelViewMatrix;
  12916. delete object._normalMatrix;
  12917. delete object.__webglActive;
  12918. }
  12919. function removeInstances( objlist, object ) {
  12920. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  12921. if ( objlist[ o ].object === object ) {
  12922. objlist.splice( o, 1 );
  12923. }
  12924. }
  12925. }
  12926. // Materials
  12927. var shaderIDs = {
  12928. MeshDepthMaterial: 'depth',
  12929. MeshNormalMaterial: 'normal',
  12930. MeshBasicMaterial: 'basic',
  12931. MeshLambertMaterial: 'lambert',
  12932. MeshPhongMaterial: 'phong',
  12933. LineBasicMaterial: 'basic',
  12934. LineDashedMaterial: 'dashed',
  12935. PointCloudMaterial: 'particle_basic'
  12936. };
  12937. function initMaterial( material, lights, fog, object ) {
  12938. material.addEventListener( 'dispose', onMaterialDispose );
  12939. var shaderID = shaderIDs[ material.type ];
  12940. if ( shaderID ) {
  12941. var shader = THREE.ShaderLib[ shaderID ];
  12942. material.__webglShader = {
  12943. uniforms: THREE.UniformsUtils.clone( shader.uniforms ),
  12944. vertexShader: shader.vertexShader,
  12945. fragmentShader: shader.fragmentShader
  12946. }
  12947. } else {
  12948. material.__webglShader = {
  12949. uniforms: material.uniforms,
  12950. vertexShader: material.vertexShader,
  12951. fragmentShader: material.fragmentShader
  12952. }
  12953. }
  12954. // heuristics to create shader parameters according to lights in the scene
  12955. // (not to blow over maxLights budget)
  12956. var maxLightCount = allocateLights( lights );
  12957. var maxShadows = allocateShadows( lights );
  12958. var maxBones = allocateBones( object );
  12959. var parameters = {
  12960. precision: _precision,
  12961. supportsVertexTextures: _supportsVertexTextures,
  12962. map: !! material.map,
  12963. envMap: !! material.envMap,
  12964. envMapMode: material.envMap && material.envMap.mapping,
  12965. lightMap: !! material.lightMap,
  12966. bumpMap: !! material.bumpMap,
  12967. normalMap: !! material.normalMap,
  12968. specularMap: !! material.specularMap,
  12969. alphaMap: !! material.alphaMap,
  12970. combine: material.combine,
  12971. vertexColors: material.vertexColors,
  12972. fog: fog,
  12973. useFog: material.fog,
  12974. fogExp: fog instanceof THREE.FogExp2,
  12975. sizeAttenuation: material.sizeAttenuation,
  12976. logarithmicDepthBuffer: _logarithmicDepthBuffer,
  12977. skinning: material.skinning,
  12978. maxBones: maxBones,
  12979. useVertexTexture: _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  12980. morphTargets: material.morphTargets,
  12981. morphNormals: material.morphNormals,
  12982. maxMorphTargets: _this.maxMorphTargets,
  12983. maxMorphNormals: _this.maxMorphNormals,
  12984. maxDirLights: maxLightCount.directional,
  12985. maxPointLights: maxLightCount.point,
  12986. maxSpotLights: maxLightCount.spot,
  12987. maxHemiLights: maxLightCount.hemi,
  12988. maxShadows: maxShadows,
  12989. shadowMapEnabled: _this.shadowMapEnabled && object.receiveShadow && maxShadows > 0,
  12990. shadowMapType: _this.shadowMapType,
  12991. shadowMapDebug: _this.shadowMapDebug,
  12992. shadowMapCascade: _this.shadowMapCascade,
  12993. alphaTest: material.alphaTest,
  12994. metal: material.metal,
  12995. wrapAround: material.wrapAround,
  12996. doubleSided: material.side === THREE.DoubleSide,
  12997. flipSided: material.side === THREE.BackSide
  12998. };
  12999. // Generate code
  13000. var chunks = [];
  13001. if ( shaderID ) {
  13002. chunks.push( shaderID );
  13003. } else {
  13004. chunks.push( material.fragmentShader );
  13005. chunks.push( material.vertexShader );
  13006. }
  13007. if ( material.defines !== undefined ) {
  13008. for ( var name in material.defines ) {
  13009. chunks.push( name );
  13010. chunks.push( material.defines[ name ] );
  13011. }
  13012. }
  13013. for ( var name in parameters ) {
  13014. chunks.push( name );
  13015. chunks.push( parameters[ name ] );
  13016. }
  13017. var code = chunks.join();
  13018. var program;
  13019. // Check if code has been already compiled
  13020. for ( var p = 0, pl = _programs.length; p < pl; p ++ ) {
  13021. var programInfo = _programs[ p ];
  13022. if ( programInfo.code === code ) {
  13023. program = programInfo;
  13024. program.usedTimes ++;
  13025. break;
  13026. }
  13027. }
  13028. if ( program === undefined ) {
  13029. program = new THREE.WebGLProgram( _this, code, material, parameters );
  13030. _programs.push( program );
  13031. _this.info.memory.programs = _programs.length;
  13032. }
  13033. material.program = program;
  13034. var attributes = program.attributes;
  13035. if ( material.morphTargets ) {
  13036. material.numSupportedMorphTargets = 0;
  13037. var id, base = 'morphTarget';
  13038. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  13039. id = base + i;
  13040. if ( attributes[ id ] >= 0 ) {
  13041. material.numSupportedMorphTargets ++;
  13042. }
  13043. }
  13044. }
  13045. if ( material.morphNormals ) {
  13046. material.numSupportedMorphNormals = 0;
  13047. var id, base = 'morphNormal';
  13048. for ( i = 0; i < _this.maxMorphNormals; i ++ ) {
  13049. id = base + i;
  13050. if ( attributes[ id ] >= 0 ) {
  13051. material.numSupportedMorphNormals ++;
  13052. }
  13053. }
  13054. }
  13055. material.uniformsList = [];
  13056. for ( var u in material.__webglShader.uniforms ) {
  13057. var location = material.program.uniforms[ u ];
  13058. if ( location ) {
  13059. material.uniformsList.push( [ material.__webglShader.uniforms[ u ], location ] );
  13060. }
  13061. }
  13062. }
  13063. function setProgram( camera, lights, fog, material, object ) {
  13064. _usedTextureUnits = 0;
  13065. if ( material.needsUpdate ) {
  13066. if ( material.program ) deallocateMaterial( material );
  13067. initMaterial( material, lights, fog, object );
  13068. material.needsUpdate = false;
  13069. }
  13070. if ( material.morphTargets ) {
  13071. if ( ! object.__webglMorphTargetInfluences ) {
  13072. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  13073. }
  13074. }
  13075. var refreshProgram = false;
  13076. var refreshMaterial = false;
  13077. var refreshLights = false;
  13078. var program = material.program,
  13079. p_uniforms = program.uniforms,
  13080. m_uniforms = material.__webglShader.uniforms;
  13081. if ( program.id !== _currentProgram ) {
  13082. _gl.useProgram( program.program );
  13083. _currentProgram = program.id;
  13084. refreshProgram = true;
  13085. refreshMaterial = true;
  13086. refreshLights = true;
  13087. }
  13088. if ( material.id !== _currentMaterialId ) {
  13089. if ( _currentMaterialId === -1 ) refreshLights = true;
  13090. _currentMaterialId = material.id;
  13091. refreshMaterial = true;
  13092. }
  13093. if ( refreshProgram || camera !== _currentCamera ) {
  13094. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  13095. if ( _logarithmicDepthBuffer ) {
  13096. _gl.uniform1f( p_uniforms.logDepthBufFC, 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  13097. }
  13098. if ( camera !== _currentCamera ) _currentCamera = camera;
  13099. // load material specific uniforms
  13100. // (shader material also gets them for the sake of genericity)
  13101. if ( material instanceof THREE.ShaderMaterial ||
  13102. material instanceof THREE.MeshPhongMaterial ||
  13103. material.envMap ) {
  13104. if ( p_uniforms.cameraPosition !== null ) {
  13105. _vector3.setFromMatrixPosition( camera.matrixWorld );
  13106. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  13107. }
  13108. }
  13109. if ( material instanceof THREE.MeshPhongMaterial ||
  13110. material instanceof THREE.MeshLambertMaterial ||
  13111. material instanceof THREE.MeshBasicMaterial ||
  13112. material instanceof THREE.ShaderMaterial ||
  13113. material.skinning ) {
  13114. if ( p_uniforms.viewMatrix !== null ) {
  13115. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  13116. }
  13117. }
  13118. }
  13119. // skinning uniforms must be set even if material didn't change
  13120. // auto-setting of texture unit for bone texture must go before other textures
  13121. // not sure why, but otherwise weird things happen
  13122. if ( material.skinning ) {
  13123. if ( object.bindMatrix && p_uniforms.bindMatrix !== null ) {
  13124. _gl.uniformMatrix4fv( p_uniforms.bindMatrix, false, object.bindMatrix.elements );
  13125. }
  13126. if ( object.bindMatrixInverse && p_uniforms.bindMatrixInverse !== null ) {
  13127. _gl.uniformMatrix4fv( p_uniforms.bindMatrixInverse, false, object.bindMatrixInverse.elements );
  13128. }
  13129. if ( _supportsBoneTextures && object.skeleton && object.skeleton.useVertexTexture ) {
  13130. if ( p_uniforms.boneTexture !== null ) {
  13131. var textureUnit = getTextureUnit();
  13132. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  13133. _this.setTexture( object.skeleton.boneTexture, textureUnit );
  13134. }
  13135. if ( p_uniforms.boneTextureWidth !== null ) {
  13136. _gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth );
  13137. }
  13138. if ( p_uniforms.boneTextureHeight !== null ) {
  13139. _gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight );
  13140. }
  13141. } else if ( object.skeleton && object.skeleton.boneMatrices ) {
  13142. if ( p_uniforms.boneGlobalMatrices !== null ) {
  13143. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices );
  13144. }
  13145. }
  13146. }
  13147. if ( refreshMaterial ) {
  13148. // refresh uniforms common to several materials
  13149. if ( fog && material.fog ) {
  13150. refreshUniformsFog( m_uniforms, fog );
  13151. }
  13152. if ( material instanceof THREE.MeshPhongMaterial ||
  13153. material instanceof THREE.MeshLambertMaterial ||
  13154. material.lights ) {
  13155. if ( _lightsNeedUpdate ) {
  13156. refreshLights = true;
  13157. setupLights( lights );
  13158. _lightsNeedUpdate = false;
  13159. }
  13160. if ( refreshLights ) {
  13161. refreshUniformsLights( m_uniforms, _lights );
  13162. markUniformsLightsNeedsUpdate( m_uniforms, true );
  13163. } else {
  13164. markUniformsLightsNeedsUpdate( m_uniforms, false );
  13165. }
  13166. }
  13167. if ( material instanceof THREE.MeshBasicMaterial ||
  13168. material instanceof THREE.MeshLambertMaterial ||
  13169. material instanceof THREE.MeshPhongMaterial ) {
  13170. refreshUniformsCommon( m_uniforms, material );
  13171. }
  13172. // refresh single material specific uniforms
  13173. if ( material instanceof THREE.LineBasicMaterial ) {
  13174. refreshUniformsLine( m_uniforms, material );
  13175. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13176. refreshUniformsLine( m_uniforms, material );
  13177. refreshUniformsDash( m_uniforms, material );
  13178. } else if ( material instanceof THREE.PointCloudMaterial ) {
  13179. refreshUniformsParticle( m_uniforms, material );
  13180. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13181. refreshUniformsPhong( m_uniforms, material );
  13182. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13183. refreshUniformsLambert( m_uniforms, material );
  13184. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  13185. m_uniforms.mNear.value = camera.near;
  13186. m_uniforms.mFar.value = camera.far;
  13187. m_uniforms.opacity.value = material.opacity;
  13188. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13189. m_uniforms.opacity.value = material.opacity;
  13190. }
  13191. if ( object.receiveShadow && ! material._shadowPass ) {
  13192. refreshUniformsShadow( m_uniforms, lights );
  13193. }
  13194. // load common uniforms
  13195. loadUniformsGeneric( material.uniformsList );
  13196. }
  13197. loadUniformsMatrices( p_uniforms, object );
  13198. if ( p_uniforms.modelMatrix !== null ) {
  13199. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  13200. }
  13201. return program;
  13202. }
  13203. // Uniforms (refresh uniforms objects)
  13204. function refreshUniformsCommon ( uniforms, material ) {
  13205. uniforms.opacity.value = material.opacity;
  13206. uniforms.diffuse.value = material.color;
  13207. uniforms.map.value = material.map;
  13208. uniforms.lightMap.value = material.lightMap;
  13209. uniforms.specularMap.value = material.specularMap;
  13210. uniforms.alphaMap.value = material.alphaMap;
  13211. if ( material.bumpMap ) {
  13212. uniforms.bumpMap.value = material.bumpMap;
  13213. uniforms.bumpScale.value = material.bumpScale;
  13214. }
  13215. if ( material.normalMap ) {
  13216. uniforms.normalMap.value = material.normalMap;
  13217. uniforms.normalScale.value.copy( material.normalScale );
  13218. }
  13219. // uv repeat and offset setting priorities
  13220. // 1. color map
  13221. // 2. specular map
  13222. // 3. normal map
  13223. // 4. bump map
  13224. // 5. alpha map
  13225. var uvScaleMap;
  13226. if ( material.map ) {
  13227. uvScaleMap = material.map;
  13228. } else if ( material.specularMap ) {
  13229. uvScaleMap = material.specularMap;
  13230. } else if ( material.normalMap ) {
  13231. uvScaleMap = material.normalMap;
  13232. } else if ( material.bumpMap ) {
  13233. uvScaleMap = material.bumpMap;
  13234. } else if ( material.alphaMap ) {
  13235. uvScaleMap = material.alphaMap;
  13236. }
  13237. if ( uvScaleMap !== undefined ) {
  13238. var offset = uvScaleMap.offset;
  13239. var repeat = uvScaleMap.repeat;
  13240. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13241. }
  13242. uniforms.envMap.value = material.envMap;
  13243. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1;
  13244. uniforms.reflectivity.value = material.reflectivity;
  13245. uniforms.refractionRatio.value = material.refractionRatio;
  13246. }
  13247. function refreshUniformsLine ( uniforms, material ) {
  13248. uniforms.diffuse.value = material.color;
  13249. uniforms.opacity.value = material.opacity;
  13250. }
  13251. function refreshUniformsDash ( uniforms, material ) {
  13252. uniforms.dashSize.value = material.dashSize;
  13253. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13254. uniforms.scale.value = material.scale;
  13255. }
  13256. function refreshUniformsParticle ( uniforms, material ) {
  13257. uniforms.psColor.value = material.color;
  13258. uniforms.opacity.value = material.opacity;
  13259. uniforms.size.value = material.size;
  13260. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  13261. uniforms.map.value = material.map;
  13262. }
  13263. function refreshUniformsFog ( uniforms, fog ) {
  13264. uniforms.fogColor.value = fog.color;
  13265. if ( fog instanceof THREE.Fog ) {
  13266. uniforms.fogNear.value = fog.near;
  13267. uniforms.fogFar.value = fog.far;
  13268. } else if ( fog instanceof THREE.FogExp2 ) {
  13269. uniforms.fogDensity.value = fog.density;
  13270. }
  13271. }
  13272. function refreshUniformsPhong ( uniforms, material ) {
  13273. uniforms.shininess.value = material.shininess;
  13274. uniforms.emissive.value = material.emissive;
  13275. uniforms.specular.value = material.specular;
  13276. if ( material.wrapAround ) {
  13277. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13278. }
  13279. }
  13280. function refreshUniformsLambert ( uniforms, material ) {
  13281. uniforms.emissive.value = material.emissive;
  13282. if ( material.wrapAround ) {
  13283. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13284. }
  13285. }
  13286. function refreshUniformsLights ( uniforms, lights ) {
  13287. uniforms.ambientLightColor.value = lights.ambient;
  13288. uniforms.directionalLightColor.value = lights.directional.colors;
  13289. uniforms.directionalLightDirection.value = lights.directional.positions;
  13290. uniforms.pointLightColor.value = lights.point.colors;
  13291. uniforms.pointLightPosition.value = lights.point.positions;
  13292. uniforms.pointLightDistance.value = lights.point.distances;
  13293. uniforms.pointLightDecay.value = lights.point.decays;
  13294. uniforms.spotLightColor.value = lights.spot.colors;
  13295. uniforms.spotLightPosition.value = lights.spot.positions;
  13296. uniforms.spotLightDistance.value = lights.spot.distances;
  13297. uniforms.spotLightDirection.value = lights.spot.directions;
  13298. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  13299. uniforms.spotLightExponent.value = lights.spot.exponents;
  13300. uniforms.spotLightDecay.value = lights.spot.decays;
  13301. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  13302. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  13303. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  13304. }
  13305. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  13306. function markUniformsLightsNeedsUpdate ( uniforms, boolean ) {
  13307. uniforms.ambientLightColor.needsUpdate = boolean;
  13308. uniforms.directionalLightColor.needsUpdate = boolean;
  13309. uniforms.directionalLightDirection.needsUpdate = boolean;
  13310. uniforms.pointLightColor.needsUpdate = boolean;
  13311. uniforms.pointLightPosition.needsUpdate = boolean;
  13312. uniforms.pointLightDistance.needsUpdate = boolean;
  13313. uniforms.pointLightDecay.needsUpdate = boolean;
  13314. uniforms.spotLightColor.needsUpdate = boolean;
  13315. uniforms.spotLightPosition.needsUpdate = boolean;
  13316. uniforms.spotLightDistance.needsUpdate = boolean;
  13317. uniforms.spotLightDirection.needsUpdate = boolean;
  13318. uniforms.spotLightAngleCos.needsUpdate = boolean;
  13319. uniforms.spotLightExponent.needsUpdate = boolean;
  13320. uniforms.spotLightDecay.needsUpdate = boolean;
  13321. uniforms.hemisphereLightSkyColor.needsUpdate = boolean;
  13322. uniforms.hemisphereLightGroundColor.needsUpdate = boolean;
  13323. uniforms.hemisphereLightDirection.needsUpdate = boolean;
  13324. }
  13325. function refreshUniformsShadow ( uniforms, lights ) {
  13326. if ( uniforms.shadowMatrix ) {
  13327. var j = 0;
  13328. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  13329. var light = lights[ i ];
  13330. if ( ! light.castShadow ) continue;
  13331. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  13332. uniforms.shadowMap.value[ j ] = light.shadowMap;
  13333. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  13334. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  13335. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  13336. uniforms.shadowBias.value[ j ] = light.shadowBias;
  13337. j ++;
  13338. }
  13339. }
  13340. }
  13341. }
  13342. // Uniforms (load to GPU)
  13343. function loadUniformsMatrices ( uniforms, object ) {
  13344. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  13345. if ( uniforms.normalMatrix ) {
  13346. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  13347. }
  13348. }
  13349. function getTextureUnit() {
  13350. var textureUnit = _usedTextureUnits;
  13351. if ( textureUnit >= _maxTextures ) {
  13352. THREE.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + _maxTextures );
  13353. }
  13354. _usedTextureUnits += 1;
  13355. return textureUnit;
  13356. }
  13357. function loadUniformsGeneric ( uniforms ) {
  13358. var texture, textureUnit, offset;
  13359. for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) {
  13360. var uniform = uniforms[ j ][ 0 ];
  13361. // needsUpdate property is not added to all uniforms.
  13362. if ( uniform.needsUpdate === false ) continue;
  13363. var type = uniform.type;
  13364. var value = uniform.value;
  13365. var location = uniforms[ j ][ 1 ];
  13366. switch ( type ) {
  13367. case '1i':
  13368. _gl.uniform1i( location, value );
  13369. break;
  13370. case '1f':
  13371. _gl.uniform1f( location, value );
  13372. break;
  13373. case '2f':
  13374. _gl.uniform2f( location, value[ 0 ], value[ 1 ] );
  13375. break;
  13376. case '3f':
  13377. _gl.uniform3f( location, value[ 0 ], value[ 1 ], value[ 2 ] );
  13378. break;
  13379. case '4f':
  13380. _gl.uniform4f( location, value[ 0 ], value[ 1 ], value[ 2 ], value[ 3 ] );
  13381. break;
  13382. case '1iv':
  13383. _gl.uniform1iv( location, value );
  13384. break;
  13385. case '3iv':
  13386. _gl.uniform3iv( location, value );
  13387. break;
  13388. case '1fv':
  13389. _gl.uniform1fv( location, value );
  13390. break;
  13391. case '2fv':
  13392. _gl.uniform2fv( location, value );
  13393. break;
  13394. case '3fv':
  13395. _gl.uniform3fv( location, value );
  13396. break;
  13397. case '4fv':
  13398. _gl.uniform4fv( location, value );
  13399. break;
  13400. case 'Matrix3fv':
  13401. _gl.uniformMatrix3fv( location, false, value );
  13402. break;
  13403. case 'Matrix4fv':
  13404. _gl.uniformMatrix4fv( location, false, value );
  13405. break;
  13406. //
  13407. case 'i':
  13408. // single integer
  13409. _gl.uniform1i( location, value );
  13410. break;
  13411. case 'f':
  13412. // single float
  13413. _gl.uniform1f( location, value );
  13414. break;
  13415. case 'v2':
  13416. // single THREE.Vector2
  13417. _gl.uniform2f( location, value.x, value.y );
  13418. break;
  13419. case 'v3':
  13420. // single THREE.Vector3
  13421. _gl.uniform3f( location, value.x, value.y, value.z );
  13422. break;
  13423. case 'v4':
  13424. // single THREE.Vector4
  13425. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  13426. break;
  13427. case 'c':
  13428. // single THREE.Color
  13429. _gl.uniform3f( location, value.r, value.g, value.b );
  13430. break;
  13431. case 'iv1':
  13432. // flat array of integers (JS or typed array)
  13433. _gl.uniform1iv( location, value );
  13434. break;
  13435. case 'iv':
  13436. // flat array of integers with 3 x N size (JS or typed array)
  13437. _gl.uniform3iv( location, value );
  13438. break;
  13439. case 'fv1':
  13440. // flat array of floats (JS or typed array)
  13441. _gl.uniform1fv( location, value );
  13442. break;
  13443. case 'fv':
  13444. // flat array of floats with 3 x N size (JS or typed array)
  13445. _gl.uniform3fv( location, value );
  13446. break;
  13447. case 'v2v':
  13448. // array of THREE.Vector2
  13449. if ( uniform._array === undefined ) {
  13450. uniform._array = new Float32Array( 2 * value.length );
  13451. }
  13452. for ( var i = 0, il = value.length; i < il; i ++ ) {
  13453. offset = i * 2;
  13454. uniform._array[ offset ] = value[ i ].x;
  13455. uniform._array[ offset + 1 ] = value[ i ].y;
  13456. }
  13457. _gl.uniform2fv( location, uniform._array );
  13458. break;
  13459. case 'v3v':
  13460. // array of THREE.Vector3
  13461. if ( uniform._array === undefined ) {
  13462. uniform._array = new Float32Array( 3 * value.length );
  13463. }
  13464. for ( var i = 0, il = value.length; i < il; i ++ ) {
  13465. offset = i * 3;
  13466. uniform._array[ offset ] = value[ i ].x;
  13467. uniform._array[ offset + 1 ] = value[ i ].y;
  13468. uniform._array[ offset + 2 ] = value[ i ].z;
  13469. }
  13470. _gl.uniform3fv( location, uniform._array );
  13471. break;
  13472. case 'v4v':
  13473. // array of THREE.Vector4
  13474. if ( uniform._array === undefined ) {
  13475. uniform._array = new Float32Array( 4 * value.length );
  13476. }
  13477. for ( var i = 0, il = value.length; i < il; i ++ ) {
  13478. offset = i * 4;
  13479. uniform._array[ offset ] = value[ i ].x;
  13480. uniform._array[ offset + 1 ] = value[ i ].y;
  13481. uniform._array[ offset + 2 ] = value[ i ].z;
  13482. uniform._array[ offset + 3 ] = value[ i ].w;
  13483. }
  13484. _gl.uniform4fv( location, uniform._array );
  13485. break;
  13486. case 'm3':
  13487. // single THREE.Matrix3
  13488. _gl.uniformMatrix3fv( location, false, value.elements );
  13489. break;
  13490. case 'm3v':
  13491. // array of THREE.Matrix3
  13492. if ( uniform._array === undefined ) {
  13493. uniform._array = new Float32Array( 9 * value.length );
  13494. }
  13495. for ( var i = 0, il = value.length; i < il; i ++ ) {
  13496. value[ i ].flattenToArrayOffset( uniform._array, i * 9 );
  13497. }
  13498. _gl.uniformMatrix3fv( location, false, uniform._array );
  13499. break;
  13500. case 'm4':
  13501. // single THREE.Matrix4
  13502. _gl.uniformMatrix4fv( location, false, value.elements );
  13503. break;
  13504. case 'm4v':
  13505. // array of THREE.Matrix4
  13506. if ( uniform._array === undefined ) {
  13507. uniform._array = new Float32Array( 16 * value.length );
  13508. }
  13509. for ( var i = 0, il = value.length; i < il; i ++ ) {
  13510. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  13511. }
  13512. _gl.uniformMatrix4fv( location, false, uniform._array );
  13513. break;
  13514. case 't':
  13515. // single THREE.Texture (2d or cube)
  13516. texture = value;
  13517. textureUnit = getTextureUnit();
  13518. _gl.uniform1i( location, textureUnit );
  13519. if ( ! texture ) continue;
  13520. if ( texture instanceof THREE.CubeTexture ||
  13521. ( texture.image instanceof Array && texture.image.length === 6 ) ) { // CompressedTexture can have Array in image :/
  13522. setCubeTexture( texture, textureUnit );
  13523. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  13524. setCubeTextureDynamic( texture, textureUnit );
  13525. } else {
  13526. _this.setTexture( texture, textureUnit );
  13527. }
  13528. break;
  13529. case 'tv':
  13530. // array of THREE.Texture (2d)
  13531. if ( uniform._array === undefined ) {
  13532. uniform._array = [];
  13533. }
  13534. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  13535. uniform._array[ i ] = getTextureUnit();
  13536. }
  13537. _gl.uniform1iv( location, uniform._array );
  13538. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  13539. texture = uniform.value[ i ];
  13540. textureUnit = uniform._array[ i ];
  13541. if ( ! texture ) continue;
  13542. _this.setTexture( texture, textureUnit );
  13543. }
  13544. break;
  13545. default:
  13546. THREE.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  13547. }
  13548. }
  13549. }
  13550. function setupMatrices ( object, camera ) {
  13551. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  13552. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  13553. }
  13554. function setColorLinear( array, offset, color, intensity ) {
  13555. array[ offset ] = color.r * intensity;
  13556. array[ offset + 1 ] = color.g * intensity;
  13557. array[ offset + 2 ] = color.b * intensity;
  13558. }
  13559. function setupLights ( lights ) {
  13560. var l, ll, light, n,
  13561. r = 0, g = 0, b = 0,
  13562. color, skyColor, groundColor,
  13563. intensity, intensitySq,
  13564. position,
  13565. distance,
  13566. zlights = _lights,
  13567. dirColors = zlights.directional.colors,
  13568. dirPositions = zlights.directional.positions,
  13569. pointColors = zlights.point.colors,
  13570. pointPositions = zlights.point.positions,
  13571. pointDistances = zlights.point.distances,
  13572. pointDecays = zlights.point.decays,
  13573. spotColors = zlights.spot.colors,
  13574. spotPositions = zlights.spot.positions,
  13575. spotDistances = zlights.spot.distances,
  13576. spotDirections = zlights.spot.directions,
  13577. spotAnglesCos = zlights.spot.anglesCos,
  13578. spotExponents = zlights.spot.exponents,
  13579. spotDecays = zlights.spot.decays,
  13580. hemiSkyColors = zlights.hemi.skyColors,
  13581. hemiGroundColors = zlights.hemi.groundColors,
  13582. hemiPositions = zlights.hemi.positions,
  13583. dirLength = 0,
  13584. pointLength = 0,
  13585. spotLength = 0,
  13586. hemiLength = 0,
  13587. dirCount = 0,
  13588. pointCount = 0,
  13589. spotCount = 0,
  13590. hemiCount = 0,
  13591. dirOffset = 0,
  13592. pointOffset = 0,
  13593. spotOffset = 0,
  13594. hemiOffset = 0;
  13595. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  13596. light = lights[ l ];
  13597. if ( light.onlyShadow ) continue;
  13598. color = light.color;
  13599. intensity = light.intensity;
  13600. distance = light.distance;
  13601. if ( light instanceof THREE.AmbientLight ) {
  13602. if ( ! light.visible ) continue;
  13603. r += color.r;
  13604. g += color.g;
  13605. b += color.b;
  13606. } else if ( light instanceof THREE.DirectionalLight ) {
  13607. dirCount += 1;
  13608. if ( ! light.visible ) continue;
  13609. _direction.setFromMatrixPosition( light.matrixWorld );
  13610. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  13611. _direction.sub( _vector3 );
  13612. _direction.normalize();
  13613. dirOffset = dirLength * 3;
  13614. dirPositions[ dirOffset ] = _direction.x;
  13615. dirPositions[ dirOffset + 1 ] = _direction.y;
  13616. dirPositions[ dirOffset + 2 ] = _direction.z;
  13617. setColorLinear( dirColors, dirOffset, color, intensity );
  13618. dirLength += 1;
  13619. } else if ( light instanceof THREE.PointLight ) {
  13620. pointCount += 1;
  13621. if ( ! light.visible ) continue;
  13622. pointOffset = pointLength * 3;
  13623. setColorLinear( pointColors, pointOffset, color, intensity );
  13624. _vector3.setFromMatrixPosition( light.matrixWorld );
  13625. pointPositions[ pointOffset ] = _vector3.x;
  13626. pointPositions[ pointOffset + 1 ] = _vector3.y;
  13627. pointPositions[ pointOffset + 2 ] = _vector3.z;
  13628. // distance is 0 if decay is 0, because there is no attenuation at all.
  13629. pointDistances[ pointLength ] = distance;
  13630. pointDecays[ pointLength ] = ( light.distance === 0 ) ? 0.0 : light.decay;
  13631. pointLength += 1;
  13632. } else if ( light instanceof THREE.SpotLight ) {
  13633. spotCount += 1;
  13634. if ( ! light.visible ) continue;
  13635. spotOffset = spotLength * 3;
  13636. setColorLinear( spotColors, spotOffset, color, intensity );
  13637. _direction.setFromMatrixPosition( light.matrixWorld );
  13638. spotPositions[ spotOffset ] = _direction.x;
  13639. spotPositions[ spotOffset + 1 ] = _direction.y;
  13640. spotPositions[ spotOffset + 2 ] = _direction.z;
  13641. spotDistances[ spotLength ] = distance;
  13642. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  13643. _direction.sub( _vector3 );
  13644. _direction.normalize();
  13645. spotDirections[ spotOffset ] = _direction.x;
  13646. spotDirections[ spotOffset + 1 ] = _direction.y;
  13647. spotDirections[ spotOffset + 2 ] = _direction.z;
  13648. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  13649. spotExponents[ spotLength ] = light.exponent;
  13650. spotDecays[ spotLength ] = ( light.distance === 0 ) ? 0.0 : light.decay;
  13651. spotLength += 1;
  13652. } else if ( light instanceof THREE.HemisphereLight ) {
  13653. hemiCount += 1;
  13654. if ( ! light.visible ) continue;
  13655. _direction.setFromMatrixPosition( light.matrixWorld );
  13656. _direction.normalize();
  13657. hemiOffset = hemiLength * 3;
  13658. hemiPositions[ hemiOffset ] = _direction.x;
  13659. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  13660. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  13661. skyColor = light.color;
  13662. groundColor = light.groundColor;
  13663. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  13664. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  13665. hemiLength += 1;
  13666. }
  13667. }
  13668. // null eventual remains from removed lights
  13669. // (this is to avoid if in shader)
  13670. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  13671. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  13672. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  13673. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  13674. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  13675. zlights.directional.length = dirLength;
  13676. zlights.point.length = pointLength;
  13677. zlights.spot.length = spotLength;
  13678. zlights.hemi.length = hemiLength;
  13679. zlights.ambient[ 0 ] = r;
  13680. zlights.ambient[ 1 ] = g;
  13681. zlights.ambient[ 2 ] = b;
  13682. }
  13683. // GL state setting
  13684. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  13685. if ( cullFace === THREE.CullFaceNone ) {
  13686. _gl.disable( _gl.CULL_FACE );
  13687. } else {
  13688. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  13689. _gl.frontFace( _gl.CW );
  13690. } else {
  13691. _gl.frontFace( _gl.CCW );
  13692. }
  13693. if ( cullFace === THREE.CullFaceBack ) {
  13694. _gl.cullFace( _gl.BACK );
  13695. } else if ( cullFace === THREE.CullFaceFront ) {
  13696. _gl.cullFace( _gl.FRONT );
  13697. } else {
  13698. _gl.cullFace( _gl.FRONT_AND_BACK );
  13699. }
  13700. _gl.enable( _gl.CULL_FACE );
  13701. }
  13702. };
  13703. this.setMaterialFaces = function ( material ) {
  13704. var doubleSided = material.side === THREE.DoubleSide;
  13705. var flipSided = material.side === THREE.BackSide;
  13706. if ( _oldDoubleSided !== doubleSided ) {
  13707. if ( doubleSided ) {
  13708. _gl.disable( _gl.CULL_FACE );
  13709. } else {
  13710. _gl.enable( _gl.CULL_FACE );
  13711. }
  13712. _oldDoubleSided = doubleSided;
  13713. }
  13714. if ( _oldFlipSided !== flipSided ) {
  13715. if ( flipSided ) {
  13716. _gl.frontFace( _gl.CW );
  13717. } else {
  13718. _gl.frontFace( _gl.CCW );
  13719. }
  13720. _oldFlipSided = flipSided;
  13721. }
  13722. };
  13723. this.setDepthTest = function ( depthTest ) {
  13724. if ( _oldDepthTest !== depthTest ) {
  13725. if ( depthTest ) {
  13726. _gl.enable( _gl.DEPTH_TEST );
  13727. } else {
  13728. _gl.disable( _gl.DEPTH_TEST );
  13729. }
  13730. _oldDepthTest = depthTest;
  13731. }
  13732. };
  13733. this.setDepthWrite = function ( depthWrite ) {
  13734. if ( _oldDepthWrite !== depthWrite ) {
  13735. _gl.depthMask( depthWrite );
  13736. _oldDepthWrite = depthWrite;
  13737. }
  13738. };
  13739. function setLineWidth ( width ) {
  13740. width *= pixelRatio;
  13741. if ( width !== _oldLineWidth ) {
  13742. _gl.lineWidth( width );
  13743. _oldLineWidth = width;
  13744. }
  13745. }
  13746. function setPolygonOffset ( polygonoffset, factor, units ) {
  13747. if ( _oldPolygonOffset !== polygonoffset ) {
  13748. if ( polygonoffset ) {
  13749. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  13750. } else {
  13751. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  13752. }
  13753. _oldPolygonOffset = polygonoffset;
  13754. }
  13755. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  13756. _gl.polygonOffset( factor, units );
  13757. _oldPolygonOffsetFactor = factor;
  13758. _oldPolygonOffsetUnits = units;
  13759. }
  13760. }
  13761. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha ) {
  13762. if ( blending !== _oldBlending ) {
  13763. if ( blending === THREE.NoBlending ) {
  13764. _gl.disable( _gl.BLEND );
  13765. } else if ( blending === THREE.AdditiveBlending ) {
  13766. _gl.enable( _gl.BLEND );
  13767. _gl.blendEquation( _gl.FUNC_ADD );
  13768. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  13769. } else if ( blending === THREE.SubtractiveBlending ) {
  13770. // TODO: Find blendFuncSeparate() combination
  13771. _gl.enable( _gl.BLEND );
  13772. _gl.blendEquation( _gl.FUNC_ADD );
  13773. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  13774. } else if ( blending === THREE.MultiplyBlending ) {
  13775. // TODO: Find blendFuncSeparate() combination
  13776. _gl.enable( _gl.BLEND );
  13777. _gl.blendEquation( _gl.FUNC_ADD );
  13778. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  13779. } else if ( blending === THREE.CustomBlending ) {
  13780. _gl.enable( _gl.BLEND );
  13781. } else {
  13782. _gl.enable( _gl.BLEND );
  13783. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  13784. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  13785. }
  13786. _oldBlending = blending;
  13787. }
  13788. if ( blending === THREE.CustomBlending ) {
  13789. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13790. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13791. blendDstAlpha = blendDstAlpha || blendDst;
  13792. if ( blendEquation !== _oldBlendEquation || blendEquationAlpha !== _oldBlendEquationAlpha ) {
  13793. _gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  13794. _oldBlendEquation = blendEquation;
  13795. _oldBlendEquationAlpha = blendEquationAlpha;
  13796. }
  13797. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst || blendSrcAlpha !== _oldBlendSrcAlpha || blendDstAlpha !== _oldBlendDstAlpha ) {
  13798. _gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  13799. _oldBlendSrc = blendSrc;
  13800. _oldBlendDst = blendDst;
  13801. _oldBlendSrcAlpha = blendSrcAlpha;
  13802. _oldBlendDstAlpha = blendDstAlpha;
  13803. }
  13804. } else {
  13805. _oldBlendEquation = null;
  13806. _oldBlendSrc = null;
  13807. _oldBlendDst = null;
  13808. _oldBlendEquationAlpha = null;
  13809. _oldBlendSrcAlpha = null;
  13810. _oldBlendDstAlpha = null;
  13811. }
  13812. };
  13813. // Textures
  13814. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  13815. var extension;
  13816. if ( isImagePowerOfTwo ) {
  13817. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  13818. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  13819. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  13820. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  13821. } else {
  13822. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  13823. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  13824. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) {
  13825. THREE.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping. ( ' + texture.sourceFile + ' )' );
  13826. }
  13827. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  13828. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  13829. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) {
  13830. THREE.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter. ( ' + texture.sourceFile + ' )' );
  13831. }
  13832. }
  13833. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  13834. if ( extension && texture.type !== THREE.FloatType && texture.type !== THREE.HalfFloatType ) {
  13835. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  13836. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _this.getMaxAnisotropy() ) );
  13837. texture.__oldAnisotropy = texture.anisotropy;
  13838. }
  13839. }
  13840. }
  13841. this.uploadTexture = function ( texture ) {
  13842. if ( texture.__webglInit === undefined ) {
  13843. texture.__webglInit = true;
  13844. texture.addEventListener( 'dispose', onTextureDispose );
  13845. texture.__webglTexture = _gl.createTexture();
  13846. _this.info.memory.textures ++;
  13847. }
  13848. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13849. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13850. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  13851. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  13852. texture.image = clampToMaxSize( texture.image, _maxTextureSize );
  13853. var image = texture.image,
  13854. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  13855. glFormat = paramThreeToGL( texture.format ),
  13856. glType = paramThreeToGL( texture.type );
  13857. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  13858. var mipmap, mipmaps = texture.mipmaps;
  13859. if ( texture instanceof THREE.DataTexture ) {
  13860. // use manually created mipmaps if available
  13861. // if there are no manual mipmaps
  13862. // set 0 level mipmap and then use GL to generate other mipmap levels
  13863. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  13864. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13865. mipmap = mipmaps[ i ];
  13866. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13867. }
  13868. texture.generateMipmaps = false;
  13869. } else {
  13870. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13871. }
  13872. } else if ( texture instanceof THREE.CompressedTexture ) {
  13873. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13874. mipmap = mipmaps[ i ];
  13875. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  13876. if ( getCompressedTextureFormats().indexOf( glFormat ) > -1 ) {
  13877. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13878. } else {
  13879. THREE.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  13880. }
  13881. } else {
  13882. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13883. }
  13884. }
  13885. } else { // regular Texture (image, video, canvas)
  13886. // use manually created mipmaps if available
  13887. // if there are no manual mipmaps
  13888. // set 0 level mipmap and then use GL to generate other mipmap levels
  13889. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  13890. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13891. mipmap = mipmaps[ i ];
  13892. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  13893. }
  13894. texture.generateMipmaps = false;
  13895. } else {
  13896. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  13897. }
  13898. }
  13899. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13900. texture.needsUpdate = false;
  13901. if ( texture.onUpdate ) texture.onUpdate();
  13902. };
  13903. this.setTexture = function ( texture, slot ) {
  13904. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13905. if ( texture.needsUpdate ) {
  13906. _this.uploadTexture( texture );
  13907. } else {
  13908. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13909. }
  13910. };
  13911. function clampToMaxSize ( image, maxSize ) {
  13912. if ( image.width > maxSize || image.height > maxSize ) {
  13913. // Warning: Scaling through the canvas will only work with images that use
  13914. // premultiplied alpha.
  13915. var scale = maxSize / Math.max( image.width, image.height );
  13916. var canvas = document.createElement( 'canvas' );
  13917. canvas.width = Math.floor( image.width * scale );
  13918. canvas.height = Math.floor( image.height * scale );
  13919. var context = canvas.getContext( '2d' );
  13920. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  13921. THREE.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  13922. return canvas;
  13923. }
  13924. return image;
  13925. }
  13926. function setCubeTexture ( texture, slot ) {
  13927. if ( texture.image.length === 6 ) {
  13928. if ( texture.needsUpdate ) {
  13929. if ( ! texture.image.__webglTextureCube ) {
  13930. texture.addEventListener( 'dispose', onTextureDispose );
  13931. texture.image.__webglTextureCube = _gl.createTexture();
  13932. _this.info.memory.textures ++;
  13933. }
  13934. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13935. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13936. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13937. var isCompressed = texture instanceof THREE.CompressedTexture;
  13938. var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture;
  13939. var cubeImage = [];
  13940. for ( var i = 0; i < 6; i ++ ) {
  13941. if ( _this.autoScaleCubemaps && ! isCompressed && ! isDataTexture ) {
  13942. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  13943. } else {
  13944. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  13945. }
  13946. }
  13947. var image = cubeImage[ 0 ],
  13948. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  13949. glFormat = paramThreeToGL( texture.format ),
  13950. glType = paramThreeToGL( texture.type );
  13951. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  13952. for ( var i = 0; i < 6; i ++ ) {
  13953. if ( ! isCompressed ) {
  13954. if ( isDataTexture ) {
  13955. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  13956. } else {
  13957. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  13958. }
  13959. } else {
  13960. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  13961. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  13962. mipmap = mipmaps[ j ];
  13963. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  13964. if ( getCompressedTextureFormats().indexOf( glFormat ) > -1 ) {
  13965. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13966. } else {
  13967. THREE.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setCubeTexture()" );
  13968. }
  13969. } else {
  13970. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13971. }
  13972. }
  13973. }
  13974. }
  13975. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  13976. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13977. }
  13978. texture.needsUpdate = false;
  13979. if ( texture.onUpdate ) texture.onUpdate();
  13980. } else {
  13981. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13982. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13983. }
  13984. }
  13985. }
  13986. function setCubeTextureDynamic ( texture, slot ) {
  13987. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13988. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  13989. }
  13990. // Render targets
  13991. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  13992. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13993. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  13994. }
  13995. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  13996. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  13997. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13998. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  13999. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14000. /* For some reason this is not working. Defaulting to RGBA4.
  14001. } else if ( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14002. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  14003. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14004. */
  14005. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14006. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  14007. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14008. } else {
  14009. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  14010. }
  14011. }
  14012. this.setRenderTarget = function ( renderTarget ) {
  14013. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  14014. if ( renderTarget && renderTarget.__webglFramebuffer === undefined ) {
  14015. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  14016. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  14017. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14018. renderTarget.__webglTexture = _gl.createTexture();
  14019. _this.info.memory.textures ++;
  14020. // Setup texture, create render and frame buffers
  14021. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ),
  14022. glFormat = paramThreeToGL( renderTarget.format ),
  14023. glType = paramThreeToGL( renderTarget.type );
  14024. if ( isCube ) {
  14025. renderTarget.__webglFramebuffer = [];
  14026. renderTarget.__webglRenderbuffer = [];
  14027. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14028. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  14029. for ( var i = 0; i < 6; i ++ ) {
  14030. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14031. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  14032. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14033. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  14034. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  14035. }
  14036. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14037. } else {
  14038. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  14039. if ( renderTarget.shareDepthFrom ) {
  14040. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  14041. } else {
  14042. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  14043. }
  14044. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14045. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  14046. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14047. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  14048. if ( renderTarget.shareDepthFrom ) {
  14049. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14050. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14051. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14052. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14053. }
  14054. } else {
  14055. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  14056. }
  14057. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14058. }
  14059. // Release everything
  14060. if ( isCube ) {
  14061. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14062. } else {
  14063. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14064. }
  14065. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14066. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14067. }
  14068. var framebuffer, width, height, vx, vy;
  14069. if ( renderTarget ) {
  14070. if ( isCube ) {
  14071. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  14072. } else {
  14073. framebuffer = renderTarget.__webglFramebuffer;
  14074. }
  14075. width = renderTarget.width;
  14076. height = renderTarget.height;
  14077. vx = 0;
  14078. vy = 0;
  14079. } else {
  14080. framebuffer = null;
  14081. width = _viewportWidth;
  14082. height = _viewportHeight;
  14083. vx = _viewportX;
  14084. vy = _viewportY;
  14085. }
  14086. if ( framebuffer !== _currentFramebuffer ) {
  14087. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14088. _gl.viewport( vx, vy, width, height );
  14089. _currentFramebuffer = framebuffer;
  14090. }
  14091. _currentWidth = width;
  14092. _currentHeight = height;
  14093. };
  14094. this.readRenderTargetPixels = function( renderTarget, x, y, width, height, buffer ) {
  14095. if ( ! ( renderTarget instanceof THREE.WebGLRenderTarget ) ) {
  14096. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  14097. return;
  14098. }
  14099. if ( renderTarget.__webglFramebuffer ) {
  14100. if ( renderTarget.format !== THREE.RGBAFormat ) {
  14101. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA format. readPixels can read only RGBA format.' );
  14102. return;
  14103. }
  14104. var restore = false;
  14105. if ( renderTarget.__webglFramebuffer !== _currentFramebuffer ) {
  14106. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTarget.__webglFramebuffer );
  14107. restore = true;
  14108. }
  14109. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  14110. _gl.readPixels( x, y, width, height, _gl.RGBA, _gl.UNSIGNED_BYTE, buffer );
  14111. } else {
  14112. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  14113. }
  14114. if ( restore ) {
  14115. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  14116. }
  14117. }
  14118. };
  14119. function updateRenderTargetMipmap ( renderTarget ) {
  14120. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  14121. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14122. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14123. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14124. } else {
  14125. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14126. _gl.generateMipmap( _gl.TEXTURE_2D );
  14127. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14128. }
  14129. }
  14130. // Fallback filters for non-power-of-2 textures
  14131. function filterFallback ( f ) {
  14132. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  14133. return _gl.NEAREST;
  14134. }
  14135. return _gl.LINEAR;
  14136. }
  14137. // Map three.js constants to WebGL constants
  14138. function paramThreeToGL ( p ) {
  14139. var extension;
  14140. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  14141. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  14142. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  14143. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  14144. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  14145. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  14146. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  14147. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  14148. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  14149. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  14150. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  14151. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  14152. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  14153. if ( p === THREE.ByteType ) return _gl.BYTE;
  14154. if ( p === THREE.ShortType ) return _gl.SHORT;
  14155. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  14156. if ( p === THREE.IntType ) return _gl.INT;
  14157. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  14158. if ( p === THREE.FloatType ) return _gl.FLOAT;
  14159. extension = extensions.get( 'OES_texture_half_float' );
  14160. if ( extension !== null ) {
  14161. if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES;
  14162. }
  14163. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  14164. if ( p === THREE.RGBFormat ) return _gl.RGB;
  14165. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  14166. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  14167. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  14168. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  14169. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  14170. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  14171. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  14172. if ( p === THREE.OneFactor ) return _gl.ONE;
  14173. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  14174. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  14175. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  14176. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  14177. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  14178. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  14179. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  14180. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  14181. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  14182. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  14183. if ( extension !== null ) {
  14184. if ( p === THREE.RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14185. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14186. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14187. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14188. }
  14189. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  14190. if ( extension !== null ) {
  14191. if ( p === THREE.RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14192. if ( p === THREE.RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14193. if ( p === THREE.RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14194. if ( p === THREE.RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14195. }
  14196. extension = extensions.get( 'EXT_blend_minmax' );
  14197. if ( extension !== null ) {
  14198. if ( p === THREE.MinEquation ) return extension.MIN_EXT;
  14199. if ( p === THREE.MaxEquation ) return extension.MAX_EXT;
  14200. }
  14201. return 0;
  14202. }
  14203. // Allocations
  14204. function allocateBones ( object ) {
  14205. if ( _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  14206. return 1024;
  14207. } else {
  14208. // default for when object is not specified
  14209. // ( for example when prebuilding shader
  14210. // to be used with multiple objects )
  14211. //
  14212. // - leave some extra space for other uniforms
  14213. // - limit here is ANGLE's 254 max uniform vectors
  14214. // (up to 54 should be safe)
  14215. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  14216. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  14217. var maxBones = nVertexMatrices;
  14218. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  14219. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  14220. if ( maxBones < object.skeleton.bones.length ) {
  14221. THREE.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  14222. }
  14223. }
  14224. return maxBones;
  14225. }
  14226. }
  14227. function allocateLights( lights ) {
  14228. var dirLights = 0;
  14229. var pointLights = 0;
  14230. var spotLights = 0;
  14231. var hemiLights = 0;
  14232. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  14233. var light = lights[ l ];
  14234. if ( light.onlyShadow || light.visible === false ) continue;
  14235. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  14236. if ( light instanceof THREE.PointLight ) pointLights ++;
  14237. if ( light instanceof THREE.SpotLight ) spotLights ++;
  14238. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  14239. }
  14240. return { 'directional': dirLights, 'point': pointLights, 'spot': spotLights, 'hemi': hemiLights };
  14241. }
  14242. function allocateShadows( lights ) {
  14243. var maxShadows = 0;
  14244. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  14245. var light = lights[ l ];
  14246. if ( ! light.castShadow ) continue;
  14247. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  14248. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  14249. }
  14250. return maxShadows;
  14251. }
  14252. // DEPRECATED
  14253. this.initMaterial = function () {
  14254. THREE.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  14255. };
  14256. this.addPrePlugin = function () {
  14257. THREE.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  14258. };
  14259. this.addPostPlugin = function () {
  14260. THREE.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  14261. };
  14262. this.updateShadowMap = function () {
  14263. THREE.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  14264. };
  14265. };
  14266. // File:src/renderers/WebGLRenderTarget.js
  14267. /**
  14268. * @author szimek / https://github.com/szimek/
  14269. * @author alteredq / http://alteredqualia.com/
  14270. */
  14271. THREE.WebGLRenderTarget = function ( width, height, options ) {
  14272. this.width = width;
  14273. this.height = height;
  14274. options = options || {};
  14275. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  14276. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  14277. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  14278. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  14279. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  14280. this.offset = new THREE.Vector2( 0, 0 );
  14281. this.repeat = new THREE.Vector2( 1, 1 );
  14282. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  14283. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  14284. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  14285. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  14286. this.generateMipmaps = true;
  14287. this.shareDepthFrom = options.shareDepthFrom !== undefined ? options.shareDepthFrom : null;
  14288. };
  14289. THREE.WebGLRenderTarget.prototype = {
  14290. constructor: THREE.WebGLRenderTarget,
  14291. setSize: function ( width, height ) {
  14292. this.width = width;
  14293. this.height = height;
  14294. },
  14295. clone: function () {
  14296. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  14297. tmp.wrapS = this.wrapS;
  14298. tmp.wrapT = this.wrapT;
  14299. tmp.magFilter = this.magFilter;
  14300. tmp.minFilter = this.minFilter;
  14301. tmp.anisotropy = this.anisotropy;
  14302. tmp.offset.copy( this.offset );
  14303. tmp.repeat.copy( this.repeat );
  14304. tmp.format = this.format;
  14305. tmp.type = this.type;
  14306. tmp.depthBuffer = this.depthBuffer;
  14307. tmp.stencilBuffer = this.stencilBuffer;
  14308. tmp.generateMipmaps = this.generateMipmaps;
  14309. tmp.shareDepthFrom = this.shareDepthFrom;
  14310. return tmp;
  14311. },
  14312. dispose: function () {
  14313. this.dispatchEvent( { type: 'dispose' } );
  14314. }
  14315. };
  14316. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  14317. // File:src/renderers/WebGLRenderTargetCube.js
  14318. /**
  14319. * @author alteredq / http://alteredqualia.com
  14320. */
  14321. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  14322. THREE.WebGLRenderTarget.call( this, width, height, options );
  14323. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  14324. };
  14325. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  14326. THREE.WebGLRenderTargetCube.prototype.constructor = THREE.WebGLRenderTargetCube;
  14327. // File:src/renderers/webgl/WebGLExtensions.js
  14328. /**
  14329. * @author mrdoob / http://mrdoob.com/
  14330. */
  14331. THREE.WebGLExtensions = function ( gl ) {
  14332. var extensions = {};
  14333. this.get = function ( name ) {
  14334. if ( extensions[ name ] !== undefined ) {
  14335. return extensions[ name ];
  14336. }
  14337. var extension;
  14338. switch ( name ) {
  14339. case 'EXT_texture_filter_anisotropic':
  14340. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  14341. break;
  14342. case 'WEBGL_compressed_texture_s3tc':
  14343. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  14344. break;
  14345. case 'WEBGL_compressed_texture_pvrtc':
  14346. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  14347. break;
  14348. default:
  14349. extension = gl.getExtension( name );
  14350. }
  14351. if ( extension === null ) {
  14352. THREE.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  14353. }
  14354. extensions[ name ] = extension;
  14355. return extension;
  14356. };
  14357. };
  14358. // File:src/renderers/webgl/WebGLProgram.js
  14359. THREE.WebGLProgram = ( function () {
  14360. var programIdCount = 0;
  14361. var generateDefines = function ( defines ) {
  14362. var value, chunk, chunks = [];
  14363. for ( var d in defines ) {
  14364. value = defines[ d ];
  14365. if ( value === false ) continue;
  14366. chunk = '#define ' + d + ' ' + value;
  14367. chunks.push( chunk );
  14368. }
  14369. return chunks.join( '\n' );
  14370. };
  14371. var cacheUniformLocations = function ( gl, program, identifiers ) {
  14372. var uniforms = {};
  14373. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  14374. var id = identifiers[ i ];
  14375. uniforms[ id ] = gl.getUniformLocation( program, id );
  14376. }
  14377. return uniforms;
  14378. };
  14379. var cacheAttributeLocations = function ( gl, program, identifiers ) {
  14380. var attributes = {};
  14381. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  14382. var id = identifiers[ i ];
  14383. attributes[ id ] = gl.getAttribLocation( program, id );
  14384. }
  14385. return attributes;
  14386. };
  14387. return function ( renderer, code, material, parameters ) {
  14388. var _this = renderer;
  14389. var _gl = _this.context;
  14390. var defines = material.defines;
  14391. var uniforms = material.__webglShader.uniforms;
  14392. var attributes = material.attributes;
  14393. var vertexShader = material.__webglShader.vertexShader;
  14394. var fragmentShader = material.__webglShader.fragmentShader;
  14395. var index0AttributeName = material.index0AttributeName;
  14396. if ( index0AttributeName === undefined && parameters.morphTargets === true ) {
  14397. // programs with morphTargets displace position out of attribute 0
  14398. index0AttributeName = 'position';
  14399. }
  14400. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  14401. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  14402. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  14403. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  14404. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  14405. }
  14406. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  14407. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  14408. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  14409. if ( parameters.envMap ) {
  14410. switch ( material.envMap.mapping ) {
  14411. case THREE.CubeReflectionMapping:
  14412. case THREE.CubeRefractionMapping:
  14413. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  14414. break;
  14415. case THREE.EquirectangularReflectionMapping:
  14416. case THREE.EquirectangularRefractionMapping:
  14417. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  14418. break;
  14419. case THREE.SphericalReflectionMapping:
  14420. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  14421. break;
  14422. }
  14423. switch ( material.envMap.mapping ) {
  14424. case THREE.CubeRefractionMapping:
  14425. case THREE.EquirectangularRefractionMapping:
  14426. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  14427. break;
  14428. }
  14429. switch ( material.combine ) {
  14430. case THREE.MultiplyOperation:
  14431. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  14432. break;
  14433. case THREE.MixOperation:
  14434. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  14435. break;
  14436. case THREE.AddOperation:
  14437. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  14438. break;
  14439. }
  14440. }
  14441. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  14442. // console.log( 'building new program ' );
  14443. //
  14444. var customDefines = generateDefines( defines );
  14445. //
  14446. var program = _gl.createProgram();
  14447. var prefix_vertex, prefix_fragment;
  14448. if ( material instanceof THREE.RawShaderMaterial ) {
  14449. prefix_vertex = '';
  14450. prefix_fragment = '';
  14451. } else {
  14452. prefix_vertex = [
  14453. 'precision ' + parameters.precision + ' float;',
  14454. 'precision ' + parameters.precision + ' int;',
  14455. customDefines,
  14456. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  14457. _this.gammaInput ? '#define GAMMA_INPUT' : '',
  14458. _this.gammaOutput ? '#define GAMMA_OUTPUT' : '',
  14459. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  14460. '#define MAX_DIR_LIGHTS ' + parameters.maxDirLights,
  14461. '#define MAX_POINT_LIGHTS ' + parameters.maxPointLights,
  14462. '#define MAX_SPOT_LIGHTS ' + parameters.maxSpotLights,
  14463. '#define MAX_HEMI_LIGHTS ' + parameters.maxHemiLights,
  14464. '#define MAX_SHADOWS ' + parameters.maxShadows,
  14465. '#define MAX_BONES ' + parameters.maxBones,
  14466. parameters.map ? '#define USE_MAP' : '',
  14467. parameters.envMap ? '#define USE_ENVMAP' : '',
  14468. parameters.envMap ? '#define ' + envMapModeDefine : '',
  14469. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  14470. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  14471. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  14472. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  14473. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  14474. parameters.vertexColors ? '#define USE_COLOR' : '',
  14475. parameters.skinning ? '#define USE_SKINNING' : '',
  14476. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  14477. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  14478. parameters.morphNormals ? '#define USE_MORPHNORMALS' : '',
  14479. parameters.wrapAround ? '#define WRAP_AROUND' : '',
  14480. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  14481. parameters.flipSided ? '#define FLIP_SIDED' : '',
  14482. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  14483. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  14484. parameters.shadowMapDebug ? '#define SHADOWMAP_DEBUG' : '',
  14485. parameters.shadowMapCascade ? '#define SHADOWMAP_CASCADE' : '',
  14486. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  14487. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  14488. //_this._glExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '',
  14489. 'uniform mat4 modelMatrix;',
  14490. 'uniform mat4 modelViewMatrix;',
  14491. 'uniform mat4 projectionMatrix;',
  14492. 'uniform mat4 viewMatrix;',
  14493. 'uniform mat3 normalMatrix;',
  14494. 'uniform vec3 cameraPosition;',
  14495. 'attribute vec3 position;',
  14496. 'attribute vec3 normal;',
  14497. 'attribute vec2 uv;',
  14498. 'attribute vec2 uv2;',
  14499. '#ifdef USE_COLOR',
  14500. ' attribute vec3 color;',
  14501. '#endif',
  14502. '#ifdef USE_MORPHTARGETS',
  14503. ' attribute vec3 morphTarget0;',
  14504. ' attribute vec3 morphTarget1;',
  14505. ' attribute vec3 morphTarget2;',
  14506. ' attribute vec3 morphTarget3;',
  14507. ' #ifdef USE_MORPHNORMALS',
  14508. ' attribute vec3 morphNormal0;',
  14509. ' attribute vec3 morphNormal1;',
  14510. ' attribute vec3 morphNormal2;',
  14511. ' attribute vec3 morphNormal3;',
  14512. ' #else',
  14513. ' attribute vec3 morphTarget4;',
  14514. ' attribute vec3 morphTarget5;',
  14515. ' attribute vec3 morphTarget6;',
  14516. ' attribute vec3 morphTarget7;',
  14517. ' #endif',
  14518. '#endif',
  14519. '#ifdef USE_SKINNING',
  14520. ' attribute vec4 skinIndex;',
  14521. ' attribute vec4 skinWeight;',
  14522. '#endif',
  14523. ''
  14524. ].join( '\n' );
  14525. prefix_fragment = [
  14526. 'precision ' + parameters.precision + ' float;',
  14527. 'precision ' + parameters.precision + ' int;',
  14528. ( parameters.bumpMap || parameters.normalMap ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  14529. customDefines,
  14530. '#define MAX_DIR_LIGHTS ' + parameters.maxDirLights,
  14531. '#define MAX_POINT_LIGHTS ' + parameters.maxPointLights,
  14532. '#define MAX_SPOT_LIGHTS ' + parameters.maxSpotLights,
  14533. '#define MAX_HEMI_LIGHTS ' + parameters.maxHemiLights,
  14534. '#define MAX_SHADOWS ' + parameters.maxShadows,
  14535. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest: '',
  14536. _this.gammaInput ? '#define GAMMA_INPUT' : '',
  14537. _this.gammaOutput ? '#define GAMMA_OUTPUT' : '',
  14538. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  14539. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  14540. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  14541. parameters.map ? '#define USE_MAP' : '',
  14542. parameters.envMap ? '#define USE_ENVMAP' : '',
  14543. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  14544. parameters.envMap ? '#define ' + envMapModeDefine : '',
  14545. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  14546. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  14547. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  14548. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  14549. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  14550. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  14551. parameters.vertexColors ? '#define USE_COLOR' : '',
  14552. parameters.metal ? '#define METAL' : '',
  14553. parameters.wrapAround ? '#define WRAP_AROUND' : '',
  14554. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  14555. parameters.flipSided ? '#define FLIP_SIDED' : '',
  14556. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  14557. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  14558. parameters.shadowMapDebug ? '#define SHADOWMAP_DEBUG' : '',
  14559. parameters.shadowMapCascade ? '#define SHADOWMAP_CASCADE' : '',
  14560. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  14561. //_this._glExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '',
  14562. 'uniform mat4 viewMatrix;',
  14563. 'uniform vec3 cameraPosition;',
  14564. ''
  14565. ].join( '\n' );
  14566. }
  14567. var glVertexShader = new THREE.WebGLShader( _gl, _gl.VERTEX_SHADER, prefix_vertex + vertexShader );
  14568. var glFragmentShader = new THREE.WebGLShader( _gl, _gl.FRAGMENT_SHADER, prefix_fragment + fragmentShader );
  14569. _gl.attachShader( program, glVertexShader );
  14570. _gl.attachShader( program, glFragmentShader );
  14571. if ( index0AttributeName !== undefined ) {
  14572. // Force a particular attribute to index 0.
  14573. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  14574. // And, color, for example is often automatically bound to index 0 so disabling it
  14575. _gl.bindAttribLocation( program, 0, index0AttributeName );
  14576. }
  14577. _gl.linkProgram( program );
  14578. var programLogInfo = _gl.getProgramInfoLog( program );
  14579. if ( _gl.getProgramParameter( program, _gl.LINK_STATUS ) === false ) {
  14580. THREE.error( 'THREE.WebGLProgram: shader error: ' + _gl.getError(), 'gl.VALIDATE_STATUS', _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ), 'gl.getPRogramInfoLog', programLogInfo );
  14581. }
  14582. if ( programLogInfo !== '' ) {
  14583. THREE.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()' + programLogInfo );
  14584. // THREE.warn( _gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  14585. // THREE.warn( _gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  14586. }
  14587. // clean up
  14588. _gl.deleteShader( glVertexShader );
  14589. _gl.deleteShader( glFragmentShader );
  14590. // cache uniform locations
  14591. var identifiers = [
  14592. 'viewMatrix',
  14593. 'modelViewMatrix',
  14594. 'projectionMatrix',
  14595. 'normalMatrix',
  14596. 'modelMatrix',
  14597. 'cameraPosition',
  14598. 'morphTargetInfluences',
  14599. 'bindMatrix',
  14600. 'bindMatrixInverse'
  14601. ];
  14602. if ( parameters.useVertexTexture ) {
  14603. identifiers.push( 'boneTexture' );
  14604. identifiers.push( 'boneTextureWidth' );
  14605. identifiers.push( 'boneTextureHeight' );
  14606. } else {
  14607. identifiers.push( 'boneGlobalMatrices' );
  14608. }
  14609. if ( parameters.logarithmicDepthBuffer ) {
  14610. identifiers.push('logDepthBufFC');
  14611. }
  14612. for ( var u in uniforms ) {
  14613. identifiers.push( u );
  14614. }
  14615. this.uniforms = cacheUniformLocations( _gl, program, identifiers );
  14616. // cache attributes locations
  14617. identifiers = [
  14618. 'position',
  14619. 'normal',
  14620. 'uv',
  14621. 'uv2',
  14622. 'tangent',
  14623. 'color',
  14624. 'skinIndex',
  14625. 'skinWeight',
  14626. 'lineDistance'
  14627. ];
  14628. for ( var i = 0; i < parameters.maxMorphTargets; i ++ ) {
  14629. identifiers.push( 'morphTarget' + i );
  14630. }
  14631. for ( var i = 0; i < parameters.maxMorphNormals; i ++ ) {
  14632. identifiers.push( 'morphNormal' + i );
  14633. }
  14634. for ( var a in attributes ) {
  14635. identifiers.push( a );
  14636. }
  14637. this.attributes = cacheAttributeLocations( _gl, program, identifiers );
  14638. this.attributesKeys = Object.keys( this.attributes );
  14639. //
  14640. this.id = programIdCount ++;
  14641. this.code = code;
  14642. this.usedTimes = 1;
  14643. this.program = program;
  14644. this.vertexShader = glVertexShader;
  14645. this.fragmentShader = glFragmentShader;
  14646. return this;
  14647. };
  14648. } )();
  14649. // File:src/renderers/webgl/WebGLShader.js
  14650. THREE.WebGLShader = ( function () {
  14651. var addLineNumbers = function ( string ) {
  14652. var lines = string.split( '\n' );
  14653. for ( var i = 0; i < lines.length; i ++ ) {
  14654. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  14655. }
  14656. return lines.join( '\n' );
  14657. };
  14658. return function ( gl, type, string ) {
  14659. var shader = gl.createShader( type );
  14660. gl.shaderSource( shader, string );
  14661. gl.compileShader( shader );
  14662. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  14663. THREE.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  14664. }
  14665. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  14666. THREE.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  14667. }
  14668. // --enable-privileged-webgl-extension
  14669. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  14670. return shader;
  14671. };
  14672. } )();
  14673. // File:src/renderers/webgl/plugins/LensFlarePlugin.js
  14674. /**
  14675. * @author mikael emtinger / http://gomo.se/
  14676. * @author alteredq / http://alteredqualia.com/
  14677. */
  14678. THREE.LensFlarePlugin = function ( renderer, flares ) {
  14679. var gl = renderer.context;
  14680. var vertexBuffer, elementBuffer;
  14681. var program, attributes, uniforms;
  14682. var hasVertexTexture;
  14683. var tempTexture, occlusionTexture;
  14684. var init = function () {
  14685. var vertices = new Float32Array( [
  14686. -1, -1, 0, 0,
  14687. 1, -1, 1, 0,
  14688. 1, 1, 1, 1,
  14689. -1, 1, 0, 1
  14690. ] );
  14691. var faces = new Uint16Array( [
  14692. 0, 1, 2,
  14693. 0, 2, 3
  14694. ] );
  14695. // buffers
  14696. vertexBuffer = gl.createBuffer();
  14697. elementBuffer = gl.createBuffer();
  14698. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  14699. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  14700. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  14701. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  14702. // textures
  14703. tempTexture = gl.createTexture();
  14704. occlusionTexture = gl.createTexture();
  14705. gl.bindTexture( gl.TEXTURE_2D, tempTexture );
  14706. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  14707. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  14708. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  14709. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  14710. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  14711. gl.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  14712. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  14713. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  14714. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  14715. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  14716. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  14717. hasVertexTexture = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) > 0;
  14718. var shader;
  14719. if ( hasVertexTexture ) {
  14720. shader = {
  14721. vertexShader: [
  14722. "uniform lowp int renderType;",
  14723. "uniform vec3 screenPosition;",
  14724. "uniform vec2 scale;",
  14725. "uniform float rotation;",
  14726. "uniform sampler2D occlusionMap;",
  14727. "attribute vec2 position;",
  14728. "attribute vec2 uv;",
  14729. "varying vec2 vUV;",
  14730. "varying float vVisibility;",
  14731. "void main() {",
  14732. "vUV = uv;",
  14733. "vec2 pos = position;",
  14734. "if( renderType == 2 ) {",
  14735. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  14736. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  14737. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  14738. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  14739. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  14740. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  14741. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  14742. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  14743. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  14744. "vVisibility = visibility.r / 9.0;",
  14745. "vVisibility *= 1.0 - visibility.g / 9.0;",
  14746. "vVisibility *= visibility.b / 9.0;",
  14747. "vVisibility *= 1.0 - visibility.a / 9.0;",
  14748. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  14749. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  14750. "}",
  14751. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  14752. "}"
  14753. ].join( "\n" ),
  14754. fragmentShader: [
  14755. "uniform lowp int renderType;",
  14756. "uniform sampler2D map;",
  14757. "uniform float opacity;",
  14758. "uniform vec3 color;",
  14759. "varying vec2 vUV;",
  14760. "varying float vVisibility;",
  14761. "void main() {",
  14762. // pink square
  14763. "if( renderType == 0 ) {",
  14764. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  14765. // restore
  14766. "} else if( renderType == 1 ) {",
  14767. "gl_FragColor = texture2D( map, vUV );",
  14768. // flare
  14769. "} else {",
  14770. "vec4 texture = texture2D( map, vUV );",
  14771. "texture.a *= opacity * vVisibility;",
  14772. "gl_FragColor = texture;",
  14773. "gl_FragColor.rgb *= color;",
  14774. "}",
  14775. "}"
  14776. ].join( "\n" )
  14777. };
  14778. } else {
  14779. shader = {
  14780. vertexShader: [
  14781. "uniform lowp int renderType;",
  14782. "uniform vec3 screenPosition;",
  14783. "uniform vec2 scale;",
  14784. "uniform float rotation;",
  14785. "attribute vec2 position;",
  14786. "attribute vec2 uv;",
  14787. "varying vec2 vUV;",
  14788. "void main() {",
  14789. "vUV = uv;",
  14790. "vec2 pos = position;",
  14791. "if( renderType == 2 ) {",
  14792. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  14793. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  14794. "}",
  14795. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  14796. "}"
  14797. ].join( "\n" ),
  14798. fragmentShader: [
  14799. "precision mediump float;",
  14800. "uniform lowp int renderType;",
  14801. "uniform sampler2D map;",
  14802. "uniform sampler2D occlusionMap;",
  14803. "uniform float opacity;",
  14804. "uniform vec3 color;",
  14805. "varying vec2 vUV;",
  14806. "void main() {",
  14807. // pink square
  14808. "if( renderType == 0 ) {",
  14809. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  14810. // restore
  14811. "} else if( renderType == 1 ) {",
  14812. "gl_FragColor = texture2D( map, vUV );",
  14813. // flare
  14814. "} else {",
  14815. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  14816. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  14817. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  14818. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  14819. "visibility = ( 1.0 - visibility / 4.0 );",
  14820. "vec4 texture = texture2D( map, vUV );",
  14821. "texture.a *= opacity * visibility;",
  14822. "gl_FragColor = texture;",
  14823. "gl_FragColor.rgb *= color;",
  14824. "}",
  14825. "}"
  14826. ].join( "\n" )
  14827. };
  14828. }
  14829. program = createProgram( shader );
  14830. attributes = {
  14831. vertex: gl.getAttribLocation ( program, "position" ),
  14832. uv: gl.getAttribLocation ( program, "uv" )
  14833. }
  14834. uniforms = {
  14835. renderType: gl.getUniformLocation( program, "renderType" ),
  14836. map: gl.getUniformLocation( program, "map" ),
  14837. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  14838. opacity: gl.getUniformLocation( program, "opacity" ),
  14839. color: gl.getUniformLocation( program, "color" ),
  14840. scale: gl.getUniformLocation( program, "scale" ),
  14841. rotation: gl.getUniformLocation( program, "rotation" ),
  14842. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  14843. };
  14844. };
  14845. /*
  14846. * Render lens flares
  14847. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  14848. * reads these back and calculates occlusion.
  14849. */
  14850. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  14851. if ( flares.length === 0 ) return;
  14852. var tempPosition = new THREE.Vector3();
  14853. var invAspect = viewportHeight / viewportWidth,
  14854. halfViewportWidth = viewportWidth * 0.5,
  14855. halfViewportHeight = viewportHeight * 0.5;
  14856. var size = 16 / viewportHeight,
  14857. scale = new THREE.Vector2( size * invAspect, size );
  14858. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  14859. screenPositionPixels = new THREE.Vector2( 1, 1 );
  14860. if ( program === undefined ) {
  14861. init();
  14862. }
  14863. gl.useProgram( program );
  14864. gl.enableVertexAttribArray( attributes.vertex );
  14865. gl.enableVertexAttribArray( attributes.uv );
  14866. // loop through all lens flares to update their occlusion and positions
  14867. // setup gl and common used attribs/unforms
  14868. gl.uniform1i( uniforms.occlusionMap, 0 );
  14869. gl.uniform1i( uniforms.map, 1 );
  14870. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  14871. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  14872. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  14873. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  14874. gl.disable( gl.CULL_FACE );
  14875. gl.depthMask( false );
  14876. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  14877. size = 16 / viewportHeight;
  14878. scale.set( size * invAspect, size );
  14879. // calc object screen position
  14880. var flare = flares[ i ];
  14881. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  14882. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  14883. tempPosition.applyProjection( camera.projectionMatrix );
  14884. // setup arrays for gl programs
  14885. screenPosition.copy( tempPosition )
  14886. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  14887. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  14888. // screen cull
  14889. if ( hasVertexTexture || (
  14890. screenPositionPixels.x > 0 &&
  14891. screenPositionPixels.x < viewportWidth &&
  14892. screenPositionPixels.y > 0 &&
  14893. screenPositionPixels.y < viewportHeight ) ) {
  14894. // save current RGB to temp texture
  14895. gl.activeTexture( gl.TEXTURE1 );
  14896. gl.bindTexture( gl.TEXTURE_2D, tempTexture );
  14897. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  14898. // render pink quad
  14899. gl.uniform1i( uniforms.renderType, 0 );
  14900. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  14901. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  14902. gl.disable( gl.BLEND );
  14903. gl.enable( gl.DEPTH_TEST );
  14904. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  14905. // copy result to occlusionMap
  14906. gl.activeTexture( gl.TEXTURE0 );
  14907. gl.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  14908. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  14909. // restore graphics
  14910. gl.uniform1i( uniforms.renderType, 1 );
  14911. gl.disable( gl.DEPTH_TEST );
  14912. gl.activeTexture( gl.TEXTURE1 );
  14913. gl.bindTexture( gl.TEXTURE_2D, tempTexture );
  14914. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  14915. // update object positions
  14916. flare.positionScreen.copy( screenPosition )
  14917. if ( flare.customUpdateCallback ) {
  14918. flare.customUpdateCallback( flare );
  14919. } else {
  14920. flare.updateLensFlares();
  14921. }
  14922. // render flares
  14923. gl.uniform1i( uniforms.renderType, 2 );
  14924. gl.enable( gl.BLEND );
  14925. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  14926. var sprite = flare.lensFlares[ j ];
  14927. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  14928. screenPosition.x = sprite.x;
  14929. screenPosition.y = sprite.y;
  14930. screenPosition.z = sprite.z;
  14931. size = sprite.size * sprite.scale / viewportHeight;
  14932. scale.x = size * invAspect;
  14933. scale.y = size;
  14934. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  14935. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  14936. gl.uniform1f( uniforms.rotation, sprite.rotation );
  14937. gl.uniform1f( uniforms.opacity, sprite.opacity );
  14938. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  14939. renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  14940. renderer.setTexture( sprite.texture, 1 );
  14941. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  14942. }
  14943. }
  14944. }
  14945. }
  14946. // restore gl
  14947. gl.enable( gl.CULL_FACE );
  14948. gl.enable( gl.DEPTH_TEST );
  14949. gl.depthMask( true );
  14950. renderer.resetGLState();
  14951. };
  14952. function createProgram ( shader ) {
  14953. var program = gl.createProgram();
  14954. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  14955. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  14956. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  14957. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  14958. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  14959. gl.compileShader( fragmentShader );
  14960. gl.compileShader( vertexShader );
  14961. gl.attachShader( program, fragmentShader );
  14962. gl.attachShader( program, vertexShader );
  14963. gl.linkProgram( program );
  14964. return program;
  14965. }
  14966. };
  14967. // File:src/renderers/webgl/plugins/ShadowMapPlugin.js
  14968. /**
  14969. * @author alteredq / http://alteredqualia.com/
  14970. */
  14971. THREE.ShadowMapPlugin = function ( _renderer, _lights, _webglObjects, _webglObjectsImmediate ) {
  14972. var _gl = _renderer.context;
  14973. var _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  14974. _frustum = new THREE.Frustum(),
  14975. _projScreenMatrix = new THREE.Matrix4(),
  14976. _min = new THREE.Vector3(),
  14977. _max = new THREE.Vector3(),
  14978. _matrixPosition = new THREE.Vector3(),
  14979. _renderList = [];
  14980. // init
  14981. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  14982. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  14983. _depthMaterial = new THREE.ShaderMaterial( {
  14984. uniforms: depthUniforms,
  14985. vertexShader: depthShader.vertexShader,
  14986. fragmentShader: depthShader.fragmentShader
  14987. } );
  14988. _depthMaterialMorph = new THREE.ShaderMaterial( {
  14989. uniforms: depthUniforms,
  14990. vertexShader: depthShader.vertexShader,
  14991. fragmentShader: depthShader.fragmentShader,
  14992. morphTargets: true
  14993. } );
  14994. _depthMaterialSkin = new THREE.ShaderMaterial( {
  14995. uniforms: depthUniforms,
  14996. vertexShader: depthShader.vertexShader,
  14997. fragmentShader: depthShader.fragmentShader,
  14998. skinning: true
  14999. } );
  15000. _depthMaterialMorphSkin = new THREE.ShaderMaterial( {
  15001. uniforms: depthUniforms,
  15002. vertexShader: depthShader.vertexShader,
  15003. fragmentShader: depthShader.fragmentShader,
  15004. morphTargets: true,
  15005. skinning: true
  15006. } );
  15007. _depthMaterial._shadowPass = true;
  15008. _depthMaterialMorph._shadowPass = true;
  15009. _depthMaterialSkin._shadowPass = true;
  15010. _depthMaterialMorphSkin._shadowPass = true;
  15011. this.render = function ( scene, camera ) {
  15012. if ( _renderer.shadowMapEnabled === false ) return;
  15013. var i, il, j, jl, n,
  15014. shadowMap, shadowMatrix, shadowCamera,
  15015. program, buffer, material,
  15016. webglObject, object, light,
  15017. lights = [],
  15018. k = 0,
  15019. fog = null;
  15020. // set GL state for depth map
  15021. _gl.clearColor( 1, 1, 1, 1 );
  15022. _gl.disable( _gl.BLEND );
  15023. _gl.enable( _gl.CULL_FACE );
  15024. _gl.frontFace( _gl.CCW );
  15025. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  15026. _gl.cullFace( _gl.FRONT );
  15027. } else {
  15028. _gl.cullFace( _gl.BACK );
  15029. }
  15030. _renderer.setDepthTest( true );
  15031. // preprocess lights
  15032. // - skip lights that are not casting shadows
  15033. // - create virtual lights for cascaded shadow maps
  15034. for ( i = 0, il = _lights.length; i < il; i ++ ) {
  15035. light = _lights[ i ];
  15036. if ( ! light.castShadow ) continue;
  15037. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  15038. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  15039. var virtualLight;
  15040. if ( ! light.shadowCascadeArray[ n ] ) {
  15041. virtualLight = createVirtualLight( light, n );
  15042. virtualLight.originalCamera = camera;
  15043. var gyro = new THREE.Gyroscope();
  15044. gyro.position.copy( light.shadowCascadeOffset );
  15045. gyro.add( virtualLight );
  15046. gyro.add( virtualLight.target );
  15047. camera.add( gyro );
  15048. light.shadowCascadeArray[ n ] = virtualLight;
  15049. //console.log( "Created virtualLight", virtualLight );
  15050. } else {
  15051. virtualLight = light.shadowCascadeArray[ n ];
  15052. }
  15053. updateVirtualLight( light, n );
  15054. lights[ k ] = virtualLight;
  15055. k ++;
  15056. }
  15057. } else {
  15058. lights[ k ] = light;
  15059. k ++;
  15060. }
  15061. }
  15062. // render depth map
  15063. for ( i = 0, il = lights.length; i < il; i ++ ) {
  15064. light = lights[ i ];
  15065. if ( ! light.shadowMap ) {
  15066. var shadowFilter = THREE.LinearFilter;
  15067. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  15068. shadowFilter = THREE.NearestFilter;
  15069. }
  15070. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  15071. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  15072. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  15073. light.shadowMatrix = new THREE.Matrix4();
  15074. }
  15075. if ( ! light.shadowCamera ) {
  15076. if ( light instanceof THREE.SpotLight ) {
  15077. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  15078. } else if ( light instanceof THREE.DirectionalLight ) {
  15079. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  15080. } else {
  15081. THREE.error( "THREE.ShadowMapPlugin: Unsupported light type for shadow", light );
  15082. continue;
  15083. }
  15084. scene.add( light.shadowCamera );
  15085. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  15086. }
  15087. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  15088. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  15089. scene.add( light.cameraHelper );
  15090. }
  15091. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  15092. updateShadowCamera( camera, light );
  15093. }
  15094. shadowMap = light.shadowMap;
  15095. shadowMatrix = light.shadowMatrix;
  15096. shadowCamera = light.shadowCamera;
  15097. //
  15098. shadowCamera.position.setFromMatrixPosition( light.matrixWorld );
  15099. _matrixPosition.setFromMatrixPosition( light.target.matrixWorld );
  15100. shadowCamera.lookAt( _matrixPosition );
  15101. shadowCamera.updateMatrixWorld();
  15102. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  15103. //
  15104. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  15105. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  15106. // compute shadow matrix
  15107. shadowMatrix.set(
  15108. 0.5, 0.0, 0.0, 0.5,
  15109. 0.0, 0.5, 0.0, 0.5,
  15110. 0.0, 0.0, 0.5, 0.5,
  15111. 0.0, 0.0, 0.0, 1.0
  15112. );
  15113. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  15114. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  15115. // update camera matrices and frustum
  15116. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  15117. _frustum.setFromMatrix( _projScreenMatrix );
  15118. // render shadow map
  15119. _renderer.setRenderTarget( shadowMap );
  15120. _renderer.clear();
  15121. // set object matrices & frustum culling
  15122. _renderList.length = 0;
  15123. projectObject( scene, scene, shadowCamera );
  15124. // render regular objects
  15125. var objectMaterial, useMorphing, useSkinning;
  15126. for ( j = 0, jl = _renderList.length; j < jl; j ++ ) {
  15127. webglObject = _renderList[ j ];
  15128. object = webglObject.object;
  15129. buffer = webglObject.buffer;
  15130. // culling is overriden globally for all objects
  15131. // while rendering depth map
  15132. // need to deal with MeshFaceMaterial somehow
  15133. // in that case just use the first of material.materials for now
  15134. // (proper solution would require to break objects by materials
  15135. // similarly to regular rendering and then set corresponding
  15136. // depth materials per each chunk instead of just once per object)
  15137. objectMaterial = getObjectMaterial( object );
  15138. useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  15139. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  15140. if ( object.customDepthMaterial ) {
  15141. material = object.customDepthMaterial;
  15142. } else if ( useSkinning ) {
  15143. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  15144. } else if ( useMorphing ) {
  15145. material = _depthMaterialMorph;
  15146. } else {
  15147. material = _depthMaterial;
  15148. }
  15149. _renderer.setMaterialFaces( objectMaterial );
  15150. if ( buffer instanceof THREE.BufferGeometry ) {
  15151. _renderer.renderBufferDirect( shadowCamera, _lights, fog, material, buffer, object );
  15152. } else {
  15153. _renderer.renderBuffer( shadowCamera, _lights, fog, material, buffer, object );
  15154. }
  15155. }
  15156. // set matrices and render immediate objects
  15157. for ( j = 0, jl = _webglObjectsImmediate.length; j < jl; j ++ ) {
  15158. webglObject = _webglObjectsImmediate[ j ];
  15159. object = webglObject.object;
  15160. if ( object.visible && object.castShadow ) {
  15161. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  15162. _renderer.renderImmediateObject( shadowCamera, _lights, fog, _depthMaterial, object );
  15163. }
  15164. }
  15165. }
  15166. // restore GL state
  15167. var clearColor = _renderer.getClearColor(),
  15168. clearAlpha = _renderer.getClearAlpha();
  15169. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  15170. _gl.enable( _gl.BLEND );
  15171. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  15172. _gl.cullFace( _gl.BACK );
  15173. }
  15174. _renderer.resetGLState();
  15175. };
  15176. function projectObject( scene, object, shadowCamera ){
  15177. if ( object.visible ) {
  15178. var webglObjects = _webglObjects[ object.id ];
  15179. if ( webglObjects && object.castShadow && (object.frustumCulled === false || _frustum.intersectsObject( object ) === true) ) {
  15180. for ( var i = 0, l = webglObjects.length; i < l; i ++ ) {
  15181. var webglObject = webglObjects[ i ];
  15182. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  15183. _renderList.push( webglObject );
  15184. }
  15185. }
  15186. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  15187. projectObject( scene, object.children[ i ], shadowCamera );
  15188. }
  15189. }
  15190. }
  15191. function createVirtualLight( light, cascade ) {
  15192. var virtualLight = new THREE.DirectionalLight();
  15193. virtualLight.isVirtual = true;
  15194. virtualLight.onlyShadow = true;
  15195. virtualLight.castShadow = true;
  15196. virtualLight.shadowCameraNear = light.shadowCameraNear;
  15197. virtualLight.shadowCameraFar = light.shadowCameraFar;
  15198. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  15199. virtualLight.shadowCameraRight = light.shadowCameraRight;
  15200. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  15201. virtualLight.shadowCameraTop = light.shadowCameraTop;
  15202. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  15203. virtualLight.shadowDarkness = light.shadowDarkness;
  15204. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  15205. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  15206. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  15207. virtualLight.pointsWorld = [];
  15208. virtualLight.pointsFrustum = [];
  15209. var pointsWorld = virtualLight.pointsWorld,
  15210. pointsFrustum = virtualLight.pointsFrustum;
  15211. for ( var i = 0; i < 8; i ++ ) {
  15212. pointsWorld[ i ] = new THREE.Vector3();
  15213. pointsFrustum[ i ] = new THREE.Vector3();
  15214. }
  15215. var nearZ = light.shadowCascadeNearZ[ cascade ];
  15216. var farZ = light.shadowCascadeFarZ[ cascade ];
  15217. pointsFrustum[ 0 ].set( - 1, - 1, nearZ );
  15218. pointsFrustum[ 1 ].set( 1, - 1, nearZ );
  15219. pointsFrustum[ 2 ].set( - 1, 1, nearZ );
  15220. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  15221. pointsFrustum[ 4 ].set( - 1, - 1, farZ );
  15222. pointsFrustum[ 5 ].set( 1, - 1, farZ );
  15223. pointsFrustum[ 6 ].set( - 1, 1, farZ );
  15224. pointsFrustum[ 7 ].set( 1, 1, farZ );
  15225. return virtualLight;
  15226. }
  15227. // Synchronize virtual light with the original light
  15228. function updateVirtualLight( light, cascade ) {
  15229. var virtualLight = light.shadowCascadeArray[ cascade ];
  15230. virtualLight.position.copy( light.position );
  15231. virtualLight.target.position.copy( light.target.position );
  15232. virtualLight.lookAt( virtualLight.target );
  15233. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  15234. virtualLight.shadowDarkness = light.shadowDarkness;
  15235. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  15236. var nearZ = light.shadowCascadeNearZ[ cascade ];
  15237. var farZ = light.shadowCascadeFarZ[ cascade ];
  15238. var pointsFrustum = virtualLight.pointsFrustum;
  15239. pointsFrustum[ 0 ].z = nearZ;
  15240. pointsFrustum[ 1 ].z = nearZ;
  15241. pointsFrustum[ 2 ].z = nearZ;
  15242. pointsFrustum[ 3 ].z = nearZ;
  15243. pointsFrustum[ 4 ].z = farZ;
  15244. pointsFrustum[ 5 ].z = farZ;
  15245. pointsFrustum[ 6 ].z = farZ;
  15246. pointsFrustum[ 7 ].z = farZ;
  15247. }
  15248. // Fit shadow camera's ortho frustum to camera frustum
  15249. function updateShadowCamera( camera, light ) {
  15250. var shadowCamera = light.shadowCamera,
  15251. pointsFrustum = light.pointsFrustum,
  15252. pointsWorld = light.pointsWorld;
  15253. _min.set( Infinity, Infinity, Infinity );
  15254. _max.set( - Infinity, - Infinity, - Infinity );
  15255. for ( var i = 0; i < 8; i ++ ) {
  15256. var p = pointsWorld[ i ];
  15257. p.copy( pointsFrustum[ i ] );
  15258. p.unproject( camera );
  15259. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  15260. if ( p.x < _min.x ) _min.x = p.x;
  15261. if ( p.x > _max.x ) _max.x = p.x;
  15262. if ( p.y < _min.y ) _min.y = p.y;
  15263. if ( p.y > _max.y ) _max.y = p.y;
  15264. if ( p.z < _min.z ) _min.z = p.z;
  15265. if ( p.z > _max.z ) _max.z = p.z;
  15266. }
  15267. shadowCamera.left = _min.x;
  15268. shadowCamera.right = _max.x;
  15269. shadowCamera.top = _max.y;
  15270. shadowCamera.bottom = _min.y;
  15271. // can't really fit near/far
  15272. //shadowCamera.near = _min.z;
  15273. //shadowCamera.far = _max.z;
  15274. shadowCamera.updateProjectionMatrix();
  15275. }
  15276. // For the moment just ignore objects that have multiple materials with different animation methods
  15277. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  15278. function getObjectMaterial( object ) {
  15279. return object.material instanceof THREE.MeshFaceMaterial
  15280. ? object.material.materials[ 0 ]
  15281. : object.material;
  15282. };
  15283. };
  15284. // File:src/renderers/webgl/plugins/SpritePlugin.js
  15285. /**
  15286. * @author mikael emtinger / http://gomo.se/
  15287. * @author alteredq / http://alteredqualia.com/
  15288. */
  15289. THREE.SpritePlugin = function ( renderer, sprites ) {
  15290. var gl = renderer.context;
  15291. var vertexBuffer, elementBuffer;
  15292. var program, attributes, uniforms;
  15293. var texture;
  15294. // decompose matrixWorld
  15295. var spritePosition = new THREE.Vector3();
  15296. var spriteRotation = new THREE.Quaternion();
  15297. var spriteScale = new THREE.Vector3();
  15298. var init = function () {
  15299. var vertices = new Float32Array( [
  15300. - 0.5, - 0.5, 0, 0,
  15301. 0.5, - 0.5, 1, 0,
  15302. 0.5, 0.5, 1, 1,
  15303. - 0.5, 0.5, 0, 1
  15304. ] );
  15305. var faces = new Uint16Array( [
  15306. 0, 1, 2,
  15307. 0, 2, 3
  15308. ] );
  15309. vertexBuffer = gl.createBuffer();
  15310. elementBuffer = gl.createBuffer();
  15311. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  15312. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  15313. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  15314. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  15315. program = createProgram();
  15316. attributes = {
  15317. position: gl.getAttribLocation ( program, 'position' ),
  15318. uv: gl.getAttribLocation ( program, 'uv' )
  15319. };
  15320. uniforms = {
  15321. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  15322. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  15323. rotation: gl.getUniformLocation( program, 'rotation' ),
  15324. scale: gl.getUniformLocation( program, 'scale' ),
  15325. color: gl.getUniformLocation( program, 'color' ),
  15326. map: gl.getUniformLocation( program, 'map' ),
  15327. opacity: gl.getUniformLocation( program, 'opacity' ),
  15328. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  15329. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  15330. fogType: gl.getUniformLocation( program, 'fogType' ),
  15331. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  15332. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  15333. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  15334. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  15335. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  15336. };
  15337. var canvas = document.createElement( 'canvas' );
  15338. canvas.width = 8;
  15339. canvas.height = 8;
  15340. var context = canvas.getContext( '2d' );
  15341. context.fillStyle = 'white';
  15342. context.fillRect( 0, 0, 8, 8 );
  15343. texture = new THREE.Texture( canvas );
  15344. texture.needsUpdate = true;
  15345. };
  15346. this.render = function ( scene, camera ) {
  15347. if ( sprites.length === 0 ) return;
  15348. // setup gl
  15349. if ( program === undefined ) {
  15350. init();
  15351. }
  15352. gl.useProgram( program );
  15353. gl.enableVertexAttribArray( attributes.position );
  15354. gl.enableVertexAttribArray( attributes.uv );
  15355. gl.disable( gl.CULL_FACE );
  15356. gl.enable( gl.BLEND );
  15357. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  15358. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  15359. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  15360. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  15361. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  15362. gl.activeTexture( gl.TEXTURE0 );
  15363. gl.uniform1i( uniforms.map, 0 );
  15364. var oldFogType = 0;
  15365. var sceneFogType = 0;
  15366. var fog = scene.fog;
  15367. if ( fog ) {
  15368. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  15369. if ( fog instanceof THREE.Fog ) {
  15370. gl.uniform1f( uniforms.fogNear, fog.near );
  15371. gl.uniform1f( uniforms.fogFar, fog.far );
  15372. gl.uniform1i( uniforms.fogType, 1 );
  15373. oldFogType = 1;
  15374. sceneFogType = 1;
  15375. } else if ( fog instanceof THREE.FogExp2 ) {
  15376. gl.uniform1f( uniforms.fogDensity, fog.density );
  15377. gl.uniform1i( uniforms.fogType, 2 );
  15378. oldFogType = 2;
  15379. sceneFogType = 2;
  15380. }
  15381. } else {
  15382. gl.uniform1i( uniforms.fogType, 0 );
  15383. oldFogType = 0;
  15384. sceneFogType = 0;
  15385. }
  15386. // update positions and sort
  15387. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  15388. var sprite = sprites[ i ];
  15389. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  15390. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  15391. }
  15392. sprites.sort( painterSortStable );
  15393. // render all sprites
  15394. var scale = [];
  15395. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  15396. var sprite = sprites[ i ];
  15397. var material = sprite.material;
  15398. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  15399. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  15400. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  15401. scale[ 0 ] = spriteScale.x;
  15402. scale[ 1 ] = spriteScale.y;
  15403. var fogType = 0;
  15404. if ( scene.fog && material.fog ) {
  15405. fogType = sceneFogType;
  15406. }
  15407. if ( oldFogType !== fogType ) {
  15408. gl.uniform1i( uniforms.fogType, fogType );
  15409. oldFogType = fogType;
  15410. }
  15411. if ( material.map !== null ) {
  15412. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  15413. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  15414. } else {
  15415. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  15416. gl.uniform2f( uniforms.uvScale, 1, 1 );
  15417. }
  15418. gl.uniform1f( uniforms.opacity, material.opacity );
  15419. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  15420. gl.uniform1f( uniforms.rotation, material.rotation );
  15421. gl.uniform2fv( uniforms.scale, scale );
  15422. renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  15423. renderer.setDepthTest( material.depthTest );
  15424. renderer.setDepthWrite( material.depthWrite );
  15425. if ( material.map && material.map.image && material.map.image.width ) {
  15426. renderer.setTexture( material.map, 0 );
  15427. } else {
  15428. renderer.setTexture( texture, 0 );
  15429. }
  15430. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  15431. }
  15432. // restore gl
  15433. gl.enable( gl.CULL_FACE );
  15434. renderer.resetGLState();
  15435. };
  15436. function createProgram () {
  15437. var program = gl.createProgram();
  15438. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  15439. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  15440. gl.shaderSource( vertexShader, [
  15441. 'precision ' + renderer.getPrecision() + ' float;',
  15442. 'uniform mat4 modelViewMatrix;',
  15443. 'uniform mat4 projectionMatrix;',
  15444. 'uniform float rotation;',
  15445. 'uniform vec2 scale;',
  15446. 'uniform vec2 uvOffset;',
  15447. 'uniform vec2 uvScale;',
  15448. 'attribute vec2 position;',
  15449. 'attribute vec2 uv;',
  15450. 'varying vec2 vUV;',
  15451. 'void main() {',
  15452. 'vUV = uvOffset + uv * uvScale;',
  15453. 'vec2 alignedPosition = position * scale;',
  15454. 'vec2 rotatedPosition;',
  15455. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  15456. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  15457. 'vec4 finalPosition;',
  15458. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  15459. 'finalPosition.xy += rotatedPosition;',
  15460. 'finalPosition = projectionMatrix * finalPosition;',
  15461. 'gl_Position = finalPosition;',
  15462. '}'
  15463. ].join( '\n' ) );
  15464. gl.shaderSource( fragmentShader, [
  15465. 'precision ' + renderer.getPrecision() + ' float;',
  15466. 'uniform vec3 color;',
  15467. 'uniform sampler2D map;',
  15468. 'uniform float opacity;',
  15469. 'uniform int fogType;',
  15470. 'uniform vec3 fogColor;',
  15471. 'uniform float fogDensity;',
  15472. 'uniform float fogNear;',
  15473. 'uniform float fogFar;',
  15474. 'uniform float alphaTest;',
  15475. 'varying vec2 vUV;',
  15476. 'void main() {',
  15477. 'vec4 texture = texture2D( map, vUV );',
  15478. 'if ( texture.a < alphaTest ) discard;',
  15479. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  15480. 'if ( fogType > 0 ) {',
  15481. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  15482. 'float fogFactor = 0.0;',
  15483. 'if ( fogType == 1 ) {',
  15484. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  15485. '} else {',
  15486. 'const float LOG2 = 1.442695;',
  15487. 'float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  15488. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  15489. '}',
  15490. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  15491. '}',
  15492. '}'
  15493. ].join( '\n' ) );
  15494. gl.compileShader( vertexShader );
  15495. gl.compileShader( fragmentShader );
  15496. gl.attachShader( program, vertexShader );
  15497. gl.attachShader( program, fragmentShader );
  15498. gl.linkProgram( program );
  15499. return program;
  15500. };
  15501. function painterSortStable ( a, b ) {
  15502. if ( a.z !== b.z ) {
  15503. return b.z - a.z;
  15504. } else {
  15505. return b.id - a.id;
  15506. }
  15507. };
  15508. };
  15509. // File:src/extras/GeometryUtils.js
  15510. /**
  15511. * @author mrdoob / http://mrdoob.com/
  15512. */
  15513. THREE.GeometryUtils = {
  15514. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  15515. THREE.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  15516. var matrix;
  15517. if ( geometry2 instanceof THREE.Mesh ) {
  15518. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  15519. matrix = geometry2.matrix;
  15520. geometry2 = geometry2.geometry;
  15521. }
  15522. geometry1.merge( geometry2, matrix, materialIndexOffset );
  15523. },
  15524. center: function ( geometry ) {
  15525. THREE.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  15526. return geometry.center();
  15527. }
  15528. };
  15529. // File:src/extras/ImageUtils.js
  15530. /**
  15531. * @author alteredq / http://alteredqualia.com/
  15532. * @author mrdoob / http://mrdoob.com/
  15533. * @author Daosheng Mu / https://github.com/DaoshengMu/
  15534. */
  15535. THREE.ImageUtils = {
  15536. crossOrigin: undefined,
  15537. loadTexture: function ( url, mapping, onLoad, onError ) {
  15538. var loader = new THREE.ImageLoader();
  15539. loader.crossOrigin = this.crossOrigin;
  15540. var texture = new THREE.Texture( undefined, mapping );
  15541. loader.load( url, function ( image ) {
  15542. texture.image = image;
  15543. texture.needsUpdate = true;
  15544. if ( onLoad ) onLoad( texture );
  15545. }, undefined, function ( event ) {
  15546. if ( onError ) onError( event );
  15547. } );
  15548. texture.sourceFile = url;
  15549. return texture;
  15550. },
  15551. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15552. var images = [];
  15553. var loader = new THREE.ImageLoader();
  15554. loader.crossOrigin = this.crossOrigin;
  15555. var texture = new THREE.CubeTexture( images, mapping );
  15556. // no flipping needed for cube textures
  15557. texture.flipY = false;
  15558. var loaded = 0;
  15559. var loadTexture = function ( i ) {
  15560. loader.load( array[ i ], function ( image ) {
  15561. texture.images[ i ] = image;
  15562. loaded += 1;
  15563. if ( loaded === 6 ) {
  15564. texture.needsUpdate = true;
  15565. if ( onLoad ) onLoad( texture );
  15566. }
  15567. }, undefined, onError );
  15568. }
  15569. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15570. loadTexture( i );
  15571. }
  15572. return texture;
  15573. },
  15574. loadCompressedTexture: function () {
  15575. THREE.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' )
  15576. },
  15577. loadCompressedTextureCube: function () {
  15578. THREE.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' )
  15579. },
  15580. getNormalMap: function ( image, depth ) {
  15581. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  15582. var cross = function ( a, b ) {
  15583. 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 ] ];
  15584. }
  15585. var subtract = function ( a, b ) {
  15586. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  15587. }
  15588. var normalize = function ( a ) {
  15589. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  15590. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  15591. }
  15592. depth = depth | 1;
  15593. var width = image.width;
  15594. var height = image.height;
  15595. var canvas = document.createElement( 'canvas' );
  15596. canvas.width = width;
  15597. canvas.height = height;
  15598. var context = canvas.getContext( '2d' );
  15599. context.drawImage( image, 0, 0 );
  15600. var data = context.getImageData( 0, 0, width, height ).data;
  15601. var imageData = context.createImageData( width, height );
  15602. var output = imageData.data;
  15603. for ( var x = 0; x < width; x ++ ) {
  15604. for ( var y = 0; y < height; y ++ ) {
  15605. var ly = y - 1 < 0 ? 0 : y - 1;
  15606. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  15607. var lx = x - 1 < 0 ? 0 : x - 1;
  15608. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  15609. var points = [];
  15610. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  15611. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  15612. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  15613. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  15614. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  15615. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  15616. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  15617. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  15618. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  15619. var normals = [];
  15620. var num_points = points.length;
  15621. for ( var i = 0; i < num_points; i ++ ) {
  15622. var v1 = points[ i ];
  15623. var v2 = points[ ( i + 1 ) % num_points ];
  15624. v1 = subtract( v1, origin );
  15625. v2 = subtract( v2, origin );
  15626. normals.push( normalize( cross( v1, v2 ) ) );
  15627. }
  15628. var normal = [ 0, 0, 0 ];
  15629. for ( var i = 0; i < normals.length; i ++ ) {
  15630. normal[ 0 ] += normals[ i ][ 0 ];
  15631. normal[ 1 ] += normals[ i ][ 1 ];
  15632. normal[ 2 ] += normals[ i ][ 2 ];
  15633. }
  15634. normal[ 0 ] /= normals.length;
  15635. normal[ 1 ] /= normals.length;
  15636. normal[ 2 ] /= normals.length;
  15637. var idx = ( y * width + x ) * 4;
  15638. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15639. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15640. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  15641. output[ idx + 3 ] = 255;
  15642. }
  15643. }
  15644. context.putImageData( imageData, 0, 0 );
  15645. return canvas;
  15646. },
  15647. generateDataTexture: function ( width, height, color ) {
  15648. var size = width * height;
  15649. var data = new Uint8Array( 3 * size );
  15650. var r = Math.floor( color.r * 255 );
  15651. var g = Math.floor( color.g * 255 );
  15652. var b = Math.floor( color.b * 255 );
  15653. for ( var i = 0; i < size; i ++ ) {
  15654. data[ i * 3 ] = r;
  15655. data[ i * 3 + 1 ] = g;
  15656. data[ i * 3 + 2 ] = b;
  15657. }
  15658. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  15659. texture.needsUpdate = true;
  15660. return texture;
  15661. }
  15662. };
  15663. // File:src/extras/SceneUtils.js
  15664. /**
  15665. * @author alteredq / http://alteredqualia.com/
  15666. */
  15667. THREE.SceneUtils = {
  15668. createMultiMaterialObject: function ( geometry, materials ) {
  15669. var group = new THREE.Object3D();
  15670. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  15671. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  15672. }
  15673. return group;
  15674. },
  15675. detach: function ( child, parent, scene ) {
  15676. child.applyMatrix( parent.matrixWorld );
  15677. parent.remove( child );
  15678. scene.add( child );
  15679. },
  15680. attach: function ( child, scene, parent ) {
  15681. var matrixWorldInverse = new THREE.Matrix4();
  15682. matrixWorldInverse.getInverse( parent.matrixWorld );
  15683. child.applyMatrix( matrixWorldInverse );
  15684. scene.remove( child );
  15685. parent.add( child );
  15686. }
  15687. };
  15688. // File:src/extras/FontUtils.js
  15689. /**
  15690. * @author zz85 / http://www.lab4games.net/zz85/blog
  15691. * @author alteredq / http://alteredqualia.com/
  15692. *
  15693. * For Text operations in three.js (See TextGeometry)
  15694. *
  15695. * It uses techniques used in:
  15696. *
  15697. * typeface.js and canvastext
  15698. * For converting fonts and rendering with javascript
  15699. * http://typeface.neocracy.org
  15700. *
  15701. * Triangulation ported from AS3
  15702. * Simple Polygon Triangulation
  15703. * http://actionsnippet.com/?p=1462
  15704. *
  15705. * A Method to triangulate shapes with holes
  15706. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  15707. *
  15708. */
  15709. THREE.FontUtils = {
  15710. faces: {},
  15711. // Just for now. face[weight][style]
  15712. face: 'helvetiker',
  15713. weight: 'normal',
  15714. style: 'normal',
  15715. size: 150,
  15716. divisions: 10,
  15717. getFace: function () {
  15718. try {
  15719. return this.faces[ this.face ][ this.weight ][ this.style ];
  15720. } catch (e) {
  15721. throw "The font " + this.face + " with " + this.weight + " weight and " + this.style + " style is missing."
  15722. };
  15723. },
  15724. loadFace: function ( data ) {
  15725. var family = data.familyName.toLowerCase();
  15726. var ThreeFont = this;
  15727. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  15728. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  15729. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15730. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15731. return data;
  15732. },
  15733. drawText: function ( text ) {
  15734. var characterPts = [], allPts = [];
  15735. // RenderText
  15736. var i, p,
  15737. face = this.getFace(),
  15738. scale = this.size / face.resolution,
  15739. offset = 0,
  15740. chars = String( text ).split( '' ),
  15741. length = chars.length;
  15742. var fontPaths = [];
  15743. for ( i = 0; i < length; i ++ ) {
  15744. var path = new THREE.Path();
  15745. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  15746. offset += ret.offset;
  15747. fontPaths.push( ret.path );
  15748. }
  15749. // get the width
  15750. var width = offset / 2;
  15751. //
  15752. // for ( p = 0; p < allPts.length; p++ ) {
  15753. //
  15754. // allPts[ p ].x -= width;
  15755. //
  15756. // }
  15757. //var extract = this.extractPoints( allPts, characterPts );
  15758. //extract.contour = allPts;
  15759. //extract.paths = fontPaths;
  15760. //extract.offset = width;
  15761. return { paths: fontPaths, offset: width };
  15762. },
  15763. extractGlyphPoints: function ( c, face, scale, offset, path ) {
  15764. var pts = [];
  15765. var i, i2, divisions,
  15766. outline, action, length,
  15767. scaleX, scaleY,
  15768. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  15769. laste,
  15770. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  15771. if ( ! glyph ) return;
  15772. if ( glyph.o ) {
  15773. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  15774. length = outline.length;
  15775. scaleX = scale;
  15776. scaleY = scale;
  15777. for ( i = 0; i < length; ) {
  15778. action = outline[ i ++ ];
  15779. //console.log( action );
  15780. switch ( action ) {
  15781. case 'm':
  15782. // Move To
  15783. x = outline[ i ++ ] * scaleX + offset;
  15784. y = outline[ i ++ ] * scaleY;
  15785. path.moveTo( x, y );
  15786. break;
  15787. case 'l':
  15788. // Line To
  15789. x = outline[ i ++ ] * scaleX + offset;
  15790. y = outline[ i ++ ] * scaleY;
  15791. path.lineTo( x,y );
  15792. break;
  15793. case 'q':
  15794. // QuadraticCurveTo
  15795. cpx = outline[ i ++ ] * scaleX + offset;
  15796. cpy = outline[ i ++ ] * scaleY;
  15797. cpx1 = outline[ i ++ ] * scaleX + offset;
  15798. cpy1 = outline[ i ++ ] * scaleY;
  15799. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  15800. laste = pts[ pts.length - 1 ];
  15801. if ( laste ) {
  15802. cpx0 = laste.x;
  15803. cpy0 = laste.y;
  15804. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15805. var t = i2 / divisions;
  15806. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  15807. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  15808. }
  15809. }
  15810. break;
  15811. case 'b':
  15812. // Cubic Bezier Curve
  15813. cpx = outline[ i ++ ] * scaleX + offset;
  15814. cpy = outline[ i ++ ] * scaleY;
  15815. cpx1 = outline[ i ++ ] * scaleX + offset;
  15816. cpy1 = outline[ i ++ ] * scaleY;
  15817. cpx2 = outline[ i ++ ] * scaleX + offset;
  15818. cpy2 = outline[ i ++ ] * scaleY;
  15819. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  15820. laste = pts[ pts.length - 1 ];
  15821. if ( laste ) {
  15822. cpx0 = laste.x;
  15823. cpy0 = laste.y;
  15824. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15825. var t = i2 / divisions;
  15826. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  15827. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  15828. }
  15829. }
  15830. break;
  15831. }
  15832. }
  15833. }
  15834. return { offset: glyph.ha * scale, path:path };
  15835. }
  15836. };
  15837. THREE.FontUtils.generateShapes = function ( text, parameters ) {
  15838. // Parameters
  15839. parameters = parameters || {};
  15840. var size = parameters.size !== undefined ? parameters.size : 100;
  15841. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments : 4;
  15842. var font = parameters.font !== undefined ? parameters.font : 'helvetiker';
  15843. var weight = parameters.weight !== undefined ? parameters.weight : 'normal';
  15844. var style = parameters.style !== undefined ? parameters.style : 'normal';
  15845. THREE.FontUtils.size = size;
  15846. THREE.FontUtils.divisions = curveSegments;
  15847. THREE.FontUtils.face = font;
  15848. THREE.FontUtils.weight = weight;
  15849. THREE.FontUtils.style = style;
  15850. // Get a Font data json object
  15851. var data = THREE.FontUtils.drawText( text );
  15852. var paths = data.paths;
  15853. var shapes = [];
  15854. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  15855. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  15856. }
  15857. return shapes;
  15858. };
  15859. /**
  15860. * This code is a quick port of code written in C++ which was submitted to
  15861. * flipcode.com by John W. Ratcliff // July 22, 2000
  15862. * See original code and more information here:
  15863. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15864. *
  15865. * ported to actionscript by Zevan Rosser
  15866. * www.actionsnippet.com
  15867. *
  15868. * ported to javascript by Joshua Koo
  15869. * http://www.lab4games.net/zz85/blog
  15870. *
  15871. */
  15872. ( function ( namespace ) {
  15873. var EPSILON = 0.0000000001;
  15874. // takes in an contour array and returns
  15875. var process = function ( contour, indices ) {
  15876. var n = contour.length;
  15877. if ( n < 3 ) return null;
  15878. var result = [],
  15879. verts = [],
  15880. vertIndices = [];
  15881. /* we want a counter-clockwise polygon in verts */
  15882. var u, v, w;
  15883. if ( area( contour ) > 0.0 ) {
  15884. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  15885. } else {
  15886. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  15887. }
  15888. var nv = n;
  15889. /* remove nv - 2 vertices, creating 1 triangle every time */
  15890. var count = 2 * nv; /* error detection */
  15891. for ( v = nv - 1; nv > 2; ) {
  15892. /* if we loop, it is probably a non-simple polygon */
  15893. if ( ( count -- ) <= 0 ) {
  15894. //** Triangulate: ERROR - probable bad polygon!
  15895. //throw ( "Warning, unable to triangulate polygon!" );
  15896. //return null;
  15897. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15898. THREE.warn( 'THREE.FontUtils: Warning, unable to triangulate polygon! in Triangulate.process()' );
  15899. if ( indices ) return vertIndices;
  15900. return result;
  15901. }
  15902. /* three consecutive vertices in current polygon, <u,v,w> */
  15903. u = v; if ( nv <= u ) u = 0; /* previous */
  15904. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15905. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15906. if ( snip( contour, u, v, w, nv, verts ) ) {
  15907. var a, b, c, s, t;
  15908. /* true names of the vertices */
  15909. a = verts[ u ];
  15910. b = verts[ v ];
  15911. c = verts[ w ];
  15912. /* output Triangle */
  15913. result.push( [ contour[ a ],
  15914. contour[ b ],
  15915. contour[ c ] ] );
  15916. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15917. /* remove v from the remaining polygon */
  15918. for ( s = v, t = v + 1; t < nv; s++, t++ ) {
  15919. verts[ s ] = verts[ t ];
  15920. }
  15921. nv --;
  15922. /* reset error detection counter */
  15923. count = 2 * nv;
  15924. }
  15925. }
  15926. if ( indices ) return vertIndices;
  15927. return result;
  15928. };
  15929. // calculate area of the contour polygon
  15930. var area = function ( contour ) {
  15931. var n = contour.length;
  15932. var a = 0.0;
  15933. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  15934. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15935. }
  15936. return a * 0.5;
  15937. };
  15938. var snip = function ( contour, u, v, w, n, verts ) {
  15939. var p;
  15940. var ax, ay, bx, by;
  15941. var cx, cy, px, py;
  15942. ax = contour[ verts[ u ] ].x;
  15943. ay = contour[ verts[ u ] ].y;
  15944. bx = contour[ verts[ v ] ].x;
  15945. by = contour[ verts[ v ] ].y;
  15946. cx = contour[ verts[ w ] ].x;
  15947. cy = contour[ verts[ w ] ].y;
  15948. if ( EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false;
  15949. var aX, aY, bX, bY, cX, cY;
  15950. var apx, apy, bpx, bpy, cpx, cpy;
  15951. var cCROSSap, bCROSScp, aCROSSbp;
  15952. aX = cx - bx; aY = cy - by;
  15953. bX = ax - cx; bY = ay - cy;
  15954. cX = bx - ax; cY = by - ay;
  15955. for ( p = 0; p < n; p ++ ) {
  15956. px = contour[ verts[ p ] ].x
  15957. py = contour[ verts[ p ] ].y
  15958. if ( ( ( px === ax ) && ( py === ay ) ) ||
  15959. ( ( px === bx ) && ( py === by ) ) ||
  15960. ( ( px === cx ) && ( py === cy ) ) ) continue;
  15961. apx = px - ax; apy = py - ay;
  15962. bpx = px - bx; bpy = py - by;
  15963. cpx = px - cx; cpy = py - cy;
  15964. // see if p is inside triangle abc
  15965. aCROSSbp = aX * bpy - aY * bpx;
  15966. cCROSSap = cX * apy - cY * apx;
  15967. bCROSScp = bX * cpy - bY * cpx;
  15968. if ( ( aCROSSbp >= - EPSILON ) && ( bCROSScp >= - EPSILON ) && ( cCROSSap >= - EPSILON ) ) return false;
  15969. }
  15970. return true;
  15971. };
  15972. namespace.Triangulate = process;
  15973. namespace.Triangulate.area = area;
  15974. return namespace;
  15975. } )( THREE.FontUtils );
  15976. // To use the typeface.js face files, hook up the API
  15977. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  15978. THREE.typeface_js = self._typeface_js;
  15979. // File:src/extras/audio/Audio.js
  15980. /**
  15981. * @author mrdoob / http://mrdoob.com/
  15982. */
  15983. THREE.Audio = function ( listener ) {
  15984. THREE.Object3D.call( this );
  15985. this.type = 'Audio';
  15986. this.context = listener.context;
  15987. this.source = this.context.createBufferSource();
  15988. this.gain = this.context.createGain();
  15989. this.gain.connect( this.context.destination );
  15990. this.panner = this.context.createPanner();
  15991. this.panner.connect( this.gain );
  15992. };
  15993. THREE.Audio.prototype = Object.create( THREE.Object3D.prototype );
  15994. THREE.Audio.prototype.constructor = THREE.Audio;
  15995. THREE.Audio.prototype.load = function ( file ) {
  15996. var scope = this;
  15997. var request = new XMLHttpRequest();
  15998. request.open( 'GET', file, true );
  15999. request.responseType = 'arraybuffer';
  16000. request.onload = function ( e ) {
  16001. scope.context.decodeAudioData( this.response, function ( buffer ) {
  16002. scope.source.buffer = buffer;
  16003. scope.source.connect( scope.panner );
  16004. scope.source.start( 0 );
  16005. } );
  16006. };
  16007. request.send();
  16008. return this;
  16009. };
  16010. THREE.Audio.prototype.setLoop = function ( value ) {
  16011. this.source.loop = value;
  16012. };
  16013. THREE.Audio.prototype.setRefDistance = function ( value ) {
  16014. this.panner.refDistance = value;
  16015. };
  16016. THREE.Audio.prototype.setRolloffFactor = function ( value ) {
  16017. this.panner.rolloffFactor = value;
  16018. };
  16019. THREE.Audio.prototype.updateMatrixWorld = ( function () {
  16020. var position = new THREE.Vector3();
  16021. return function ( force ) {
  16022. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  16023. position.setFromMatrixPosition( this.matrixWorld );
  16024. this.panner.setPosition( position.x, position.y, position.z );
  16025. };
  16026. } )();
  16027. // File:src/extras/audio/AudioListener.js
  16028. /**
  16029. * @author mrdoob / http://mrdoob.com/
  16030. */
  16031. THREE.AudioListener = function () {
  16032. THREE.Object3D.call( this );
  16033. this.type = 'AudioListener';
  16034. this.context = new ( window.AudioContext || window.webkitAudioContext )();
  16035. };
  16036. THREE.AudioListener.prototype = Object.create( THREE.Object3D.prototype );
  16037. THREE.AudioListener.prototype.constructor = THREE.AudioListener;
  16038. THREE.AudioListener.prototype.updateMatrixWorld = ( function () {
  16039. var position = new THREE.Vector3();
  16040. var quaternion = new THREE.Quaternion();
  16041. var scale = new THREE.Vector3();
  16042. var orientation = new THREE.Vector3();
  16043. var velocity = new THREE.Vector3();
  16044. var positionPrev = new THREE.Vector3();
  16045. return function ( force ) {
  16046. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  16047. var listener = this.context.listener;
  16048. var up = this.up;
  16049. this.matrixWorld.decompose( position, quaternion, scale );
  16050. orientation.set( 0, 0, -1 ).applyQuaternion( quaternion );
  16051. velocity.subVectors( position, positionPrev );
  16052. listener.setPosition( position.x, position.y, position.z );
  16053. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  16054. listener.setVelocity( velocity.x, velocity.y, velocity.z );
  16055. positionPrev.copy( position );
  16056. };
  16057. } )();
  16058. // File:src/extras/core/Curve.js
  16059. /**
  16060. * @author zz85 / http://www.lab4games.net/zz85/blog
  16061. * Extensible curve object
  16062. *
  16063. * Some common of Curve methods
  16064. * .getPoint(t), getTangent(t)
  16065. * .getPointAt(u), getTagentAt(u)
  16066. * .getPoints(), .getSpacedPoints()
  16067. * .getLength()
  16068. * .updateArcLengths()
  16069. *
  16070. * This following classes subclasses THREE.Curve:
  16071. *
  16072. * -- 2d classes --
  16073. * THREE.LineCurve
  16074. * THREE.QuadraticBezierCurve
  16075. * THREE.CubicBezierCurve
  16076. * THREE.SplineCurve
  16077. * THREE.ArcCurve
  16078. * THREE.EllipseCurve
  16079. *
  16080. * -- 3d classes --
  16081. * THREE.LineCurve3
  16082. * THREE.QuadraticBezierCurve3
  16083. * THREE.CubicBezierCurve3
  16084. * THREE.SplineCurve3
  16085. * THREE.ClosedSplineCurve3
  16086. *
  16087. * A series of curves can be represented as a THREE.CurvePath
  16088. *
  16089. **/
  16090. /**************************************************************
  16091. * Abstract Curve base class
  16092. **************************************************************/
  16093. THREE.Curve = function () {
  16094. };
  16095. // Virtual base class method to overwrite and implement in subclasses
  16096. // - t [0 .. 1]
  16097. THREE.Curve.prototype.getPoint = function ( t ) {
  16098. THREE.warn( "THREE.Curve: Warning, getPoint() not implemented!" );
  16099. return null;
  16100. };
  16101. // Get point at relative position in curve according to arc length
  16102. // - u [0 .. 1]
  16103. THREE.Curve.prototype.getPointAt = function ( u ) {
  16104. var t = this.getUtoTmapping( u );
  16105. return this.getPoint( t );
  16106. };
  16107. // Get sequence of points using getPoint( t )
  16108. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16109. if ( ! divisions ) divisions = 5;
  16110. var d, pts = [];
  16111. for ( d = 0; d <= divisions; d ++ ) {
  16112. pts.push( this.getPoint( d / divisions ) );
  16113. }
  16114. return pts;
  16115. };
  16116. // Get sequence of points using getPointAt( u )
  16117. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16118. if ( ! divisions ) divisions = 5;
  16119. var d, pts = [];
  16120. for ( d = 0; d <= divisions; d ++ ) {
  16121. pts.push( this.getPointAt( d / divisions ) );
  16122. }
  16123. return pts;
  16124. };
  16125. // Get total curve arc length
  16126. THREE.Curve.prototype.getLength = function () {
  16127. var lengths = this.getLengths();
  16128. return lengths[ lengths.length - 1 ];
  16129. };
  16130. // Get list of cumulative segment lengths
  16131. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16132. if ( ! divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16133. if ( this.cacheArcLengths
  16134. && ( this.cacheArcLengths.length == divisions + 1 )
  16135. && ! this.needsUpdate) {
  16136. //console.log( "cached", this.cacheArcLengths );
  16137. return this.cacheArcLengths;
  16138. }
  16139. this.needsUpdate = false;
  16140. var cache = [];
  16141. var current, last = this.getPoint( 0 );
  16142. var p, sum = 0;
  16143. cache.push( 0 );
  16144. for ( p = 1; p <= divisions; p ++ ) {
  16145. current = this.getPoint ( p / divisions );
  16146. sum += current.distanceTo( last );
  16147. cache.push( sum );
  16148. last = current;
  16149. }
  16150. this.cacheArcLengths = cache;
  16151. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16152. };
  16153. THREE.Curve.prototype.updateArcLengths = function() {
  16154. this.needsUpdate = true;
  16155. this.getLengths();
  16156. };
  16157. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16158. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16159. var arcLengths = this.getLengths();
  16160. var i = 0, il = arcLengths.length;
  16161. var targetArcLength; // The targeted u distance value to get
  16162. if ( distance ) {
  16163. targetArcLength = distance;
  16164. } else {
  16165. targetArcLength = u * arcLengths[ il - 1 ];
  16166. }
  16167. //var time = Date.now();
  16168. // binary search for the index with largest value smaller than target u distance
  16169. var low = 0, high = il - 1, comparison;
  16170. while ( low <= high ) {
  16171. 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
  16172. comparison = arcLengths[ i ] - targetArcLength;
  16173. if ( comparison < 0 ) {
  16174. low = i + 1;
  16175. } else if ( comparison > 0 ) {
  16176. high = i - 1;
  16177. } else {
  16178. high = i;
  16179. break;
  16180. // DONE
  16181. }
  16182. }
  16183. i = high;
  16184. //console.log('b' , i, low, high, Date.now()- time);
  16185. if ( arcLengths[ i ] == targetArcLength ) {
  16186. var t = i / ( il - 1 );
  16187. return t;
  16188. }
  16189. // we could get finer grain at lengths, or use simple interpolatation between two points
  16190. var lengthBefore = arcLengths[ i ];
  16191. var lengthAfter = arcLengths[ i + 1 ];
  16192. var segmentLength = lengthAfter - lengthBefore;
  16193. // determine where we are between the 'before' and 'after' points
  16194. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16195. // add that fractional amount to t
  16196. var t = ( i + segmentFraction ) / ( il -1 );
  16197. return t;
  16198. };
  16199. // Returns a unit vector tangent at t
  16200. // In case any sub curve does not implement its tangent derivation,
  16201. // 2 points a small delta apart will be used to find its gradient
  16202. // which seems to give a reasonable approximation
  16203. THREE.Curve.prototype.getTangent = function( t ) {
  16204. var delta = 0.0001;
  16205. var t1 = t - delta;
  16206. var t2 = t + delta;
  16207. // Capping in case of danger
  16208. if ( t1 < 0 ) t1 = 0;
  16209. if ( t2 > 1 ) t2 = 1;
  16210. var pt1 = this.getPoint( t1 );
  16211. var pt2 = this.getPoint( t2 );
  16212. var vec = pt2.clone().sub(pt1);
  16213. return vec.normalize();
  16214. };
  16215. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16216. var t = this.getUtoTmapping( u );
  16217. return this.getTangent( t );
  16218. };
  16219. /**************************************************************
  16220. * Utils
  16221. **************************************************************/
  16222. THREE.Curve.Utils = {
  16223. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16224. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16225. },
  16226. // Puay Bing, thanks for helping with this derivative!
  16227. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16228. return - 3 * p0 * (1 - t) * (1 - t) +
  16229. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16230. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16231. 3 * t * t * p3;
  16232. },
  16233. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16234. // To check if my formulas are correct
  16235. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16236. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16237. var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2
  16238. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16239. return h00 + h10 + h01 + h11;
  16240. },
  16241. // Catmull-Rom
  16242. interpolate: function( p0, p1, p2, p3, t ) {
  16243. var v0 = ( p2 - p0 ) * 0.5;
  16244. var v1 = ( p3 - p1 ) * 0.5;
  16245. var t2 = t * t;
  16246. var t3 = t * t2;
  16247. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16248. }
  16249. };
  16250. // TODO: Transformation for Curves?
  16251. /**************************************************************
  16252. * 3D Curves
  16253. **************************************************************/
  16254. // A Factory method for creating new curve subclasses
  16255. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16256. constructor.prototype = Object.create( THREE.Curve.prototype );
  16257. constructor.prototype.constructor = constructor;
  16258. constructor.prototype.getPoint = getPointFunc;
  16259. return constructor;
  16260. };
  16261. // File:src/extras/core/CurvePath.js
  16262. /**
  16263. * @author zz85 / http://www.lab4games.net/zz85/blog
  16264. *
  16265. **/
  16266. /**************************************************************
  16267. * Curved Path - a curve path is simply a array of connected
  16268. * curves, but retains the api of a curve
  16269. **************************************************************/
  16270. THREE.CurvePath = function () {
  16271. this.curves = [];
  16272. this.bends = [];
  16273. this.autoClose = false; // Automatically closes the path
  16274. };
  16275. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16276. THREE.CurvePath.prototype.constructor = THREE.CurvePath;
  16277. THREE.CurvePath.prototype.add = function ( curve ) {
  16278. this.curves.push( curve );
  16279. };
  16280. THREE.CurvePath.prototype.checkConnection = function() {
  16281. // TODO
  16282. // If the ending of curve is not connected to the starting
  16283. // or the next curve, then, this is not a real path
  16284. };
  16285. THREE.CurvePath.prototype.closePath = function() {
  16286. // TODO Test
  16287. // and verify for vector3 (needs to implement equals)
  16288. // Add a line curve if start and end of lines are not connected
  16289. var startPoint = this.curves[0].getPoint(0);
  16290. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16291. if (! startPoint.equals(endPoint)) {
  16292. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16293. }
  16294. };
  16295. // To get accurate point with reference to
  16296. // entire path distance at time t,
  16297. // following has to be done:
  16298. // 1. Length of each sub path have to be known
  16299. // 2. Locate and identify type of curve
  16300. // 3. Get t for the curve
  16301. // 4. Return curve.getPointAt(t')
  16302. THREE.CurvePath.prototype.getPoint = function( t ) {
  16303. var d = t * this.getLength();
  16304. var curveLengths = this.getCurveLengths();
  16305. var i = 0, diff, curve;
  16306. // To think about boundaries points.
  16307. while ( i < curveLengths.length ) {
  16308. if ( curveLengths[ i ] >= d ) {
  16309. diff = curveLengths[ i ] - d;
  16310. curve = this.curves[ i ];
  16311. var u = 1 - diff / curve.getLength();
  16312. return curve.getPointAt( u );
  16313. }
  16314. i ++;
  16315. }
  16316. return null;
  16317. // loop where sum != 0, sum > d , sum+1 <d
  16318. };
  16319. /*
  16320. THREE.CurvePath.prototype.getTangent = function( t ) {
  16321. };*/
  16322. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16323. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16324. // getPoint() depends on getLength
  16325. THREE.CurvePath.prototype.getLength = function() {
  16326. var lens = this.getCurveLengths();
  16327. return lens[ lens.length - 1 ];
  16328. };
  16329. // Compute lengths and cache them
  16330. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16331. THREE.CurvePath.prototype.getCurveLengths = function() {
  16332. // We use cache values if curves and cache array are same length
  16333. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16334. return this.cacheLengths;
  16335. };
  16336. // Get length of subsurve
  16337. // Push sums into cached array
  16338. var lengths = [], sums = 0;
  16339. var i, il = this.curves.length;
  16340. for ( i = 0; i < il; i ++ ) {
  16341. sums += this.curves[ i ].getLength();
  16342. lengths.push( sums );
  16343. }
  16344. this.cacheLengths = lengths;
  16345. return lengths;
  16346. };
  16347. // Returns min and max coordinates
  16348. THREE.CurvePath.prototype.getBoundingBox = function () {
  16349. var points = this.getPoints();
  16350. var maxX, maxY, maxZ;
  16351. var minX, minY, minZ;
  16352. maxX = maxY = Number.NEGATIVE_INFINITY;
  16353. minX = minY = Number.POSITIVE_INFINITY;
  16354. var p, i, il, sum;
  16355. var v3 = points[0] instanceof THREE.Vector3;
  16356. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16357. for ( i = 0, il = points.length; i < il; i ++ ) {
  16358. p = points[ i ];
  16359. if ( p.x > maxX ) maxX = p.x;
  16360. else if ( p.x < minX ) minX = p.x;
  16361. if ( p.y > maxY ) maxY = p.y;
  16362. else if ( p.y < minY ) minY = p.y;
  16363. if ( v3 ) {
  16364. if ( p.z > maxZ ) maxZ = p.z;
  16365. else if ( p.z < minZ ) minZ = p.z;
  16366. }
  16367. sum.add( p );
  16368. }
  16369. var ret = {
  16370. minX: minX,
  16371. minY: minY,
  16372. maxX: maxX,
  16373. maxY: maxY
  16374. };
  16375. if ( v3 ) {
  16376. ret.maxZ = maxZ;
  16377. ret.minZ = minZ;
  16378. }
  16379. return ret;
  16380. };
  16381. /**************************************************************
  16382. * Create Geometries Helpers
  16383. **************************************************************/
  16384. /// Generate geometry from path points (for Line or Points objects)
  16385. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16386. var pts = this.getPoints( divisions, true );
  16387. return this.createGeometry( pts );
  16388. };
  16389. // Generate geometry from equidistance sampling along the path
  16390. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16391. var pts = this.getSpacedPoints( divisions, true );
  16392. return this.createGeometry( pts );
  16393. };
  16394. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16395. var geometry = new THREE.Geometry();
  16396. for ( var i = 0; i < points.length; i ++ ) {
  16397. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16398. }
  16399. return geometry;
  16400. };
  16401. /**************************************************************
  16402. * Bend / Wrap Helper Methods
  16403. **************************************************************/
  16404. // Wrap path / Bend modifiers?
  16405. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16406. this.bends.push( bendpath );
  16407. };
  16408. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16409. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16410. var i, il;
  16411. if ( ! bends ) {
  16412. bends = this.bends;
  16413. }
  16414. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16415. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16416. }
  16417. return oldPts;
  16418. };
  16419. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16420. var oldPts = this.getSpacedPoints( segments );
  16421. var i, il;
  16422. if ( ! bends ) {
  16423. bends = this.bends;
  16424. }
  16425. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16426. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16427. }
  16428. return oldPts;
  16429. };
  16430. // This returns getPoints() bend/wrapped around the contour of a path.
  16431. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16432. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16433. var bounds = this.getBoundingBox();
  16434. var i, il, p, oldX, oldY, xNorm;
  16435. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16436. p = oldPts[ i ];
  16437. oldX = p.x;
  16438. oldY = p.y;
  16439. xNorm = oldX / bounds.maxX;
  16440. // If using actual distance, for length > path, requires line extrusions
  16441. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16442. xNorm = path.getUtoTmapping( xNorm, oldX );
  16443. // check for out of bounds?
  16444. var pathPt = path.getPoint( xNorm );
  16445. var normal = path.getTangent( xNorm );
  16446. normal.set( - normal.y, normal.x ).multiplyScalar( oldY );
  16447. p.x = pathPt.x + normal.x;
  16448. p.y = pathPt.y + normal.y;
  16449. }
  16450. return oldPts;
  16451. };
  16452. // File:src/extras/core/Gyroscope.js
  16453. /**
  16454. * @author alteredq / http://alteredqualia.com/
  16455. */
  16456. THREE.Gyroscope = function () {
  16457. THREE.Object3D.call( this );
  16458. };
  16459. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16460. THREE.Gyroscope.prototype.constructor = THREE.Gyroscope;
  16461. THREE.Gyroscope.prototype.updateMatrixWorld = ( function () {
  16462. var translationObject = new THREE.Vector3();
  16463. var quaternionObject = new THREE.Quaternion();
  16464. var scaleObject = new THREE.Vector3();
  16465. var translationWorld = new THREE.Vector3();
  16466. var quaternionWorld = new THREE.Quaternion();
  16467. var scaleWorld = new THREE.Vector3();
  16468. return function ( force ) {
  16469. this.matrixAutoUpdate && this.updateMatrix();
  16470. // update matrixWorld
  16471. if ( this.matrixWorldNeedsUpdate || force ) {
  16472. if ( this.parent ) {
  16473. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  16474. this.matrixWorld.decompose( translationWorld, quaternionWorld, scaleWorld );
  16475. this.matrix.decompose( translationObject, quaternionObject, scaleObject );
  16476. this.matrixWorld.compose( translationWorld, quaternionObject, scaleWorld );
  16477. } else {
  16478. this.matrixWorld.copy( this.matrix );
  16479. }
  16480. this.matrixWorldNeedsUpdate = false;
  16481. force = true;
  16482. }
  16483. // update children
  16484. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16485. this.children[ i ].updateMatrixWorld( force );
  16486. }
  16487. };
  16488. }() );
  16489. // File:src/extras/core/Path.js
  16490. /**
  16491. * @author zz85 / http://www.lab4games.net/zz85/blog
  16492. * Creates free form 2d path using series of points, lines or curves.
  16493. *
  16494. **/
  16495. THREE.Path = function ( points ) {
  16496. THREE.CurvePath.call(this);
  16497. this.actions = [];
  16498. if ( points ) {
  16499. this.fromPoints( points );
  16500. }
  16501. };
  16502. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16503. THREE.Path.prototype.constructor = THREE.Path;
  16504. THREE.PathActions = {
  16505. MOVE_TO: 'moveTo',
  16506. LINE_TO: 'lineTo',
  16507. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16508. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16509. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16510. ARC: 'arc', // Circle
  16511. ELLIPSE: 'ellipse'
  16512. };
  16513. // TODO Clean up PATH API
  16514. // Create path using straight lines to connect all points
  16515. // - vectors: array of Vector2
  16516. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16517. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16518. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16519. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16520. };
  16521. };
  16522. // startPath() endPath()?
  16523. THREE.Path.prototype.moveTo = function ( x, y ) {
  16524. var args = Array.prototype.slice.call( arguments );
  16525. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16526. };
  16527. THREE.Path.prototype.lineTo = function ( x, y ) {
  16528. var args = Array.prototype.slice.call( arguments );
  16529. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16530. var x0 = lastargs[ lastargs.length - 2 ];
  16531. var y0 = lastargs[ lastargs.length - 1 ];
  16532. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16533. this.curves.push( curve );
  16534. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16535. };
  16536. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16537. var args = Array.prototype.slice.call( arguments );
  16538. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16539. var x0 = lastargs[ lastargs.length - 2 ];
  16540. var y0 = lastargs[ lastargs.length - 1 ];
  16541. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16542. new THREE.Vector2( aCPx, aCPy ),
  16543. new THREE.Vector2( aX, aY ) );
  16544. this.curves.push( curve );
  16545. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16546. };
  16547. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16548. aCP2x, aCP2y,
  16549. aX, aY ) {
  16550. var args = Array.prototype.slice.call( arguments );
  16551. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16552. var x0 = lastargs[ lastargs.length - 2 ];
  16553. var y0 = lastargs[ lastargs.length - 1 ];
  16554. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16555. new THREE.Vector2( aCP1x, aCP1y ),
  16556. new THREE.Vector2( aCP2x, aCP2y ),
  16557. new THREE.Vector2( aX, aY ) );
  16558. this.curves.push( curve );
  16559. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16560. };
  16561. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16562. var args = Array.prototype.slice.call( arguments );
  16563. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16564. var x0 = lastargs[ lastargs.length - 2 ];
  16565. var y0 = lastargs[ lastargs.length - 1 ];
  16566. //---
  16567. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16568. Array.prototype.push.apply( npts, pts );
  16569. var curve = new THREE.SplineCurve( npts );
  16570. this.curves.push( curve );
  16571. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16572. };
  16573. // FUTURE: Change the API or follow canvas API?
  16574. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16575. aStartAngle, aEndAngle, aClockwise ) {
  16576. var lastargs = this.actions[ this.actions.length - 1].args;
  16577. var x0 = lastargs[ lastargs.length - 2 ];
  16578. var y0 = lastargs[ lastargs.length - 1 ];
  16579. this.absarc(aX + x0, aY + y0, aRadius,
  16580. aStartAngle, aEndAngle, aClockwise );
  16581. };
  16582. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16583. aStartAngle, aEndAngle, aClockwise ) {
  16584. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16585. };
  16586. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16587. aStartAngle, aEndAngle, aClockwise ) {
  16588. var lastargs = this.actions[ this.actions.length - 1].args;
  16589. var x0 = lastargs[ lastargs.length - 2 ];
  16590. var y0 = lastargs[ lastargs.length - 1 ];
  16591. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16592. aStartAngle, aEndAngle, aClockwise );
  16593. };
  16594. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16595. aStartAngle, aEndAngle, aClockwise ) {
  16596. var args = Array.prototype.slice.call( arguments );
  16597. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16598. aStartAngle, aEndAngle, aClockwise );
  16599. this.curves.push( curve );
  16600. var lastPoint = curve.getPoint(1);
  16601. args.push(lastPoint.x);
  16602. args.push(lastPoint.y);
  16603. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16604. };
  16605. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16606. if ( ! divisions ) divisions = 40;
  16607. var points = [];
  16608. for ( var i = 0; i < divisions; i ++ ) {
  16609. points.push( this.getPoint( i / divisions ) );
  16610. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16611. }
  16612. // if ( closedPath ) {
  16613. //
  16614. // points.push( points[ 0 ] );
  16615. //
  16616. // }
  16617. return points;
  16618. };
  16619. /* Return an array of vectors based on contour of the path */
  16620. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  16621. if (this.useSpacedPoints) {
  16622. console.log('tata');
  16623. return this.getSpacedPoints( divisions, closedPath );
  16624. }
  16625. divisions = divisions || 12;
  16626. var points = [];
  16627. var i, il, item, action, args;
  16628. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  16629. laste, j,
  16630. t, tx, ty;
  16631. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16632. item = this.actions[ i ];
  16633. action = item.action;
  16634. args = item.args;
  16635. switch( action ) {
  16636. case THREE.PathActions.MOVE_TO:
  16637. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16638. break;
  16639. case THREE.PathActions.LINE_TO:
  16640. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16641. break;
  16642. case THREE.PathActions.QUADRATIC_CURVE_TO:
  16643. cpx = args[ 2 ];
  16644. cpy = args[ 3 ];
  16645. cpx1 = args[ 0 ];
  16646. cpy1 = args[ 1 ];
  16647. if ( points.length > 0 ) {
  16648. laste = points[ points.length - 1 ];
  16649. cpx0 = laste.x;
  16650. cpy0 = laste.y;
  16651. } else {
  16652. laste = this.actions[ i - 1 ].args;
  16653. cpx0 = laste[ laste.length - 2 ];
  16654. cpy0 = laste[ laste.length - 1 ];
  16655. }
  16656. for ( j = 1; j <= divisions; j ++ ) {
  16657. t = j / divisions;
  16658. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16659. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16660. points.push( new THREE.Vector2( tx, ty ) );
  16661. }
  16662. break;
  16663. case THREE.PathActions.BEZIER_CURVE_TO:
  16664. cpx = args[ 4 ];
  16665. cpy = args[ 5 ];
  16666. cpx1 = args[ 0 ];
  16667. cpy1 = args[ 1 ];
  16668. cpx2 = args[ 2 ];
  16669. cpy2 = args[ 3 ];
  16670. if ( points.length > 0 ) {
  16671. laste = points[ points.length - 1 ];
  16672. cpx0 = laste.x;
  16673. cpy0 = laste.y;
  16674. } else {
  16675. laste = this.actions[ i - 1 ].args;
  16676. cpx0 = laste[ laste.length - 2 ];
  16677. cpy0 = laste[ laste.length - 1 ];
  16678. }
  16679. for ( j = 1; j <= divisions; j ++ ) {
  16680. t = j / divisions;
  16681. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16682. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16683. points.push( new THREE.Vector2( tx, ty ) );
  16684. }
  16685. break;
  16686. case THREE.PathActions.CSPLINE_THRU:
  16687. laste = this.actions[ i - 1 ].args;
  16688. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  16689. var spts = [ last ];
  16690. var n = divisions * args[ 0 ].length;
  16691. spts = spts.concat( args[ 0 ] );
  16692. var spline = new THREE.SplineCurve( spts );
  16693. for ( j = 1; j <= n; j ++ ) {
  16694. points.push( spline.getPointAt( j / n ) ) ;
  16695. }
  16696. break;
  16697. case THREE.PathActions.ARC:
  16698. var aX = args[ 0 ], aY = args[ 1 ],
  16699. aRadius = args[ 2 ],
  16700. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  16701. aClockwise = !! args[ 5 ];
  16702. var deltaAngle = aEndAngle - aStartAngle;
  16703. var angle;
  16704. var tdivisions = divisions * 2;
  16705. for ( j = 1; j <= tdivisions; j ++ ) {
  16706. t = j / tdivisions;
  16707. if ( ! aClockwise ) {
  16708. t = 1 - t;
  16709. }
  16710. angle = aStartAngle + t * deltaAngle;
  16711. tx = aX + aRadius * Math.cos( angle );
  16712. ty = aY + aRadius * Math.sin( angle );
  16713. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16714. points.push( new THREE.Vector2( tx, ty ) );
  16715. }
  16716. //console.log(points);
  16717. break;
  16718. case THREE.PathActions.ELLIPSE:
  16719. var aX = args[ 0 ], aY = args[ 1 ],
  16720. xRadius = args[ 2 ],
  16721. yRadius = args[ 3 ],
  16722. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  16723. aClockwise = !! args[ 6 ];
  16724. var deltaAngle = aEndAngle - aStartAngle;
  16725. var angle;
  16726. var tdivisions = divisions * 2;
  16727. for ( j = 1; j <= tdivisions; j ++ ) {
  16728. t = j / tdivisions;
  16729. if ( ! aClockwise ) {
  16730. t = 1 - t;
  16731. }
  16732. angle = aStartAngle + t * deltaAngle;
  16733. tx = aX + xRadius * Math.cos( angle );
  16734. ty = aY + yRadius * Math.sin( angle );
  16735. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16736. points.push( new THREE.Vector2( tx, ty ) );
  16737. }
  16738. //console.log(points);
  16739. break;
  16740. } // end switch
  16741. }
  16742. // Normalize to remove the closing point by default.
  16743. var lastPoint = points[ points.length - 1];
  16744. var EPSILON = 0.0000000001;
  16745. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  16746. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  16747. points.splice( points.length - 1, 1);
  16748. if ( closedPath ) {
  16749. points.push( points[ 0 ] );
  16750. }
  16751. return points;
  16752. };
  16753. //
  16754. // Breaks path into shapes
  16755. //
  16756. // Assumptions (if parameter isCCW==true the opposite holds):
  16757. // - solid shapes are defined clockwise (CW)
  16758. // - holes are defined counterclockwise (CCW)
  16759. //
  16760. // If parameter noHoles==true:
  16761. // - all subPaths are regarded as solid shapes
  16762. // - definition order CW/CCW has no relevance
  16763. //
  16764. THREE.Path.prototype.toShapes = function( isCCW, noHoles ) {
  16765. function extractSubpaths( inActions ) {
  16766. var i, il, item, action, args;
  16767. var subPaths = [], lastPath = new THREE.Path();
  16768. for ( i = 0, il = inActions.length; i < il; i ++ ) {
  16769. item = inActions[ i ];
  16770. args = item.args;
  16771. action = item.action;
  16772. if ( action == THREE.PathActions.MOVE_TO ) {
  16773. if ( lastPath.actions.length != 0 ) {
  16774. subPaths.push( lastPath );
  16775. lastPath = new THREE.Path();
  16776. }
  16777. }
  16778. lastPath[ action ].apply( lastPath, args );
  16779. }
  16780. if ( lastPath.actions.length != 0 ) {
  16781. subPaths.push( lastPath );
  16782. }
  16783. // console.log(subPaths);
  16784. return subPaths;
  16785. }
  16786. function toShapesNoHoles( inSubpaths ) {
  16787. var shapes = [];
  16788. for ( var i = 0, il = inSubpaths.length; i < il; i ++ ) {
  16789. var tmpPath = inSubpaths[ i ];
  16790. var tmpShape = new THREE.Shape();
  16791. tmpShape.actions = tmpPath.actions;
  16792. tmpShape.curves = tmpPath.curves;
  16793. shapes.push( tmpShape );
  16794. }
  16795. //console.log("shape", shapes);
  16796. return shapes;
  16797. };
  16798. function isPointInsidePolygon( inPt, inPolygon ) {
  16799. var EPSILON = 0.0000000001;
  16800. var polyLen = inPolygon.length;
  16801. // inPt on polygon contour => immediate success or
  16802. // toggling of inside/outside at every single! intersection point of an edge
  16803. // with the horizontal line through inPt, left of inPt
  16804. // not counting lowerY endpoints of edges and whole edges on that line
  16805. var inside = false;
  16806. for( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  16807. var edgeLowPt = inPolygon[ p ];
  16808. var edgeHighPt = inPolygon[ q ];
  16809. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  16810. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  16811. if ( Math.abs(edgeDy) > EPSILON ) { // not parallel
  16812. if ( edgeDy < 0 ) {
  16813. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  16814. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  16815. }
  16816. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  16817. if ( inPt.y == edgeLowPt.y ) {
  16818. if ( inPt.x == edgeLowPt.x ) return true; // inPt is on contour ?
  16819. // continue; // no intersection or edgeLowPt => doesn't count !!!
  16820. } else {
  16821. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  16822. if ( perpEdge == 0 ) return true; // inPt is on contour ?
  16823. if ( perpEdge < 0 ) continue;
  16824. inside = ! inside; // true intersection left of inPt
  16825. }
  16826. } else { // parallel or colinear
  16827. if ( inPt.y != edgeLowPt.y ) continue; // parallel
  16828. // egde lies on the same horizontal line as inPt
  16829. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  16830. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  16831. // continue;
  16832. }
  16833. }
  16834. return inside;
  16835. }
  16836. var subPaths = extractSubpaths( this.actions );
  16837. if ( subPaths.length == 0 ) return [];
  16838. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  16839. var solid, tmpPath, tmpShape, shapes = [];
  16840. if ( subPaths.length == 1) {
  16841. tmpPath = subPaths[0];
  16842. tmpShape = new THREE.Shape();
  16843. tmpShape.actions = tmpPath.actions;
  16844. tmpShape.curves = tmpPath.curves;
  16845. shapes.push( tmpShape );
  16846. return shapes;
  16847. }
  16848. var holesFirst = ! THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  16849. holesFirst = isCCW ? ! holesFirst : holesFirst;
  16850. // console.log("Holes first", holesFirst);
  16851. var betterShapeHoles = [];
  16852. var newShapes = [];
  16853. var newShapeHoles = [];
  16854. var mainIdx = 0;
  16855. var tmpPoints;
  16856. newShapes[mainIdx] = undefined;
  16857. newShapeHoles[mainIdx] = [];
  16858. var i, il;
  16859. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  16860. tmpPath = subPaths[ i ];
  16861. tmpPoints = tmpPath.getPoints();
  16862. solid = THREE.Shape.Utils.isClockWise( tmpPoints );
  16863. solid = isCCW ? ! solid : solid;
  16864. if ( solid ) {
  16865. if ( (! holesFirst ) && ( newShapes[mainIdx] ) ) mainIdx ++;
  16866. newShapes[mainIdx] = { s: new THREE.Shape(), p: tmpPoints };
  16867. newShapes[mainIdx].s.actions = tmpPath.actions;
  16868. newShapes[mainIdx].s.curves = tmpPath.curves;
  16869. if ( holesFirst ) mainIdx ++;
  16870. newShapeHoles[mainIdx] = [];
  16871. //console.log('cw', i);
  16872. } else {
  16873. newShapeHoles[mainIdx].push( { h: tmpPath, p: tmpPoints[0] } );
  16874. //console.log('ccw', i);
  16875. }
  16876. }
  16877. // only Holes? -> probably all Shapes with wrong orientation
  16878. if ( ! newShapes[0] ) return toShapesNoHoles( subPaths );
  16879. if ( newShapes.length > 1 ) {
  16880. var ambigious = false;
  16881. var toChange = [];
  16882. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  16883. betterShapeHoles[sIdx] = [];
  16884. }
  16885. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  16886. var sh = newShapes[sIdx];
  16887. var sho = newShapeHoles[sIdx];
  16888. for (var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  16889. var ho = sho[hIdx];
  16890. var hole_unassigned = true;
  16891. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  16892. if ( isPointInsidePolygon( ho.p, newShapes[s2Idx].p ) ) {
  16893. if ( sIdx != s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  16894. if ( hole_unassigned ) {
  16895. hole_unassigned = false;
  16896. betterShapeHoles[s2Idx].push( ho );
  16897. } else {
  16898. ambigious = true;
  16899. }
  16900. }
  16901. }
  16902. if ( hole_unassigned ) { betterShapeHoles[sIdx].push( ho ); }
  16903. }
  16904. }
  16905. // console.log("ambigious: ", ambigious);
  16906. if ( toChange.length > 0 ) {
  16907. // console.log("to change: ", toChange);
  16908. if (! ambigious) newShapeHoles = betterShapeHoles;
  16909. }
  16910. }
  16911. var tmpHoles, j, jl;
  16912. for ( i = 0, il = newShapes.length; i < il; i ++ ) {
  16913. tmpShape = newShapes[i].s;
  16914. shapes.push( tmpShape );
  16915. tmpHoles = newShapeHoles[i];
  16916. for ( j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  16917. tmpShape.holes.push( tmpHoles[j].h );
  16918. }
  16919. }
  16920. //console.log("shape", shapes);
  16921. return shapes;
  16922. };
  16923. // File:src/extras/core/Shape.js
  16924. /**
  16925. * @author zz85 / http://www.lab4games.net/zz85/blog
  16926. * Defines a 2d shape plane using paths.
  16927. **/
  16928. // STEP 1 Create a path.
  16929. // STEP 2 Turn path into shape.
  16930. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  16931. // STEP 3a - Extract points from each shape, turn to vertices
  16932. // STEP 3b - Triangulate each shape, add faces.
  16933. THREE.Shape = function () {
  16934. THREE.Path.apply( this, arguments );
  16935. this.holes = [];
  16936. };
  16937. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  16938. THREE.Shape.prototype.constructor = THREE.Shape;
  16939. // Convenience method to return ExtrudeGeometry
  16940. THREE.Shape.prototype.extrude = function ( options ) {
  16941. var extruded = new THREE.ExtrudeGeometry( this, options );
  16942. return extruded;
  16943. };
  16944. // Convenience method to return ShapeGeometry
  16945. THREE.Shape.prototype.makeGeometry = function ( options ) {
  16946. var geometry = new THREE.ShapeGeometry( this, options );
  16947. return geometry;
  16948. };
  16949. // Get points of holes
  16950. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  16951. var i, il = this.holes.length, holesPts = [];
  16952. for ( i = 0; i < il; i ++ ) {
  16953. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  16954. }
  16955. return holesPts;
  16956. };
  16957. // Get points of holes (spaced by regular distance)
  16958. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  16959. var i, il = this.holes.length, holesPts = [];
  16960. for ( i = 0; i < il; i ++ ) {
  16961. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  16962. }
  16963. return holesPts;
  16964. };
  16965. // Get points of shape and holes (keypoints based on segments parameter)
  16966. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  16967. return {
  16968. shape: this.getTransformedPoints( divisions ),
  16969. holes: this.getPointsHoles( divisions )
  16970. };
  16971. };
  16972. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  16973. if (this.useSpacedPoints) {
  16974. return this.extractAllSpacedPoints(divisions);
  16975. }
  16976. return this.extractAllPoints(divisions);
  16977. };
  16978. //
  16979. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  16980. //
  16981. // return {
  16982. //
  16983. // shape: this.transform( bend, divisions ),
  16984. // holes: this.getPointsHoles( divisions, bend )
  16985. //
  16986. // };
  16987. //
  16988. // };
  16989. // Get points of shape and holes (spaced by regular distance)
  16990. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  16991. return {
  16992. shape: this.getTransformedSpacedPoints( divisions ),
  16993. holes: this.getSpacedPointsHoles( divisions )
  16994. };
  16995. };
  16996. /**************************************************************
  16997. * Utils
  16998. **************************************************************/
  16999. THREE.Shape.Utils = {
  17000. triangulateShape: function ( contour, holes ) {
  17001. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  17002. // inOtherPt needs to be colinear to the inSegment
  17003. if ( inSegPt1.x != inSegPt2.x ) {
  17004. if ( inSegPt1.x < inSegPt2.x ) {
  17005. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  17006. } else {
  17007. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  17008. }
  17009. } else {
  17010. if ( inSegPt1.y < inSegPt2.y ) {
  17011. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  17012. } else {
  17013. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  17014. }
  17015. }
  17016. }
  17017. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  17018. var EPSILON = 0.0000000001;
  17019. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  17020. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  17021. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  17022. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  17023. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  17024. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  17025. if ( Math.abs(limit) > EPSILON ) { // not parallel
  17026. var perpSeg2;
  17027. if ( limit > 0 ) {
  17028. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  17029. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17030. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  17031. } else {
  17032. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  17033. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17034. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  17035. }
  17036. // i.e. to reduce rounding errors
  17037. // intersection at endpoint of segment#1?
  17038. if ( perpSeg2 == 0 ) {
  17039. if ( ( inExcludeAdjacentSegs ) &&
  17040. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17041. return [ inSeg1Pt1 ];
  17042. }
  17043. if ( perpSeg2 == limit ) {
  17044. if ( ( inExcludeAdjacentSegs ) &&
  17045. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17046. return [ inSeg1Pt2 ];
  17047. }
  17048. // intersection at endpoint of segment#2?
  17049. if ( perpSeg1 == 0 ) return [ inSeg2Pt1 ];
  17050. if ( perpSeg1 == limit ) return [ inSeg2Pt2 ];
  17051. // return real intersection point
  17052. var factorSeg1 = perpSeg2 / limit;
  17053. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  17054. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  17055. } else { // parallel or colinear
  17056. if ( ( perpSeg1 != 0 ) ||
  17057. ( seg2dy * seg1seg2dx != seg2dx * seg1seg2dy ) ) return [];
  17058. // they are collinear or degenerate
  17059. var seg1Pt = ( (seg1dx == 0) && (seg1dy == 0) ); // segment1 ist just a point?
  17060. var seg2Pt = ( (seg2dx == 0) && (seg2dy == 0) ); // segment2 ist just a point?
  17061. // both segments are points
  17062. if ( seg1Pt && seg2Pt ) {
  17063. if ( (inSeg1Pt1.x != inSeg2Pt1.x) ||
  17064. (inSeg1Pt1.y != inSeg2Pt1.y) ) return []; // they are distinct points
  17065. return [ inSeg1Pt1 ]; // they are the same point
  17066. }
  17067. // segment#1 is a single point
  17068. if ( seg1Pt ) {
  17069. if (! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  17070. return [ inSeg1Pt1 ];
  17071. }
  17072. // segment#2 is a single point
  17073. if ( seg2Pt ) {
  17074. if (! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  17075. return [ inSeg2Pt1 ];
  17076. }
  17077. // they are collinear segments, which might overlap
  17078. var seg1min, seg1max, seg1minVal, seg1maxVal;
  17079. var seg2min, seg2max, seg2minVal, seg2maxVal;
  17080. if (seg1dx != 0) { // the segments are NOT on a vertical line
  17081. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  17082. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  17083. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  17084. } else {
  17085. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  17086. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  17087. }
  17088. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  17089. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  17090. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  17091. } else {
  17092. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  17093. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  17094. }
  17095. } else { // the segments are on a vertical line
  17096. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  17097. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  17098. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  17099. } else {
  17100. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  17101. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  17102. }
  17103. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  17104. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  17105. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  17106. } else {
  17107. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  17108. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  17109. }
  17110. }
  17111. if ( seg1minVal <= seg2minVal ) {
  17112. if ( seg1maxVal < seg2minVal ) return [];
  17113. if ( seg1maxVal == seg2minVal ) {
  17114. if ( inExcludeAdjacentSegs ) return [];
  17115. return [ seg2min ];
  17116. }
  17117. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  17118. return [ seg2min, seg2max ];
  17119. } else {
  17120. if ( seg1minVal > seg2maxVal ) return [];
  17121. if ( seg1minVal == seg2maxVal ) {
  17122. if ( inExcludeAdjacentSegs ) return [];
  17123. return [ seg1min ];
  17124. }
  17125. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  17126. return [ seg1min, seg2max ];
  17127. }
  17128. }
  17129. }
  17130. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  17131. // The order of legs is important
  17132. var EPSILON = 0.0000000001;
  17133. // translation of all points, so that Vertex is at (0,0)
  17134. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  17135. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  17136. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  17137. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  17138. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  17139. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  17140. if ( Math.abs(from2toAngle) > EPSILON ) { // angle != 180 deg.
  17141. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  17142. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  17143. if ( from2toAngle > 0 ) { // main angle < 180 deg.
  17144. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  17145. } else { // main angle > 180 deg.
  17146. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  17147. }
  17148. } else { // angle == 180 deg.
  17149. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  17150. return ( from2otherAngle > 0 );
  17151. }
  17152. }
  17153. function removeHoles( contour, holes ) {
  17154. var shape = contour.concat(); // work on this shape
  17155. var hole;
  17156. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  17157. // Check if hole point lies within angle around shape point
  17158. var lastShapeIdx = shape.length - 1;
  17159. var prevShapeIdx = inShapeIdx - 1;
  17160. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  17161. var nextShapeIdx = inShapeIdx + 1;
  17162. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  17163. var insideAngle = isPointInsideAngle( shape[inShapeIdx], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[inHoleIdx] );
  17164. if (! insideAngle ) {
  17165. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  17166. return false;
  17167. }
  17168. // Check if shape point lies within angle around hole point
  17169. var lastHoleIdx = hole.length - 1;
  17170. var prevHoleIdx = inHoleIdx - 1;
  17171. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  17172. var nextHoleIdx = inHoleIdx + 1;
  17173. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  17174. insideAngle = isPointInsideAngle( hole[inHoleIdx], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[inShapeIdx] );
  17175. if (! insideAngle ) {
  17176. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  17177. return false;
  17178. }
  17179. return true;
  17180. }
  17181. function intersectsShapeEdge( inShapePt, inHolePt ) {
  17182. // checks for intersections with shape edges
  17183. var sIdx, nextIdx, intersection;
  17184. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  17185. nextIdx = sIdx+1; nextIdx %= shape.length;
  17186. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[sIdx], shape[nextIdx], true );
  17187. if ( intersection.length > 0 ) return true;
  17188. }
  17189. return false;
  17190. }
  17191. var indepHoles = [];
  17192. function intersectsHoleEdge( inShapePt, inHolePt ) {
  17193. // checks for intersections with hole edges
  17194. var ihIdx, chkHole,
  17195. hIdx, nextIdx, intersection;
  17196. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  17197. chkHole = holes[indepHoles[ihIdx]];
  17198. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  17199. nextIdx = hIdx+1; nextIdx %= chkHole.length;
  17200. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[hIdx], chkHole[nextIdx], true );
  17201. if ( intersection.length > 0 ) return true;
  17202. }
  17203. }
  17204. return false;
  17205. }
  17206. var holeIndex, shapeIndex,
  17207. shapePt, holePt,
  17208. holeIdx, cutKey, failedCuts = [],
  17209. tmpShape1, tmpShape2,
  17210. tmpHole1, tmpHole2;
  17211. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17212. indepHoles.push( h );
  17213. }
  17214. var minShapeIndex = 0;
  17215. var counter = indepHoles.length * 2;
  17216. while ( indepHoles.length > 0 ) {
  17217. counter --;
  17218. if ( counter < 0 ) {
  17219. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  17220. break;
  17221. }
  17222. // search for shape-vertex and hole-vertex,
  17223. // which can be connected without intersections
  17224. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  17225. shapePt = shape[ shapeIndex ];
  17226. holeIndex = - 1;
  17227. // search for hole which can be reached without intersections
  17228. for ( var h = 0; h < indepHoles.length; h ++ ) {
  17229. holeIdx = indepHoles[h];
  17230. // prevent multiple checks
  17231. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  17232. if ( failedCuts[cutKey] !== undefined ) continue;
  17233. hole = holes[holeIdx];
  17234. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  17235. holePt = hole[ h2 ];
  17236. if (! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  17237. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  17238. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  17239. holeIndex = h2;
  17240. indepHoles.splice(h,1);
  17241. tmpShape1 = shape.slice( 0, shapeIndex+1 );
  17242. tmpShape2 = shape.slice( shapeIndex );
  17243. tmpHole1 = hole.slice( holeIndex );
  17244. tmpHole2 = hole.slice( 0, holeIndex+1 );
  17245. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17246. minShapeIndex = shapeIndex;
  17247. // Debug only, to show the selected cuts
  17248. // glob_CutLines.push( [ shapePt, holePt ] );
  17249. break;
  17250. }
  17251. if ( holeIndex >= 0 ) break; // hole-vertex found
  17252. failedCuts[cutKey] = true; // remember failure
  17253. }
  17254. if ( holeIndex >= 0 ) break; // hole-vertex found
  17255. }
  17256. }
  17257. return shape; /* shape with no holes */
  17258. }
  17259. var i, il, f, face,
  17260. key, index,
  17261. allPointsMap = {};
  17262. // 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.
  17263. var allpoints = contour.concat();
  17264. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17265. Array.prototype.push.apply( allpoints, holes[h] );
  17266. }
  17267. //console.log( "allpoints",allpoints, allpoints.length );
  17268. // prepare all points map
  17269. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17270. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17271. if ( allPointsMap[ key ] !== undefined ) {
  17272. THREE.warn( "THREE.Shape: Duplicate point", key );
  17273. }
  17274. allPointsMap[ key ] = i;
  17275. }
  17276. // remove holes by cutting paths to holes and adding them to the shape
  17277. var shapeWithoutHoles = removeHoles( contour, holes );
  17278. var triangles = THREE.FontUtils.Triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  17279. //console.log( "triangles",triangles, triangles.length );
  17280. // check all face vertices against all points map
  17281. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17282. face = triangles[ i ];
  17283. for ( f = 0; f < 3; f ++ ) {
  17284. key = face[ f ].x + ":" + face[ f ].y;
  17285. index = allPointsMap[ key ];
  17286. if ( index !== undefined ) {
  17287. face[ f ] = index;
  17288. }
  17289. }
  17290. }
  17291. return triangles.concat();
  17292. },
  17293. isClockWise: function ( pts ) {
  17294. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17295. },
  17296. // Bezier Curves formulas obtained from
  17297. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17298. // Quad Bezier Functions
  17299. b2p0: function ( t, p ) {
  17300. var k = 1 - t;
  17301. return k * k * p;
  17302. },
  17303. b2p1: function ( t, p ) {
  17304. return 2 * ( 1 - t ) * t * p;
  17305. },
  17306. b2p2: function ( t, p ) {
  17307. return t * t * p;
  17308. },
  17309. b2: function ( t, p0, p1, p2 ) {
  17310. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17311. },
  17312. // Cubic Bezier Functions
  17313. b3p0: function ( t, p ) {
  17314. var k = 1 - t;
  17315. return k * k * k * p;
  17316. },
  17317. b3p1: function ( t, p ) {
  17318. var k = 1 - t;
  17319. return 3 * k * k * t * p;
  17320. },
  17321. b3p2: function ( t, p ) {
  17322. var k = 1 - t;
  17323. return 3 * k * t * t * p;
  17324. },
  17325. b3p3: function ( t, p ) {
  17326. return t * t * t * p;
  17327. },
  17328. b3: function ( t, p0, p1, p2, p3 ) {
  17329. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17330. }
  17331. };
  17332. // File:src/extras/curves/LineCurve.js
  17333. /**************************************************************
  17334. * Line
  17335. **************************************************************/
  17336. THREE.LineCurve = function ( v1, v2 ) {
  17337. this.v1 = v1;
  17338. this.v2 = v2;
  17339. };
  17340. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  17341. THREE.LineCurve.prototype.constructor = THREE.LineCurve;
  17342. THREE.LineCurve.prototype.getPoint = function ( t ) {
  17343. var point = this.v2.clone().sub(this.v1);
  17344. point.multiplyScalar( t ).add( this.v1 );
  17345. return point;
  17346. };
  17347. // Line curve is linear, so we can overwrite default getPointAt
  17348. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  17349. return this.getPoint( u );
  17350. };
  17351. THREE.LineCurve.prototype.getTangent = function( t ) {
  17352. var tangent = this.v2.clone().sub(this.v1);
  17353. return tangent.normalize();
  17354. };
  17355. // File:src/extras/curves/QuadraticBezierCurve.js
  17356. /**************************************************************
  17357. * Quadratic Bezier curve
  17358. **************************************************************/
  17359. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  17360. this.v0 = v0;
  17361. this.v1 = v1;
  17362. this.v2 = v2;
  17363. };
  17364. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17365. THREE.QuadraticBezierCurve.prototype.constructor = THREE.QuadraticBezierCurve;
  17366. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  17367. var vector = new THREE.Vector2();
  17368. vector.x = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17369. vector.y = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17370. return vector;
  17371. };
  17372. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  17373. var vector = new THREE.Vector2();
  17374. vector.x = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  17375. vector.y = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  17376. // returns unit vector
  17377. return vector.normalize();
  17378. };
  17379. // File:src/extras/curves/CubicBezierCurve.js
  17380. /**************************************************************
  17381. * Cubic Bezier curve
  17382. **************************************************************/
  17383. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  17384. this.v0 = v0;
  17385. this.v1 = v1;
  17386. this.v2 = v2;
  17387. this.v3 = v3;
  17388. };
  17389. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17390. THREE.CubicBezierCurve.prototype.constructor = THREE.CubicBezierCurve;
  17391. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  17392. var tx, ty;
  17393. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17394. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17395. return new THREE.Vector2( tx, ty );
  17396. };
  17397. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  17398. var tx, ty;
  17399. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17400. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17401. var tangent = new THREE.Vector2( tx, ty );
  17402. tangent.normalize();
  17403. return tangent;
  17404. };
  17405. // File:src/extras/curves/SplineCurve.js
  17406. /**************************************************************
  17407. * Spline curve
  17408. **************************************************************/
  17409. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  17410. this.points = ( points == undefined ) ? [] : points;
  17411. };
  17412. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  17413. THREE.SplineCurve.prototype.constructor = THREE.SplineCurve;
  17414. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  17415. var points = this.points;
  17416. var point = ( points.length - 1 ) * t;
  17417. var intPoint = Math.floor( point );
  17418. var weight = point - intPoint;
  17419. var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ]
  17420. var point1 = points[ intPoint ]
  17421. var point2 = points[ intPoint > points.length - 2 ? points.length -1 : intPoint + 1 ]
  17422. var point3 = points[ intPoint > points.length - 3 ? points.length -1 : intPoint + 2 ]
  17423. var vector = new THREE.Vector2();
  17424. vector.x = THREE.Curve.Utils.interpolate( point0.x, point1.x, point2.x, point3.x, weight );
  17425. vector.y = THREE.Curve.Utils.interpolate( point0.y, point1.y, point2.y, point3.y, weight );
  17426. return vector;
  17427. };
  17428. // File:src/extras/curves/EllipseCurve.js
  17429. /**************************************************************
  17430. * Ellipse curve
  17431. **************************************************************/
  17432. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) {
  17433. this.aX = aX;
  17434. this.aY = aY;
  17435. this.xRadius = xRadius;
  17436. this.yRadius = yRadius;
  17437. this.aStartAngle = aStartAngle;
  17438. this.aEndAngle = aEndAngle;
  17439. this.aClockwise = aClockwise;
  17440. };
  17441. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  17442. THREE.EllipseCurve.prototype.constructor = THREE.EllipseCurve;
  17443. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  17444. var deltaAngle = this.aEndAngle - this.aStartAngle;
  17445. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  17446. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  17447. var angle;
  17448. if ( this.aClockwise === true ) {
  17449. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  17450. } else {
  17451. angle = this.aStartAngle + t * deltaAngle;
  17452. }
  17453. var vector = new THREE.Vector2();
  17454. vector.x = this.aX + this.xRadius * Math.cos( angle );
  17455. vector.y = this.aY + this.yRadius * Math.sin( angle );
  17456. return vector;
  17457. };
  17458. // File:src/extras/curves/ArcCurve.js
  17459. /**************************************************************
  17460. * Arc curve
  17461. **************************************************************/
  17462. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  17463. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  17464. };
  17465. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  17466. THREE.ArcCurve.prototype.constructor = THREE.ArcCurve;
  17467. // File:src/extras/curves/LineCurve3.js
  17468. /**************************************************************
  17469. * Line3D
  17470. **************************************************************/
  17471. THREE.LineCurve3 = THREE.Curve.create(
  17472. function ( v1, v2 ) {
  17473. this.v1 = v1;
  17474. this.v2 = v2;
  17475. },
  17476. function ( t ) {
  17477. var vector = new THREE.Vector3();
  17478. vector.subVectors( this.v2, this.v1 ); // diff
  17479. vector.multiplyScalar( t );
  17480. vector.add( this.v1 );
  17481. return vector;
  17482. }
  17483. );
  17484. // File:src/extras/curves/QuadraticBezierCurve3.js
  17485. /**************************************************************
  17486. * Quadratic Bezier 3D curve
  17487. **************************************************************/
  17488. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  17489. function ( v0, v1, v2 ) {
  17490. this.v0 = v0;
  17491. this.v1 = v1;
  17492. this.v2 = v2;
  17493. },
  17494. function ( t ) {
  17495. var vector = new THREE.Vector3();
  17496. vector.x = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17497. vector.y = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17498. vector.z = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  17499. return vector;
  17500. }
  17501. );
  17502. // File:src/extras/curves/CubicBezierCurve3.js
  17503. /**************************************************************
  17504. * Cubic Bezier 3D curve
  17505. **************************************************************/
  17506. THREE.CubicBezierCurve3 = THREE.Curve.create(
  17507. function ( v0, v1, v2, v3 ) {
  17508. this.v0 = v0;
  17509. this.v1 = v1;
  17510. this.v2 = v2;
  17511. this.v3 = v3;
  17512. },
  17513. function ( t ) {
  17514. var vector = new THREE.Vector3();
  17515. vector.x = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17516. vector.y = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17517. vector.z = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  17518. return vector;
  17519. }
  17520. );
  17521. // File:src/extras/curves/SplineCurve3.js
  17522. /**************************************************************
  17523. * Spline 3D curve
  17524. **************************************************************/
  17525. THREE.SplineCurve3 = THREE.Curve.create(
  17526. function ( points /* array of Vector3 */) {
  17527. this.points = ( points == undefined ) ? [] : points;
  17528. },
  17529. function ( t ) {
  17530. var points = this.points;
  17531. var point = ( points.length - 1 ) * t;
  17532. var intPoint = Math.floor( point );
  17533. var weight = point - intPoint;
  17534. var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ];
  17535. var point1 = points[ intPoint ];
  17536. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  17537. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  17538. var vector = new THREE.Vector3();
  17539. vector.x = THREE.Curve.Utils.interpolate( point0.x, point1.x, point2.x, point3.x, weight );
  17540. vector.y = THREE.Curve.Utils.interpolate( point0.y, point1.y, point2.y, point3.y, weight );
  17541. vector.z = THREE.Curve.Utils.interpolate( point0.z, point1.z, point2.z, point3.z, weight );
  17542. return vector;
  17543. }
  17544. );
  17545. // File:src/extras/curves/ClosedSplineCurve3.js
  17546. /**************************************************************
  17547. * Closed Spline 3D curve
  17548. **************************************************************/
  17549. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  17550. function ( points /* array of Vector3 */) {
  17551. this.points = ( points == undefined ) ? [] : points;
  17552. },
  17553. function ( t ) {
  17554. var points = this.points;
  17555. var point = ( points.length - 0 ) * t; // This needs to be from 0-length +1
  17556. var intPoint = Math.floor( point );
  17557. var weight = point - intPoint;
  17558. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  17559. var point0 = points[ ( intPoint - 1 ) % points.length ];
  17560. var point1 = points[ ( intPoint ) % points.length ];
  17561. var point2 = points[ ( intPoint + 1 ) % points.length ];
  17562. var point3 = points[ ( intPoint + 2 ) % points.length ];
  17563. var vector = new THREE.Vector3();
  17564. vector.x = THREE.Curve.Utils.interpolate( point0.x, point1.x, point2.x, point3.x, weight );
  17565. vector.y = THREE.Curve.Utils.interpolate( point0.y, point1.y, point2.y, point3.y, weight );
  17566. vector.z = THREE.Curve.Utils.interpolate( point0.z, point1.z, point2.z, point3.z, weight );
  17567. return vector;
  17568. }
  17569. );
  17570. // File:src/extras/animation/AnimationHandler.js
  17571. /**
  17572. * @author mikael emtinger / http://gomo.se/
  17573. */
  17574. THREE.AnimationHandler = {
  17575. LINEAR: 0,
  17576. CATMULLROM: 1,
  17577. CATMULLROM_FORWARD: 2,
  17578. //
  17579. add: function () { THREE.warn( 'THREE.AnimationHandler.add() has been deprecated.' ); },
  17580. get: function () { THREE.warn( 'THREE.AnimationHandler.get() has been deprecated.' ); },
  17581. remove: function () { THREE.warn( 'THREE.AnimationHandler.remove() has been deprecated.' ); },
  17582. //
  17583. animations: [],
  17584. init: function ( data ) {
  17585. if ( data.initialized === true ) return data;
  17586. // loop through all keys
  17587. for ( var h = 0; h < data.hierarchy.length; h ++ ) {
  17588. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17589. // remove minus times
  17590. if ( data.hierarchy[ h ].keys[ k ].time < 0 ) {
  17591. data.hierarchy[ h ].keys[ k ].time = 0;
  17592. }
  17593. // create quaternions
  17594. if ( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17595. ! ( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17596. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17597. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion().fromArray( quat );
  17598. }
  17599. }
  17600. // prepare morph target keys
  17601. if ( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17602. // get all used
  17603. var usedMorphTargets = {};
  17604. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17605. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17606. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17607. usedMorphTargets[ morphTargetName ] = - 1;
  17608. }
  17609. }
  17610. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17611. // set all used on all frames
  17612. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17613. var influences = {};
  17614. for ( var morphTargetName in usedMorphTargets ) {
  17615. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17616. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17617. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17618. break;
  17619. }
  17620. }
  17621. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17622. influences[ morphTargetName ] = 0;
  17623. }
  17624. }
  17625. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17626. }
  17627. }
  17628. // remove all keys that are on the same time
  17629. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17630. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17631. data.hierarchy[ h ].keys.splice( k, 1 );
  17632. k --;
  17633. }
  17634. }
  17635. // set index
  17636. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17637. data.hierarchy[ h ].keys[ k ].index = k;
  17638. }
  17639. }
  17640. data.initialized = true;
  17641. return data;
  17642. },
  17643. parse: function ( root ) {
  17644. var parseRecurseHierarchy = function ( root, hierarchy ) {
  17645. hierarchy.push( root );
  17646. for ( var c = 0; c < root.children.length; c ++ )
  17647. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17648. };
  17649. // setup hierarchy
  17650. var hierarchy = [];
  17651. if ( root instanceof THREE.SkinnedMesh ) {
  17652. for ( var b = 0; b < root.skeleton.bones.length; b ++ ) {
  17653. hierarchy.push( root.skeleton.bones[ b ] );
  17654. }
  17655. } else {
  17656. parseRecurseHierarchy( root, hierarchy );
  17657. }
  17658. return hierarchy;
  17659. },
  17660. play: function ( animation ) {
  17661. if ( this.animations.indexOf( animation ) === - 1 ) {
  17662. this.animations.push( animation );
  17663. }
  17664. },
  17665. stop: function ( animation ) {
  17666. var index = this.animations.indexOf( animation );
  17667. if ( index !== - 1 ) {
  17668. this.animations.splice( index, 1 );
  17669. }
  17670. },
  17671. update: function ( deltaTimeMS ) {
  17672. for ( var i = 0; i < this.animations.length; i ++ ) {
  17673. this.animations[ i ].resetBlendWeights( );
  17674. }
  17675. for ( var i = 0; i < this.animations.length; i ++ ) {
  17676. this.animations[ i ].update( deltaTimeMS );
  17677. }
  17678. }
  17679. };
  17680. // File:src/extras/animation/Animation.js
  17681. /**
  17682. * @author mikael emtinger / http://gomo.se/
  17683. * @author mrdoob / http://mrdoob.com/
  17684. * @author alteredq / http://alteredqualia.com/
  17685. */
  17686. THREE.Animation = function ( root, data ) {
  17687. this.root = root;
  17688. this.data = THREE.AnimationHandler.init( data );
  17689. this.hierarchy = THREE.AnimationHandler.parse( root );
  17690. this.currentTime = 0;
  17691. this.timeScale = 1;
  17692. this.isPlaying = false;
  17693. this.loop = true;
  17694. this.weight = 0;
  17695. this.interpolationType = THREE.AnimationHandler.LINEAR;
  17696. };
  17697. THREE.Animation.prototype.keyTypes = [ "pos", "rot", "scl" ];
  17698. THREE.Animation.prototype.play = function ( startTime, weight ) {
  17699. this.currentTime = startTime !== undefined ? startTime : 0;
  17700. this.weight = weight !== undefined ? weight: 1;
  17701. this.isPlaying = true;
  17702. this.reset();
  17703. THREE.AnimationHandler.play( this );
  17704. };
  17705. THREE.Animation.prototype.stop = function() {
  17706. this.isPlaying = false;
  17707. THREE.AnimationHandler.stop( this );
  17708. };
  17709. THREE.Animation.prototype.reset = function () {
  17710. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17711. var object = this.hierarchy[ h ];
  17712. if ( object.animationCache === undefined ) {
  17713. object.animationCache = {
  17714. animations: {},
  17715. blending: {
  17716. positionWeight: 0.0,
  17717. quaternionWeight: 0.0,
  17718. scaleWeight: 0.0
  17719. }
  17720. };
  17721. }
  17722. if ( object.animationCache.animations[this.data.name] === undefined ) {
  17723. object.animationCache.animations[this.data.name] = {};
  17724. object.animationCache.animations[this.data.name].prevKey = { pos: 0, rot: 0, scl: 0 };
  17725. object.animationCache.animations[this.data.name].nextKey = { pos: 0, rot: 0, scl: 0 };
  17726. object.animationCache.animations[this.data.name].originalMatrix = object.matrix;
  17727. }
  17728. var animationCache = object.animationCache.animations[this.data.name];
  17729. // Get keys to match our current time
  17730. for ( var t = 0; t < 3; t ++ ) {
  17731. var type = this.keyTypes[ t ];
  17732. var prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17733. var nextKey = this.getNextKeyWith( type, h, 1 );
  17734. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  17735. prevKey = nextKey;
  17736. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17737. }
  17738. animationCache.prevKey[ type ] = prevKey;
  17739. animationCache.nextKey[ type ] = nextKey;
  17740. }
  17741. }
  17742. };
  17743. THREE.Animation.prototype.resetBlendWeights = function () {
  17744. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17745. var object = this.hierarchy[ h ];
  17746. if ( object.animationCache !== undefined ) {
  17747. object.animationCache.blending.positionWeight = 0.0;
  17748. object.animationCache.blending.quaternionWeight = 0.0;
  17749. object.animationCache.blending.scaleWeight = 0.0;
  17750. }
  17751. }
  17752. };
  17753. THREE.Animation.prototype.update = (function(){
  17754. var points = [];
  17755. var target = new THREE.Vector3();
  17756. var newVector = new THREE.Vector3();
  17757. var newQuat = new THREE.Quaternion();
  17758. // Catmull-Rom spline
  17759. var interpolateCatmullRom = function ( points, scale ) {
  17760. var c = [], v3 = [],
  17761. point, intPoint, weight, w2, w3,
  17762. pa, pb, pc, pd;
  17763. point = ( points.length - 1 ) * scale;
  17764. intPoint = Math.floor( point );
  17765. weight = point - intPoint;
  17766. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  17767. c[ 1 ] = intPoint;
  17768. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  17769. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  17770. pa = points[ c[ 0 ] ];
  17771. pb = points[ c[ 1 ] ];
  17772. pc = points[ c[ 2 ] ];
  17773. pd = points[ c[ 3 ] ];
  17774. w2 = weight * weight;
  17775. w3 = weight * w2;
  17776. v3[ 0 ] = interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  17777. v3[ 1 ] = interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  17778. v3[ 2 ] = interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  17779. return v3;
  17780. };
  17781. var interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  17782. var v0 = ( p2 - p0 ) * 0.5,
  17783. v1 = ( p3 - p1 ) * 0.5;
  17784. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17785. };
  17786. return function ( delta ) {
  17787. if ( this.isPlaying === false ) return;
  17788. this.currentTime += delta * this.timeScale;
  17789. if ( this.weight === 0 )
  17790. return;
  17791. //
  17792. var duration = this.data.length;
  17793. if ( this.currentTime > duration || this.currentTime < 0 ) {
  17794. if ( this.loop ) {
  17795. this.currentTime %= duration;
  17796. if ( this.currentTime < 0 )
  17797. this.currentTime += duration;
  17798. this.reset();
  17799. } else {
  17800. this.stop();
  17801. }
  17802. }
  17803. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17804. var object = this.hierarchy[ h ];
  17805. var animationCache = object.animationCache.animations[this.data.name];
  17806. var blending = object.animationCache.blending;
  17807. // loop through pos/rot/scl
  17808. for ( var t = 0; t < 3; t ++ ) {
  17809. // get keys
  17810. var type = this.keyTypes[ t ];
  17811. var prevKey = animationCache.prevKey[ type ];
  17812. var nextKey = animationCache.nextKey[ type ];
  17813. if ( ( this.timeScale > 0 && nextKey.time <= this.currentTime ) ||
  17814. ( this.timeScale < 0 && prevKey.time >= this.currentTime ) ) {
  17815. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17816. nextKey = this.getNextKeyWith( type, h, 1 );
  17817. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  17818. prevKey = nextKey;
  17819. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17820. }
  17821. animationCache.prevKey[ type ] = prevKey;
  17822. animationCache.nextKey[ type ] = nextKey;
  17823. }
  17824. var scale = ( this.currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  17825. var prevXYZ = prevKey[ type ];
  17826. var nextXYZ = nextKey[ type ];
  17827. if ( scale < 0 ) scale = 0;
  17828. if ( scale > 1 ) scale = 1;
  17829. // interpolate
  17830. if ( type === "pos" ) {
  17831. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  17832. newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17833. newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17834. newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17835. // blend
  17836. var proportionalWeight = this.weight / ( this.weight + blending.positionWeight );
  17837. object.position.lerp( newVector, proportionalWeight );
  17838. blending.positionWeight += this.weight;
  17839. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17840. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17841. points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  17842. points[ 1 ] = prevXYZ;
  17843. points[ 2 ] = nextXYZ;
  17844. points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  17845. scale = scale * 0.33 + 0.33;
  17846. var currentPoint = interpolateCatmullRom( points, scale );
  17847. var proportionalWeight = this.weight / ( this.weight + blending.positionWeight );
  17848. blending.positionWeight += this.weight;
  17849. // blend
  17850. var vector = object.position;
  17851. vector.x = vector.x + ( currentPoint[ 0 ] - vector.x ) * proportionalWeight;
  17852. vector.y = vector.y + ( currentPoint[ 1 ] - vector.y ) * proportionalWeight;
  17853. vector.z = vector.z + ( currentPoint[ 2 ] - vector.z ) * proportionalWeight;
  17854. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17855. var forwardPoint = interpolateCatmullRom( points, scale * 1.01 );
  17856. target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  17857. target.sub( vector );
  17858. target.y = 0;
  17859. target.normalize();
  17860. var angle = Math.atan2( target.x, target.z );
  17861. object.rotation.set( 0, angle, 0 );
  17862. }
  17863. }
  17864. } else if ( type === "rot" ) {
  17865. THREE.Quaternion.slerp( prevXYZ, nextXYZ, newQuat, scale );
  17866. // Avoid paying the cost of an additional slerp if we don't have to
  17867. if ( blending.quaternionWeight === 0 ) {
  17868. object.quaternion.copy(newQuat);
  17869. blending.quaternionWeight = this.weight;
  17870. } else {
  17871. var proportionalWeight = this.weight / ( this.weight + blending.quaternionWeight );
  17872. THREE.Quaternion.slerp( object.quaternion, newQuat, object.quaternion, proportionalWeight );
  17873. blending.quaternionWeight += this.weight;
  17874. }
  17875. } else if ( type === "scl" ) {
  17876. newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17877. newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17878. newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17879. var proportionalWeight = this.weight / ( this.weight + blending.scaleWeight );
  17880. object.scale.lerp( newVector, proportionalWeight );
  17881. blending.scaleWeight += this.weight;
  17882. }
  17883. }
  17884. }
  17885. return true;
  17886. };
  17887. })();
  17888. // Get next key with
  17889. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  17890. var keys = this.data.hierarchy[ h ].keys;
  17891. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17892. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17893. key = key < keys.length - 1 ? key : keys.length - 1;
  17894. } else {
  17895. key = key % keys.length;
  17896. }
  17897. for ( ; key < keys.length; key ++ ) {
  17898. if ( keys[ key ][ type ] !== undefined ) {
  17899. return keys[ key ];
  17900. }
  17901. }
  17902. return this.data.hierarchy[ h ].keys[ 0 ];
  17903. };
  17904. // Get previous key with
  17905. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  17906. var keys = this.data.hierarchy[ h ].keys;
  17907. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17908. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17909. key = key > 0 ? key : 0;
  17910. } else {
  17911. key = key >= 0 ? key : key + keys.length;
  17912. }
  17913. for ( ; key >= 0; key -- ) {
  17914. if ( keys[ key ][ type ] !== undefined ) {
  17915. return keys[ key ];
  17916. }
  17917. }
  17918. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  17919. };
  17920. // File:src/extras/animation/KeyFrameAnimation.js
  17921. /**
  17922. * @author mikael emtinger / http://gomo.se/
  17923. * @author mrdoob / http://mrdoob.com/
  17924. * @author alteredq / http://alteredqualia.com/
  17925. * @author khang duong
  17926. * @author erik kitson
  17927. */
  17928. THREE.KeyFrameAnimation = function ( data ) {
  17929. this.root = data.node;
  17930. this.data = THREE.AnimationHandler.init( data );
  17931. this.hierarchy = THREE.AnimationHandler.parse( this.root );
  17932. this.currentTime = 0;
  17933. this.timeScale = 0.001;
  17934. this.isPlaying = false;
  17935. this.isPaused = true;
  17936. this.loop = true;
  17937. // initialize to first keyframes
  17938. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17939. var keys = this.data.hierarchy[h].keys,
  17940. sids = this.data.hierarchy[h].sids,
  17941. obj = this.hierarchy[h];
  17942. if ( keys.length && sids ) {
  17943. for ( var s = 0; s < sids.length; s ++ ) {
  17944. var sid = sids[ s ],
  17945. next = this.getNextKeyWith( sid, h, 0 );
  17946. if ( next ) {
  17947. next.apply( sid );
  17948. }
  17949. }
  17950. obj.matrixAutoUpdate = false;
  17951. this.data.hierarchy[h].node.updateMatrix();
  17952. obj.matrixWorldNeedsUpdate = true;
  17953. }
  17954. }
  17955. };
  17956. THREE.KeyFrameAnimation.prototype.play = function ( startTime ) {
  17957. this.currentTime = startTime !== undefined ? startTime : 0;
  17958. if ( this.isPlaying === false ) {
  17959. this.isPlaying = true;
  17960. // reset key cache
  17961. var h, hl = this.hierarchy.length,
  17962. object,
  17963. node;
  17964. for ( h = 0; h < hl; h ++ ) {
  17965. object = this.hierarchy[ h ];
  17966. node = this.data.hierarchy[ h ];
  17967. if ( node.animationCache === undefined ) {
  17968. node.animationCache = {};
  17969. node.animationCache.prevKey = null;
  17970. node.animationCache.nextKey = null;
  17971. node.animationCache.originalMatrix = object.matrix;
  17972. }
  17973. var keys = this.data.hierarchy[h].keys;
  17974. if (keys.length) {
  17975. node.animationCache.prevKey = keys[ 0 ];
  17976. node.animationCache.nextKey = keys[ 1 ];
  17977. this.startTime = Math.min( keys[0].time, this.startTime );
  17978. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  17979. }
  17980. }
  17981. this.update( 0 );
  17982. }
  17983. this.isPaused = false;
  17984. THREE.AnimationHandler.play( this );
  17985. };
  17986. THREE.KeyFrameAnimation.prototype.stop = function() {
  17987. this.isPlaying = false;
  17988. this.isPaused = false;
  17989. THREE.AnimationHandler.stop( this );
  17990. // reset JIT matrix and remove cache
  17991. for ( var h = 0; h < this.data.hierarchy.length; h ++ ) {
  17992. var obj = this.hierarchy[ h ];
  17993. var node = this.data.hierarchy[ h ];
  17994. if ( node.animationCache !== undefined ) {
  17995. var original = node.animationCache.originalMatrix;
  17996. original.copy( obj.matrix );
  17997. obj.matrix = original;
  17998. delete node.animationCache;
  17999. }
  18000. }
  18001. };
  18002. // Update
  18003. THREE.KeyFrameAnimation.prototype.update = function ( delta ) {
  18004. if ( this.isPlaying === false ) return;
  18005. this.currentTime += delta * this.timeScale;
  18006. //
  18007. var duration = this.data.length;
  18008. if ( this.loop === true && this.currentTime > duration ) {
  18009. this.currentTime %= duration;
  18010. }
  18011. this.currentTime = Math.min( this.currentTime, duration );
  18012. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18013. var object = this.hierarchy[ h ];
  18014. var node = this.data.hierarchy[ h ];
  18015. var keys = node.keys,
  18016. animationCache = node.animationCache;
  18017. if ( keys.length ) {
  18018. var prevKey = animationCache.prevKey;
  18019. var nextKey = animationCache.nextKey;
  18020. if ( nextKey.time <= this.currentTime ) {
  18021. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18022. prevKey = nextKey;
  18023. nextKey = keys[ prevKey.index + 1 ];
  18024. }
  18025. animationCache.prevKey = prevKey;
  18026. animationCache.nextKey = nextKey;
  18027. }
  18028. if ( nextKey.time >= this.currentTime ) {
  18029. prevKey.interpolate( nextKey, this.currentTime );
  18030. } else {
  18031. prevKey.interpolate( nextKey, nextKey.time );
  18032. }
  18033. this.data.hierarchy[ h ].node.updateMatrix();
  18034. object.matrixWorldNeedsUpdate = true;
  18035. }
  18036. }
  18037. };
  18038. // Get next key with
  18039. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18040. var keys = this.data.hierarchy[ h ].keys;
  18041. key = key % keys.length;
  18042. for ( ; key < keys.length; key ++ ) {
  18043. if ( keys[ key ].hasTarget( sid ) ) {
  18044. return keys[ key ];
  18045. }
  18046. }
  18047. return keys[ 0 ];
  18048. };
  18049. // Get previous key with
  18050. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18051. var keys = this.data.hierarchy[ h ].keys;
  18052. key = key >= 0 ? key : key + keys.length;
  18053. for ( ; key >= 0; key -- ) {
  18054. if ( keys[ key ].hasTarget( sid ) ) {
  18055. return keys[ key ];
  18056. }
  18057. }
  18058. return keys[ keys.length - 1 ];
  18059. };
  18060. // File:src/extras/animation/MorphAnimation.js
  18061. /**
  18062. * @author mrdoob / http://mrdoob.com
  18063. * @author willy-vvu / http://willy-vvu.github.io
  18064. */
  18065. THREE.MorphAnimation = function ( mesh ) {
  18066. this.mesh = mesh;
  18067. this.frames = mesh.morphTargetInfluences.length;
  18068. this.currentTime = 0;
  18069. this.duration = 1000;
  18070. this.loop = true;
  18071. this.lastFrame = 0;
  18072. this.currentFrame = 0;
  18073. this.isPlaying = false;
  18074. };
  18075. THREE.MorphAnimation.prototype = {
  18076. constructor: THREE.MorphAnimation,
  18077. play: function () {
  18078. this.isPlaying = true;
  18079. },
  18080. pause: function () {
  18081. this.isPlaying = false;
  18082. },
  18083. update: function ( delta ) {
  18084. if ( this.isPlaying === false ) return;
  18085. this.currentTime += delta;
  18086. if ( this.loop === true && this.currentTime > this.duration ) {
  18087. this.currentTime %= this.duration;
  18088. }
  18089. this.currentTime = Math.min( this.currentTime, this.duration );
  18090. var interpolation = this.duration / this.frames;
  18091. var frame = Math.floor( this.currentTime / interpolation );
  18092. if ( frame != this.currentFrame ) {
  18093. this.mesh.morphTargetInfluences[ this.lastFrame ] = 0;
  18094. this.mesh.morphTargetInfluences[ this.currentFrame ] = 1;
  18095. this.mesh.morphTargetInfluences[ frame ] = 0;
  18096. this.lastFrame = this.currentFrame;
  18097. this.currentFrame = frame;
  18098. }
  18099. this.mesh.morphTargetInfluences[ frame ] = ( this.currentTime % interpolation ) / interpolation;
  18100. this.mesh.morphTargetInfluences[ this.lastFrame ] = 1 - this.mesh.morphTargetInfluences[ frame ];
  18101. }
  18102. };
  18103. // File:src/extras/geometries/BoxGeometry.js
  18104. /**
  18105. * @author mrdoob / http://mrdoob.com/
  18106. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18107. */
  18108. THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18109. THREE.Geometry.call( this );
  18110. this.type = 'BoxGeometry';
  18111. this.parameters = {
  18112. width: width,
  18113. height: height,
  18114. depth: depth,
  18115. widthSegments: widthSegments,
  18116. heightSegments: heightSegments,
  18117. depthSegments: depthSegments
  18118. };
  18119. this.widthSegments = widthSegments || 1;
  18120. this.heightSegments = heightSegments || 1;
  18121. this.depthSegments = depthSegments || 1;
  18122. var scope = this;
  18123. var width_half = width / 2;
  18124. var height_half = height / 2;
  18125. var depth_half = depth / 2;
  18126. buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, 0 ); // px
  18127. buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, 1 ); // nx
  18128. buildPlane( 'x', 'z', 1, 1, width, depth, height_half, 2 ); // py
  18129. buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, 3 ); // ny
  18130. buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, 4 ); // pz
  18131. buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, 5 ); // nz
  18132. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18133. var w, ix, iy,
  18134. gridX = scope.widthSegments,
  18135. gridY = scope.heightSegments,
  18136. width_half = width / 2,
  18137. height_half = height / 2,
  18138. offset = scope.vertices.length;
  18139. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18140. w = 'z';
  18141. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18142. w = 'y';
  18143. gridY = scope.depthSegments;
  18144. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18145. w = 'x';
  18146. gridX = scope.depthSegments;
  18147. }
  18148. var gridX1 = gridX + 1,
  18149. gridY1 = gridY + 1,
  18150. segment_width = width / gridX,
  18151. segment_height = height / gridY,
  18152. normal = new THREE.Vector3();
  18153. normal[ w ] = depth > 0 ? 1 : - 1;
  18154. for ( iy = 0; iy < gridY1; iy ++ ) {
  18155. for ( ix = 0; ix < gridX1; ix ++ ) {
  18156. var vector = new THREE.Vector3();
  18157. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18158. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18159. vector[ w ] = depth;
  18160. scope.vertices.push( vector );
  18161. }
  18162. }
  18163. for ( iy = 0; iy < gridY; iy ++ ) {
  18164. for ( ix = 0; ix < gridX; ix ++ ) {
  18165. var a = ix + gridX1 * iy;
  18166. var b = ix + gridX1 * ( iy + 1 );
  18167. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18168. var d = ( ix + 1 ) + gridX1 * iy;
  18169. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  18170. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  18171. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  18172. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  18173. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  18174. face.normal.copy( normal );
  18175. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18176. face.materialIndex = materialIndex;
  18177. scope.faces.push( face );
  18178. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  18179. face = new THREE.Face3( b + offset, c + offset, d + offset );
  18180. face.normal.copy( normal );
  18181. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18182. face.materialIndex = materialIndex;
  18183. scope.faces.push( face );
  18184. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  18185. }
  18186. }
  18187. }
  18188. this.mergeVertices();
  18189. };
  18190. THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18191. THREE.BoxGeometry.prototype.constructor = THREE.BoxGeometry;
  18192. // File:src/extras/geometries/CircleGeometry.js
  18193. /**
  18194. * @author hughes
  18195. */
  18196. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18197. THREE.Geometry.call( this );
  18198. this.type = 'CircleGeometry';
  18199. this.parameters = {
  18200. radius: radius,
  18201. segments: segments,
  18202. thetaStart: thetaStart,
  18203. thetaLength: thetaLength
  18204. };
  18205. radius = radius || 50;
  18206. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18207. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18208. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18209. var i, uvs = [],
  18210. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18211. this.vertices.push(center);
  18212. uvs.push( centerUV );
  18213. for ( i = 0; i <= segments; i ++ ) {
  18214. var vertex = new THREE.Vector3();
  18215. var segment = thetaStart + i / segments * thetaLength;
  18216. vertex.x = radius * Math.cos( segment );
  18217. vertex.y = radius * Math.sin( segment );
  18218. this.vertices.push( vertex );
  18219. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  18220. }
  18221. var n = new THREE.Vector3( 0, 0, 1 );
  18222. for ( i = 1; i <= segments; i ++ ) {
  18223. this.faces.push( new THREE.Face3( i, i + 1, 0, [ n.clone(), n.clone(), n.clone() ] ) );
  18224. this.faceVertexUvs[ 0 ].push( [ uvs[ i ].clone(), uvs[ i + 1 ].clone(), centerUV.clone() ] );
  18225. }
  18226. this.computeFaceNormals();
  18227. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18228. };
  18229. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18230. THREE.CircleGeometry.prototype.constructor = THREE.CircleGeometry;
  18231. // File:src/extras/geometries/CubeGeometry.js
  18232. /**
  18233. * @author mrdoob / http://mrdoob.com/
  18234. */
  18235. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18236. THREE.warn( 'THREE.CubeGeometry has been renamed to THREE.BoxGeometry.' );
  18237. return new THREE.BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments );
  18238. };
  18239. // File:src/extras/geometries/CylinderGeometry.js
  18240. /**
  18241. * @author mrdoob / http://mrdoob.com/
  18242. */
  18243. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  18244. THREE.Geometry.call( this );
  18245. this.type = 'CylinderGeometry';
  18246. this.parameters = {
  18247. radiusTop: radiusTop,
  18248. radiusBottom: radiusBottom,
  18249. height: height,
  18250. radialSegments: radialSegments,
  18251. heightSegments: heightSegments,
  18252. openEnded: openEnded,
  18253. thetaStart: thetaStart,
  18254. thetaLength: thetaLength
  18255. };
  18256. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18257. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18258. height = height !== undefined ? height : 100;
  18259. radialSegments = radialSegments || 8;
  18260. heightSegments = heightSegments || 1;
  18261. openEnded = openEnded !== undefined ? openEnded : false;
  18262. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18263. thetaLength = thetaLength !== undefined ? thetaLength : 2 * Math.PI;
  18264. var heightHalf = height / 2;
  18265. var x, y, vertices = [], uvs = [];
  18266. for ( y = 0; y <= heightSegments; y ++ ) {
  18267. var verticesRow = [];
  18268. var uvsRow = [];
  18269. var v = y / heightSegments;
  18270. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18271. for ( x = 0; x <= radialSegments; x ++ ) {
  18272. var u = x / radialSegments;
  18273. var vertex = new THREE.Vector3();
  18274. vertex.x = radius * Math.sin( u * thetaLength + thetaStart );
  18275. vertex.y = - v * height + heightHalf;
  18276. vertex.z = radius * Math.cos( u * thetaLength + thetaStart );
  18277. this.vertices.push( vertex );
  18278. verticesRow.push( this.vertices.length - 1 );
  18279. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18280. }
  18281. vertices.push( verticesRow );
  18282. uvs.push( uvsRow );
  18283. }
  18284. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18285. var na, nb;
  18286. for ( x = 0; x < radialSegments; x ++ ) {
  18287. if ( radiusTop !== 0 ) {
  18288. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18289. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18290. } else {
  18291. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18292. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18293. }
  18294. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18295. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18296. for ( y = 0; y < heightSegments; y ++ ) {
  18297. var v1 = vertices[ y ][ x ];
  18298. var v2 = vertices[ y + 1 ][ x ];
  18299. var v3 = vertices[ y + 1 ][ x + 1 ];
  18300. var v4 = vertices[ y ][ x + 1 ];
  18301. var n1 = na.clone();
  18302. var n2 = na.clone();
  18303. var n3 = nb.clone();
  18304. var n4 = nb.clone();
  18305. var uv1 = uvs[ y ][ x ].clone();
  18306. var uv2 = uvs[ y + 1 ][ x ].clone();
  18307. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18308. var uv4 = uvs[ y ][ x + 1 ].clone();
  18309. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  18310. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  18311. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  18312. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  18313. }
  18314. }
  18315. // top cap
  18316. if ( openEnded === false && radiusTop > 0 ) {
  18317. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18318. for ( x = 0; x < radialSegments; x ++ ) {
  18319. var v1 = vertices[ 0 ][ x ];
  18320. var v2 = vertices[ 0 ][ x + 1 ];
  18321. var v3 = this.vertices.length - 1;
  18322. var n1 = new THREE.Vector3( 0, 1, 0 );
  18323. var n2 = new THREE.Vector3( 0, 1, 0 );
  18324. var n3 = new THREE.Vector3( 0, 1, 0 );
  18325. var uv1 = uvs[ 0 ][ x ].clone();
  18326. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18327. var uv3 = new THREE.Vector2( uv2.x, 0 );
  18328. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18329. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18330. }
  18331. }
  18332. // bottom cap
  18333. if ( openEnded === false && radiusBottom > 0 ) {
  18334. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18335. for ( x = 0; x < radialSegments; x ++ ) {
  18336. var v1 = vertices[ heightSegments ][ x + 1 ];
  18337. var v2 = vertices[ heightSegments ][ x ];
  18338. var v3 = this.vertices.length - 1;
  18339. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18340. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18341. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18342. var uv1 = uvs[ heightSegments ][ x + 1 ].clone();
  18343. var uv2 = uvs[ heightSegments ][ x ].clone();
  18344. var uv3 = new THREE.Vector2( uv2.x, 1 );
  18345. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18346. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18347. }
  18348. }
  18349. this.computeFaceNormals();
  18350. };
  18351. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18352. THREE.CylinderGeometry.prototype.constructor = THREE.CylinderGeometry;
  18353. // File:src/extras/geometries/ExtrudeGeometry.js
  18354. /**
  18355. * @author zz85 / http://www.lab4games.net/zz85/blog
  18356. *
  18357. * Creates extruded geometry from a path shape.
  18358. *
  18359. * parameters = {
  18360. *
  18361. * curveSegments: <int>, // number of points on the curves
  18362. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18363. * amount: <int>, // Depth to extrude the shape
  18364. *
  18365. * bevelEnabled: <bool>, // turn on bevel
  18366. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18367. * bevelSize: <float>, // how far from shape outline is bevel
  18368. * bevelSegments: <int>, // number of bevel layers
  18369. *
  18370. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18371. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18372. *
  18373. * material: <int> // material index for front and back faces
  18374. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18375. * uvGenerator: <Object> // object that provides UV generator functions
  18376. *
  18377. * }
  18378. **/
  18379. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18380. if ( typeof( shapes ) === "undefined" ) {
  18381. shapes = [];
  18382. return;
  18383. }
  18384. THREE.Geometry.call( this );
  18385. this.type = 'ExtrudeGeometry';
  18386. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18387. this.addShapeList( shapes, options );
  18388. this.computeFaceNormals();
  18389. // can't really use automatic vertex normals
  18390. // as then front and back sides get smoothed too
  18391. // should do separate smoothing just for sides
  18392. //this.computeVertexNormals();
  18393. //console.log( "took", ( Date.now() - startTime ) );
  18394. };
  18395. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18396. THREE.ExtrudeGeometry.prototype.constructor = THREE.ExtrudeGeometry;
  18397. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18398. var sl = shapes.length;
  18399. for ( var s = 0; s < sl; s ++ ) {
  18400. var shape = shapes[ s ];
  18401. this.addShape( shape, options );
  18402. }
  18403. };
  18404. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18405. var amount = options.amount !== undefined ? options.amount : 100;
  18406. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18407. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18408. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18409. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18410. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18411. var steps = options.steps !== undefined ? options.steps : 1;
  18412. var extrudePath = options.extrudePath;
  18413. var extrudePts, extrudeByPath = false;
  18414. var material = options.material;
  18415. var extrudeMaterial = options.extrudeMaterial;
  18416. // Use default WorldUVGenerator if no UV generators are specified.
  18417. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18418. var splineTube, binormal, normal, position2;
  18419. if ( extrudePath ) {
  18420. extrudePts = extrudePath.getSpacedPoints( steps );
  18421. extrudeByPath = true;
  18422. bevelEnabled = false; // bevels not supported for path extrusion
  18423. // SETUP TNB variables
  18424. // Reuse TNB from TubeGeomtry for now.
  18425. // TODO1 - have a .isClosed in spline?
  18426. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18427. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18428. binormal = new THREE.Vector3();
  18429. normal = new THREE.Vector3();
  18430. position2 = new THREE.Vector3();
  18431. }
  18432. // Safeguards if bevels are not enabled
  18433. if ( ! bevelEnabled ) {
  18434. bevelSegments = 0;
  18435. bevelThickness = 0;
  18436. bevelSize = 0;
  18437. }
  18438. // Variables initalization
  18439. var ahole, h, hl; // looping of holes
  18440. var scope = this;
  18441. var bevelPoints = [];
  18442. var shapesOffset = this.vertices.length;
  18443. var shapePoints = shape.extractPoints( curveSegments );
  18444. var vertices = shapePoints.shape;
  18445. var holes = shapePoints.holes;
  18446. var reverse = ! THREE.Shape.Utils.isClockWise( vertices ) ;
  18447. if ( reverse ) {
  18448. vertices = vertices.reverse();
  18449. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18450. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18451. ahole = holes[ h ];
  18452. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18453. holes[ h ] = ahole.reverse();
  18454. }
  18455. }
  18456. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18457. }
  18458. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18459. /* Vertices */
  18460. var contour = vertices; // vertices has all points but contour has only points of circumference
  18461. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18462. ahole = holes[ h ];
  18463. vertices = vertices.concat( ahole );
  18464. }
  18465. function scalePt2 ( pt, vec, size ) {
  18466. if ( ! vec ) THREE.error( "THREE.ExtrudeGeometry: vec does not exist" );
  18467. return vec.clone().multiplyScalar( size ).add( pt );
  18468. }
  18469. var b, bs, t, z,
  18470. vert, vlen = vertices.length,
  18471. face, flen = faces.length,
  18472. cont, clen = contour.length;
  18473. // Find directions for point movement
  18474. var RAD_TO_DEGREES = 180 / Math.PI;
  18475. function getBevelVec( inPt, inPrev, inNext ) {
  18476. var EPSILON = 0.0000000001;
  18477. // computes for inPt the corresponding point inPt' on a new contour
  18478. // shiftet by 1 unit (length of normalized vector) to the left
  18479. // if we walk along contour clockwise, this new contour is outside the old one
  18480. //
  18481. // inPt' is the intersection of the two lines parallel to the two
  18482. // adjacent edges of inPt at a distance of 1 unit on the left side.
  18483. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  18484. // good reading for geometry algorithms (here: line-line intersection)
  18485. // http://geomalgorithms.com/a05-_intersect-1.html
  18486. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  18487. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  18488. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  18489. // check for colinear edges
  18490. var colinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18491. if ( Math.abs( colinear0 ) > EPSILON ) { // not colinear
  18492. // length of vectors for normalizing
  18493. var v_prev_len = Math.sqrt( v_prev_lensq );
  18494. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  18495. // shift adjacent points by unit vectors to the left
  18496. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  18497. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  18498. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  18499. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  18500. // scaling factor for v_prev to intersection point
  18501. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  18502. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  18503. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18504. // vector from inPt to intersection point
  18505. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  18506. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  18507. // Don't normalize!, otherwise sharp corners become ugly
  18508. // but prevent crazy spikes
  18509. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y )
  18510. if ( v_trans_lensq <= 2 ) {
  18511. return new THREE.Vector2( v_trans_x, v_trans_y );
  18512. } else {
  18513. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  18514. }
  18515. } else { // handle special case of colinear edges
  18516. var direction_eq = false; // assumes: opposite
  18517. if ( v_prev_x > EPSILON ) {
  18518. if ( v_next_x > EPSILON ) { direction_eq = true; }
  18519. } else {
  18520. if ( v_prev_x < - EPSILON ) {
  18521. if ( v_next_x < - EPSILON ) { direction_eq = true; }
  18522. } else {
  18523. if ( Math.sign(v_prev_y) == Math.sign(v_next_y) ) { direction_eq = true; }
  18524. }
  18525. }
  18526. if ( direction_eq ) {
  18527. // console.log("Warning: lines are a straight sequence");
  18528. v_trans_x = - v_prev_y;
  18529. v_trans_y = v_prev_x;
  18530. shrink_by = Math.sqrt( v_prev_lensq );
  18531. } else {
  18532. // console.log("Warning: lines are a straight spike");
  18533. v_trans_x = v_prev_x;
  18534. v_trans_y = v_prev_y;
  18535. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  18536. }
  18537. }
  18538. return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  18539. }
  18540. var contourMovements = [];
  18541. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18542. if ( j === il ) j = 0;
  18543. if ( k === il ) k = 0;
  18544. // (j)---(i)---(k)
  18545. // console.log('i,j,k', i, j , k)
  18546. var pt_i = contour[ i ];
  18547. var pt_j = contour[ j ];
  18548. var pt_k = contour[ k ];
  18549. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18550. }
  18551. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18552. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18553. ahole = holes[ h ];
  18554. oneHoleMovements = [];
  18555. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18556. if ( j === il ) j = 0;
  18557. if ( k === il ) k = 0;
  18558. // (j)---(i)---(k)
  18559. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18560. }
  18561. holesMovements.push( oneHoleMovements );
  18562. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18563. }
  18564. // Loop bevelSegments, 1 for the front, 1 for the back
  18565. for ( b = 0; b < bevelSegments; b ++ ) {
  18566. //for ( b = bevelSegments; b > 0; b -- ) {
  18567. t = b / bevelSegments;
  18568. z = bevelThickness * ( 1 - t );
  18569. //z = bevelThickness * t;
  18570. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18571. //bs = bevelSize * t ; // linear
  18572. // contract shape
  18573. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18574. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18575. v( vert.x, vert.y, - z );
  18576. }
  18577. // expand holes
  18578. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18579. ahole = holes[ h ];
  18580. oneHoleMovements = holesMovements[ h ];
  18581. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18582. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18583. v( vert.x, vert.y, - z );
  18584. }
  18585. }
  18586. }
  18587. bs = bevelSize;
  18588. // Back facing vertices
  18589. for ( i = 0; i < vlen; i ++ ) {
  18590. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18591. if ( ! extrudeByPath ) {
  18592. v( vert.x, vert.y, 0 );
  18593. } else {
  18594. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18595. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18596. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18597. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  18598. v( position2.x, position2.y, position2.z );
  18599. }
  18600. }
  18601. // Add stepped vertices...
  18602. // Including front facing vertices
  18603. var s;
  18604. for ( s = 1; s <= steps; s ++ ) {
  18605. for ( i = 0; i < vlen; i ++ ) {
  18606. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18607. if ( ! extrudeByPath ) {
  18608. v( vert.x, vert.y, amount / steps * s );
  18609. } else {
  18610. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18611. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18612. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18613. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  18614. v( position2.x, position2.y, position2.z );
  18615. }
  18616. }
  18617. }
  18618. // Add bevel segments planes
  18619. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18620. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18621. t = b / bevelSegments;
  18622. z = bevelThickness * ( 1 - t );
  18623. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18624. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  18625. // contract shape
  18626. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18627. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18628. v( vert.x, vert.y, amount + z );
  18629. }
  18630. // expand holes
  18631. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18632. ahole = holes[ h ];
  18633. oneHoleMovements = holesMovements[ h ];
  18634. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18635. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18636. if ( ! extrudeByPath ) {
  18637. v( vert.x, vert.y, amount + z );
  18638. } else {
  18639. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18640. }
  18641. }
  18642. }
  18643. }
  18644. /* Faces */
  18645. // Top and bottom faces
  18646. buildLidFaces();
  18647. // Sides faces
  18648. buildSideFaces();
  18649. ///// Internal functions
  18650. function buildLidFaces() {
  18651. if ( bevelEnabled ) {
  18652. var layer = 0 ; // steps + 1
  18653. var offset = vlen * layer;
  18654. // Bottom faces
  18655. for ( i = 0; i < flen; i ++ ) {
  18656. face = faces[ i ];
  18657. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset );
  18658. }
  18659. layer = steps + bevelSegments * 2;
  18660. offset = vlen * layer;
  18661. // Top faces
  18662. for ( i = 0; i < flen; i ++ ) {
  18663. face = faces[ i ];
  18664. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  18665. }
  18666. } else {
  18667. // Bottom faces
  18668. for ( i = 0; i < flen; i ++ ) {
  18669. face = faces[ i ];
  18670. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  18671. }
  18672. // Top faces
  18673. for ( i = 0; i < flen; i ++ ) {
  18674. face = faces[ i ];
  18675. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  18676. }
  18677. }
  18678. }
  18679. // Create faces for the z-sides of the shape
  18680. function buildSideFaces() {
  18681. var layeroffset = 0;
  18682. sidewalls( contour, layeroffset );
  18683. layeroffset += contour.length;
  18684. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18685. ahole = holes[ h ];
  18686. sidewalls( ahole, layeroffset );
  18687. //, true
  18688. layeroffset += ahole.length;
  18689. }
  18690. }
  18691. function sidewalls( contour, layeroffset ) {
  18692. var j, k;
  18693. i = contour.length;
  18694. while ( --i >= 0 ) {
  18695. j = i;
  18696. k = i - 1;
  18697. if ( k < 0 ) k = contour.length - 1;
  18698. //console.log('b', i,j, i-1, k,vertices.length);
  18699. var s = 0, sl = steps + bevelSegments * 2;
  18700. for ( s = 0; s < sl; s ++ ) {
  18701. var slen1 = vlen * s;
  18702. var slen2 = vlen * ( s + 1 );
  18703. var a = layeroffset + j + slen1,
  18704. b = layeroffset + k + slen1,
  18705. c = layeroffset + k + slen2,
  18706. d = layeroffset + j + slen2;
  18707. f4( a, b, c, d, contour, s, sl, j, k );
  18708. }
  18709. }
  18710. }
  18711. function v( x, y, z ) {
  18712. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  18713. }
  18714. function f3( a, b, c ) {
  18715. a += shapesOffset;
  18716. b += shapesOffset;
  18717. c += shapesOffset;
  18718. // normal, color, material
  18719. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18720. var uvs = uvgen.generateTopUV( scope, a, b, c );
  18721. scope.faceVertexUvs[ 0 ].push( uvs );
  18722. }
  18723. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18724. a += shapesOffset;
  18725. b += shapesOffset;
  18726. c += shapesOffset;
  18727. d += shapesOffset;
  18728. scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) );
  18729. scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) );
  18730. var uvs = uvgen.generateSideWallUV( scope, a, b, c, d );
  18731. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  18732. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  18733. }
  18734. };
  18735. THREE.ExtrudeGeometry.WorldUVGenerator = {
  18736. generateTopUV: function ( geometry, indexA, indexB, indexC ) {
  18737. var vertices = geometry.vertices;
  18738. var a = vertices[ indexA ];
  18739. var b = vertices[ indexB ];
  18740. var c = vertices[ indexC ];
  18741. return [
  18742. new THREE.Vector2( a.x, a.y ),
  18743. new THREE.Vector2( b.x, b.y ),
  18744. new THREE.Vector2( c.x, c.y )
  18745. ];
  18746. },
  18747. generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) {
  18748. var vertices = geometry.vertices;
  18749. var a = vertices[ indexA ];
  18750. var b = vertices[ indexB ];
  18751. var c = vertices[ indexC ];
  18752. var d = vertices[ indexD ];
  18753. if ( Math.abs( a.y - b.y ) < 0.01 ) {
  18754. return [
  18755. new THREE.Vector2( a.x, 1 - a.z ),
  18756. new THREE.Vector2( b.x, 1 - b.z ),
  18757. new THREE.Vector2( c.x, 1 - c.z ),
  18758. new THREE.Vector2( d.x, 1 - d.z )
  18759. ];
  18760. } else {
  18761. return [
  18762. new THREE.Vector2( a.y, 1 - a.z ),
  18763. new THREE.Vector2( b.y, 1 - b.z ),
  18764. new THREE.Vector2( c.y, 1 - c.z ),
  18765. new THREE.Vector2( d.y, 1 - d.z )
  18766. ];
  18767. }
  18768. }
  18769. };
  18770. // File:src/extras/geometries/ShapeGeometry.js
  18771. /**
  18772. * @author jonobr1 / http://jonobr1.com
  18773. *
  18774. * Creates a one-sided polygonal geometry from a path shape. Similar to
  18775. * ExtrudeGeometry.
  18776. *
  18777. * parameters = {
  18778. *
  18779. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  18780. *
  18781. * material: <int> // material index for front and back faces
  18782. * uvGenerator: <Object> // object that provides UV generator functions
  18783. *
  18784. * }
  18785. **/
  18786. THREE.ShapeGeometry = function ( shapes, options ) {
  18787. THREE.Geometry.call( this );
  18788. this.type = 'ShapeGeometry';
  18789. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  18790. this.addShapeList( shapes, options );
  18791. this.computeFaceNormals();
  18792. };
  18793. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18794. THREE.ShapeGeometry.prototype.constructor = THREE.ShapeGeometry;
  18795. /**
  18796. * Add an array of shapes to THREE.ShapeGeometry.
  18797. */
  18798. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18799. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  18800. this.addShape( shapes[ i ], options );
  18801. }
  18802. return this;
  18803. };
  18804. /**
  18805. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  18806. */
  18807. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  18808. if ( options === undefined ) options = {};
  18809. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18810. var material = options.material;
  18811. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  18812. //
  18813. var i, l, hole, s;
  18814. var shapesOffset = this.vertices.length;
  18815. var shapePoints = shape.extractPoints( curveSegments );
  18816. var vertices = shapePoints.shape;
  18817. var holes = shapePoints.holes;
  18818. var reverse = ! THREE.Shape.Utils.isClockWise( vertices );
  18819. if ( reverse ) {
  18820. vertices = vertices.reverse();
  18821. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  18822. for ( i = 0, l = holes.length; i < l; i ++ ) {
  18823. hole = holes[ i ];
  18824. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  18825. holes[ i ] = hole.reverse();
  18826. }
  18827. }
  18828. reverse = false;
  18829. }
  18830. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  18831. // Vertices
  18832. var contour = vertices;
  18833. for ( i = 0, l = holes.length; i < l; i ++ ) {
  18834. hole = holes[ i ];
  18835. vertices = vertices.concat( hole );
  18836. }
  18837. //
  18838. var vert, vlen = vertices.length;
  18839. var face, flen = faces.length;
  18840. var cont, clen = contour.length;
  18841. for ( i = 0; i < vlen; i ++ ) {
  18842. vert = vertices[ i ];
  18843. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  18844. }
  18845. for ( i = 0; i < flen; i ++ ) {
  18846. face = faces[ i ];
  18847. var a = face[ 0 ] + shapesOffset;
  18848. var b = face[ 1 ] + shapesOffset;
  18849. var c = face[ 2 ] + shapesOffset;
  18850. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18851. this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) );
  18852. }
  18853. };
  18854. // File:src/extras/geometries/LatheGeometry.js
  18855. /**
  18856. * @author astrodud / http://astrodud.isgreat.org/
  18857. * @author zz85 / https://github.com/zz85
  18858. * @author bhouston / http://exocortex.com
  18859. */
  18860. // points - to create a closed torus, one must use a set of points
  18861. // like so: [ a, b, c, d, a ], see first is the same as last.
  18862. // segments - the number of circumference segments to create
  18863. // phiStart - the starting radian
  18864. // phiLength - the radian (0 to 2*PI) range of the lathed section
  18865. // 2*pi is a closed lathe, less than 2PI is a portion.
  18866. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  18867. THREE.Geometry.call( this );
  18868. this.type = 'LatheGeometry';
  18869. this.parameters = {
  18870. points: points,
  18871. segments: segments,
  18872. phiStart: phiStart,
  18873. phiLength: phiLength
  18874. };
  18875. segments = segments || 12;
  18876. phiStart = phiStart || 0;
  18877. phiLength = phiLength || 2 * Math.PI;
  18878. var inversePointLength = 1.0 / ( points.length - 1 );
  18879. var inverseSegments = 1.0 / segments;
  18880. for ( var i = 0, il = segments; i <= il; i ++ ) {
  18881. var phi = phiStart + i * inverseSegments * phiLength;
  18882. var c = Math.cos( phi ),
  18883. s = Math.sin( phi );
  18884. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  18885. var pt = points[ j ];
  18886. var vertex = new THREE.Vector3();
  18887. vertex.x = c * pt.x - s * pt.y;
  18888. vertex.y = s * pt.x + c * pt.y;
  18889. vertex.z = pt.z;
  18890. this.vertices.push( vertex );
  18891. }
  18892. }
  18893. var np = points.length;
  18894. for ( var i = 0, il = segments; i < il; i ++ ) {
  18895. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  18896. var base = j + np * i;
  18897. var a = base;
  18898. var b = base + np;
  18899. var c = base + 1 + np;
  18900. var d = base + 1;
  18901. var u0 = i * inverseSegments;
  18902. var v0 = j * inversePointLength;
  18903. var u1 = u0 + inverseSegments;
  18904. var v1 = v0 + inversePointLength;
  18905. this.faces.push( new THREE.Face3( a, b, d ) );
  18906. this.faceVertexUvs[ 0 ].push( [
  18907. new THREE.Vector2( u0, v0 ),
  18908. new THREE.Vector2( u1, v0 ),
  18909. new THREE.Vector2( u0, v1 )
  18910. ] );
  18911. this.faces.push( new THREE.Face3( b, c, d ) );
  18912. this.faceVertexUvs[ 0 ].push( [
  18913. new THREE.Vector2( u1, v0 ),
  18914. new THREE.Vector2( u1, v1 ),
  18915. new THREE.Vector2( u0, v1 )
  18916. ] );
  18917. }
  18918. }
  18919. this.mergeVertices();
  18920. this.computeFaceNormals();
  18921. this.computeVertexNormals();
  18922. };
  18923. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18924. THREE.LatheGeometry.prototype.constructor = THREE.LatheGeometry;
  18925. // File:src/extras/geometries/PlaneGeometry.js
  18926. /**
  18927. * @author mrdoob / http://mrdoob.com/
  18928. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  18929. */
  18930. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  18931. console.info( 'THREE.PlaneGeometry: Consider using THREE.PlaneBufferGeometry for lower memory footprint.' );
  18932. THREE.Geometry.call( this );
  18933. this.type = 'PlaneGeometry';
  18934. this.parameters = {
  18935. width: width,
  18936. height: height,
  18937. widthSegments: widthSegments,
  18938. heightSegments: heightSegments
  18939. };
  18940. this.fromBufferGeometry( new THREE.PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  18941. };
  18942. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18943. THREE.PlaneGeometry.prototype.constructor = THREE.PlaneGeometry;
  18944. // File:src/extras/geometries/PlaneBufferGeometry.js
  18945. /**
  18946. * @author mrdoob / http://mrdoob.com/
  18947. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  18948. */
  18949. THREE.PlaneBufferGeometry = function ( width, height, widthSegments, heightSegments ) {
  18950. THREE.BufferGeometry.call( this );
  18951. this.type = 'PlaneBufferGeometry';
  18952. this.parameters = {
  18953. width: width,
  18954. height: height,
  18955. widthSegments: widthSegments,
  18956. heightSegments: heightSegments
  18957. };
  18958. var width_half = width / 2;
  18959. var height_half = height / 2;
  18960. var gridX = widthSegments || 1;
  18961. var gridY = heightSegments || 1;
  18962. var gridX1 = gridX + 1;
  18963. var gridY1 = gridY + 1;
  18964. var segment_width = width / gridX;
  18965. var segment_height = height / gridY;
  18966. var vertices = new Float32Array( gridX1 * gridY1 * 3 );
  18967. var normals = new Float32Array( gridX1 * gridY1 * 3 );
  18968. var uvs = new Float32Array( gridX1 * gridY1 * 2 );
  18969. var offset = 0;
  18970. var offset2 = 0;
  18971. for ( var iy = 0; iy < gridY1; iy ++ ) {
  18972. var y = iy * segment_height - height_half;
  18973. for ( var ix = 0; ix < gridX1; ix ++ ) {
  18974. var x = ix * segment_width - width_half;
  18975. vertices[ offset ] = x;
  18976. vertices[ offset + 1 ] = - y;
  18977. normals[ offset + 2 ] = 1;
  18978. uvs[ offset2 ] = ix / gridX;
  18979. uvs[ offset2 + 1 ] = 1 - ( iy / gridY );
  18980. offset += 3;
  18981. offset2 += 2;
  18982. }
  18983. }
  18984. offset = 0;
  18985. var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 );
  18986. for ( var iy = 0; iy < gridY; iy ++ ) {
  18987. for ( var ix = 0; ix < gridX; ix ++ ) {
  18988. var a = ix + gridX1 * iy;
  18989. var b = ix + gridX1 * ( iy + 1 );
  18990. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18991. var d = ( ix + 1 ) + gridX1 * iy;
  18992. indices[ offset ] = a;
  18993. indices[ offset + 1 ] = b;
  18994. indices[ offset + 2 ] = d;
  18995. indices[ offset + 3 ] = b;
  18996. indices[ offset + 4 ] = c;
  18997. indices[ offset + 5 ] = d;
  18998. offset += 6;
  18999. }
  19000. }
  19001. this.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) );
  19002. this.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  19003. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  19004. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  19005. };
  19006. THREE.PlaneBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  19007. THREE.PlaneBufferGeometry.prototype.constructor = THREE.PlaneBufferGeometry;
  19008. // File:src/extras/geometries/RingGeometry.js
  19009. /**
  19010. * @author Kaleb Murphy
  19011. */
  19012. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19013. THREE.Geometry.call( this );
  19014. this.type = 'RingGeometry';
  19015. this.parameters = {
  19016. innerRadius: innerRadius,
  19017. outerRadius: outerRadius,
  19018. thetaSegments: thetaSegments,
  19019. phiSegments: phiSegments,
  19020. thetaStart: thetaStart,
  19021. thetaLength: thetaLength
  19022. };
  19023. innerRadius = innerRadius || 0;
  19024. outerRadius = outerRadius || 50;
  19025. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19026. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19027. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19028. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 8;
  19029. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19030. for ( i = 0; i < phiSegments + 1; i ++ ) { // concentric circles inside ring
  19031. for ( o = 0; o < thetaSegments + 1; o ++ ) { // number of segments per circle
  19032. var vertex = new THREE.Vector3();
  19033. var segment = thetaStart + o / thetaSegments * thetaLength;
  19034. vertex.x = radius * Math.cos( segment );
  19035. vertex.y = radius * Math.sin( segment );
  19036. this.vertices.push( vertex );
  19037. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  19038. }
  19039. radius += radiusStep;
  19040. }
  19041. var n = new THREE.Vector3( 0, 0, 1 );
  19042. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19043. var thetaSegment = i * (thetaSegments + 1);
  19044. for ( o = 0; o < thetaSegments ; o ++ ) { // number of segments per circle
  19045. var segment = o + thetaSegment;
  19046. var v1 = segment;
  19047. var v2 = segment + thetaSegments + 1;
  19048. var v3 = segment + thetaSegments + 2;
  19049. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19050. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19051. v1 = segment;
  19052. v2 = segment + thetaSegments + 2;
  19053. v3 = segment + 1;
  19054. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19055. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19056. }
  19057. }
  19058. this.computeFaceNormals();
  19059. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19060. };
  19061. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19062. THREE.RingGeometry.prototype.constructor = THREE.RingGeometry;
  19063. // File:src/extras/geometries/SphereGeometry.js
  19064. /**
  19065. * @author mrdoob / http://mrdoob.com/
  19066. */
  19067. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19068. THREE.Geometry.call( this );
  19069. this.type = 'SphereGeometry';
  19070. this.parameters = {
  19071. radius: radius,
  19072. widthSegments: widthSegments,
  19073. heightSegments: heightSegments,
  19074. phiStart: phiStart,
  19075. phiLength: phiLength,
  19076. thetaStart: thetaStart,
  19077. thetaLength: thetaLength
  19078. };
  19079. radius = radius || 50;
  19080. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19081. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19082. phiStart = phiStart !== undefined ? phiStart : 0;
  19083. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19084. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19085. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19086. var x, y, vertices = [], uvs = [];
  19087. for ( y = 0; y <= heightSegments; y ++ ) {
  19088. var verticesRow = [];
  19089. var uvsRow = [];
  19090. for ( x = 0; x <= widthSegments; x ++ ) {
  19091. var u = x / widthSegments;
  19092. var v = y / heightSegments;
  19093. var vertex = new THREE.Vector3();
  19094. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19095. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19096. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19097. this.vertices.push( vertex );
  19098. verticesRow.push( this.vertices.length - 1 );
  19099. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19100. }
  19101. vertices.push( verticesRow );
  19102. uvs.push( uvsRow );
  19103. }
  19104. for ( y = 0; y < heightSegments; y ++ ) {
  19105. for ( x = 0; x < widthSegments; x ++ ) {
  19106. var v1 = vertices[ y ][ x + 1 ];
  19107. var v2 = vertices[ y ][ x ];
  19108. var v3 = vertices[ y + 1 ][ x ];
  19109. var v4 = vertices[ y + 1 ][ x + 1 ];
  19110. var n1 = this.vertices[ v1 ].clone().normalize();
  19111. var n2 = this.vertices[ v2 ].clone().normalize();
  19112. var n3 = this.vertices[ v3 ].clone().normalize();
  19113. var n4 = this.vertices[ v4 ].clone().normalize();
  19114. var uv1 = uvs[ y ][ x + 1 ].clone();
  19115. var uv2 = uvs[ y ][ x ].clone();
  19116. var uv3 = uvs[ y + 1 ][ x ].clone();
  19117. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19118. if ( Math.abs( this.vertices[ v1 ].y ) === radius ) {
  19119. uv1.x = ( uv1.x + uv2.x ) / 2;
  19120. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19121. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19122. } else if ( Math.abs( this.vertices[ v3 ].y ) === radius ) {
  19123. uv3.x = ( uv3.x + uv4.x ) / 2;
  19124. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19125. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19126. } else {
  19127. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19128. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19129. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  19130. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  19131. }
  19132. }
  19133. }
  19134. this.computeFaceNormals();
  19135. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19136. };
  19137. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19138. THREE.SphereGeometry.prototype.constructor = THREE.SphereGeometry;
  19139. // File:src/extras/geometries/TextGeometry.js
  19140. /**
  19141. * @author zz85 / http://www.lab4games.net/zz85/blog
  19142. * @author alteredq / http://alteredqualia.com/
  19143. *
  19144. * For creating 3D text geometry in three.js
  19145. *
  19146. * Text = 3D Text
  19147. *
  19148. * parameters = {
  19149. * size: <float>, // size of the text
  19150. * height: <float>, // thickness to extrude text
  19151. * curveSegments: <int>, // number of points on the curves
  19152. *
  19153. * font: <string>, // font name
  19154. * weight: <string>, // font weight (normal, bold)
  19155. * style: <string>, // font style (normal, italics)
  19156. *
  19157. * bevelEnabled: <bool>, // turn on bevel
  19158. * bevelThickness: <float>, // how deep into text bevel goes
  19159. * bevelSize: <float>, // how far from text outline is bevel
  19160. * }
  19161. *
  19162. */
  19163. /* Usage Examples
  19164. // TextGeometry wrapper
  19165. var text3d = new TextGeometry( text, options );
  19166. // Complete manner
  19167. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19168. var text3d = new ExtrudeGeometry( textShapes, options );
  19169. */
  19170. THREE.TextGeometry = function ( text, parameters ) {
  19171. parameters = parameters || {};
  19172. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19173. // translate parameters to ExtrudeGeometry API
  19174. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19175. // defaults
  19176. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19177. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19178. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19179. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19180. this.type = 'TextGeometry';
  19181. };
  19182. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19183. THREE.TextGeometry.prototype.constructor = THREE.TextGeometry;
  19184. // File:src/extras/geometries/TorusGeometry.js
  19185. /**
  19186. * @author oosmoxiecode
  19187. * @author mrdoob / http://mrdoob.com/
  19188. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19189. */
  19190. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19191. THREE.Geometry.call( this );
  19192. this.type = 'TorusGeometry';
  19193. this.parameters = {
  19194. radius: radius,
  19195. tube: tube,
  19196. radialSegments: radialSegments,
  19197. tubularSegments: tubularSegments,
  19198. arc: arc
  19199. };
  19200. radius = radius || 100;
  19201. tube = tube || 40;
  19202. radialSegments = radialSegments || 8;
  19203. tubularSegments = tubularSegments || 6;
  19204. arc = arc || Math.PI * 2;
  19205. var center = new THREE.Vector3(), uvs = [], normals = [];
  19206. for ( var j = 0; j <= radialSegments; j ++ ) {
  19207. for ( var i = 0; i <= tubularSegments; i ++ ) {
  19208. var u = i / tubularSegments * arc;
  19209. var v = j / radialSegments * Math.PI * 2;
  19210. center.x = radius * Math.cos( u );
  19211. center.y = radius * Math.sin( u );
  19212. var vertex = new THREE.Vector3();
  19213. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  19214. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  19215. vertex.z = tube * Math.sin( v );
  19216. this.vertices.push( vertex );
  19217. uvs.push( new THREE.Vector2( i / tubularSegments, j / radialSegments ) );
  19218. normals.push( vertex.clone().sub( center ).normalize() );
  19219. }
  19220. }
  19221. for ( var j = 1; j <= radialSegments; j ++ ) {
  19222. for ( var i = 1; i <= tubularSegments; i ++ ) {
  19223. var a = ( tubularSegments + 1 ) * j + i - 1;
  19224. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19225. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  19226. var d = ( tubularSegments + 1 ) * j + i;
  19227. var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
  19228. this.faces.push( face );
  19229. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  19230. face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
  19231. this.faces.push( face );
  19232. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19233. }
  19234. }
  19235. this.computeFaceNormals();
  19236. };
  19237. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19238. THREE.TorusGeometry.prototype.constructor = THREE.TorusGeometry;
  19239. // File:src/extras/geometries/TorusKnotGeometry.js
  19240. /**
  19241. * @author oosmoxiecode
  19242. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19243. */
  19244. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19245. THREE.Geometry.call( this );
  19246. this.type = 'TorusKnotGeometry';
  19247. this.parameters = {
  19248. radius: radius,
  19249. tube: tube,
  19250. radialSegments: radialSegments,
  19251. tubularSegments: tubularSegments,
  19252. p: p,
  19253. q: q,
  19254. heightScale: heightScale
  19255. };
  19256. radius = radius || 100;
  19257. tube = tube || 40;
  19258. radialSegments = radialSegments || 64;
  19259. tubularSegments = tubularSegments || 8;
  19260. p = p || 2;
  19261. q = q || 3;
  19262. heightScale = heightScale || 1;
  19263. var grid = new Array( radialSegments );
  19264. var tang = new THREE.Vector3();
  19265. var n = new THREE.Vector3();
  19266. var bitan = new THREE.Vector3();
  19267. for ( var i = 0; i < radialSegments; ++ i ) {
  19268. grid[ i ] = new Array( tubularSegments );
  19269. var u = i / radialSegments * 2 * p * Math.PI;
  19270. var p1 = getPos( u, q, p, radius, heightScale );
  19271. var p2 = getPos( u + 0.01, q, p, radius, heightScale );
  19272. tang.subVectors( p2, p1 );
  19273. n.addVectors( p2, p1 );
  19274. bitan.crossVectors( tang, n );
  19275. n.crossVectors( bitan, tang );
  19276. bitan.normalize();
  19277. n.normalize();
  19278. for ( var j = 0; j < tubularSegments; ++ j ) {
  19279. var v = j / tubularSegments * 2 * Math.PI;
  19280. var cx = - tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19281. var cy = tube * Math.sin( v );
  19282. var pos = new THREE.Vector3();
  19283. pos.x = p1.x + cx * n.x + cy * bitan.x;
  19284. pos.y = p1.y + cx * n.y + cy * bitan.y;
  19285. pos.z = p1.z + cx * n.z + cy * bitan.z;
  19286. grid[ i ][ j ] = this.vertices.push( pos ) - 1;
  19287. }
  19288. }
  19289. for ( var i = 0; i < radialSegments; ++ i ) {
  19290. for ( var j = 0; j < tubularSegments; ++ j ) {
  19291. var ip = ( i + 1 ) % radialSegments;
  19292. var jp = ( j + 1 ) % tubularSegments;
  19293. var a = grid[ i ][ j ];
  19294. var b = grid[ ip ][ j ];
  19295. var c = grid[ ip ][ jp ];
  19296. var d = grid[ i ][ jp ];
  19297. var uva = new THREE.Vector2( i / radialSegments, j / tubularSegments );
  19298. var uvb = new THREE.Vector2( ( i + 1 ) / radialSegments, j / tubularSegments );
  19299. var uvc = new THREE.Vector2( ( i + 1 ) / radialSegments, ( j + 1 ) / tubularSegments );
  19300. var uvd = new THREE.Vector2( i / radialSegments, ( j + 1 ) / tubularSegments );
  19301. this.faces.push( new THREE.Face3( a, b, d ) );
  19302. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19303. this.faces.push( new THREE.Face3( b, c, d ) );
  19304. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19305. }
  19306. }
  19307. this.computeFaceNormals();
  19308. this.computeVertexNormals();
  19309. function getPos( u, in_q, in_p, radius, heightScale ) {
  19310. var cu = Math.cos( u );
  19311. var su = Math.sin( u );
  19312. var quOverP = in_q / in_p * u;
  19313. var cs = Math.cos( quOverP );
  19314. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19315. var ty = radius * ( 2 + cs ) * su * 0.5;
  19316. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19317. return new THREE.Vector3( tx, ty, tz );
  19318. }
  19319. };
  19320. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19321. THREE.TorusKnotGeometry.prototype.constructor = THREE.TorusKnotGeometry;
  19322. // File:src/extras/geometries/TubeGeometry.js
  19323. /**
  19324. * @author WestLangley / https://github.com/WestLangley
  19325. * @author zz85 / https://github.com/zz85
  19326. * @author miningold / https://github.com/miningold
  19327. * @author jonobr1 / https://github.com/jonobr1
  19328. *
  19329. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19330. *
  19331. * Creates a tube which extrudes along a 3d spline
  19332. *
  19333. * Uses parallel transport frames as described in
  19334. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19335. */
  19336. THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, taper ) {
  19337. THREE.Geometry.call( this );
  19338. this.type = 'TubeGeometry';
  19339. this.parameters = {
  19340. path: path,
  19341. segments: segments,
  19342. radius: radius,
  19343. radialSegments: radialSegments,
  19344. closed: closed
  19345. };
  19346. segments = segments || 64;
  19347. radius = radius || 1;
  19348. radialSegments = radialSegments || 8;
  19349. closed = closed || false;
  19350. taper = taper || THREE.TubeGeometry.NoTaper;
  19351. var grid = [];
  19352. var scope = this,
  19353. tangent,
  19354. normal,
  19355. binormal,
  19356. numpoints = segments + 1,
  19357. x, y, z,
  19358. tx, ty, tz,
  19359. u, v, r,
  19360. cx, cy,
  19361. pos, pos2 = new THREE.Vector3(),
  19362. i, j,
  19363. ip, jp,
  19364. a, b, c, d,
  19365. uva, uvb, uvc, uvd;
  19366. var frames = new THREE.TubeGeometry.FrenetFrames( path, segments, closed ),
  19367. tangents = frames.tangents,
  19368. normals = frames.normals,
  19369. binormals = frames.binormals;
  19370. // proxy internals
  19371. this.tangents = tangents;
  19372. this.normals = normals;
  19373. this.binormals = binormals;
  19374. function vert( x, y, z ) {
  19375. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19376. }
  19377. // consruct the grid
  19378. for ( i = 0; i < numpoints; i ++ ) {
  19379. grid[ i ] = [];
  19380. u = i / ( numpoints - 1 );
  19381. pos = path.getPointAt( u );
  19382. tangent = tangents[ i ];
  19383. normal = normals[ i ];
  19384. binormal = binormals[ i ];
  19385. r = radius * taper( u );
  19386. for ( j = 0; j < radialSegments; j ++ ) {
  19387. v = j / radialSegments * 2 * Math.PI;
  19388. cx = - r * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19389. cy = r * Math.sin( v );
  19390. pos2.copy( pos );
  19391. pos2.x += cx * normal.x + cy * binormal.x;
  19392. pos2.y += cx * normal.y + cy * binormal.y;
  19393. pos2.z += cx * normal.z + cy * binormal.z;
  19394. grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19395. }
  19396. }
  19397. // construct the mesh
  19398. for ( i = 0; i < segments; i ++ ) {
  19399. for ( j = 0; j < radialSegments; j ++ ) {
  19400. ip = ( closed ) ? (i + 1) % segments : i + 1;
  19401. jp = (j + 1) % radialSegments;
  19402. a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19403. b = grid[ ip ][ j ];
  19404. c = grid[ ip ][ jp ];
  19405. d = grid[ i ][ jp ];
  19406. uva = new THREE.Vector2( i / segments, j / radialSegments );
  19407. uvb = new THREE.Vector2( ( i + 1 ) / segments, j / radialSegments );
  19408. uvc = new THREE.Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments );
  19409. uvd = new THREE.Vector2( i / segments, ( j + 1 ) / radialSegments );
  19410. this.faces.push( new THREE.Face3( a, b, d ) );
  19411. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19412. this.faces.push( new THREE.Face3( b, c, d ) );
  19413. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19414. }
  19415. }
  19416. this.computeFaceNormals();
  19417. this.computeVertexNormals();
  19418. };
  19419. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19420. THREE.TubeGeometry.prototype.constructor = THREE.TubeGeometry;
  19421. THREE.TubeGeometry.NoTaper = function ( u ) {
  19422. return 1;
  19423. };
  19424. THREE.TubeGeometry.SinusoidalTaper = function ( u ) {
  19425. return Math.sin( Math.PI * u );
  19426. };
  19427. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19428. THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) {
  19429. var tangent = new THREE.Vector3(),
  19430. normal = new THREE.Vector3(),
  19431. binormal = new THREE.Vector3(),
  19432. tangents = [],
  19433. normals = [],
  19434. binormals = [],
  19435. vec = new THREE.Vector3(),
  19436. mat = new THREE.Matrix4(),
  19437. numpoints = segments + 1,
  19438. theta,
  19439. epsilon = 0.0001,
  19440. smallest,
  19441. tx, ty, tz,
  19442. i, u, v;
  19443. // expose internals
  19444. this.tangents = tangents;
  19445. this.normals = normals;
  19446. this.binormals = binormals;
  19447. // compute the tangent vectors for each segment on the path
  19448. for ( i = 0; i < numpoints; i ++ ) {
  19449. u = i / ( numpoints - 1 );
  19450. tangents[ i ] = path.getTangentAt( u );
  19451. tangents[ i ].normalize();
  19452. }
  19453. initialNormal3();
  19454. /*
  19455. function initialNormal1(lastBinormal) {
  19456. // fixed start binormal. Has dangers of 0 vectors
  19457. normals[ 0 ] = new THREE.Vector3();
  19458. binormals[ 0 ] = new THREE.Vector3();
  19459. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19460. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19461. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19462. }
  19463. function initialNormal2() {
  19464. // This uses the Frenet-Serret formula for deriving binormal
  19465. var t2 = path.getTangentAt( epsilon );
  19466. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  19467. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  19468. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19469. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19470. }
  19471. */
  19472. function initialNormal3() {
  19473. // select an initial normal vector perpenicular to the first tangent vector,
  19474. // and in the direction of the smallest tangent xyz component
  19475. normals[ 0 ] = new THREE.Vector3();
  19476. binormals[ 0 ] = new THREE.Vector3();
  19477. smallest = Number.MAX_VALUE;
  19478. tx = Math.abs( tangents[ 0 ].x );
  19479. ty = Math.abs( tangents[ 0 ].y );
  19480. tz = Math.abs( tangents[ 0 ].z );
  19481. if ( tx <= smallest ) {
  19482. smallest = tx;
  19483. normal.set( 1, 0, 0 );
  19484. }
  19485. if ( ty <= smallest ) {
  19486. smallest = ty;
  19487. normal.set( 0, 1, 0 );
  19488. }
  19489. if ( tz <= smallest ) {
  19490. normal.set( 0, 0, 1 );
  19491. }
  19492. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19493. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19494. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19495. }
  19496. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19497. for ( i = 1; i < numpoints; i ++ ) {
  19498. normals[ i ] = normals[ i-1 ].clone();
  19499. binormals[ i ] = binormals[ i-1 ].clone();
  19500. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  19501. if ( vec.length() > epsilon ) {
  19502. vec.normalize();
  19503. theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  19504. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19505. }
  19506. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19507. }
  19508. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19509. if ( closed ) {
  19510. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), - 1, 1 ) );
  19511. theta /= ( numpoints - 1 );
  19512. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19513. theta = - theta;
  19514. }
  19515. for ( i = 1; i < numpoints; i ++ ) {
  19516. // twist a little...
  19517. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19518. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19519. }
  19520. }
  19521. };
  19522. // File:src/extras/geometries/PolyhedronGeometry.js
  19523. /**
  19524. * @author clockworkgeek / https://github.com/clockworkgeek
  19525. * @author timothypratley / https://github.com/timothypratley
  19526. * @author WestLangley / http://github.com/WestLangley
  19527. */
  19528. THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) {
  19529. THREE.Geometry.call( this );
  19530. this.type = 'PolyhedronGeometry';
  19531. this.parameters = {
  19532. vertices: vertices,
  19533. indices: indices,
  19534. radius: radius,
  19535. detail: detail
  19536. };
  19537. radius = radius || 1;
  19538. detail = detail || 0;
  19539. var that = this;
  19540. for ( var i = 0, l = vertices.length; i < l; i += 3 ) {
  19541. prepare( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  19542. }
  19543. var midpoints = [], p = this.vertices;
  19544. var faces = [];
  19545. for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) {
  19546. var v1 = p[ indices[ i ] ];
  19547. var v2 = p[ indices[ i + 1 ] ];
  19548. var v3 = p[ indices[ i + 2 ] ];
  19549. faces[ j ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19550. }
  19551. var centroid = new THREE.Vector3();
  19552. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19553. subdivide( faces[ i ], detail );
  19554. }
  19555. // Handle case when face straddles the seam
  19556. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  19557. var uvs = this.faceVertexUvs[ 0 ][ i ];
  19558. var x0 = uvs[ 0 ].x;
  19559. var x1 = uvs[ 1 ].x;
  19560. var x2 = uvs[ 2 ].x;
  19561. var max = Math.max( x0, Math.max( x1, x2 ) );
  19562. var min = Math.min( x0, Math.min( x1, x2 ) );
  19563. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  19564. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  19565. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  19566. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  19567. }
  19568. }
  19569. // Apply radius
  19570. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19571. this.vertices[ i ].multiplyScalar( radius );
  19572. }
  19573. // Merge vertices
  19574. this.mergeVertices();
  19575. this.computeFaceNormals();
  19576. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19577. // Project vector onto sphere's surface
  19578. function prepare( vector ) {
  19579. var vertex = vector.normalize().clone();
  19580. vertex.index = that.vertices.push( vertex ) - 1;
  19581. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19582. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19583. var v = inclination( vector ) / Math.PI + 0.5;
  19584. vertex.uv = new THREE.Vector2( u, 1 - v );
  19585. return vertex;
  19586. }
  19587. // Approximate a curved face with recursively sub-divided triangles.
  19588. function make( v1, v2, v3 ) {
  19589. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19590. that.faces.push( face );
  19591. centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  19592. var azi = azimuth( centroid );
  19593. that.faceVertexUvs[ 0 ].push( [
  19594. correctUV( v1.uv, v1, azi ),
  19595. correctUV( v2.uv, v2, azi ),
  19596. correctUV( v3.uv, v3, azi )
  19597. ] );
  19598. }
  19599. // Analytically subdivide a face to the required detail level.
  19600. function subdivide( face, detail ) {
  19601. var cols = Math.pow(2, detail);
  19602. var cells = Math.pow(4, detail);
  19603. var a = prepare( that.vertices[ face.a ] );
  19604. var b = prepare( that.vertices[ face.b ] );
  19605. var c = prepare( that.vertices[ face.c ] );
  19606. var v = [];
  19607. // Construct all of the vertices for this subdivision.
  19608. for ( var i = 0 ; i <= cols; i ++ ) {
  19609. v[ i ] = [];
  19610. var aj = prepare( a.clone().lerp( c, i / cols ) );
  19611. var bj = prepare( b.clone().lerp( c, i / cols ) );
  19612. var rows = cols - i;
  19613. for ( var j = 0; j <= rows; j ++) {
  19614. if ( j == 0 && i == cols ) {
  19615. v[ i ][ j ] = aj;
  19616. } else {
  19617. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  19618. }
  19619. }
  19620. }
  19621. // Construct all of the faces.
  19622. for ( var i = 0; i < cols ; i ++ ) {
  19623. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  19624. var k = Math.floor( j / 2 );
  19625. if ( j % 2 == 0 ) {
  19626. make(
  19627. v[ i ][ k + 1],
  19628. v[ i + 1 ][ k ],
  19629. v[ i ][ k ]
  19630. );
  19631. } else {
  19632. make(
  19633. v[ i ][ k + 1 ],
  19634. v[ i + 1][ k + 1],
  19635. v[ i + 1 ][ k ]
  19636. );
  19637. }
  19638. }
  19639. }
  19640. }
  19641. // Angle around the Y axis, counter-clockwise when looking from above.
  19642. function azimuth( vector ) {
  19643. return Math.atan2( vector.z, - vector.x );
  19644. }
  19645. // Angle above the XZ plane.
  19646. function inclination( vector ) {
  19647. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19648. }
  19649. // Texture fixing helper. Spheres have some odd behaviours.
  19650. function correctUV( uv, vector, azimuth ) {
  19651. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  19652. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  19653. return uv.clone();
  19654. }
  19655. };
  19656. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19657. THREE.PolyhedronGeometry.prototype.constructor = THREE.PolyhedronGeometry;
  19658. // File:src/extras/geometries/DodecahedronGeometry.js
  19659. /**
  19660. * @author Abe Pazos / https://hamoid.com
  19661. */
  19662. THREE.DodecahedronGeometry = function ( radius, detail ) {
  19663. this.parameters = {
  19664. radius: radius,
  19665. detail: detail
  19666. };
  19667. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19668. var r = 1 / t;
  19669. var vertices = [
  19670. // (±1, ±1, ±1)
  19671. -1, -1, -1, -1, -1, 1,
  19672. -1, 1, -1, -1, 1, 1,
  19673. 1, -1, -1, 1, -1, 1,
  19674. 1, 1, -1, 1, 1, 1,
  19675. // (0, ±1/φ, ±φ)
  19676. 0, -r, -t, 0, -r, t,
  19677. 0, r, -t, 0, r, t,
  19678. // (±1/φ, ±φ, 0)
  19679. -r, -t, 0, -r, t, 0,
  19680. r, -t, 0, r, t, 0,
  19681. // (±φ, 0, ±1/φ)
  19682. -t, 0, -r, t, 0, -r,
  19683. -t, 0, r, t, 0, r
  19684. ];
  19685. var indices = [
  19686. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  19687. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  19688. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  19689. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  19690. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  19691. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  19692. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  19693. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  19694. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  19695. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  19696. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  19697. 1, 12, 14, 1, 14, 5, 1, 5, 9
  19698. ];
  19699. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  19700. };
  19701. THREE.DodecahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19702. THREE.DodecahedronGeometry.prototype.constructor = THREE.DodecahedronGeometry;
  19703. // File:src/extras/geometries/IcosahedronGeometry.js
  19704. /**
  19705. * @author timothypratley / https://github.com/timothypratley
  19706. */
  19707. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19708. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19709. var vertices = [
  19710. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  19711. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  19712. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  19713. ];
  19714. var indices = [
  19715. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  19716. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  19717. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  19718. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  19719. ];
  19720. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  19721. this.type = 'IcosahedronGeometry';
  19722. this.parameters = {
  19723. radius: radius,
  19724. detail: detail
  19725. };
  19726. };
  19727. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19728. THREE.IcosahedronGeometry.prototype.constructor = THREE.IcosahedronGeometry;
  19729. // File:src/extras/geometries/OctahedronGeometry.js
  19730. /**
  19731. * @author timothypratley / https://github.com/timothypratley
  19732. */
  19733. THREE.OctahedronGeometry = function ( radius, detail ) {
  19734. this.parameters = {
  19735. radius: radius,
  19736. detail: detail
  19737. };
  19738. var vertices = [
  19739. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0,- 1, 0, 0, 0, 1, 0, 0,- 1
  19740. ];
  19741. var indices = [
  19742. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  19743. ];
  19744. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  19745. this.type = 'OctahedronGeometry';
  19746. this.parameters = {
  19747. radius: radius,
  19748. detail: detail
  19749. };
  19750. };
  19751. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19752. THREE.OctahedronGeometry.prototype.constructor = THREE.OctahedronGeometry;
  19753. // File:src/extras/geometries/TetrahedronGeometry.js
  19754. /**
  19755. * @author timothypratley / https://github.com/timothypratley
  19756. */
  19757. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19758. var vertices = [
  19759. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  19760. ];
  19761. var indices = [
  19762. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  19763. ];
  19764. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  19765. this.type = 'TetrahedronGeometry';
  19766. this.parameters = {
  19767. radius: radius,
  19768. detail: detail
  19769. };
  19770. };
  19771. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19772. THREE.TetrahedronGeometry.prototype.constructor = THREE.TetrahedronGeometry;
  19773. // File:src/extras/geometries/ParametricGeometry.js
  19774. /**
  19775. * @author zz85 / https://github.com/zz85
  19776. * Parametric Surfaces Geometry
  19777. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19778. *
  19779. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  19780. *
  19781. */
  19782. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  19783. THREE.Geometry.call( this );
  19784. this.type = 'ParametricGeometry';
  19785. this.parameters = {
  19786. func: func,
  19787. slices: slices,
  19788. stacks: stacks
  19789. };
  19790. var verts = this.vertices;
  19791. var faces = this.faces;
  19792. var uvs = this.faceVertexUvs[ 0 ];
  19793. var i, j, p;
  19794. var u, v;
  19795. var stackCount = stacks + 1;
  19796. var sliceCount = slices + 1;
  19797. for ( i = 0; i <= stacks; i ++ ) {
  19798. v = i / stacks;
  19799. for ( j = 0; j <= slices; j ++ ) {
  19800. u = j / slices;
  19801. p = func( u, v );
  19802. verts.push( p );
  19803. }
  19804. }
  19805. var a, b, c, d;
  19806. var uva, uvb, uvc, uvd;
  19807. for ( i = 0; i < stacks; i ++ ) {
  19808. for ( j = 0; j < slices; j ++ ) {
  19809. a = i * sliceCount + j;
  19810. b = i * sliceCount + j + 1;
  19811. c = (i + 1) * sliceCount + j + 1;
  19812. d = (i + 1) * sliceCount + j;
  19813. uva = new THREE.Vector2( j / slices, i / stacks );
  19814. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  19815. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  19816. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  19817. faces.push( new THREE.Face3( a, b, d ) );
  19818. uvs.push( [ uva, uvb, uvd ] );
  19819. faces.push( new THREE.Face3( b, c, d ) );
  19820. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  19821. }
  19822. }
  19823. // console.log(this);
  19824. // magic bullet
  19825. // var diff = this.mergeVertices();
  19826. // console.log('removed ', diff, ' vertices by merging');
  19827. this.computeFaceNormals();
  19828. this.computeVertexNormals();
  19829. };
  19830. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19831. THREE.ParametricGeometry.prototype.constructor = THREE.ParametricGeometry;
  19832. // File:src/extras/helpers/AxisHelper.js
  19833. /**
  19834. * @author sroucheray / http://sroucheray.org/
  19835. * @author mrdoob / http://mrdoob.com/
  19836. */
  19837. THREE.AxisHelper = function ( size ) {
  19838. size = size || 1;
  19839. var vertices = new Float32Array( [
  19840. 0, 0, 0, size, 0, 0,
  19841. 0, 0, 0, 0, size, 0,
  19842. 0, 0, 0, 0, 0, size
  19843. ] );
  19844. var colors = new Float32Array( [
  19845. 1, 0, 0, 1, 0.6, 0,
  19846. 0, 1, 0, 0.6, 1, 0,
  19847. 0, 0, 1, 0, 0.6, 1
  19848. ] );
  19849. var geometry = new THREE.BufferGeometry();
  19850. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  19851. geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
  19852. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  19853. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  19854. };
  19855. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  19856. THREE.AxisHelper.prototype.constructor = THREE.AxisHelper;
  19857. // File:src/extras/helpers/ArrowHelper.js
  19858. /**
  19859. * @author WestLangley / http://github.com/WestLangley
  19860. * @author zz85 / http://github.com/zz85
  19861. * @author bhouston / http://exocortex.com
  19862. *
  19863. * Creates an arrow for visualizing directions
  19864. *
  19865. * Parameters:
  19866. * dir - Vector3
  19867. * origin - Vector3
  19868. * length - Number
  19869. * color - color in hex value
  19870. * headLength - Number
  19871. * headWidth - Number
  19872. */
  19873. THREE.ArrowHelper = ( function () {
  19874. var lineGeometry = new THREE.Geometry();
  19875. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) );
  19876. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  19877. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  19878. return function ( dir, origin, length, color, headLength, headWidth ) {
  19879. // dir is assumed to be normalized
  19880. THREE.Object3D.call( this );
  19881. if ( color === undefined ) color = 0xffff00;
  19882. if ( length === undefined ) length = 1;
  19883. if ( headLength === undefined ) headLength = 0.2 * length;
  19884. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  19885. this.position.copy( origin );
  19886. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: color } ) );
  19887. this.line.matrixAutoUpdate = false;
  19888. this.add( this.line );
  19889. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: color } ) );
  19890. this.cone.matrixAutoUpdate = false;
  19891. this.add( this.cone );
  19892. this.setDirection( dir );
  19893. this.setLength( length, headLength, headWidth );
  19894. }
  19895. }() );
  19896. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  19897. THREE.ArrowHelper.prototype.constructor = THREE.ArrowHelper;
  19898. THREE.ArrowHelper.prototype.setDirection = ( function () {
  19899. var axis = new THREE.Vector3();
  19900. var radians;
  19901. return function ( dir ) {
  19902. // dir is assumed to be normalized
  19903. if ( dir.y > 0.99999 ) {
  19904. this.quaternion.set( 0, 0, 0, 1 );
  19905. } else if ( dir.y < - 0.99999 ) {
  19906. this.quaternion.set( 1, 0, 0, 0 );
  19907. } else {
  19908. axis.set( dir.z, 0, - dir.x ).normalize();
  19909. radians = Math.acos( dir.y );
  19910. this.quaternion.setFromAxisAngle( axis, radians );
  19911. }
  19912. };
  19913. }() );
  19914. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  19915. if ( headLength === undefined ) headLength = 0.2 * length;
  19916. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  19917. this.line.scale.set( 1, length - headLength, 1 );
  19918. this.line.updateMatrix();
  19919. this.cone.scale.set( headWidth, headLength, headWidth );
  19920. this.cone.position.y = length;
  19921. this.cone.updateMatrix();
  19922. };
  19923. THREE.ArrowHelper.prototype.setColor = function ( color ) {
  19924. this.line.material.color.set( color );
  19925. this.cone.material.color.set( color );
  19926. };
  19927. // File:src/extras/helpers/BoxHelper.js
  19928. /**
  19929. * @author mrdoob / http://mrdoob.com/
  19930. */
  19931. THREE.BoxHelper = function ( object ) {
  19932. var geometry = new THREE.BufferGeometry();
  19933. geometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( 72 ), 3 ) );
  19934. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  19935. if ( object !== undefined ) {
  19936. this.update( object );
  19937. }
  19938. };
  19939. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  19940. THREE.BoxHelper.prototype.constructor = THREE.BoxHelper;
  19941. THREE.BoxHelper.prototype.update = function ( object ) {
  19942. var geometry = object.geometry;
  19943. if ( geometry.boundingBox === null ) {
  19944. geometry.computeBoundingBox();
  19945. }
  19946. var min = geometry.boundingBox.min;
  19947. var max = geometry.boundingBox.max;
  19948. /*
  19949. 5____4
  19950. 1/___0/|
  19951. | 6__|_7
  19952. 2/___3/
  19953. 0: max.x, max.y, max.z
  19954. 1: min.x, max.y, max.z
  19955. 2: min.x, min.y, max.z
  19956. 3: max.x, min.y, max.z
  19957. 4: max.x, max.y, min.z
  19958. 5: min.x, max.y, min.z
  19959. 6: min.x, min.y, min.z
  19960. 7: max.x, min.y, min.z
  19961. */
  19962. var vertices = this.geometry.attributes.position.array;
  19963. vertices[ 0 ] = max.x; vertices[ 1 ] = max.y; vertices[ 2 ] = max.z;
  19964. vertices[ 3 ] = min.x; vertices[ 4 ] = max.y; vertices[ 5 ] = max.z;
  19965. vertices[ 6 ] = min.x; vertices[ 7 ] = max.y; vertices[ 8 ] = max.z;
  19966. vertices[ 9 ] = min.x; vertices[ 10 ] = min.y; vertices[ 11 ] = max.z;
  19967. vertices[ 12 ] = min.x; vertices[ 13 ] = min.y; vertices[ 14 ] = max.z;
  19968. vertices[ 15 ] = max.x; vertices[ 16 ] = min.y; vertices[ 17 ] = max.z;
  19969. vertices[ 18 ] = max.x; vertices[ 19 ] = min.y; vertices[ 20 ] = max.z;
  19970. vertices[ 21 ] = max.x; vertices[ 22 ] = max.y; vertices[ 23 ] = max.z;
  19971. //
  19972. vertices[ 24 ] = max.x; vertices[ 25 ] = max.y; vertices[ 26 ] = min.z;
  19973. vertices[ 27 ] = min.x; vertices[ 28 ] = max.y; vertices[ 29 ] = min.z;
  19974. vertices[ 30 ] = min.x; vertices[ 31 ] = max.y; vertices[ 32 ] = min.z;
  19975. vertices[ 33 ] = min.x; vertices[ 34 ] = min.y; vertices[ 35 ] = min.z;
  19976. vertices[ 36 ] = min.x; vertices[ 37 ] = min.y; vertices[ 38 ] = min.z;
  19977. vertices[ 39 ] = max.x; vertices[ 40 ] = min.y; vertices[ 41 ] = min.z;
  19978. vertices[ 42 ] = max.x; vertices[ 43 ] = min.y; vertices[ 44 ] = min.z;
  19979. vertices[ 45 ] = max.x; vertices[ 46 ] = max.y; vertices[ 47 ] = min.z;
  19980. //
  19981. vertices[ 48 ] = max.x; vertices[ 49 ] = max.y; vertices[ 50 ] = max.z;
  19982. vertices[ 51 ] = max.x; vertices[ 52 ] = max.y; vertices[ 53 ] = min.z;
  19983. vertices[ 54 ] = min.x; vertices[ 55 ] = max.y; vertices[ 56 ] = max.z;
  19984. vertices[ 57 ] = min.x; vertices[ 58 ] = max.y; vertices[ 59 ] = min.z;
  19985. vertices[ 60 ] = min.x; vertices[ 61 ] = min.y; vertices[ 62 ] = max.z;
  19986. vertices[ 63 ] = min.x; vertices[ 64 ] = min.y; vertices[ 65 ] = min.z;
  19987. vertices[ 66 ] = max.x; vertices[ 67 ] = min.y; vertices[ 68 ] = max.z;
  19988. vertices[ 69 ] = max.x; vertices[ 70 ] = min.y; vertices[ 71 ] = min.z;
  19989. this.geometry.attributes.position.needsUpdate = true;
  19990. this.geometry.computeBoundingSphere();
  19991. this.matrix = object.matrixWorld;
  19992. this.matrixAutoUpdate = false;
  19993. };
  19994. // File:src/extras/helpers/BoundingBoxHelper.js
  19995. /**
  19996. * @author WestLangley / http://github.com/WestLangley
  19997. */
  19998. // a helper to show the world-axis-aligned bounding box for an object
  19999. THREE.BoundingBoxHelper = function ( object, hex ) {
  20000. var color = ( hex !== undefined ) ? hex : 0x888888;
  20001. this.object = object;
  20002. this.box = new THREE.Box3();
  20003. THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20004. };
  20005. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20006. THREE.BoundingBoxHelper.prototype.constructor = THREE.BoundingBoxHelper;
  20007. THREE.BoundingBoxHelper.prototype.update = function () {
  20008. this.box.setFromObject( this.object );
  20009. this.box.size( this.scale );
  20010. this.box.center( this.position );
  20011. };
  20012. // File:src/extras/helpers/CameraHelper.js
  20013. /**
  20014. * @author alteredq / http://alteredqualia.com/
  20015. *
  20016. * - shows frustum, line of sight and up of the camera
  20017. * - suitable for fast updates
  20018. * - based on frustum visualization in lightgl.js shadowmap example
  20019. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20020. */
  20021. THREE.CameraHelper = function ( camera ) {
  20022. var geometry = new THREE.Geometry();
  20023. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20024. var pointMap = {};
  20025. // colors
  20026. var hexFrustum = 0xffaa00;
  20027. var hexCone = 0xff0000;
  20028. var hexUp = 0x00aaff;
  20029. var hexTarget = 0xffffff;
  20030. var hexCross = 0x333333;
  20031. // near
  20032. addLine( "n1", "n2", hexFrustum );
  20033. addLine( "n2", "n4", hexFrustum );
  20034. addLine( "n4", "n3", hexFrustum );
  20035. addLine( "n3", "n1", hexFrustum );
  20036. // far
  20037. addLine( "f1", "f2", hexFrustum );
  20038. addLine( "f2", "f4", hexFrustum );
  20039. addLine( "f4", "f3", hexFrustum );
  20040. addLine( "f3", "f1", hexFrustum );
  20041. // sides
  20042. addLine( "n1", "f1", hexFrustum );
  20043. addLine( "n2", "f2", hexFrustum );
  20044. addLine( "n3", "f3", hexFrustum );
  20045. addLine( "n4", "f4", hexFrustum );
  20046. // cone
  20047. addLine( "p", "n1", hexCone );
  20048. addLine( "p", "n2", hexCone );
  20049. addLine( "p", "n3", hexCone );
  20050. addLine( "p", "n4", hexCone );
  20051. // up
  20052. addLine( "u1", "u2", hexUp );
  20053. addLine( "u2", "u3", hexUp );
  20054. addLine( "u3", "u1", hexUp );
  20055. // target
  20056. addLine( "c", "t", hexTarget );
  20057. addLine( "p", "c", hexCross );
  20058. // cross
  20059. addLine( "cn1", "cn2", hexCross );
  20060. addLine( "cn3", "cn4", hexCross );
  20061. addLine( "cf1", "cf2", hexCross );
  20062. addLine( "cf3", "cf4", hexCross );
  20063. function addLine( a, b, hex ) {
  20064. addPoint( a, hex );
  20065. addPoint( b, hex );
  20066. }
  20067. function addPoint( id, hex ) {
  20068. geometry.vertices.push( new THREE.Vector3() );
  20069. geometry.colors.push( new THREE.Color( hex ) );
  20070. if ( pointMap[ id ] === undefined ) {
  20071. pointMap[ id ] = [];
  20072. }
  20073. pointMap[ id ].push( geometry.vertices.length - 1 );
  20074. }
  20075. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20076. this.camera = camera;
  20077. this.matrix = camera.matrixWorld;
  20078. this.matrixAutoUpdate = false;
  20079. this.pointMap = pointMap;
  20080. this.update();
  20081. };
  20082. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20083. THREE.CameraHelper.prototype.constructor = THREE.CameraHelper;
  20084. THREE.CameraHelper.prototype.update = function () {
  20085. var geometry, pointMap;
  20086. var vector = new THREE.Vector3();
  20087. var camera = new THREE.Camera();
  20088. var setPoint = function ( point, x, y, z ) {
  20089. vector.set( x, y, z ).unproject( camera );
  20090. var points = pointMap[ point ];
  20091. if ( points !== undefined ) {
  20092. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20093. geometry.vertices[ points[ i ] ].copy( vector );
  20094. }
  20095. }
  20096. };
  20097. return function () {
  20098. geometry = this.geometry;
  20099. pointMap = this.pointMap;
  20100. var w = 1, h = 1;
  20101. // we need just camera projection matrix
  20102. // world matrix must be identity
  20103. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20104. // center / target
  20105. setPoint( "c", 0, 0, - 1 );
  20106. setPoint( "t", 0, 0, 1 );
  20107. // near
  20108. setPoint( "n1", - w, - h, - 1 );
  20109. setPoint( "n2", w, - h, - 1 );
  20110. setPoint( "n3", - w, h, - 1 );
  20111. setPoint( "n4", w, h, - 1 );
  20112. // far
  20113. setPoint( "f1", - w, - h, 1 );
  20114. setPoint( "f2", w, - h, 1 );
  20115. setPoint( "f3", - w, h, 1 );
  20116. setPoint( "f4", w, h, 1 );
  20117. // up
  20118. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  20119. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  20120. setPoint( "u3", 0, h * 2, - 1 );
  20121. // cross
  20122. setPoint( "cf1", - w, 0, 1 );
  20123. setPoint( "cf2", w, 0, 1 );
  20124. setPoint( "cf3", 0, - h, 1 );
  20125. setPoint( "cf4", 0, h, 1 );
  20126. setPoint( "cn1", - w, 0, - 1 );
  20127. setPoint( "cn2", w, 0, - 1 );
  20128. setPoint( "cn3", 0, - h, - 1 );
  20129. setPoint( "cn4", 0, h, - 1 );
  20130. geometry.verticesNeedUpdate = true;
  20131. };
  20132. }();
  20133. // File:src/extras/helpers/DirectionalLightHelper.js
  20134. /**
  20135. * @author alteredq / http://alteredqualia.com/
  20136. * @author mrdoob / http://mrdoob.com/
  20137. * @author WestLangley / http://github.com/WestLangley
  20138. */
  20139. THREE.DirectionalLightHelper = function ( light, size ) {
  20140. THREE.Object3D.call( this );
  20141. this.light = light;
  20142. this.light.updateMatrixWorld();
  20143. this.matrix = light.matrixWorld;
  20144. this.matrixAutoUpdate = false;
  20145. size = size || 1;
  20146. var geometry = new THREE.Geometry();
  20147. geometry.vertices.push(
  20148. new THREE.Vector3( - size, size, 0 ),
  20149. new THREE.Vector3( size, size, 0 ),
  20150. new THREE.Vector3( size, - size, 0 ),
  20151. new THREE.Vector3( - size, - size, 0 ),
  20152. new THREE.Vector3( - size, size, 0 )
  20153. );
  20154. var material = new THREE.LineBasicMaterial( { fog: false } );
  20155. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20156. this.lightPlane = new THREE.Line( geometry, material );
  20157. this.add( this.lightPlane );
  20158. geometry = new THREE.Geometry();
  20159. geometry.vertices.push(
  20160. new THREE.Vector3(),
  20161. new THREE.Vector3()
  20162. );
  20163. material = new THREE.LineBasicMaterial( { fog: false } );
  20164. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20165. this.targetLine = new THREE.Line( geometry, material );
  20166. this.add( this.targetLine );
  20167. this.update();
  20168. };
  20169. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20170. THREE.DirectionalLightHelper.prototype.constructor = THREE.DirectionalLightHelper;
  20171. THREE.DirectionalLightHelper.prototype.dispose = function () {
  20172. this.lightPlane.geometry.dispose();
  20173. this.lightPlane.material.dispose();
  20174. this.targetLine.geometry.dispose();
  20175. this.targetLine.material.dispose();
  20176. };
  20177. THREE.DirectionalLightHelper.prototype.update = function () {
  20178. var v1 = new THREE.Vector3();
  20179. var v2 = new THREE.Vector3();
  20180. var v3 = new THREE.Vector3();
  20181. return function () {
  20182. v1.setFromMatrixPosition( this.light.matrixWorld );
  20183. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20184. v3.subVectors( v2, v1 );
  20185. this.lightPlane.lookAt( v3 );
  20186. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20187. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  20188. this.targetLine.geometry.verticesNeedUpdate = true;
  20189. this.targetLine.material.color.copy( this.lightPlane.material.color );
  20190. };
  20191. }();
  20192. // File:src/extras/helpers/EdgesHelper.js
  20193. /**
  20194. * @author WestLangley / http://github.com/WestLangley
  20195. */
  20196. THREE.EdgesHelper = function ( object, hex ) {
  20197. var color = ( hex !== undefined ) ? hex : 0xffffff;
  20198. var edge = [ 0, 0 ], hash = {};
  20199. var sortFunction = function ( a, b ) { return a - b };
  20200. var keys = [ 'a', 'b', 'c' ];
  20201. var geometry = new THREE.BufferGeometry();
  20202. var geometry2;
  20203. if ( object.geometry instanceof THREE.BufferGeometry ) {
  20204. geometry2 = new THREE.Geometry();
  20205. geometry2.fromBufferGeometry( object.geometry );
  20206. } else {
  20207. geometry2 = object.geometry.clone();
  20208. }
  20209. geometry2.mergeVertices();
  20210. geometry2.computeFaceNormals();
  20211. var vertices = geometry2.vertices;
  20212. var faces = geometry2.faces;
  20213. var numEdges = 0;
  20214. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20215. var face = faces[ i ];
  20216. for ( var j = 0; j < 3; j ++ ) {
  20217. edge[ 0 ] = face[ keys[ j ] ];
  20218. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20219. edge.sort( sortFunction );
  20220. var key = edge.toString();
  20221. if ( hash[ key ] === undefined ) {
  20222. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  20223. numEdges ++;
  20224. } else {
  20225. hash[ key ].face2 = i;
  20226. }
  20227. }
  20228. }
  20229. var coords = new Float32Array( numEdges * 2 * 3 );
  20230. var index = 0;
  20231. for ( var key in hash ) {
  20232. var h = hash[ key ];
  20233. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) < 0.9999 ) { // hardwired const OK
  20234. var vertex = vertices[ h.vert1 ];
  20235. coords[ index ++ ] = vertex.x;
  20236. coords[ index ++ ] = vertex.y;
  20237. coords[ index ++ ] = vertex.z;
  20238. vertex = vertices[ h.vert2 ];
  20239. coords[ index ++ ] = vertex.x;
  20240. coords[ index ++ ] = vertex.y;
  20241. coords[ index ++ ] = vertex.z;
  20242. }
  20243. }
  20244. geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20245. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  20246. this.matrix = object.matrixWorld;
  20247. this.matrixAutoUpdate = false;
  20248. };
  20249. THREE.EdgesHelper.prototype = Object.create( THREE.Line.prototype );
  20250. THREE.EdgesHelper.prototype.constructor = THREE.EdgesHelper;
  20251. // File:src/extras/helpers/FaceNormalsHelper.js
  20252. /**
  20253. * @author mrdoob / http://mrdoob.com/
  20254. * @author WestLangley / http://github.com/WestLangley
  20255. */
  20256. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  20257. this.object = object;
  20258. this.size = ( size !== undefined ) ? size : 1;
  20259. var color = ( hex !== undefined ) ? hex : 0xffff00;
  20260. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20261. var geometry = new THREE.Geometry();
  20262. var faces = this.object.geometry.faces;
  20263. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20264. geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() );
  20265. }
  20266. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20267. this.matrixAutoUpdate = false;
  20268. this.normalMatrix = new THREE.Matrix3();
  20269. this.update();
  20270. };
  20271. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20272. THREE.FaceNormalsHelper.prototype.constructor = THREE.FaceNormalsHelper;
  20273. THREE.FaceNormalsHelper.prototype.update = function () {
  20274. var vertices = this.geometry.vertices;
  20275. var object = this.object;
  20276. var objectVertices = object.geometry.vertices;
  20277. var objectFaces = object.geometry.faces;
  20278. var objectWorldMatrix = object.matrixWorld;
  20279. object.updateMatrixWorld( true );
  20280. this.normalMatrix.getNormalMatrix( objectWorldMatrix );
  20281. for ( var i = 0, i2 = 0, l = objectFaces.length; i < l; i ++, i2 += 2 ) {
  20282. var face = objectFaces[ i ];
  20283. vertices[ i2 ].copy( objectVertices[ face.a ] )
  20284. .add( objectVertices[ face.b ] )
  20285. .add( objectVertices[ face.c ] )
  20286. .divideScalar( 3 )
  20287. .applyMatrix4( objectWorldMatrix );
  20288. vertices[ i2 + 1 ].copy( face.normal )
  20289. .applyMatrix3( this.normalMatrix )
  20290. .normalize()
  20291. .multiplyScalar( this.size )
  20292. .add( vertices[ i2 ] );
  20293. }
  20294. this.geometry.verticesNeedUpdate = true;
  20295. return this;
  20296. };
  20297. // File:src/extras/helpers/GridHelper.js
  20298. /**
  20299. * @author mrdoob / http://mrdoob.com/
  20300. */
  20301. THREE.GridHelper = function ( size, step ) {
  20302. var geometry = new THREE.Geometry();
  20303. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20304. this.color1 = new THREE.Color( 0x444444 );
  20305. this.color2 = new THREE.Color( 0x888888 );
  20306. for ( var i = - size; i <= size; i += step ) {
  20307. geometry.vertices.push(
  20308. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  20309. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  20310. );
  20311. var color = i === 0 ? this.color1 : this.color2;
  20312. geometry.colors.push( color, color, color, color );
  20313. }
  20314. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20315. };
  20316. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  20317. THREE.GridHelper.prototype.constructor = THREE.GridHelper;
  20318. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  20319. this.color1.set( colorCenterLine );
  20320. this.color2.set( colorGrid );
  20321. this.geometry.colorsNeedUpdate = true;
  20322. }
  20323. // File:src/extras/helpers/HemisphereLightHelper.js
  20324. /**
  20325. * @author alteredq / http://alteredqualia.com/
  20326. * @author mrdoob / http://mrdoob.com/
  20327. */
  20328. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20329. THREE.Object3D.call( this );
  20330. this.light = light;
  20331. this.light.updateMatrixWorld();
  20332. this.matrix = light.matrixWorld;
  20333. this.matrixAutoUpdate = false;
  20334. this.colors = [ new THREE.Color(), new THREE.Color() ];
  20335. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20336. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20337. for ( var i = 0, il = 8; i < il; i ++ ) {
  20338. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  20339. }
  20340. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  20341. this.lightSphere = new THREE.Mesh( geometry, material );
  20342. this.add( this.lightSphere );
  20343. this.update();
  20344. };
  20345. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20346. THREE.HemisphereLightHelper.prototype.constructor = THREE.HemisphereLightHelper;
  20347. THREE.HemisphereLightHelper.prototype.dispose = function () {
  20348. this.lightSphere.geometry.dispose();
  20349. this.lightSphere.material.dispose();
  20350. };
  20351. THREE.HemisphereLightHelper.prototype.update = function () {
  20352. var vector = new THREE.Vector3();
  20353. return function () {
  20354. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  20355. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  20356. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20357. this.lightSphere.geometry.colorsNeedUpdate = true;
  20358. }
  20359. }();
  20360. // File:src/extras/helpers/PointLightHelper.js
  20361. /**
  20362. * @author alteredq / http://alteredqualia.com/
  20363. * @author mrdoob / http://mrdoob.com/
  20364. */
  20365. THREE.PointLightHelper = function ( light, sphereSize ) {
  20366. this.light = light;
  20367. this.light.updateMatrixWorld();
  20368. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20369. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20370. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20371. THREE.Mesh.call( this, geometry, material );
  20372. this.matrix = this.light.matrixWorld;
  20373. this.matrixAutoUpdate = false;
  20374. /*
  20375. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20376. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20377. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20378. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20379. var d = light.distance;
  20380. if ( d === 0.0 ) {
  20381. this.lightDistance.visible = false;
  20382. } else {
  20383. this.lightDistance.scale.set( d, d, d );
  20384. }
  20385. this.add( this.lightDistance );
  20386. */
  20387. };
  20388. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  20389. THREE.PointLightHelper.prototype.constructor = THREE.PointLightHelper;
  20390. THREE.PointLightHelper.prototype.dispose = function () {
  20391. this.geometry.dispose();
  20392. this.material.dispose();
  20393. };
  20394. THREE.PointLightHelper.prototype.update = function () {
  20395. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20396. /*
  20397. var d = this.light.distance;
  20398. if ( d === 0.0 ) {
  20399. this.lightDistance.visible = false;
  20400. } else {
  20401. this.lightDistance.visible = true;
  20402. this.lightDistance.scale.set( d, d, d );
  20403. }
  20404. */
  20405. };
  20406. // File:src/extras/helpers/SkeletonHelper.js
  20407. /**
  20408. * @author Sean Griffin / http://twitter.com/sgrif
  20409. * @author Michael Guerrero / http://realitymeltdown.com
  20410. * @author mrdoob / http://mrdoob.com/
  20411. * @author ikerr / http://verold.com
  20412. */
  20413. THREE.SkeletonHelper = function ( object ) {
  20414. this.bones = this.getBoneList( object );
  20415. var geometry = new THREE.Geometry();
  20416. for ( var i = 0; i < this.bones.length; i ++ ) {
  20417. var bone = this.bones[ i ];
  20418. if ( bone.parent instanceof THREE.Bone ) {
  20419. geometry.vertices.push( new THREE.Vector3() );
  20420. geometry.vertices.push( new THREE.Vector3() );
  20421. geometry.colors.push( new THREE.Color( 0, 0, 1 ) );
  20422. geometry.colors.push( new THREE.Color( 0, 1, 0 ) );
  20423. }
  20424. }
  20425. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  20426. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20427. this.root = object;
  20428. this.matrix = object.matrixWorld;
  20429. this.matrixAutoUpdate = false;
  20430. this.update();
  20431. };
  20432. THREE.SkeletonHelper.prototype = Object.create( THREE.Line.prototype );
  20433. THREE.SkeletonHelper.prototype.constructor = THREE.SkeletonHelper;
  20434. THREE.SkeletonHelper.prototype.getBoneList = function( object ) {
  20435. var boneList = [];
  20436. if ( object instanceof THREE.Bone ) {
  20437. boneList.push( object );
  20438. }
  20439. for ( var i = 0; i < object.children.length; i ++ ) {
  20440. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  20441. }
  20442. return boneList;
  20443. };
  20444. THREE.SkeletonHelper.prototype.update = function () {
  20445. var geometry = this.geometry;
  20446. var matrixWorldInv = new THREE.Matrix4().getInverse( this.root.matrixWorld );
  20447. var boneMatrix = new THREE.Matrix4();
  20448. var j = 0;
  20449. for ( var i = 0; i < this.bones.length; i ++ ) {
  20450. var bone = this.bones[ i ];
  20451. if ( bone.parent instanceof THREE.Bone ) {
  20452. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  20453. geometry.vertices[ j ].setFromMatrixPosition( boneMatrix );
  20454. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  20455. geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix );
  20456. j += 2;
  20457. }
  20458. }
  20459. geometry.verticesNeedUpdate = true;
  20460. geometry.computeBoundingSphere();
  20461. };
  20462. // File:src/extras/helpers/SpotLightHelper.js
  20463. /**
  20464. * @author alteredq / http://alteredqualia.com/
  20465. * @author mrdoob / http://mrdoob.com/
  20466. * @author WestLangley / http://github.com/WestLangley
  20467. */
  20468. THREE.SpotLightHelper = function ( light ) {
  20469. THREE.Object3D.call( this );
  20470. this.light = light;
  20471. this.light.updateMatrixWorld();
  20472. this.matrix = light.matrixWorld;
  20473. this.matrixAutoUpdate = false;
  20474. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  20475. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  20476. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20477. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20478. this.cone = new THREE.Mesh( geometry, material );
  20479. this.add( this.cone );
  20480. this.update();
  20481. };
  20482. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20483. THREE.SpotLightHelper.prototype.constructor = THREE.SpotLightHelper;
  20484. THREE.SpotLightHelper.prototype.dispose = function () {
  20485. this.cone.geometry.dispose();
  20486. this.cone.material.dispose();
  20487. };
  20488. THREE.SpotLightHelper.prototype.update = function () {
  20489. var vector = new THREE.Vector3();
  20490. var vector2 = new THREE.Vector3();
  20491. return function () {
  20492. var coneLength = this.light.distance ? this.light.distance : 10000;
  20493. var coneWidth = coneLength * Math.tan( this.light.angle );
  20494. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20495. vector.setFromMatrixPosition( this.light.matrixWorld );
  20496. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  20497. this.cone.lookAt( vector2.sub( vector ) );
  20498. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20499. };
  20500. }();
  20501. // File:src/extras/helpers/VertexNormalsHelper.js
  20502. /**
  20503. * @author mrdoob / http://mrdoob.com/
  20504. * @author WestLangley / http://github.com/WestLangley
  20505. */
  20506. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  20507. this.object = object;
  20508. this.size = ( size !== undefined ) ? size : 1;
  20509. var color = ( hex !== undefined ) ? hex : 0xff0000;
  20510. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20511. var geometry = new THREE.Geometry();
  20512. var vertices = object.geometry.vertices;
  20513. var faces = object.geometry.faces;
  20514. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20515. var face = faces[ i ];
  20516. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20517. geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() );
  20518. }
  20519. }
  20520. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20521. this.matrixAutoUpdate = false;
  20522. this.normalMatrix = new THREE.Matrix3();
  20523. this.update();
  20524. };
  20525. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20526. THREE.VertexNormalsHelper.prototype.constructor = THREE.VertexNormalsHelper;
  20527. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  20528. var v1 = new THREE.Vector3();
  20529. return function( object ) {
  20530. var keys = [ 'a', 'b', 'c', 'd' ];
  20531. this.object.updateMatrixWorld( true );
  20532. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20533. var vertices = this.geometry.vertices;
  20534. var verts = this.object.geometry.vertices;
  20535. var faces = this.object.geometry.faces;
  20536. var worldMatrix = this.object.matrixWorld;
  20537. var idx = 0;
  20538. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20539. var face = faces[ i ];
  20540. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20541. var vertexId = face[ keys[ j ] ];
  20542. var vertex = verts[ vertexId ];
  20543. var normal = face.vertexNormals[ j ];
  20544. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20545. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20546. v1.add( vertices[ idx ] );
  20547. idx = idx + 1;
  20548. vertices[ idx ].copy( v1 );
  20549. idx = idx + 1;
  20550. }
  20551. }
  20552. this.geometry.verticesNeedUpdate = true;
  20553. return this;
  20554. }
  20555. }());
  20556. // File:src/extras/helpers/VertexTangentsHelper.js
  20557. /**
  20558. * @author mrdoob / http://mrdoob.com/
  20559. * @author WestLangley / http://github.com/WestLangley
  20560. */
  20561. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  20562. this.object = object;
  20563. this.size = ( size !== undefined ) ? size : 1;
  20564. var color = ( hex !== undefined ) ? hex : 0x0000ff;
  20565. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20566. var geometry = new THREE.Geometry();
  20567. var vertices = object.geometry.vertices;
  20568. var faces = object.geometry.faces;
  20569. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20570. var face = faces[ i ];
  20571. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20572. geometry.vertices.push( new THREE.Vector3() );
  20573. geometry.vertices.push( new THREE.Vector3() );
  20574. }
  20575. }
  20576. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20577. this.matrixAutoUpdate = false;
  20578. this.update();
  20579. };
  20580. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  20581. THREE.VertexTangentsHelper.prototype.constructor = THREE.VertexTangentsHelper;
  20582. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  20583. var v1 = new THREE.Vector3();
  20584. return function( object ) {
  20585. var keys = [ 'a', 'b', 'c', 'd' ];
  20586. this.object.updateMatrixWorld( true );
  20587. var vertices = this.geometry.vertices;
  20588. var verts = this.object.geometry.vertices;
  20589. var faces = this.object.geometry.faces;
  20590. var worldMatrix = this.object.matrixWorld;
  20591. var idx = 0;
  20592. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20593. var face = faces[ i ];
  20594. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20595. var vertexId = face[ keys[ j ] ];
  20596. var vertex = verts[ vertexId ];
  20597. var tangent = face.vertexTangents[ j ];
  20598. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20599. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  20600. v1.add( vertices[ idx ] );
  20601. idx = idx + 1;
  20602. vertices[ idx ].copy( v1 );
  20603. idx = idx + 1;
  20604. }
  20605. }
  20606. this.geometry.verticesNeedUpdate = true;
  20607. return this;
  20608. }
  20609. }());
  20610. // File:src/extras/helpers/WireframeHelper.js
  20611. /**
  20612. * @author mrdoob / http://mrdoob.com/
  20613. */
  20614. THREE.WireframeHelper = function ( object, hex ) {
  20615. var color = ( hex !== undefined ) ? hex : 0xffffff;
  20616. var edge = [ 0, 0 ], hash = {};
  20617. var sortFunction = function ( a, b ) { return a - b };
  20618. var keys = [ 'a', 'b', 'c' ];
  20619. var geometry = new THREE.BufferGeometry();
  20620. if ( object.geometry instanceof THREE.Geometry ) {
  20621. var vertices = object.geometry.vertices;
  20622. var faces = object.geometry.faces;
  20623. var numEdges = 0;
  20624. // allocate maximal size
  20625. var edges = new Uint32Array( 6 * faces.length );
  20626. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20627. var face = faces[ i ];
  20628. for ( var j = 0; j < 3; j ++ ) {
  20629. edge[ 0 ] = face[ keys[ j ] ];
  20630. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20631. edge.sort( sortFunction );
  20632. var key = edge.toString();
  20633. if ( hash[ key ] === undefined ) {
  20634. edges[ 2 * numEdges ] = edge[ 0 ];
  20635. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  20636. hash[ key ] = true;
  20637. numEdges ++;
  20638. }
  20639. }
  20640. }
  20641. var coords = new Float32Array( numEdges * 2 * 3 );
  20642. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  20643. for ( var j = 0; j < 2; j ++ ) {
  20644. var vertex = vertices[ edges [ 2 * i + j] ];
  20645. var index = 6 * i + 3 * j;
  20646. coords[ index + 0 ] = vertex.x;
  20647. coords[ index + 1 ] = vertex.y;
  20648. coords[ index + 2 ] = vertex.z;
  20649. }
  20650. }
  20651. geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20652. } else if ( object.geometry instanceof THREE.BufferGeometry ) {
  20653. if ( object.geometry.attributes.index !== undefined ) { // Indexed BufferGeometry
  20654. var vertices = object.geometry.attributes.position.array;
  20655. var indices = object.geometry.attributes.index.array;
  20656. var drawcalls = object.geometry.drawcalls;
  20657. var numEdges = 0;
  20658. if ( drawcalls.length === 0 ) {
  20659. drawcalls = [ { count : indices.length, index : 0, start : 0 } ];
  20660. }
  20661. // allocate maximal size
  20662. var edges = new Uint32Array( 2 * indices.length );
  20663. for ( var o = 0, ol = drawcalls.length; o < ol; ++ o ) {
  20664. var start = drawcalls[ o ].start;
  20665. var count = drawcalls[ o ].count;
  20666. var index = drawcalls[ o ].index;
  20667. for ( var i = start, il = start + count; i < il; i += 3 ) {
  20668. for ( var j = 0; j < 3; j ++ ) {
  20669. edge[ 0 ] = index + indices[ i + j ];
  20670. edge[ 1 ] = index + indices[ i + ( j + 1 ) % 3 ];
  20671. edge.sort( sortFunction );
  20672. var key = edge.toString();
  20673. if ( hash[ key ] === undefined ) {
  20674. edges[ 2 * numEdges ] = edge[ 0 ];
  20675. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  20676. hash[ key ] = true;
  20677. numEdges ++;
  20678. }
  20679. }
  20680. }
  20681. }
  20682. var coords = new Float32Array( numEdges * 2 * 3 );
  20683. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  20684. for ( var j = 0; j < 2; j ++ ) {
  20685. var index = 6 * i + 3 * j;
  20686. var index2 = 3 * edges[ 2 * i + j];
  20687. coords[ index + 0 ] = vertices[ index2 ];
  20688. coords[ index + 1 ] = vertices[ index2 + 1 ];
  20689. coords[ index + 2 ] = vertices[ index2 + 2 ];
  20690. }
  20691. }
  20692. geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20693. } else { // non-indexed BufferGeometry
  20694. var vertices = object.geometry.attributes.position.array;
  20695. var numEdges = vertices.length / 3;
  20696. var numTris = numEdges / 3;
  20697. var coords = new Float32Array( numEdges * 2 * 3 );
  20698. for ( var i = 0, l = numTris; i < l; i ++ ) {
  20699. for ( var j = 0; j < 3; j ++ ) {
  20700. var index = 18 * i + 6 * j;
  20701. var index1 = 9 * i + 3 * j;
  20702. coords[ index + 0 ] = vertices[ index1 ];
  20703. coords[ index + 1 ] = vertices[ index1 + 1 ];
  20704. coords[ index + 2 ] = vertices[ index1 + 2 ];
  20705. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  20706. coords[ index + 3 ] = vertices[ index2 ];
  20707. coords[ index + 4 ] = vertices[ index2 + 1 ];
  20708. coords[ index + 5 ] = vertices[ index2 + 2 ];
  20709. }
  20710. }
  20711. geometry.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20712. }
  20713. }
  20714. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  20715. this.matrix = object.matrixWorld;
  20716. this.matrixAutoUpdate = false;
  20717. };
  20718. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  20719. THREE.WireframeHelper.prototype.constructor = THREE.WireframeHelper;
  20720. // File:src/extras/objects/ImmediateRenderObject.js
  20721. /**
  20722. * @author alteredq / http://alteredqualia.com/
  20723. */
  20724. THREE.ImmediateRenderObject = function () {
  20725. THREE.Object3D.call( this );
  20726. this.render = function ( renderCallback ) {};
  20727. };
  20728. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20729. THREE.ImmediateRenderObject.prototype.constructor = THREE.ImmediateRenderObject;
  20730. // File:src/extras/objects/MorphBlendMesh.js
  20731. /**
  20732. * @author alteredq / http://alteredqualia.com/
  20733. */
  20734. THREE.MorphBlendMesh = function( geometry, material ) {
  20735. THREE.Mesh.call( this, geometry, material );
  20736. this.animationsMap = {};
  20737. this.animationsList = [];
  20738. // prepare default animation
  20739. // (all frames played together in 1 second)
  20740. var numFrames = this.geometry.morphTargets.length;
  20741. var name = "__default";
  20742. var startFrame = 0;
  20743. var endFrame = numFrames - 1;
  20744. var fps = numFrames / 1;
  20745. this.createAnimation( name, startFrame, endFrame, fps );
  20746. this.setAnimationWeight( name, 1 );
  20747. };
  20748. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20749. THREE.MorphBlendMesh.prototype.constructor = THREE.MorphBlendMesh;
  20750. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20751. var animation = {
  20752. startFrame: start,
  20753. endFrame: end,
  20754. length: end - start + 1,
  20755. fps: fps,
  20756. duration: ( end - start ) / fps,
  20757. lastFrame: 0,
  20758. currentFrame: 0,
  20759. active: false,
  20760. time: 0,
  20761. direction: 1,
  20762. weight: 1,
  20763. directionBackwards: false,
  20764. mirroredLoop: false
  20765. };
  20766. this.animationsMap[ name ] = animation;
  20767. this.animationsList.push( animation );
  20768. };
  20769. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20770. var pattern = /([a-z]+)_?(\d+)/;
  20771. var firstAnimation, frameRanges = {};
  20772. var geometry = this.geometry;
  20773. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20774. var morph = geometry.morphTargets[ i ];
  20775. var chunks = morph.name.match( pattern );
  20776. if ( chunks && chunks.length > 1 ) {
  20777. var name = chunks[ 1 ];
  20778. var num = chunks[ 2 ];
  20779. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  20780. var range = frameRanges[ name ];
  20781. if ( i < range.start ) range.start = i;
  20782. if ( i > range.end ) range.end = i;
  20783. if ( ! firstAnimation ) firstAnimation = name;
  20784. }
  20785. }
  20786. for ( var name in frameRanges ) {
  20787. var range = frameRanges[ name ];
  20788. this.createAnimation( name, range.start, range.end, fps );
  20789. }
  20790. this.firstAnimation = firstAnimation;
  20791. };
  20792. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20793. var animation = this.animationsMap[ name ];
  20794. if ( animation ) {
  20795. animation.direction = 1;
  20796. animation.directionBackwards = false;
  20797. }
  20798. };
  20799. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20800. var animation = this.animationsMap[ name ];
  20801. if ( animation ) {
  20802. animation.direction = - 1;
  20803. animation.directionBackwards = true;
  20804. }
  20805. };
  20806. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20807. var animation = this.animationsMap[ name ];
  20808. if ( animation ) {
  20809. animation.fps = fps;
  20810. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20811. }
  20812. };
  20813. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20814. var animation = this.animationsMap[ name ];
  20815. if ( animation ) {
  20816. animation.duration = duration;
  20817. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20818. }
  20819. };
  20820. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20821. var animation = this.animationsMap[ name ];
  20822. if ( animation ) {
  20823. animation.weight = weight;
  20824. }
  20825. };
  20826. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20827. var animation = this.animationsMap[ name ];
  20828. if ( animation ) {
  20829. animation.time = time;
  20830. }
  20831. };
  20832. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20833. var time = 0;
  20834. var animation = this.animationsMap[ name ];
  20835. if ( animation ) {
  20836. time = animation.time;
  20837. }
  20838. return time;
  20839. };
  20840. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20841. var duration = - 1;
  20842. var animation = this.animationsMap[ name ];
  20843. if ( animation ) {
  20844. duration = animation.duration;
  20845. }
  20846. return duration;
  20847. };
  20848. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20849. var animation = this.animationsMap[ name ];
  20850. if ( animation ) {
  20851. animation.time = 0;
  20852. animation.active = true;
  20853. } else {
  20854. THREE.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  20855. }
  20856. };
  20857. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20858. var animation = this.animationsMap[ name ];
  20859. if ( animation ) {
  20860. animation.active = false;
  20861. }
  20862. };
  20863. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20864. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20865. var animation = this.animationsList[ i ];
  20866. if ( ! animation.active ) continue;
  20867. var frameTime = animation.duration / animation.length;
  20868. animation.time += animation.direction * delta;
  20869. if ( animation.mirroredLoop ) {
  20870. if ( animation.time > animation.duration || animation.time < 0 ) {
  20871. animation.direction *= - 1;
  20872. if ( animation.time > animation.duration ) {
  20873. animation.time = animation.duration;
  20874. animation.directionBackwards = true;
  20875. }
  20876. if ( animation.time < 0 ) {
  20877. animation.time = 0;
  20878. animation.directionBackwards = false;
  20879. }
  20880. }
  20881. } else {
  20882. animation.time = animation.time % animation.duration;
  20883. if ( animation.time < 0 ) animation.time += animation.duration;
  20884. }
  20885. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20886. var weight = animation.weight;
  20887. if ( keyframe !== animation.currentFrame ) {
  20888. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20889. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20890. this.morphTargetInfluences[ keyframe ] = 0;
  20891. animation.lastFrame = animation.currentFrame;
  20892. animation.currentFrame = keyframe;
  20893. }
  20894. var mix = ( animation.time % frameTime ) / frameTime;
  20895. if ( animation.directionBackwards ) mix = 1 - mix;
  20896. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20897. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20898. }
  20899. };
粤ICP备19079148号